How do I construct a thin controller with a dependent service?

Question: For the first time I am trying to architect a reasonably complex Drupal 8 module, and not sure of best practice for the controller.

I need to route paths to a controller.
I intend the controller to be
thin (very little logic, doesn't need to testable)
Heavy lifting will be via service class/es configured and defined by the module.

Extending ControllerBase should be the right path for a thin controller, however when I look in Core at the moment I notice a number of controllers that both extend ControllerBase and implement ContainerInjectionInterface. I would only implement ContainerInjectionInterface to be able to inject a different container for testing, not just selection of service in the create method, but Core is still in flux and I am not sure exactly why they are doing this.
I feel that I should extend ControllerBase, add a __construct that fetches the container and pulls in the non-standard service/s that I require via $this->container()->get() and indeed that does work. I also don't need the create method required to implement ContainerInjectionInterface.
Am I correct? I know I will need to go through a few iterations of getting the services right but want to get THIS bit right from the start and understand why I am doing it.
Thanks in advance.
Comment: In this context, I have more context with the Symfony components rather than Drupal. With that said, I don't understand why you'd create a special container solution with __construct rather than just implement ContainerInjectionInterface.
Comment: Because with only extending controllerBase I can access the container provided in my __construct function to get the instance of my service (a bunch of standard services are automatically available but not my non-standard one).
Comment: Sorry editing on a tablet, this is extension of above comment. If I implement ContainerInjection interface I have to add a create method to pull desired services from an injected controller, AND a construct method to receive them as parameters, rather long winded.
Comment: ControllerBase::container() is being removed shortly. Do not rely on it.
Answer: ContainerInjectionInterface is used as a part of a static factory method pattern.
This way, a class's constructor can specify all of the services it needs, and its factory method, in this case create(), can satisfy the constructor by retrieving services from the container.
The instantiated controller should never have its own copy of the container, if at all avoidable.
A brief example:
<?php

namespace Drupal\book\Controller;

use Drupal\book\BookManager;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class BookController extends ControllerBase implements ContainerInjectionInterface {
  protected $bookManager;

  public function __construct(BookManager $bookManager) {
    $this->bookManager = $bookManager;
  }

  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('book.manager')
    );
  }

  public function bookRender() {
    $book_list = array();
    foreach ($this->bookManager->getAllBooks() as $book) {
      $book_list[] = l($book['title'], $book['href'], $book['options']);
    }
    return array(
      '#theme' => 'item_list',
      '#items' => $book_list,
    );
  }
}

This would be declared as a controller in a routing file like this:
_content: \Drupal\book\Controller\BookController::bookRender
Comment: Removing container from ControllerBase that is food for thought, feels like many contrib devs will start with this class and then get stuck when they need to access non-standard services. ControllerBase was touted as lighter way to make a controller but begins to look like a dead end.
Comment: You would use ContainerInjectionInterface for any non-standard services. ControllerBase is just to get you started with the common services.


JSF f:ajax listener vs commandButton action

Question: I'm curious what is the difference between these two ways of executing ajax calls:
<h:commandButton value="Submit" action="#{bean.action}">
   <f:ajax execute="@form" render="component"/>
</h:commandButton>

and
<h:commandButton value="Submit">
   <f:ajax listener="#{bean.action}" execute="@form" render="component"/>
</h:commandButton>

It appears that people use the first way more often, but the second seems to work just fine as well...
Answer: The first way allows for navigation by returning a String outcome and the second not. The second way won't invoke anything if the client has JS disabled, while the first way gracefully degrades. Indeed, the first way is used more often.
The second way is the only way in components which doesn't have an action attribute, such as <h:selectOneMenu> and so on.


Trying to add ajax to RoR app

Question: I get an ActionView::MissingTemplate error trying to add ajax to a Twitter-like micropost controller.  Here's the full error:
ActionView::MissingTemplate (Missing template microposts/create with {:handlers=>[:rhtml, :erb, :rxml, :builder, :rjs], :locale=>[:en, :en], :formats=>[:js, :html]} in view paths "/rubyprograms/sample_app/app/views"):
app/controllers/microposts_controller.rb:9:in `create'

Here's my create method. Btw line 9 is the respond_to line:
  def create
@micropost  = current_user.microposts.build(params[:micropost])
if @micropost.save
  flash[:success] = "Micropost created!"
  respond_to do |format|
    format.html { redirect_to root_path }
    format.js
  end
else
  @feed_items = []
  render 'pages/home'
 end
end

What am I doing wrong?
UPDATE: I have my .rjs file in my views folder. Is that where it should be? Should the file have a specific name? It's currently called create.rjs
Answer: The create.rjs should be under app/views/microposts
Answer: The name of the file should be
create.js.erb

Then in your controller you must use a:
respond_to do |format|
  format.js # view create.js.erb
end

Answer: In order to use rjs in rails 3, use *

prototype-rails

* gem

Trying to add ajax to RoR app


Integral solutions of linear equation

Question: How does one find the number of integral solutions of equations like,
$2x + 5y + 4z = 20$
I know how to do this counting if the coefficient of every variable on the LHS is $1$.
But I don't know how to do this counting with arbitrary coefficients.
Comment: Do you mean *positive* integral solutions?  (Or nonnegative?) There are infinitely many integral solutions.
Comment: I don't know if this helps, but what you have there is a linear Diophantine equation in which Bézout's identity applies (http://en.wikipedia.org/wiki/B%C3%A9zout%27s_identity). It doesn't give any guidance with respect to counting though.
Answer: The linear equation $2x + 5y + 4z = 20$ has a two-parameter family of infinite solutions in integers. Note that $y$ has to be even. Further any even $y$ will give a one parameter family of infinite solutions for the equation $2x + 4z = 20 - 5y$.
Let $y = 2y_1$. Then we need to solve $2x + 4z = 20 - 10y_1 \implies x + 2z = 10 -5y_1$.
Hence, the set of all integer solutions is the two parameter family $$(10-5y_1-2z_1,2y_1,z_1)$$ where $y_1,z_1 \in \mathbb{Z}$
If you are interested in non-negative integral solutions for $(x,y,z)$, then we need $y_1 \geq 0$,$z_1 \geq 0$ and $5y_1 + 2z_1 \leq 10$.
This implies $y_1 \in \{0,1,2\}$.
If $y_1 = 0$, then $z_1 = \{0,1,2,3,4,5\}$.
If $y_1 = 1$, then $z_1 = \{0,1,2\}$.
If $y_1 = 2$, then $z_1 = \{0\}$.
Hence, the set of all non-negative solutions are
$$\{ (10,0,0),(8,0,1),(6,0,2),(4,0,3),(2,0,4),(0,0,5),(5,2,0),(3,2,1),(1,2,2),(0,4,0) \}$$
The set of all positive solutions are
$$\{(3,2,1),(1,2,2)\}$$
Answer: here is a paper on the problem i just happened to see somewhere else
Comment: What is the connection? I can't see how that helps solves my question!
Answer:  Let $x' = 2x$, $y' = 5y$ and $z' = 4z$. Then $2 \leq x' \leq 18$, $5 \leq y' \leq 15$ and $4 \leq z' \leq 16$ for $x',y',z' \in \mathbb{Z}^{+}$. So you can apply the same techniques for counting the number of integral solutions if all the coefficients on the LHS are $1$.
So the number of solutions would be the coefficient of $x^{20}$ in $$\left[(x^2)^{a_1}+(x^2)^{a_1+1}+ \cdots+ (x^a)^{a_2} \right] \cdot \left[(x^5)^{b_1}+(x^5)^{b_1+1}+ \cdots+ (x^5)^{b_2}\right] \cdot \left[(x^4)^{c_1}+(x^4)^{c_1+1}+ \cdots+ (x^4)^{c_2} \right]$$
where $a_1 \leq x \leq a_2$, $b_1 \leq y \leq b_2$ and $c_1 \leq z \leq c_2$.
Comment: So you're assuming that each is positive.  But then your bounds are quite weak relative to what is given.  E.g. $y'>4$ and $z'>3$ implies $x'<12$.  How do you know you can apply the same techniques?  I don't know what techniques the OP uses when the coefficients are 1, but note that modified unknowns aren't allowed to take on all integer values, only multiples of 2,5,4, respectively, so it isn't exactly reduced to the previous problem.
Comment: I didn't understand your answer. What is $a_1$, $a_2$, $b_1$, $b_2$, $c_1$ and $c_2$ ? Can you give some background, references and some more explanations?

Integral solutions of linear equation


Is the following multivariable limit exist?

Question: It is part of my HW, I solved it and got that the following limit is 2,
But Wolfram says that the limit does not exists \ path dependent.
After few hours of trying to find a path to dismiss the limit I came up with nothing..
Would appreciate any help (sorry in advance for not writing it nicely xD )
$\lim_ {(x,y) \rightarrow(0,0)} \frac{\ln(1+2x^2+4y^2)}{\arctan(x^2+2y^2)}$
Comment: What paths did you use?
Comment: My answer for http://math.stackexchange.com/questions/572125/show-discontinuity-of-fracxyx2y2/572148#572148 might be helpful to some extent..
Answer: Consider writing your expression as Log[1+2z]/ArcTan[z]."z" being small, replace both numerator and denominator by the first order Taylor expansion. You then get a limit equal to 2. If you draw a 3D plot of your function fo x and y (say between - 1 and + 1), it is a very nice surface (cowboy hat ?) showing a maximum value at [0,0].


How do I transfer data from a chip over Bluetooth?

Question: I am trying to develop an android application that will use Bluetooth capabilities to transfer data from a chip to an Android phone. I have not changed the code from the tutorial on the developer's website at all.
I am getting the following error:
_context cannot be resolved as a variable

Here is my code:
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    LocalBluetoothDevice localBT = LocalBluetoothDevice.initLocalDevice(_context);
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBluetoothAdapter == null) {
        // Device does not support Bluetooth
    }
    if (!mBluetoothAdapter.isEnabled()) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    }
}

Answer: Use
LocalBluetoothDevice localBT = LocalBluetoothDevice.initLocalDevice(this);

or
Context context = this;
LocalBluetoothDevice localBT = LocalBluetoothDevice.initLocalDevice(context);

Comment: which is the main activity of your project? you need to do Context context = YourMainActivity.this, and then use it
Comment: When i tried this it came up with the error that initLocalDevice is undefined for the type LocalBluetoothDevice


PHP creating new session with each reload

Question: For my website, session management mostly works ok. Sessions are created, saved and used later without problems.
But when the code is using session_start(), it always creates new, totally empty session. Code in question below.
header('Content-Type: text/html; charset=UTF-8');

$main_domain = $_SERVER["HTTP_HOST"];
$expld = explode('.', $main_domain);

if(count($expld) > 2) {
   $tld = array_pop($expld);
   $domain = array_pop($expld);
   $main_domain = $domain . "." . $tld;
}

session_set_cookie_params (0, '/', $main_domain);
session_name('sid');
session_start();
echo session_id();
exit;

When this script is executed, in every reload new session is created.
smar@ran ~> ls /tmp/sess_* | wc -l
10
smar@ran ~> ls /tmp/sess_* | wc -l
11
..
smar@ran ~> ls /tmp/sess_* | wc -l
17

But only the one of those sessions has any data inside it, and is used by application.
Output in browser is always same: 87412d5882jr85gh5mkasmngg7, which is id in browser's cookie and session id in /tmp that has data populated to it.
What could be cause of this behaviour? Those empty files aren't exactly huge problem, but they do make /tmp (or session dir) quite populated for no reason.
EDIT 1:
Looks like this is server related problem, since it works for some people. My configuration is Gentoo Linux (32 bit) with Apache and PHP 5.3.6.
If I force it to create new session (like removing my own cookie), it creates two session files instead of one. If it reuses old one, it creates "only" one.
EDIT 2:
Session configuration, as requested (all config rows with session.):
session.save_handler = files
session.save_path = "/tmp"
session.use_cookies = 1
session.use_only_cookies = 1
session.name = PHPSESSID
session.auto_start = 0
session.cookie_lifetime = 0
session.cookie_path = /
session.cookie_domain =
session.cookie_httponly =
session.serialize_handler = php
session.gc_probability = 1
session.gc_divisor = 1000
session.gc_maxlifetime = 1440
session.bug_compat_42 = On
session.bug_compat_warn = On
session.referer_check =
session.entropy_length = 0
session.entropy_file =
session.cache_limiter = nocache
session.cache_expire = 180
session.use_trans_sid = 0
session.hash_function = 0
session.hash_bits_per_character = 5

EDIT 3:
Even more strangely, I tried to use sessions from CLI. There, where no session cookies are set, it always created one new session. When setting fixed session value with session_id() stopped new session creation altogether and used old session instead.
This behaviour is identical with Apache, so I'm starting to suspect this is bug in PHP. No new sessions created if name specially set with session_id(), and session correctly used.
Even more absurdly, when I took phpsessid from $_COOKIE["PHPSESSID"] and set that to session_id(), it started to create new (useless empty ones) sessions again.
EDIT 4:
Since I didn't write it enough clearly: simply having
session_start()

as single argument causes this problem to happen, it is not specific to my code.
Comment: @Subdigger: yup, no avail. Even if it is the place it is, it doesn't create session before the session stuff, so I suspect this is server configuration related things. *updates the question*
Comment: what about session time? and try to comment `session_set_cookie_params (0, '/', $main_domain);` may be other place witch to put session named 'sid'
Comment: And what happens whether you put your session_start before sending the headers... ?
Comment: I'm running PHP 5.3.3-7+squeeze1 with Suhosin-Patch (cli) (built: Mar 18 2011 20:10:12), similar problem
Comment: Ain't that a security breach to allow users reading from `/tmp` ? It's shared and the session ID is readable...
Comment: @Dor: /tmp is default location where PHP saves sessions. I'd guess about 99% of PHP installations saves sessions there. That much for common security. Myself, I don't run my code in shared host, so the location is as safe as anything *PHP* can read. That's the security hole to the server most likely anyway.
Comment: The fact that 99% of the installations do that, doesn't make it correct... Once a man thought the world is round while the rest of the world thought it's flat. Update the question with session configuration options.
Comment: @Dor I still have to hear a reason for it to be changed. *updates*
Comment: @Smar: Maybe a configuration change isn't *necessary*. That's what we're trying to find out...
Comment: @Dor: sorry if I sounded rude, but I am concerned of security, so if there is valid reason for not having sessions in /tmp but in some other reason (for a server no-one but admin can be legally logged in), I'd like to hear it. But maybe that would actually be content of another question...
Comment: Is your site running on a port ? What you have for `$main_domain` won't run as expected if your domain contains a port.
Comment: @tftd: Nope, it is standard port. Please also note that simply calling session_start() causes this problem.
Comment: Can you please try setting `$main_domain` to your domain `$main_domain = '.example.com';` ? I've changed that and your code works fine here. ( http://pastebin.com/iCEV2sWm )
Comment: Are you running the scripts on a dedicated/vps server or you're using a shared hosting ? Also are you sure there isn't any additional php.ini files that overwrite the session settings ?
Comment: There isn't any scripts that could  affect the php... No crons, and I do my scripts with something completely different language than PHP. Nor there should be any PHP overrides, I tested without xdebug already, so it isn't its fault...
Comment: Could you please add a php script with ``. Open it from a browser and search for `Configuration File (php.ini) Path`, `Loaded Configuration File`, `Scan this dir for additional .ini files`, `Additional .ini files parsed`. See if you have additional .ini files loaded. My theories are: you have a php.ini file you don't know of; you have an php addon that's causing this;you're php package is bugged somehow - try compiling or installing a new package ( uninstall the previous one before that ).
Comment: @tftd: I have Gentoo, so basically everything is compiled already. Maybe I could try with minimal useflags or such to see if it happens without any special module... I'll test those ini files tomorrow.
Comment: @tftd: The default php.ini (/etc/php/apach2-php5.3/php.ini) is used, and there is no other ini files (except xdebug.ini which I tested without already) There is mention about .user.ini file for user defined ini things, but I think this is default of PHP and nothing Apache sets it itself (I don't know where to search it from, for start....)
Comment: Can you post your `uname -a` and PHP and Apache versions?
Answer: Cookies are only returned to the vhost / path where they were set from.
Since your path is '/', that implies that the pages are not being requested via $domain . "." . $tld;
e.g. user requests page via www.example.com
cookie is set for example.com
user access subsequent page from www.example.com - the cookie is not in scope.
From RFC 2965

x.y.com domain-matches .Y.com but not Y.com.

Actually, if you read on, the spec does say that the user agent should prefix the host with a dot if none is supplied however you getting into the realm where browser behavuiour varies.
If you simply return the cookie with a vhost matching the request it will work as expected.
Comment: You are correct about me missing dot at start of the cookie; browsers seems not to require it though. Whole point of this exploding (visible in the example for clarify) is to have cookie set in top level domain so they are also visible in sub level domain. .foo.tld would do this, and it works; sessions works, it just creates those empty files for each reload.
Comment: This is a very useful bit of information that clarified this issue in my situation and solved the problem of session id's being regenerated on reload. As a note, i could not get it to work by prefixing the host with a . as it seems in most modern browsers that this is interpreted as an invalid url? Thanks symcbean!
Answer: Use session_start() as first session command, before all other session_*() methods!
Comment: This only disables those cookie settings, and doesn't solve problem. Already tested, as seen in comments of the question. (I tested again just to be sure)
Comment: It's not a problem to set the session later in your code but you have to be 1000% sure that you send headers before your session_*() commands and you don't get any error_reporting lines. If you don't have anything like that you can set session_*() wherever you want or need :)
Comment: simple session_start() as only row in the application causes the problem, so I doubt it's anything like that.
Answer: I think powtac is right in a way, but session_start(); should be your first operation you do, even before the header('Content-Type: text/html; charset=UTF-8');
Answer: This is not exactly about the original cause, but the resolution is exactly same: new session ids gets defined with each reload.
In this case, fault was Varnish, which was set to put every request to pass mode (return (pass)) instead of caching everything. As consequence, every request made it to the backend, where session_start() was called every time.
But when the response was sent through Varnish to the client, cookies were removed from the response. This is due that backend sets cookies (session id, along with others) even when we want to have the site be cached. Anyway, cookies get removed, client does another request and does not pass any cookies (it never received any!) and there PHP goes again calling session_start() without any session id present...
This is more of fault in recognization of error in this case, which appeared as multitude of unnecessary sessions created. Those would've not been created in first place if caching was enabled in first place.
There is also another way to manage to create these sessions: have browser not to accept cookies at all. Stupid reason, I know, but it does happen...
For the original problem, I haven't stumbled it since moving from original development machine away.
Answer: I'd hate to be the stick in the mud, but have you checked that /tmp is both readable and writeable by PHP (in most cases, this means the www-data user)? If not, move the session save location to a location that you can write to.
Comment: Yes, that was not the problem. Session were created without problems, by php, there.
Comment: Okay, try `phpinfo()` and see if anything overwrites the session cookie domain, etc. or sets secure=1. (I'm assuming the session config above is from php.ini)
Comment: FWIW, this problem was ages ago and nowadays has disappeared, when switching machine to another, so I can't test this problem anymore. I've never done changes to those flags, and the config I had was Gentoo's default PHP config at the time, so I doubt that was it either.


c# - how to access a list inside a generic object

Question: I have a generic object containing a list with objects, which I like to access. By using
object sourceValue = new List<tab> {new tab()};
PropertyInfo[] sourcePropertyInfo = sourceValue.GetType().GetProperties();
//First field of PropertyInfo is the list, second is a Raw instance
object result = sourcePropertyInfo[0].GetValue(sourceValue, null);

Where the tab object looks like this:
public partial class tab
{
    public long TabId { get; set; }
    public string Title { get; set; }
}

Here I would like to access the list throught the result variable but it results in result = 0, which is an integer. Most likley it takes the count property from the list. How can I access the values in the objects in the list (of type tab)?

Note, I can not access or change the type of the object sourceValue.
Comment: I don't understand why you are using `reflection` here, you don't need to. Just cast `sourceValue` into `List` and it should works.
Comment: This following link may helpful to you http://stackoverflow.com/questions/10710156/using-reflection-to-get-values-from-properties-from-a-list-of-a-class
Comment: The first field of your `PropertyInfo`-array is neither the list itself nor any instance within it, is is the first property of the type `List`, which is probably the `Count`-property. I suppose you´re asking a completely different question actually, this seems like an XY-problem, where you´re thinking this is the solution to your actual problem, have a problem on this solution where you should solve your *actual* one instead.
Answer: You are getting properties of list type, not the type of elements.
foreach (object element in (sourceValue as IEnumerable ?? Enumerable.Empty<object>()))
{
   var type = element.GetType();
   var props = type.GetProperties();
   object result = props.First().GetValue(element, null);
}

Note: this can be optimized :)
Comment: Awesome this worked for me... thanks for saving my time :)


EXCEL: IF statement with AND and NOT with SUMIFS

Question: Please can I have help: I have an IF statement in Excel.  In the first Statement I want it to be linked to NET transactions and ALL - $C$6="NET",$C$5="ALL" - this works fine.  I next want a statement to say NET transactions but NOT all.
How do I add a rule for the NOT part.  The first two IF statements work, the 3rd IF statement is causing errors.
    =IF((AND($C$6="NET",$C$5="ALL")),SUMIFS(DATA!$I:$I,DATA!$A:$A,'Transactions'!$D$8,DATA!$B:$B,'Transactions'!D$9,DATA!$C:$C,'Transactions'!$B11,DATA!$D:$D,'Transactions'!$C11),
IF((AND($C$6="GROSS",$C$5="ALL")),SUMIFS(DATA!$J:$J,DATA!$A:$A,'Transactions'!$D$8,DATA!$B:$B,'Transactions'!D$9,DATA!$C:$C,'Transactions'!$B11,DATA!$D:$D,'Transactions'!$C11)),
IF((AND($C$6="GROSS",NOT($C$5="ALL"))),SUMIFS(DATA!$J:$J,DATA!$A:$A,'Transactions'!$D$8,DATA!$B:$B,'Transactions'!D$9,DATA!$C:$C,'Transactions'!$B11,DATA!$D:$D,'Transactions'!$C11)))

Comment: Am I seeing this right that the second and the third `SumIfs()` parameter lists are equal? If you have "if this, do something and in another case, do that same something", you might better say "if this or in another case, do something". That's easier to read.
Answer: You are misisng a T and you want the ) for the second IF to be at the end:
=IF((AND($C$6="NET",$C$5="ALL")),SUMIFS(DATA!$I:$I,DATA!$A:$A,'Transactions'!$D$8,DATA!$B:$B,'Transactions'!D$9,DATA!$C:$C,'Transactions'!$B11,DATA!$D:$D,'Transactions'!$C11),
IF((AND($C$6="GROSS",$C$5="ALL")),SUMIFS(DATA!$J:$J,DATA!$A:$A,'Transactions'!$D$8,DATA!$B:$B,'Transactions'!D$9,DATA!$C:$C,'Transactions'!$B11,DATA!$D:$D,'Transactions'!$C11),
IF((AND($C$6="GROSS",NOT($C$5="ALL"))),SUMIFS(DATA!$J:$J,DATA!$A:$A,'Transactions'!$D$8,DATA!$B:$B,'Transactions'!D$9,DATA!$C:$C,'Transactions'!$B11,DATA!$D:$D,'Transactions'!$C11))))


How to calculate odds ratios and probabilities in case-control studies?

Question: I came across this study, Case-control study of stroke and the quality of hypertension control in north west England. In this study I find numerous odds ratio.
As far as I understand, all the Case are eventful (with stroke) because they recruited them from a stroke registry already; while the Control are people with similar demographics to Case but without strokes.

Questions:

How is the crude odds ratio calculated?
e.g. In the category <140, I calulated $OR = \frac{23/43}{101/287}=1.519\neq1.7$.
Is it possible to calculate probability from adjusted OR?
Can we say $Odds(\text{not hypertensive})=101/287=0.3519$.
So the $Adjusted\;Odds(<140)=1.3\times0.3519=0.4575$. And event probability $p=\frac{0.4575}{1+0.4575}=0.3139$?
Comment: I do not suppose the calculation to be different just because it is a case-control studies. But it seems to me this way so I titled this post with "in case-control studies".
Answer: You're attempting to calculate the relative risk, not the odds ratio. The crude odds ratio is:
(Exposed Cases / Exposed Controls) / (Unexposed Cases / Unexposed Controls)
In this example:
(23/43) / (78/244) = 0.5348837/0.3196721 = 1.67
For the second part of your question, I don't believe that you can, because 0.3519 isn't the conditional odds of not being hypertensive, which is what the adjusted OR is using for its calculation. Beyond that, even if you can, it would only give you the event probability in the study itself, not the population as a whole (case-control studies are deliberately non-random samples intended to approximate risk, not calculate it directly).


simple real analysis question on integration

Question: it is trivial that $\int_0^{2\pi} \cos(x)\,dx = 0$.
Intuitively, it is clear that for a strictly decreasing
positive function $f(x)$,
$$
\int_0^{2\pi} f(x) \cos(x)\,dx \ge 0
$$
but I have no glue how to prove that one. Any hints?
Cheers, Eric
edit: I checked it for power-type functions $(a+t)^{-\alpha}$ numerically.
Comment: Split the integral into two parts, from 0 to $\pi$ and from $\pi$ to $2\pi$. Then use some estimates for either of them...
Comment: You should use the fact that $|\cos(x)|\le 1$.
Comment: @Fabian: I see that the part on $[0, \pi/2]$ dominates that of $[\pi/2, \pi$, this integral is clearly positive. But on $[\pi, 2\pi]$ the integral is negative. How do you see that the sum is postitive?
Comment: @eric: I did not read your question too carefully. I thought you integrate $\int_0^{2\pi} f(x) \sin(x)$. In fact, if you replace $\cos$ by $\sin$ the statement is true.
Answer: This is not true. For $\epsilon>0$ small, consider the function whose graph consists of the straight line segments:
$\ \ \bullet\ $from $[0, 1+\epsilon]$ to $[{3\pi\over2}-\epsilon,1]$
$\ \ \bullet\ $from $[{3\pi\over2}-\epsilon,1]$ to $[{3\pi\over2},\epsilon]$
and
$\ \ \bullet\ $from $[{3\pi\over2},\epsilon]$ to $[2\pi,{\epsilon\over2}]$.
Here, $\int_0^{3\pi/2} f(x)\cos x\,dx\approx -1$ and $\int_{3\pi/2}^{2\pi}f(x)\cos x\,dx\approx 0$.

Comment: Thank you very much. Indeed, 40-x^2 wors as well. Both have one in common: non-convexity. indeed, when $f$ is additionally $C^2$ and convex, splitting in half in two integrals yields $$ \int_0^\pi [f(x)-f(x+\pi)] |\cos(x)|\,dx$$. Notice that, $f'(x)-f'(x+\pi) = \pi f''(\eta)\le 0$ whence  $g(x) = [f(x)-f(x+\pi)]$ decreases. Now split again on $[0,\pi/2]$ and estimate $g$ the positive part by the smallest value $g(1/2)$ and the negative part on $[\pi/2,\pi]$ by its largest value: $g(1/2)$. Result: $\int f(x) \cos(x)\,dx \ge 0$.
Comment: Rem. I saw that convexity point some time after I put the question, but I was not allowed to write an answer. Thank you very much for your help.
Answer: For real numbers $a>b>c>d>0$ consider the function
$$
f:[0,2\pi]\ni x
\mapsto\left\{\begin{array}{ll}
\frac{2}{3\pi}\left[a\left(\frac{3\pi}{2}-x\right)+bx\right] & \text{, }x\in\left[0,\frac{3\pi}{2}\right] \\
\frac{2}{\pi}\left[c\left(2\pi-x\right)+d\left(x-\frac{3\pi}{2}\right)\right] & \text{, }x\in\left(\frac{3\pi}{2},2\pi\right]
\end{array}\right\}
\in\mathbb{R}\text{.}
$$
By construction, $f$ is positive and stricly decreasing.
Furthermore, it holds
$$
\int_0^{\frac{3\pi}{2}} f(x) \cos(x)\,\mathrm{d} x
=-\frac{(3\pi+2) b-2 a}{3\pi}
$$
and
$$
\int_{\frac{3\pi}{2}}^{2\pi} f(x) \cos(x)\,\mathrm{d} x
=\frac{2 d+(\pi-2) c}{\pi}\text{.}
$$
Choosing $b>\frac{2 a}{3\pi+2}$ makes the value of the first integral negative.
Clearly, $c$ and $d$ can be chosen such that the value of the second integral becomes arbitrarily small.
Thus, there exists a function violating the original conjecture.
Answer: As the answers by precarious and David Mitra show, your intuited result is false.  On the other hand, for a function $f(x)$ that is strictly decreasing and positive on $[0,2\pi)$, it is certainly true that
$$\int_0^{2\pi} f(x)\sin(x)\mathrm dx > 0$$
and this can be shown by the method suggested to you by Fabian, viz.,
$$\begin{align*}
\int_0^{2\pi} f(x)\sin(x)\mathrm dx
&= \int_0^{\pi} f(x)\sin(x)\mathrm dx +  \int_{\pi}^{2\pi} f(x)\sin(x)\mathrm dx\\
&=  \int_0^{\pi} f(x)\sin(x)\mathrm dx -  \int_0^{\pi} f(x+\pi)\sin(x)\mathrm dx\\
&= \int_0^{\pi} [f(x) - f(x+\pi)]\sin(x)\mathrm dx\\
&> 0.
\end{align*}$$
Perhaps you were thinking sine but absent-mindedly wrote cosine instead?
Answer: How about integration by parts...
$$ \int_0^{2\pi} f(x) \cos x\,{\rm d}x = \left[ f(x)\sin x \right]_{x=0}^{x=2\pi}-\int_0^{2\pi} \sin x\,f'(x)\,{\rm d}x$$
$$ \left[ f(x)\sin x \right]_{x=0}^{x=2\pi} = 0$$
$$ f'(x) \leq 0 $$
So now you have to prove that
$$ -\int_0^{2\pi} \sin x\,f'(x)\,{\rm d}x \ge 0$$
or expanded as
$$ \int_0^{2\pi} \sin x\,f'(x)\,{\rm d}x = \int_0^{\pi} \sin x\,f'(x)\,{\rm d}x +\int_\pi^{2\pi} \sin x\,f'(x)\,{\rm d}x \leq 0$$
Since $\sin x$ is positive between $x=0\ldots\pi$ and negative otherwise the above can be written as
$$ \int_0^{\pi} \sin x\,f'(x)\,{\rm d}x -\int_0^{\pi} \sin x\,f'(x+\pi)\,{\rm d}x \leq 0$$
or
$$ \int_0^{\pi} \sin x\,\left(f'(x)-f'(x+\pi)\right)\,{\rm d}x \leq 0 $$
Which is true only if $f'(x)-f'(x+\pi)\leq0$ for $x=0\ldots\pi$. If $f(x)$ is decreasing with negative slope then $|f'(\pi)|\leq|f'(0)|$ and thus the above is true.
Comment: Original function is not supposed to be differentiable.
Comment: I agree that $f(\pi) \leq f(0)$ since $f(x)$ is a decreasing function, but I don't understand why $|f'(\pi)|\leq|f'(0)|$ also holds.  Could you explain this?


How to generate a multidimensional array of indexed variables in Maxima?

Question: I want to take a list of non-negative integers D=[d1,...,dm] and and generate a multidimensional array of indexed symbols A in the form of:

where 0<=i_j<=d_j. For example if D=[2,3] then A should be
[[a_[0,0],a_[0,1],a_[0,2]],
 [a_[1,0],a_[1,1],a_[1,2]]]

For this case I could nest two for loops to generate the said array, however D does not necessarily have a length of 2 and I don't know how to nest an arbitrary number of for loops!
I would appreciate if you could help me know how I can generate A from D.
P.S. What I want to finally achieve is to create a multivariate polynomial as explained here.
Comment: Does `genmatrix` help you? Try `genmatrix(a, 2, 3);`
Comment: I suppose you could use `genmatrix(lambda ([i,j], x[1]^i*x[2]^j), 2, 3, 0, 0) * genmatrix(a, 2, 3, 0, 0))` and then `list_matrix_entries(%)` and `apply("+", %)`. I don't know if that would be the best way to do it.
Comment: @Eelvex No I have not. Would you be so kind to share an example below in a post?
Comment: @Eelvex I tested this. this is amazing. Is it also possible to use for generating the X tensor as I have explained [here](https://stackoverflow.com/questions/51628270/how-to-generate-a-symbolic-multivariate-polynomial-of-a-given-dimension-in-sympy)?
Comment: @Eelvex Great. I was wondering if you would write this is a post below?
Answer: Here's one way to do it. The essential part is that I called cartesian_product to construct the list of all combinations of indices, and then arrayapply to create the subscripted expressions.
(%i11) ii:setify(makelist(i, i, 0, n)), n=2;
(%o11)                      {0, 1, 2}
(%i12) apply (cartesian_product, makelist (ii, m)), m=3;
(%o12) {[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 1, 0], [0, 1, 1],
[0, 1, 2], [0, 2, 0], [0, 2, 1], [0, 2, 2], [1, 0, 0],
[1, 0, 1], [1, 0, 2], [1, 1, 0], [1, 1, 1], [1, 1, 2],
[1, 2, 0], [1, 2, 1], [1, 2, 2], [2, 0, 0], [2, 0, 1],
[2, 0, 2], [2, 1, 0], [2, 1, 1], [2, 1, 2], [2, 2, 0],
[2, 2, 1], [2, 2, 2]}
(%i13) map (lambda ([l], arrayapply (_a, l)), %);
(%o13) {_a       , _a       , _a       , _a       , _a       ,
          0, 0, 0    0, 0, 1    0, 0, 2    0, 1, 0    0, 1, 1
_a       , _a       , _a       , _a       , _a       ,
  0, 1, 2    0, 2, 0    0, 2, 1    0, 2, 2    1, 0, 0
_a       , _a       , _a       , _a       , _a       ,
  1, 0, 1    1, 0, 2    1, 1, 0    1, 1, 1    1, 1, 2
_a       , _a       , _a       , _a       , _a       ,
  1, 2, 0    1, 2, 1    1, 2, 2    2, 0, 0    2, 0, 1
_a       , _a       , _a       , _a       , _a       ,
  2, 0, 2    2, 1, 0    2, 1, 1    2, 1, 2    2, 2, 0
_a       , _a       }
  2, 2, 1    2, 2, 2
(%i14) grind (%);

{_a[0,0,0],_a[0,0,1],_a[0,0,2],_a[0,1,0],_a[0,1,1],_a[0,1,2],
 _a[0,2,0],_a[0,2,1],_a[0,2,2],_a[1,0,0],_a[1,0,1],_a[1,0,2],
 _a[1,1,0],_a[1,1,1],_a[1,1,2],_a[1,2,0],_a[1,2,1],_a[1,2,2],
 _a[2,0,0],_a[2,0,1],_a[2,0,2],_a[2,1,0],_a[2,1,1],_a[2,1,2],
 _a[2,2,0],_a[2,2,1],_a[2,2,2]}$
(%o14)                        done

This is just working at the top-level interactive prompt; if you need to construct a function, I think you'll see how to do it.
EDIT: Here's a way to create the polynomial.
(%i16) S : {[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 1, 0], [0, 1, 1],
[0, 1, 2], [0, 2, 0], [0, 2, 1], [0, 2, 2], [1, 0, 0],
[1, 0, 1], [1, 0, 2], [1, 1, 0], [1, 1, 1], [1, 1, 2],
[1, 2, 0], [1, 2, 1], [1, 2, 2], [2, 0, 0], [2, 0, 1],
[2, 0, 2], [2, 1, 0], [2, 1, 1], [2, 1, 2], [2, 2, 0],
[2, 2, 1], [2, 2, 2]} $

(%i17) L : listify (S) $

(%i18) A : map (lambda ([l], arrayapply (_a, l)), L);
(%o18) [_a       , _a       , _a       , _a       , _a       ,
          0, 0, 0    0, 0, 1    0, 0, 2    0, 1, 0    0, 1, 1
_a       , _a       , _a       , _a       , _a       ,
  0, 1, 2    0, 2, 0    0, 2, 1    0, 2, 2    1, 0, 0
_a       , _a       , _a       , _a       , _a       ,
  1, 0, 1    1, 0, 2    1, 1, 0    1, 1, 1    1, 1, 2
_a       , _a       , _a       , _a       , _a       ,
  1, 2, 0    1, 2, 1    1, 2, 2    2, 0, 0    2, 0, 1
_a       , _a       , _a       , _a       , _a       ,
  2, 0, 2    2, 1, 0    2, 1, 1    2, 1, 2    2, 2, 0
_a       , _a       ]
  2, 2, 1    2, 2, 2
(%i19) U : map (lambda ([l], product (u[i]^l[i], i, 1, length(l))), L);
                2                 2   2   2      2  2
(%o19) [1, u , u , u , u  u , u  u , u , u  u , u  u , u ,
            3   3   2   2  3   2  3   2   2  3   2  3   1
           2                          2      2      2
u  u , u  u , u  u , u  u  u , u  u  u , u  u , u  u  u ,
 1  3   1  3   1  2   1  2  3   1  2  3   1  2   1  2  3
    2  2   2   2      2  2   2      2         2     2   2  2
u  u  u , u , u  u , u  u , u  u , u  u  u , u  u  u , u  u ,
 1  2  3   1   1  3   1  3   1  2   1  2  3   1  2  3   1  2
 2  2      2  2  2
u  u  u , u  u  u ]
 1  2  3   1  2  3
(%i20) A.U;
        2  2            2    2               2    2            2
(%o20) u  u  _a        u  + u  u  _a        u  + u  _a        u
        1  2   2, 2, 2  3    1  2   2, 1, 2  3    1   2, 0, 2  3
                 2  2              2  2                    2
 + u  _a        u  u  + _a        u  u  + u  _a        u  u
    1   1, 2, 2  2  3     0, 2, 2  2  3    1   1, 1, 2  2  3
                 2                 2              2
 + _a        u  u  + u  _a        u  + _a        u
     0, 1, 2  2  3    1   1, 0, 2  3     0, 0, 2  3
    2  2                 2                    2
 + u  u  _a        u  + u  u  _a        u  + u  _a        u
    1  2   2, 2, 1  3    1  2   2, 1, 1  3    1   2, 0, 1  3
                 2                 2
 + u  _a        u  u  + _a        u  u  + u  _a        u  u
    1   1, 2, 1  2  3     0, 2, 1  2  3    1   1, 1, 1  2  3
 + _a        u  u  + u  _a        u  + _a        u
     0, 1, 1  2  3    1   1, 0, 1  3     0, 0, 1  3
    2  2              2                 2
 + u  u  _a        + u  u  _a        + u  _a
    1  2   2, 2, 0    1  2   2, 1, 0    1   2, 0, 0
                 2              2
 + u  _a        u  + _a        u  + u  _a        u
    1   1, 2, 0  2     0, 2, 0  2    1   1, 1, 0  2
 + _a        u  + u  _a        + _a
     0, 1, 0  2    1   1, 0, 0     0, 0, 0

Note that the ordering of terms within each product doesn't conform to what humans would consider the usual convention, e.g. [1]^2*u[2]^2*_a[2,2,2]*u[3]^2 is the first term. Maxima is ordering the terms according to the subscripts, therefore _a[2,2,2] comes after u[1] and before u[3]. In some contexts this coincides with what humans expect, but here it doesn't; in any event, Maxima is consistent in hope of making programmatic manipulation work better.
(%i21) grind (%);

u[1]^2*u[2]^2*_a[2,2,2]*u[3]^2+u[1]^2*u[2]*_a[2,1,2]*u[3]^2
                              +u[1]^2*_a[2,0,2]*u[3]^2
                              +u[1]*_a[1,2,2]*u[2]^2*u[3]^2
                              +_a[0,2,2]*u[2]^2*u[3]^2
                              +u[1]*_a[1,1,2]*u[2]*u[3]^2
                              +_a[0,1,2]*u[2]*u[3]^2
                              +u[1]*_a[1,0,2]*u[3]^2
                              +_a[0,0,2]*u[3]^2
                              +u[1]^2*u[2]^2*_a[2,2,1]*u[3]
                              +u[1]^2*u[2]*_a[2,1,1]*u[3]
                              +u[1]^2*_a[2,0,1]*u[3]
                              +u[1]*_a[1,2,1]*u[2]^2*u[3]
                              +_a[0,2,1]*u[2]^2*u[3]
                              +u[1]*_a[1,1,1]*u[2]*u[3]
                              +_a[0,1,1]*u[2]*u[3]
                              +u[1]*_a[1,0,1]*u[3]
                              +_a[0,0,1]*u[3]
                              +u[1]^2*u[2]^2*_a[2,2,0]
                              +u[1]^2*u[2]*_a[2,1,0]
                              +u[1]^2*_a[2,0,0]
                              +u[1]*_a[1,2,0]*u[2]^2
                              +_a[0,2,0]*u[2]^2
                              +u[1]*_a[1,1,0]*u[2]
                              +_a[0,1,0]*u[2]+u[1]*_a[1,0,0]
                              +_a[0,0,0]$
(%o21)                        done

Comment: @Foad I've edited my answer to include a way to create the polynomial. Let me know if I've misunderstood the goal.
Comment: Thanks a lot. this is very close to what I want, except it is not a multidimensional array/list. What I want to finally achieve is to create a multivariate polynomial as explained [here](https://stackoverflow.com/questions/51628270/how-to-generate-a-symbolic-multivariate-polynomial-of-a-given-dimension-in-sympy). and for that I think I need a multidimensional list to perform the  Frobenius inner product later.
Comment: you are awesome. I'm gonna first try the code, and then edit my post to fit with the answer you gave me. I was also wondering if you could be so kind to take a look at my follow up question [here](https://cs.stackexchange.com/questions/95886/algorithm-for-using-power-series-to-numerically-solve-a-partial-differential-equ)?


dictionary comprehension code to count the occurances of a word in a string

Question: I am learning about list and dict comprehensions and for most of the simple cases I am OK.
I have the following code that counts the occurrences of a word in a string. I am looking to make it into a comprehension if possible..
Can it be done?
st_dict={}
for word in words:
   if word in st_dict:
      st_dict[word] +=1
   else:
    st_dict[word] =1

Answer: use built in library
from collections import Counter
counts = Counter(word.split())


Monty Hall: What is the "unconditional probability of success" and "conditional probability of success"?

Question: Can someone explain the highlighted paragraph from Blitzstein, Introduction to Probability (2019 2 edn), p 69? I'm not understanding the subtlety the author is trying to get at. What is the "unconditional probability of success"? How is it not conditional because we're conditioning on what door the car is behind to solve the law of total probability equation. What is the "conditional probability of success"? Are "unconditional probability of success" and "conditional probability of success" the same thing?

For the normal Monty Hall problem, it seems that the "unconditional probability of success" and "conditional probability of success" are the same; they output the same number (2/3). But they're different in op. cit. Exercise 40, p 91.

Consider the Monty Hall problem, except that Monty enjoys opening Door
2 more than he enjoys opening Door 3, and if he has a choice between
opening these two doors, he opens Door 2 with probability p, where
$\frac{1}{2} \leq p \leq 1$.
(a) Find the unconditional probability that the strategy of always switching succeeds (unconditional in the sense that we do not condition on which of Doors 2,3 Monty opens).
(b) Find the probability that the strategy of always switching succeeds, given that Monty opens Door 2.
(c) Find the probability that the strategy of always switching succeeds, given that Monty opens Door 3.

The answer is 2/3 for (a) because $0 \cdot 1/3 + 1 \cdot 1/3 + 1 \cdot 1/3 = 2/3$ by LOTP. Why this answer is the same as the normal Monty Hall problem, where Monty enjoys all three doors equally?
The answer for (b) is $\frac{1}{p+1}$ and for (c) it's $\frac{1}{2-p}$.
Comment: Not sure I'd use those terms, but for the "unconditional" case the writer is just  considering the strategy  "Just switch doors no matter what he says.".  If you had originally taken $\#1$ this has the effect of just giving you *both* doors $\#2$ and $\#3$ so of course it has a $\frac 23$ chance of working.  Note that this strategy is entirely independent of whatever rule Monty uses to choose which of two worthless doors to open.
Comment: @lulu What do you mean here? "If you had originally taken #1 this has the effect of just giving you both doors #2 and #3 so of course it has a 2/3 chance of working."
Comment: I mean exactly what I say (well, presuming that the worthless door Monty opens contains nothing at all).  By switching I get the contents of the other two doors.
Comment: To stress:  I would not really consider these to be two different strategies, since the resultant action is the same in all cases.  To be sure, if Monty plays favorites in his door selection, then your reasoning might be slightly different, though again this is a pretty hollow distinction.  (N.B.  there are variants of the problem in which this distinction matters, but you aren't dealing with those here).
Comment: To illustrate the point:  say Monty will always open $\#2$ if that's an option for him.  Then, if I have chosen $\#1$ and he opens $\#3$ I can be certain that the prize is behind $\#2$.  However if he opens $\#2$ then I have a $\frac 12$ chance of winning whether I switch or not.  Note, of course, that my net probability of success if I blindly switch is still $\frac 23$.
Comment: @lulu I think I get it? The first approach basically says, "We're going to examine the cases in which the car is behind door 1,2, and 3, and switch in all three cases. The probability that we will succeed is 2/3." This is "unconditional" in the sense we examine all three cases. The second approach is saying: what is the probability we will succeed if Monty opens door 2? what is the probability that we will succeed if Monty opens door 3? This is "conditional" in the sense we examine a specific case (whether Monty opens door 2 or door 3). Is that correct? I will read your comments now.
Comment: Sure, that's fine.
Comment: @lulu Thank you very much! The example really helped.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/119917/discussion-between-beginner-and-lulu).
Answer: The difference between unconditional and conditional is that for unconditional, we are conditioning on C, and for conditional, we are conditioning on M. Simply put, the thing being conditioned on is different.
You start by picking door 1, it seems as the problem describes.
<code> |
 |
 v
 _   _   _
| | | | | |
| | | | | |
 -   -   -
 1   2   3
</code>

The unconditional property only depends on C, the event that the car is behind door C, so we have the following, where "car" really means "get car by switching." You'll notice that this has no information about M. That is why it is the same no matter the probability that the host chooses door 2. It's not in the formula. It only depends on where the car was initially placed. Maybe this is not a satisfactory explanation, but let's move on.

$$P(car)=P(car|C_1)P(C_1)+P(car|C_2)P(C_2)+P(car|C_3)P(C_3)\\
=0*\frac 1 3+1*\frac 1 3+1*\frac 1 3=\frac 2 3$$

You want to find the probability that switching succeeds, given that Monty opens door 2. Let's draw a tree. Maybe take a minute or so to figure out why it is.

<code>                                      prob
                      / car     0     0
          / M2  p
                      \ no_car  1     p/3
/ C1  1/3
                      / car     0     0
          \ M3  1-p
                      \ no_car  1     (1-p)/3

                      / car     1     1/3
- C2  1/3 - M3  1
                      \ no_car  0     0

                      / car     1     1/3
\ C3  1/3 - M2  1
                      \ no_car  0     0
</code>
You want $P(car|M_2)=\frac{P(car, M_2)}{P(M_2)}=\frac{P(car,M_2,C_1)+P(car,M_2,C_2)+P(car,M_2,C_3)}{P(M_2,C_1)+P(M_2,C_2)+P(M_2,C_2)}=\frac{0+0+1/3}{p/3+0+1/3}=\frac{1}{p+1}$

Similarly, you want $P(car|M_3)=\frac{P(car, M_3)}{P(M_3)}=\frac{P(car,M_3,C_1)+P(car,M_3,C_2)+P(car,M_3,C_3)}{P(M_3,C_1)+P(M_3,C_2)+P(M_3,C_2)}=\frac{0+1/3+0}{(1-p)/3+1/3+0}=\frac{1}{2-p}$

Lastly, we go back to verify that the "conditional probability" of getting the car conditioning on M is the same as the "unconditional probability" of getting a car conditioning on C, which was 2/3 as determined in part 1. We need the law of total probability $P(car)=P(car|M_2)P(M_2)+P(car|M_3)P(M_3)=P(M_2)\frac{1}{p+1}+P(M_3)\frac{1}{2-p}$.

Convince yourself with the following diagram that the $P(M_2)=\frac 1 3+\frac p 3$. That is, again $P(M_2)=P(M_2,C_1)+P(M_2,C_2)+P(M_2,C_3)=P(M_2|C_1)P(C_1)+P(M_2|C_2)P(C_2)+P(M_2|C_3)P(C_3)=1*\frac 1 3+0*\frac 1 3+p*\frac 1 3=\frac 1 3+\frac 1 3 p$. Alternatively, you could have used the huge tree above. Since opening door 3 is the complement to opening door 2, $P(M_3)=1-P(M_2)=1-\left(\frac 1 3+\frac 1 3p\right)$. Now you can finally find the "conditional" probability that you win a car by switching:
$$\left(\frac 1 3+\frac 1 3p\right)\frac{1}{p+1}+\left(1-\left(\frac 1 3+\frac 1 3p\right)\right)\frac{1}{2-p}=\frac 2 3$$
<code>  _
|[ ]| [ ] [c]
|[ ]| [c] [ ]
|[c]| [ ] [ ]
  -
</code>
It is the same as the "unconditional" probability conditioning on C instead of M.
Comment: I would say what makes $P(car)$ an unconditional probability is it is **not** conditioned on $C.$ It's true you can compute it by a sum involving conditional probabilities, but this does not make it a conditional probability, any more than you can say that $8$ is an odd number because it is the sum of $3$ and $5$, which are odd numbers.
Comment: 1. Can you please rename "Car", which befuddled me, to S (for switching and winning) or W (winning by switching)? Because you wrote, and intended to write that, *""car" really means "get car by switching"*. 2. Can you please explain your top and bottom pictures typed in backtick `, and backgrounded in gray? What are you trying to picture?
Comment: 3. Your answer contains typos. See [Meta](https://math.meta.stackexchange.com/q/34431), or my rejected [Suggested Edit](https://math.stackexchange.com/review/suggested-edits/1725174).
Comment: Feel free to edit your answer, rather than comment. Comments can get deleted.


How to echo block title render in specific  D7

Question: After creating a dynamic block I need to print block title in specific div or customize it to add css class .
Please check image for more details
Answer: To add classes to block you can use below module:
https://www.drupal.org/project/block_class
To add class to block title there is similar question before:
Adding classes to block title
Thanks!
Comment: thanks bro, solved by

@block.tpl.php

>

 >

because after adding css from block configuration interface mini tags distorted in this case thanks U
Comment: @MohamedHafez  not a problem :)


About Perimeter - Circumference of Quarter Circle

Question:

ASB is  quarter circle. PQRS is a rectangle with side PQ=8 and PS=6 . What is length of ARC AQB ? Ans $5\pi$

Here is how I am solving it:
Radius of Quarter circle = diagonal of rectangle = $\sqrt {100} = 10$
For a Full Circle : $Length_{Arc}=\frac{Arc_{Angle}}{360} \times Circumference$--->A
Now Circumference of complete circle will be : $2\pi10 = 20\pi$
Circumference of $\frac{1}{4}$ of circle = $5\pi + 10 + 10 =5\pi + 20$
Now For Quarter Circle $Length_{Arc}= \frac{90}{90} \times (5\pi + 20)$
EDIT:
I realize that I could have gotten the answer by simply not adding the 20 in the circumference. But according to this link. Circumference is the same as parameter and we should add the radius twice when determining the perimeter/circumference of quarter circle (refer to example 2 on bottom of the page) , since the formula above (Equ. A) requires the circumference I wanted to know why we shouldn't be adding the 20 since after all isnt it a part of the circumference of circle portion ?
For convenience I have posted an image of the example from that site
Comment: Circumference is the perimeter of a full circle.  If you don't have a full circle, then you don't have a circumference.
Comment: Circumference and perimeter are only the same for a full circle.  The question is asking for arc length AQB, which is only the curved part.
Comment: Does that mean in case the circle is not full they will have different definitions ?
Answer: Once you get circumference $ = 20\pi$, just divide by $4$ to get the quarter circumference.
Answer is $20\pi / 4 = 5\pi$. simple.
However, the title of the question seems to be misleading. The question in the body seems to have nothing to do with the area and the circumference (perimeter?) of the quadrant.
Comment: But I thought that when we need to find the circumference we need to make up for the horizontal and vertical bars?
Comment: @Rajeshwar But the question only seems to be asking about the length of the **arc** $AQB$.
Comment: YES I agree and that is for the parameter of the quarter-circle thanks..
Comment: Also I was initially doing $\frac{90}{360}$ which is suppose to be $\frac{90}{90}$ for a quarter circle
Comment: Hi , I was having some doubts about the question so I re-edited it and re-opened the question. Could you kindly look at the changes and post your opinion.
Comment: Not sure why you unaccepted my answer. As the question stands, it is asking about the arc length $AQB$ which is $5\pi$ as I said earlier.
Answer: Note that the radius is $r=SQ=\sqrt{(SR)^2+(SP)^2}=\sqrt{8^2+6^2}=\sqrt{100}=10$ by the Pythagorean theorem.
Then, we know that the perimeter of a whole circle is $2\pi r$, so a quarter of a circle has an arc length of
$$L=\frac{1}{4} 2\pi r = \frac{\pi r}{2}$$
Plugging in the radius of the circle that we found above
$$L=\frac{\pi r}{2}=\frac{\pi \cdot 10}{2}=5\pi$$


Views throw an Ajax error in the admin page

Question: When I go to a View edit page in the admin of Drupal 7, two of them (one that's called front page and was already there, and one that's a jcarousel) throw an error:
An AJAX HTTP error occurred.
HTTP Result Code: 500
Debugging information follows.
Path: /admin/structure/views/view/frontpagecarousel/preview/page/ajax
StatusText: error
ResponseText:

"ResponseText" is followed by a huge load of unformatted text (not even a newline character). But I believe that it must have something to do with the "Path", which I don't believe exists. I'm not certain, but I think this is interfering with jCarousel's options, as it expects something to appear in the Fields section, but the Fields section says "The selected style or row format does not utilize fields."
So, what's going wrong, and how can I fix it?
Answer: I've had this problem many times before. For me, it was because I had the theme developer module enabled. I think the firebug module has the same effect. Basically, they are both adding extra markup to the response text and it isn't able to parse it then.
Comment: I don't have either of those, but it sounds like it could be any module that adds to the response text. Unfortunately, the problem seemed to mysteriously vanish a while back, but it had already been a while, and I can't tell what changes fixed it.


Isometric image of an open ball.

Question: Let $(X,d)$ be a compact metric space, where $f: X \rightarrow X$ is a distance preserving map, ie, $\forall x, y \in X$ we have that $d(f(x),f(y)) = d(x,y)$.
a) Show that f is injective.
b) Show that $\forall x \in X$ and every open ball of radius $\epsilon$ centered at $x$, $B_{\epsilon}(x)$, one of the balls in the sequence:
$f(B_{\epsilon}(x)),f(f(B_{\epsilon}(x))), ...$ has non-empty intersection with $B_{\epsilon}(x)$
c) Use part b) or another reasoning to show that f is surjective.
I proved part a), but am stuck on part b). I'm thinking of assuming that all the images (composed any amount of times) of the ball all have empty intersection with the original ball, but am having trouble trying to concretize what the image of the ball should be or look like.
Answer: HINT: Let $f^{(0)}$ be the identity function on $X$, and for $n\in\Bbb N$ let $f^{(n+1)}=f\circ f^{(n)}$. Note that $f^{(1)}=f$. For $n\in\Bbb N$ let $B_n=f^{(n)}[B_\epsilon(x)]$; $\langle B_n:n\in\Bbb N\rangle$ is your sequence of balls in (b).
Suppose that there are $m,n\in\Bbb N$ such that $m<n$ and $B_m\cap B_n\ne\varnothing$, and let $y\in B_m\cap B_n$.

Show that there is a $z\in B_0$ such that $f^{(m)}(z)=y$.
Show further that $z\in B_{n-m}$.
Conclude that $B_0\cap B_{n-m}\ne\varnothing$.

This shows that if $B_0\cap B_n=\varnothing$ for each $n\ge 1$, then the family $\{B_n:n\in\Bbb N\}$ is pairwise disjoint.

Use the compactness of $X$ to show that the family $\{B_n:n\in\Bbb N\}$ cannot be pairwise disjoint.

Isometric image of an open ball.


Can confirmatory factor analysis be used to test a hypothesis about a one-factor solution

Question: I want to test the hypothesis that observed variables can be explained by one latent variable (factor), does a confirmatory factor analysis allow me to test such a hypothesis?
Example:

Data: 200 responses on 23 questions (measured on a 5-point Likert scale)
Method: confirmatory factor analysis with one factor loading on all the questions
Hypothesis: One factor is sufficient to explain the variation in the observed variables

Can I say it tests my hypothesis that a one factor is sufficient to explain the observed data? What is the null hypothesis in confirmatory factor analysis?
Comment: I don't see why people are suggesting to close as "unclear". This is a reasonable, although a novice's, question on CFA.
Comment: It seems you are mixing up exploratry and confirmatory analysis. Kaiser may (perhaps) help to suggest the number of factors in exploratoty analysis. Confirmatory analysis is not the _alternative_ to the exploratory, they have different destinations.
Comment: @ttnphns I understand, but since at my department not many people use CFA (they usually use EFA because it is provided with SPSS) I have to explain why it is inappropriate to give the number of factors based on the Kiser criterion as a test of the number of factors hypothesis, and if CFA is appropriate instead.
Comment: @StasK: I did not vote here, but it seems to have been less clear before the edit. Now it's good, +1 both to the Q and to your A.
Answer: Testing the model structure is exactly what confirmatory factor analysis does. The null hypothesis is "The hypothesized structure fits the data well" vs. a non-committal alternative "The hypothesized structure does not fit the data well enough", which includes alternatives like "more factors are needed" or "some unique errors for items are correlated", but you need to construct these specific alternatives to look into these specific tests.
Personally, I think EFA is only applicable when you know NOTHING about your object of the study. If you constructed your instrument with an idea in mind of measuring some psychological construct, you implicitly have that single factor model built into it. If you know that you have several subscales, then you should fit a CFA that has that many factors, or may be a hierarchical CFA with one higher level factor. But running an EFA to say "Gee, turns out we have three factors in this scale... or wait, let me try a different rotation" -- that does not seem very scientific to me.
Comment: So I understand that the Chi-squared test does not test the hypothesis that the hypothesised structure fits the data well, but rather, if it fits the data poorly?


Android Camera2 issue on Samsung devices

Question: I have an Android video capture app but in Samsung devices I'm getting the error below.
I have tried to remove the startPreview() from the mRecordButton.click (which is the button to stop recording actually), no success.
What can I possibly do?
The error:
Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'android.hardware.camera2.CaptureRequest$Builder android.hardware.camera2.CameraDevice.createCaptureRequest(int)' on a null object reference
       at com.jobconvo.www.newjcapp.CameraActivity.startPreview(CameraActivity.java:427)
       at com.jobconvo.www.newjcapp.CameraActivity.access$800(CameraActivity.java:53)
       at com.jobconvo.www.newjcapp.CameraActivity$5.onClick(CameraActivity.java:268)
       at android.view.View.performClick(View.java:5716)
       at android.widget.TextView.performClick(TextView.java:10926)
       at android.view.View$PerformClick.run(View.java:22596)
       at android.os.Handler.handleCallback(Handler.java:739)
       at android.os.Handler.dispatchMessage(Handler.java:95)
       at android.os.Looper.loop(Looper.java:148)
       at android.app.ActivityThread.main(ActivityThread.java:7325)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

My Camera Activity code:
public class CameraActivity extends AppCompatActivity {

private static final int STATE_PREVIEW = 0;
private static final int STATE_WAIT_LOCK = 1;
private int mCaptureState = STATE_PREVIEW;

private TextureView mTextureView;
private TextureView.SurfaceTextureListener mSurfaceTextureListener = new TextureView.SurfaceTextureListener() {
    @Override
    public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
        setupCamera(width, height);
        try {
            connectCamera();
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {

    }

    @Override
    public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
        return false;
    }

    @Override
    public void onSurfaceTextureUpdated(SurfaceTexture surface) {

    }
};

private CameraDevice mCameraDevice;
private CameraDevice.StateCallback mCameraDeviceStateCallback = new CameraDevice.StateCallback() {
    @Override
    public void onOpened(CameraDevice camera) {
        mCameraDevice = camera;
        mMediaRecorder = new MediaRecorder();
        if (mIsRecording) {
            try {
                createVideoFileName();
            } catch (IOException e) {
                e.printStackTrace();
            }
            startRecord();
            mMediaRecorder.start();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    countDownTimer.start();
                }
            });
        } else {
            startPreview();
        }
    }

    @Override
    public void onDisconnected(CameraDevice camera) {
        camera.close();
        mCameraDevice = null;
    }

    @Override
    public void onError(CameraDevice camera, int error) {
        camera.close();
        mCameraDevice = null;
    }
};

private HandlerThread mBackgroundHandlerThread;
private Handler mBackgroundHandler;
private String mCameraId;
private Size mPreviewSize;
private Size mVideoSize;

private MediaRecorder mMediaRecorder;
private int mTotalRotation;
private CameraCaptureSession mPreviewCaptureSession;
private CameraCaptureSession.CaptureCallback mPreviewCaptureCallback = new
        CameraCaptureSession.CaptureCallback() {

            private void process(CaptureResult captureResult) {
                switch (mCaptureState) {
                    case STATE_PREVIEW:
                        // Do nothing
                        break;
                    case STATE_WAIT_LOCK:
                        mCaptureState = STATE_PREVIEW;
                        Integer afState = captureResult.get(CaptureResult.CONTROL_AF_STATE);
                        if (afState == CaptureResult.CONTROL_AF_STATE_FOCUSED_LOCKED ||
                                afState == CaptureResult.CONTROL_AF_STATE_NOT_FOCUSED_LOCKED) {
                            Toast.makeText(getApplicationContext(), "AF Locked!", Toast.LENGTH_SHORT).show();
                        }
                        break;
                }
            }

            @Override
            public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
                super.onCaptureCompleted(session, request, result);

                process(result);
            }
        };

private CameraCaptureSession mRecordCaptureSession;

private CameraCaptureSession.CaptureCallback mRecordCaptureCallback = new
        CameraCaptureSession.CaptureCallback() {

            private void process(CaptureResult captureResult) {
                switch (mCaptureState) {
                    case STATE_PREVIEW:
                        // Do nothing
                        break;
                    case STATE_WAIT_LOCK:
                        mCaptureState = STATE_PREVIEW;
                        Integer afState = captureResult.get(CaptureResult.CONTROL_AF_STATE);
                        if (afState == CaptureResult.CONTROL_AF_STATE_FOCUSED_LOCKED ||
                                afState == CaptureResult.CONTROL_AF_STATE_NOT_FOCUSED_LOCKED) {
                            Toast.makeText(getApplicationContext(), "AF Locked!", Toast.LENGTH_SHORT).show();
                        }
                        break;
                }
            }

            @Override
            public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
                super.onCaptureCompleted(session, request, result);

                process(result);
            }
        };

private CaptureRequest.Builder mCaptureRequestBuilder;

private Button mRecordButton;
private boolean mIsRecording = false;
private boolean mIsTimelapse = false;

private File mVideoFolder;
private String mVideoFileName;

private MainModel mainModel;

private static SparseIntArray ORIENTATIONS = new SparseIntArray();

static {
    ORIENTATIONS.append(Surface.ROTATION_0, 0);
    ORIENTATIONS.append(Surface.ROTATION_90, 90);
    ORIENTATIONS.append(Surface.ROTATION_180, 180);
    ORIENTATIONS.append(Surface.ROTATION_270, 270);
}

private static class CompareSizeByArea implements Comparator<Size> {

    @Override
    public int compare(Size lhs, Size rhs) {
        return Long.signum((long) (lhs.getWidth() * lhs.getHeight()) -
                (long) (rhs.getWidth() * rhs.getHeight()));
    }
}

int questionId;
int questionAnswerTime;
String interviewId;
TextView showTimer;

private static String formatTime(int elapsed) {
    int ss = elapsed % 60;
    elapsed /= 60;
    int min = elapsed % 60;
    elapsed /= 60;
    int hh = elapsed % 24;
    return strzero(min) + ":" + strzero(ss);
}

private static String strzero(int n) {
    if (n < 10)
        return "0" + String.valueOf(n);
    return String.valueOf(n);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_camera);

    Fabric.with(this, new Crashlytics());

    mainModel = (MainModel) getIntent().getSerializableExtra("serialized_data");

    interviewId = mainModel.getInterviewID();
    final ScriptQuestion getQuestion = mainModel.questions.get(0);
    questionId = getQuestion.getQuestionId();
    questionAnswerTime = getQuestion.getQuestionAnswerTime();

    showTimer = (TextView) findViewById(R.id.chronometer);
    mTextureView = (TextureView) findViewById(R.id.textureView);
    mRecordButton = (Button) findViewById(R.id.videoButton);

    mRecordButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            countDownTimer.cancel();
            mIsRecording = false;
            mIsTimelapse = false;

            // Starting the preview prior to stopping recording which should hopefully
            // resolve issues being seen in Samsung devices.

            startPreview();
            mMediaRecorder.stop();
            mMediaRecorder.reset();

            Intent mediaStoreUpdateIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            mediaStoreUpdateIntent.setData(Uri.fromFile(new File(mVideoFileName)));
            sendBroadcast(mediaStoreUpdateIntent);

            goNext();
        }
    });

}

private CountDownTimer countDownTimer = new CountDownTimer(600000, 1000) {
    public void onTick(long millisUntilFinished) {
        // 600000 = 10 minutes
        int restTime = questionAnswerTime * 60 - (600 - ((int) (millisUntilFinished) / 1000));
        String tmpRest = formatTime(restTime);

        showTimer.setText(tmpRest);
        if (restTime < 1) {
            onFinish();
        }
    }

    public void onFinish() {
        mRecordButton.performClick();
    }
};

@Override
protected void onResume() {
    super.onResume();

    startBackgroundThread();

    if (mTextureView.isAvailable()) {
        setupCamera(mTextureView.getWidth(), mTextureView.getHeight());

    } else {
        mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);
    }

    mIsRecording = true;

}

@Override
protected void onPause() {
    closeCamera();

    stopBackgroundThread();

    super.onPause();
}

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    View decorView = getWindow().getDecorView();
    if (hasFocus) {
        decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_FULLSCREEN
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
    }
}

private void setupCamera(int width, int height) {
    CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
    try {
        for (String cameraId : cameraManager.getCameraIdList()) {
            CameraCharacteristics cameraCharacteristics = cameraManager.getCameraCharacteristics(cameraId);
            if (cameraCharacteristics.get(CameraCharacteristics.LENS_FACING) ==
                    CameraCharacteristics.LENS_FACING_BACK) {
                continue;
            }
            StreamConfigurationMap map = cameraCharacteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
            int deviceOrientation = getWindowManager().getDefaultDisplay().getRotation();
            mTotalRotation = sensorToDeviceRotation(cameraCharacteristics, deviceOrientation);
            boolean swapRotation = mTotalRotation == 90 || mTotalRotation == 270;
            int rotatedWidth = width;
            int rotatedHeight = height;
            if (swapRotation) {
                rotatedWidth = height;
                rotatedHeight = width;
            }
            mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class), rotatedWidth, rotatedHeight);
            mVideoSize = chooseOptimalSize(map.getOutputSizes(MediaRecorder.class), rotatedWidth, rotatedHeight);

            mCameraId = cameraId;
            return;
        }
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}

private void connectCamera() throws CameraAccessException {
    CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    cameraManager.openCamera(mCameraId, mCameraDeviceStateCallback, mBackgroundHandler);
}

private void startRecord() {

    try {
        if(mIsRecording) {
            setupMediaRecorder();
        } else if(mIsTimelapse) {
            setupTimelapse();
        }
        SurfaceTexture surfaceTexture = mTextureView.getSurfaceTexture();
        surfaceTexture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
        Surface previewSurface = new Surface(surfaceTexture);
        Surface recordSurface = mMediaRecorder.getSurface();
        mCaptureRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_RECORD);
        mCaptureRequestBuilder.addTarget(previewSurface);
        mCaptureRequestBuilder.addTarget(recordSurface);

        mCameraDevice.createCaptureSession(Arrays.asList(previewSurface, recordSurface),
                new CameraCaptureSession.StateCallback() {
                    @Override
                    public void onConfigured(CameraCaptureSession session) {
                        mRecordCaptureSession = session;
                        try {
                            mRecordCaptureSession.setRepeatingRequest(
                                    mCaptureRequestBuilder.build(), null, null
                            );
                        } catch (CameraAccessException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onConfigureFailed(CameraCaptureSession session) {
                        //Log.d(TAG, "onConfigureFailed: startRecord");
                    }
                }, null);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

private void startPreview() {

    SurfaceTexture surfaceTexture = mTextureView.getSurfaceTexture();
    assert surfaceTexture != null;
    surfaceTexture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
    Surface previewSurface = new Surface(surfaceTexture);

    try {
        mCaptureRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
        mCaptureRequestBuilder.addTarget(previewSurface);

        mCameraDevice.createCaptureSession(Arrays.asList(previewSurface),
                new CameraCaptureSession.StateCallback() {
                    @Override
                    public void onConfigured(CameraCaptureSession session) {
                        //Log.d(TAG, "onConfigured: startPreview");
                        mPreviewCaptureSession = session;
                        try {
                            mPreviewCaptureSession.setRepeatingRequest(mCaptureRequestBuilder.build(),
                                    null, mBackgroundHandler);
                        } catch (CameraAccessException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onConfigureFailed(CameraCaptureSession session) {
                        //Log.d(TAG, "onConfigureFailed: startPreview");

                    }
                }, null);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}

private void closeCamera() {
    if(mCameraDevice != null) {
        mCameraDevice.close();
        mCameraDevice = null;
    }
    if(mMediaRecorder != null) {
        mMediaRecorder.release();
        mMediaRecorder = null;
    }
}

private void startBackgroundThread() {
    mBackgroundHandlerThread = new HandlerThread("Camera2VideoImage");
    mBackgroundHandlerThread.start();
    mBackgroundHandler = new Handler(mBackgroundHandlerThread.getLooper());
}

private void stopBackgroundThread() {
    mBackgroundHandlerThread.quitSafely();
    try {
        mBackgroundHandlerThread.join();
        mBackgroundHandlerThread = null;
        mBackgroundHandler = null;
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

private static int sensorToDeviceRotation(CameraCharacteristics cameraCharacteristics, int deviceOrientation) {
    int sensorOrienatation = cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
    deviceOrientation = ORIENTATIONS.get(deviceOrientation);
    return (sensorOrienatation + deviceOrientation + 360) % 360;
}

private static Size chooseOptimalSize(Size[] choices, int width, int height) {
    List<Size> bigEnough = new ArrayList<Size>();
    for(Size option : choices) {
        if(option.getHeight() == option.getWidth() * height / width &&
                option.getWidth() >= width && option.getHeight() >= height) {
            bigEnough.add(option);
        }
    }
    if(bigEnough.size() > 0) {
        return Collections.min(bigEnough, new CompareSizeByArea());
    } else {
        return choices[0];
    }
}

private File createVideoFileName() throws IOException {

    File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), "JobConvoVideos");
    mVideoFolder = new File(mediaStorageDir, "JobConvoVideos");
    if(!mVideoFolder.exists()) {
        mVideoFolder.mkdirs();
    }

    String prepend = "android-" + interviewId + "-" + String.valueOf(questionId) + ".mp4";
    File videoFile = new File(mediaStorageDir.getPath() + File.separator + prepend);
    mVideoFileName = videoFile.getAbsolutePath();

    return videoFile;
}

public static File getOutputMediaFile(String _interviewId, int qstId, Context _context){

    String idInterview = _interviewId;
    idInterview =  "android-" + idInterview + "-" + String.valueOf(qstId) + ".mp4";

    File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), "JobConvoVideos");
    _context.getExternalFilesDir("JobConvoVideos");
    File f = new File(mediaStorageDir.getPath() + File.separator + idInterview);
    return f;
}

private void setupMediaRecorder() throws IOException {
    mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
    mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
    mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
    mMediaRecorder.setOutputFile(mVideoFileName);
    mMediaRecorder.setVideoEncodingBitRate(1000000);
    mMediaRecorder.setVideoFrameRate(30);
    mMediaRecorder.setVideoSize(mVideoSize.getWidth(), mVideoSize.getHeight());
    mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
    mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    mMediaRecorder.setOrientationHint(mTotalRotation);
    mMediaRecorder.getMaxAmplitude();
    mMediaRecorder.prepare();
}

private void setupTimelapse() throws IOException {
    mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
    mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_QVGA));
    mMediaRecorder.setOutputFile(mVideoFileName);
    mMediaRecorder.setCaptureRate(2);
    mMediaRecorder.setOrientationHint(mTotalRotation);
    mMediaRecorder.prepare();
}

private void goNext() {

    finish();

    Intent goUpload = new Intent(this, VideoUploadActivity.class);
    goUpload.putExtra("serialized_data", mainModel);
    startActivity(goUpload);

}

@Override
public void onBackPressed() {
    Toast.makeText(getApplicationContext(), R.string.getBack, Toast.LENGTH_LONG).show();
}

}
Answer: I added a try catch here in which the app has shown a great improvement. Nonetheless it still crashes sometimes. Not very often.
mRecordButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                countDownTimer.cancel();
                mIsRecording = false;
                mIsTimelapse = false;

                // Starting the preview prior to stopping recording which should hopefully
                // resolve issues being seen in Samsung devices.

                try {
                    startPreview();
                    mMediaRecorder.stop();
                    mMediaRecorder.reset();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                Intent mediaStoreUpdateIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                mediaStoreUpdateIntent.setData(Uri.fromFile(new File(mVideoFileName)));
                sendBroadcast(mediaStoreUpdateIntent);

                goNext();
            }
        });


Prove / Provide counter example - about inner product, orthogonal matrix

Question: Let $A ∈ M_n (\Bbb R)$ and let $(•, •)$ be the standard inner product on $\Bbb R^n$.

If for all $u \in \Bbb R^n$ we have $||Au||=||u||$ then $A$ is an orthogonal matrix.
If for all $\Bbb v,u \in \Bbb R^n$ such that $\Bbb v \perp u$ we have $A \Bbb v \perp Au$ then $A$ is an orthogonal matrix.

I have proved the other side for both of those statements (if $A$ is orthogonal, then...), but I'd like to know what happens from the other direction.
Thanks a lot!
Comment: 2 is not true, as $A$ can also be the zero matrix and the statement

$$\forall v, u\in\mathbb R^n: v\bot u\implies Av\bot Au$$ will still be true.
Comment: @CalculusLover Still no, for example $A = 2 I$ (where $I$ is the identity matrix).
Comment: @CalculusLover We can show, however, that if $v \perp u \implies Av \perp Au$, then $A$ is a *multiple of* an orthogonal matrix.
Comment: @5xum Nice! and what if we have $\forall u,v \in V , u \perp v \Leftrightarrow Au \perp Av$ ?
Comment: The first statement is true. Use standard basis vectors to show diagonal entries of $A^TA$ are one. And use sum of some standard basis vectors to show $A^TA$ is skew symmetric. However $A^TA$ is symmetric, so $A^TA$ is diagonal, thus identity. Second statement is wrong obviously, you must modify it as Ben wrote.
Comment: Second statement can be written as if $A$ is a multiple of orthogonal matrix then $$v \perp u \iff Av \perp Au$$. Then write $u=(u_1,...,u_n)$ and $v=(v_1,...,v_n)$. We have one equality indeed. So $A^TA$ must be $kI$ for some positive $k$.
Answer: Statement (1) relies on the following fact:
Fact: If $X\in\mathbb{R}^{n\times n}$ is symmetric, and if $u^TXu=0$ for all $u\in \mathbb{R}^n$, then $X=O$.
Proof: Write $X=QDQ^T$ where $D=\text{diag}(\lambda_1,\ldots,\lambda_n)$ and $Q$ is orthogonal. Fix any $j\in \{1,...,n\}$ and put $u:=Qe_j$. Then we have $$\lambda_j=e_j^TDe_j=e_j^TQ^TXQe_j=u^TXu=0$$ This shows $D=O$ and hence so is $X$.
Now if $\|Au\|=\|u\|$ for all $u$ then $u^T\Big(A^TA-I\Big)u=0$ for all $u$. Since $A^TA-I$ is symmetric, we must have $A^TA-I=O$ i.e. $A^TA=I$ and we're done.
Comment: Thanks a lot! :)
Answer: The defining property of an orthogonal matrix is that it preserves inner products. In $\mathbb{R}^n$, the inner product is just $(u, v) = u^Tv$, viewing $u$ and $v$ as column vectors.
Hence, $(Au, Av) = u^TA^TAv$. In the case of $u = v$, we have the situation you described in part 1.
Preserving the norm means $A$ satisfies $u^TA^TAu = u^Tu$. This equation holds for every vector $u$, including the basis vectors. Choose an orthonormal basis, $\{e_i\}_{i = 1}^n$.
Hence, $e_i^TA^TAe_i = 1$ for every basis vector.
But since we have an orthonormal basis, this equation just says that the component of $A^TAe_i$ along the $e_i$ direction is preserved, i.e. equals 1. Since this holds for all $i$, the component along every basis vector is preserved by $A^TA$.
But this is nothing but saying that $A^TA$ is the identity, i.e. $A$ is orthogonal.
This proves the direction you were asking for in part 1.
Comment: In fact, statement 1 is true. Not that $u^TA^TAu = u^Tu$ also holds for $u = e_i \pm e_j$, and that $A^TA$ is necessarily a symmetric matrix.


Proving two lengths to be equal

Question: Given this picture how do you proof that GJ=JA.
I am really stuck with this problem.
I know that you get 4 equilateral triangles, but I do not know how to proceed from here.
P.S. $AJ \parallel FG$.
Comment: Is $GF$ parallel to $JA$?
Comment: Yes they are parallel
Answer: You could do it geometrically by noting that $\angle FGA = \angle GAJ$ (alternate angles are equal).
Then note that $IG = BG$ and that $AB = AI$.
$\therefore$ $ABGI$ is a kite.
Note that $AG$ is a diagonal and so it bisects $\angle BGI$.
So $\angle BGA = \angle AGI$.
So $\angle JGA = \angle JAG$.
Thus $GJ = JA$.
Or it can be done by calculating the gradient of $GF$ and the point $A (2, 2)$.
Then you can calculate the coordinates of $J$ and calculate $|GJ|$ and $|JA|$ and show that they are equal.
I personally prefer the first method but use whichever is easier and helps more.
Comment: + 1 simple and elegant
Comment: @GNUSupporter thanks for appreciating it. The key to solving these kinds of problems is to realize that everything is there for a reason, such as the circle and the two tangents. And to realize that sometimes drawing a single extra line solves the equation; in this case the line $GA$.
Comment: Plus there is one other trick: realizing the deeper meaning of things. Why do you think that only the y-intercept of the line $AJ$ was plotted. Figuring out things like that is difficult. Practice with this:                                                What do I mean when I say that differentiation is an integral part of maths?
Comment: As you say, everything in the figure comes with a reason.  My upvote also: I thought of $A=rs/2$ to calculate the height of origin from the hypotenuse of the great triangle, so I joined up $A$ and $I$ in some sense, but this leads to tedious calculations of side lengths.  That's why I find your way more simpler than mine.  $x$-intercept has no role to play in this deductive geometric proof, unlike an analytic geometric one. I'm not sure if I get the last question right. What's behind $d/dx$ can be written as an integral $\int f(x) dx$. When you see differentiation, there's an integral behind.
Comment: @GNUSupporter it was actually a (bad) pun about the $2$ different meanings of integral: $\int f(x) dx$ and important. The first meaning is actually the opposite of differentiation so that is where my (bad) pun intended :)
Comment: Interestingly, I don't see your upvote! Well that was you joking with me B)
Comment: P.S. could you show me those $4$ equilateral triangles. I could not find them.
Comment: I love telling jokes, but not lies.
 Once your rep ≥1000, you'll be able to see [upvotes vs downvotes](https://i.stack.imgur.com/0Tv1n.png).  I think it should be " isoceles" instead.
Comment: @GNUSupporter Oh okay thanks! But the P.S. part was directed to Zimo not you. I personally found the $4$ isosceles triangles but could not locate the $4$ equilateral triangles.
Answer: Drop a perpendicular $JX $ from $J $ onto the line $FG $. Note triangles $\triangle GJX $ and $\triangle JAB $ are congruent, as both are right, $\angle JGX=\angle AJB $ and $AB=AI=JX $. Thus, $GJ=JA $ follows directly.
Answer: Well, first of all we can write a general function for a first order equation:
$$\text{y}\left(x\right):=\text{a}\cdot x+\text{b}\tag1$$
Now, we have two line:

$$
\begin{cases}
\text{y}_1\left(0\right)=8=\text{a}_1\cdot0+\text{b}_1\\
\\
\text{y}_1\left(x\right)=0=\text{a}_1\cdot6+\text{b}_1
\end{cases}\space\space\space\space\space\space\space\space\space\space\space\therefore\space\space\space\space\space\space\space\space\space\space\space\begin{cases}
\text{a}_1=-\frac{4}{3}\\
\\
\text{b}_1=8
\end{cases}\tag2
$$
$$
\begin{cases}
\text{y}_2\left(2\right)=2=\text{a}_2\cdot2+\text{b}_2\\
\\
\text{a}_1=\text{a}_2=-\frac{4}{3}
\end{cases}\space\space\space\space\space\space\space\space\space\space\space\therefore\space\space\space\space\space\space\space\space\space\space\space\begin{cases}
\text{a}_2=-\frac{4}{3}\\
\\
\text{b}_2=\frac{14}{3}
\end{cases}\tag3
$$

We can write $\text{a}_1=\text{a}_2$ because the lines are parallel.
Now, we can write:
$$\left|\text{GJ}\right|=\text{y}_1\left(0\right)-\text{y}_2\left(0\right)=-\frac{4}{3}\cdot0+8-\left(-\frac{4}{3}\cdot0+\frac{14}{3}\right)=\frac{10}{3}\tag4$$
And:
$$\left|\text{AJ}\right|=\sqrt{\left|\text{BJ}\right|^2+\left|\text{AB}\right|^2}=\sqrt{\left(\text{y}_2\left(0\right)-2\right)^2+2^2}=$$
$$\sqrt{\left(-\frac{4}{3}\cdot0+\frac{14}{3}-2\right)^2+2^2}=\frac{10}{3}\tag5$$

DONE!

Proving two lengths to be equal


Node.js global variable accessibility

Question: I am trying to write a NodeJS based application for which I declare a global variable and try to modify it in one of the functions in my code. But it does not get modified. The code looks something like this:
var num=0, check = true;
function( a, b){
  var parts = a.split("/");
  while (num == 0){
    check=false;
    fileSystem.readFile(parts[parts.length-1], function (err, fileData) {  .
    .
    check= true
    }
 }
 if(check == true){
   num++;
   console.log("check: "+check+"num"+num);
 }
}

I see value of num as 0 always. I also tried to use global.num inside the function but it dint work. Please help. Thanks in advance.
Comment: Isn't `.readFile()` asynchronous? Its callback (where you set `num=1`) won't be called until sometime later, so I would expect you've got an infinite loop with `while(num==0)`.
Comment: The value of variable doesn't change even after the callback is invoked which I check by console.log() in callback.
Comment: Line 6: SyntaxError: Unexpected token .
Comment: that might be because of dots I put to skip non relevant part of code.
Answer: Your function hasn't been invoked yet, so there's no reason for the value of num to have changed.
Comment: Updated the code to reflect the problem I am facing.I hope you understand the issue. Can you please suggest how can I solve this problem?
Comment: my answer is the same. I don't see where your function is being invoked.
Answer: Even if your function were to be invoked, it contains an infinite loop (as far as I can tell, since you seem to have omitted some code in the loop). It will loop forever because it tests if num is 0, but num is only changed after the loop exits.
Comment: The loop is not running infinite. The code within doesn't let it run forever. But even after the process is invoked and run finitely the global variable value does not change.
Comment: Perhaps you need to show all your code. The code that is currently shown *does* let the loop run forever.
Comment: Remember Node is asynchronous but runs in a single thread.  Your 'while' loop is saturating the thread so the callback never gets a chance to execute and therefore its caught in an infinite loop.
Comment: Even if the callback gets hit there is no way out of the while loop as it is presented.

Node.js global variable accessibility


Does gmcs or xbuild predefine any properties?

Question: I'm porting some .NET code to mono, which involves #if blocks like:
#if !MONO
// Stuff that only works in >NET
#endif

I can define these things in the csproj file and set a mono build target. However, I was wondering if xbuild or gmcs predefined anything  so I know if I'm compiling on mono.
Comment: [gmcs.exe defines __MonoCS__](http://stackoverflow.com/questions/329043/how-can-i-conditionally-compile-my-c-sharp-for-mono-vs-microsoft-net/329072#329072). This is a duplicate.
Answer: Short answer: no. There's no default flag.
For gmcs, use gmcs -d:MONO. If you build using xbuild, you can set the flag in the .csproj.


Proving $L(R,R) \otimes L(R,R) \cong L(R \otimes R , R \otimes R)$.

Question: Lang wrote in page 627, Algebra, proof of Corollary, that the isomoprhism

$L(R,R) \otimes L(R,R) \rightarrow L(R \otimes R, R \otimes R)$

is clear. Where given $R$-modules $E,F$, $L(E,F)$ is the set of $R$-module homomorphisms. What I did was

$R \otimes R \cong R$ given by $\pi: x \otimes y \mapsto xy$, inverse by $i: x \mapsto x \otimes 1$. Given  $f \in RHS$,$$f \mapsto (\pi \circ f \circ i ) \otimes id $$
Conversely, a map from LHS to RHS is given by $f \otimes g \mapsto T(f,g)$ where $$T(f,g): x \otimes y \mapsto f(x) \otimes g(y)$$
The map are inverses. $$f \mapsto T( (\pi \circ f \circ i), id ) : x \otimes y \mapsto (\pi \circ f \circ i)(x) \otimes y= f(x \otimes y)$$
  $$f \otimes g \mapsto (\pi \circ T(f,g) \circ i) \otimes id = f \otimes g$$
Last equality holds as
  $$ (\pi \circ T(f,g) \circ i) \equiv \alpha_f \alpha_g \, id $$
  which holds because $f \equiv \alpha_f \,  id$, $g \equiv \alpha_g \, id $

It took me some playing to figure out the first map from RHS to LHS. Is there are higher perspective which explains this map?
Comment: It is simply the map, defined for the elementary tensors, as $\;u\otimes v\longmapsto\bigl(x\otimes y\mapsto u(x)\otimes v(y)\bigr)$.
Answer: It's even simpler than that. There is an isomorphism $L(R,R) \cong R$ given by $f \mapsto f(1)$. Its inverse is $x \mapsto f_x$ where $f_x(y) = xy$. Since Therefore $L(R,R) \otimes_R L(R,R) \cong R \otimes_R R \cong R$.
Comment: Ah, thanks a lot, I think the main problem for me is I haven't been thinking isomorphisms $Hom$ and $\otimes$ as functors. For example, how would you show your first congruence? Is it as,

\begin{align} L(R,R) \otimes_R L(R,R) & \cong  R \otimes_R L(R,R) \\
 & \cong R \otimes_R R
\end{align}

using that functors preserves isomorphisms.


When will change in one class be reflected on another class?

Question: I have 2 classes. The second class receive the first class as a parameter during class object initialization. The code is:
import random

class DataSet(object):
    def __init__(self, num):
        self.num=num
        self.data = self._gen_data()

    def _gen_data(self):

        return random.sample(list(range(100)), self.num)

    def regenerate_data(self):
        self.data = self._gen_data()

    def show_data(self):
        print(self.data)

class DataLoader(object):
    def __init__(self, dataset):
        self.data = dataset.data
    def show_all_data(self):
        print(self.data)

mydata = DataSet(num=5)
mydata.show_data()

myloader = DataLoader(dataset=mydata)
myloader.show_all_data()

mydata.regenerate_data()
mydata.show_data()

myloader.show_all_data()

If I use the regenerate_data() method of mydata, I expect that the DataLoader object will also show the changed data. But apparently, I was wrong.
The change in mydata is not reflected on myloader, which still shows the old data.
Then I construct a second example,
import random

class DataSet(object):
    def __init__(self, num):
        self.num=num
        self.data = self._gen_data()

    def _gen_data(self):
        return random.sample(list(range(100)), self.num)

    def __getitem__(self, index):
        return self.data[index]

    def regenerate_data(self):
        self.data = self._gen_data()

    def show_data(self):
        print(self.data)

    def __len__(self):
        return len(self.data)

class DataLoader(object):
    def __init__(self, dataset):
        self.dataset = dataset

    def show_batch(self):
        print([self.dataset[i] for i in [0, 1]])

mydata = DataSet(num=5)
mydata.show_data()

myloader = DataLoader(dataset=mydata)
myloader.show_batch()

mydata.regenerate_data()
mydata.show_data()

myloader.show_batch()

Now change in mydata object is reflected on myloader.
My question is, why in the first example, the change in first class is not reflected on second class, while in the second example, change in first class will be reflected on second class? Is there some rule?
Answer: In your first example, regenerate_data() only returns newly generated data, it doesn't assign it to anything. In your second example, since myloader holds a reference to mydata, changing an attribute in mydata by assigning it, also changes it in myloader, because they refference the same object.
Edit: here is how you can test that your classes are indeed mutable;
class ExampleClass:

    def __init__(self):
        self.data = 'foo'

    def __str__(self):
        return self.data

example = ExampleClass()
example.data = 'bar'
print(example)

What does this tell you?
Comment: Just let me know if its unclear or if you need some further elaborating.
Comment: so if I have a `change_data()`  method for `mydata` which changes the `data` element in `mydata`, this change will be reflected also on `myloader`, right? What if the `data` member of `mydata` is immutalbe type such as tuple, then change in `data` will not be reflected on `myloader`.
Comment: @jdhao It doesn't really matter if it is immutable, for example, I can do `x = (1, 2)`, and then later do `x = (3, 2)`. This will change the value of `x`, which indeed is immutable. What immutable implies, is that you can't change elements separately, you can only reassign it, for example `x[0] = 3` will not work.
Comment: yes, that is what I mean. Since immutable type can not change. If we change its reference. Then `myloader` will can not reflect this change. Also, I am curious if the two custom class is mutable or immutable. Is there a method to test it?
Comment: @jdhao I think you misunderstood. The attribute can be immutable, but it doesn't matter, you can still change it, you just can't *mutate* it. **Reassigning** it is completely fine. Edit: both of your custom classes are *mutable*.
Answer: Disclaimer: bad answer. See the other one.
In the first example, you're using this: self.data = dataset.data, and dataset.data is a new list generated by the function random.sample. While it's true that if you do list1 = list2 you are pointing to the same list with 2 variables, with random.sample you create a new one, with no other variables containing it, so if you generate another one, in self.data you'll still have the one you generated before because it's the only variable pointing to that list.
In your second example you store the object you instantiated, not a copy, so the opposite happens: both variables point to the same object, and if you modify the attributes of the class using one of those two variables, you'll get the same attributes if you get them from the other one.
Comment: The first you say is correct, but he actually stores a reference to the same object in both cases, but only in the second the new data is actually assigned to something.
Comment: hm you're right, I think I supposed that `random.sample()` returned a generator, not a list, and that's why I said it didn't return the same list but a different one.