Why doesn't Random Forest handle missing values in predictors?

Question: What are theoretical reasons to not handle missing values? Gradient boosting machines, regression trees handle missing values. Why doesn't Random Forest do that?
Comment: They are handled in the `party` R package. One blog article here: http://www.exegetic.biz/blog/2013/05/package-party-conditional-inference-trees/
Answer: Gradient Boosting Trees uses CART trees (in a standard setup, as it was proposed by its authors). CART trees are also used in Random Forests. What @user777 said is true, that RF trees handles missing values either by imputation with average, either by rough average/mode, either by an averaging/mode based on proximities. These methods were proposed by Breiman and Cutler and are used for RF. This is a reference from authors Missing values in training set.
However, one can build a GBM or RF with other type of decision trees. The usual replacement for CART is C4.5 proposed by Quinlan. In C4.5 the missing values are not replaced on data set. Instead, the impurity function computed takes into account the missing values by penalizing the impurity score with the ration of missing values. On test set the evaluation in a node which has a test with missing value, the prediction is built for each child node and aggregated later (by weighting).
Now, in many implementations C4.5 is used instead of CART. The main reason is to avoid expensive computation (CART has more rigorous statistical approaches, which require more computation), the results seems to be similar, the resulted trees are often smaller (since CART is binary and C4.5 not). I know that Weka uses this approach. I do not know other libraries, but I expect it to not be a singular situation. If that is the case with your GBM implementation, than this would be an answer.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/19409/discussion-between-prophet60091-and-gung).
Comment: You touched on "penalizing the impurity score with the ration of missing values".  How does this directly affect the selection of optimal dimension values selected at a particular level/branch of the tree?
Answer:
"What are [the] theoretical reasons [for RF] to not handle missing values? Gradient boosting machines, regression trees handle missing values. Why doesn't Random Forest do that?"

RF does handle missing values, just not in the same way that CART and other similar decision tree algorithms do. User777 correctly describes the two methods used by RF to handle missing data (median imputation and/or proximity based measure), whereas Frank Harrell correctly describes how missing values are handled in CART (surrogate splits). For more info, see links on missing data handling for CART (or it's FOSS cousin: RPART) and RF.
An answer to your actual question is covered clearly, IMHO, in Ishwaran et al's 2008 paper entitled Random Survival Forests. They provide the following plausible explanation for why RF does not handle missing data in the same way as CART or similar single decision tree classifiers:

"Although surrogate splitting works well for trees, the method may not
be well suited for forests. Speed is one issue. Finding a surrogate
split is computationally intensive and may become infeasible when
growing a large number of trees, especially for fully saturated trees
used by forests. Further, surrogate splits may not even be meaningful
in a forest paradigm. RF randomly selects variables when splitting a
node and, as such, variables within a node may be uncorrelated, and a
reasonable surrogate split may not exist. Another concern is that
surrogate splitting alters the interpretation of a variable, which
affects measures such as [Variable Importance].
For these reasons, a different strategy is required for RF."

This is an aside, but for me, this calls into question those who claim that RF uses an ensemble of CART models. I've seen this claim made in many articles, but I've never seen such statements sourced to any authoritative text on RF. For one, the trees in a RF are grown without pruning, which is usually not the standard approach when building a CART model. Another reason would be the one you allude to in your question: CART and other ensembles of decision trees handle missing values, whereas [the original] RF does not, at least not internally like CART does.
With those caveats in mind, I think you could say that RF uses an ensemble of CART-like decision trees (i.e., a bunch of unpruned trees, grown to their maximum extent, without the ability to handle missing data through surrogate splitting). Perhaps this is one of those punctilious semantic differences, but it's one I think worth noting.

EDIT: On my side note, which is unrelated to the actual question asked, I stated that "I've never seen such statements sourced to any authoritative text on RF". Turns out Breiman DID specifically state that CART decision trees are used in the original RF algorithm:

"The simplest random forest with random features is formed by selecting
at random, at each node, a small group of input variables to split on.
Grow the tree using CART methodology to maximum size and do not prune." [My emphasis]

Source: p.9 of Random Forests. Breiman (2001)
However, I still stand (albeit more precariously) on the notion that these are CART-like decision trees in that they are grown without pruning, whereas a CART is normally never run in this configuration as it will almost certainly over-fit your data (hence the pruning in the first place).
Answer: Random forest does handle missing data and there are two distinct ways
it does so:
1) Without imputation of missing data, but providing inference.
2) Imputing the data.  Imputed data is then used for inference.
Both methods are implemented in my R-package randomForestSRC
(co-written with Udaya Kogalur).  First, it is important to remember
that because random forests employs random feature selection,
traditional missing data methods used by single trees (CART and the
like) do not apply.  This point was made in Ishwaran et al. (2008), "Random Survival Forests", Annals of Applied Statistics, 2, 3, and nicely articulated by one of the
commenters.
Method (1) is an "on the fly imputation" (OTFI) method.  Prior to
splitting a node, missing data for a variable is imputed by randomly
drawing values from non-missing in-bag data.  The purpose of this
imputed data is to make it possible to assign cases to daughter nodes
in the event the node is split on a variable with missing data.
Imputed data is however not used to calculate the split-statistic
which uses non-missing data only.  Following a node split, imputed
data are reset to missing and the process is repeated until terminal
nodes are reached.  OTFI preserves the integrity of out-of-bag data
and therefore performance values such as variable importance (VIMP)
remain unbiased.  The OTFI algorithm was described in Ishwaran et al
(2008) and implemented in the retired randomSurvivalForest package,
and has now been extended to randomForestSRC to apply to all families
(i.e. not just survival).
Method (2) is implemented using the "impute" function in
randomForestSRC.  Unsupervised, randomized, and multivariate splitting
methods for imputing data are available.  For example, multivariate
splitting generalizes the highly successful missForest imputation
method (Stekhoven & Bühlmann (2012), "MissForest—non-parametric missing value imputation for mixed-type data", Bioinformatics, 28, 1).  Calling the impute function
with missing data will return an imputed data frame which can be fit
using the primary forest function "rfsrc".
A detailed comparison of the different forest missing data algorithms
implemented using "impute" was described in a recent paper with Fei
Tang "Random forest missing data algorithms", 2017.  I recommend
consulting the help files of "rfsrc" and "impute" from randomForestSRC
for more details about imputation and OTFI.
Comment: Welcome to our site! Note that your username, identicon, & a link to your user page
are automatically added to every post you make, so there is no need to sign
your posts. In fact, we prefer you don't.
Comment: Thanks for an interesting answer (+1). I took the liberty of adding full references & links for a couple of the cited papers, but couldn't find Tang & Ishwaran (2015), "Random forest missing data algorithms". Has it been published yet?
Answer: Recursive partitioning uses surrogate splits based on non-missing predictors that are correlated with the predictor possessing the missing value for an observation.  It would seem possible in theory for random forests to be implemented that use the same idea.  I don't know if any random forest software has done so.
Answer: Random Forest has two methods for handling missing values, according to Leo Breiman and Adele Cutler, who invented it.
The first is quick and dirty: it just fills in the median value for continuous variables, or the most common non-missing value by class.
The second method fills in missing values, then runs RF, then for missing continuous values, RF computes the proximity-weighted average of the missing values. Then this process is repeated several times. Then the model is trained a final time using the RF-imputed data set.
Comment: Thank you for your answer!
But, both this methods are replacing missing values.
But in GBM or regression trees missing values don't replace for anything. What is theoretical difference between, for example GBM and RF in this sense?
Comment: I'm not an expert on GBM, but the RF handling of missing values appears to be rooted in the idea of imputation, http://en.wikipedia.org/wiki/Imputation_(statistics) In cases where missing values are not missing at random, your results can be biased due to missingness. Imputation attempts to recover this missing values and reduce bias.
Answer: For CART, you can apply the missing-in-attributes (MIA) approach. That is, for categorical predictors, you code missing as a separate category. For numerical predictors, you create two new variables for every variable with missings: one where you code missings as -Inf and one where you code missings as +Inf. Then you apply a random forest function as usual to your data.
Advantages of MIA:

Computationally cheap
Does not yield multiple datasets and thereby models, as multiple imputation does (the imputation-of-missing-data literature generally agrees that one imputed dataset is not enough)
Does not require you to choose a statistical method and/or model for imputing the data.
If values are MNAR, and missingness is in fact predictive of the outcome, MIA may outperform multiple imputation

Functions ctree() and cforest() from package partykit allow for applying MIA by passing ctree_control(MIA = TRUE) to their control arguments.
Jerome Friedman's RuleFit program appears to use MIA for dealing with missings, see https://statweb.stanford.edu/~jhf/r-rulefit/rulefit3/RuleFit_help.html#xmiss.
A description of the MIA approach can be found in Twala et al. (2008):
Twala, B.E.T.H., Jones, M.C., and Hand, D.J. (2008). Good methods for coping with missing data in decision trees. Pattern Recognition Letters, 29(7), 950-956.
Answer: Instead of using median values, etc., I would highly recommend looking at the missRanger package (currently in development on Github) or the R package missForest). Both of these packages use random forests to first impute your data using a method similar to multiple imputation via chained equations (MICE). This would be the appropriate imputation method to use as it corresponds closely to your actual analysis model. You can then use all your data without having to worry about dropping individual rows due to missing observations. In addition, the imputed values will be far more realistic than simply selecting medians or modes.
You can use just one filled-in imputed data set for your analyses, but the best way to incorporate uncertainty over missing values is to run multiple runs of these imputation methods, and then estimate your model on each of the resulting datasets (i.e., multiple imputation) and then combine the estimates using Rubin's rules (see R package mitools).


Proofs by Schubert calculus and combinatorics

Question: Do you know some examples proved by two different methods: 1. Schubert calculus, 2. combinatorial method.
Answer: Unimodality of partitions inside a box of size $m\times n$ (i.e. partitions with number of parts at most $m$ and size of the largest part at most $n$) follows from applying Hard Lefschetz Theorem to the Grassmann variety $G_{m+n,n}$ (see the paper 'Combinatorial Applications of the Hard Lefschetz Theorem' by Stanley). A combinatorial proof of this was given by Kathy O'Hara (reference: Unimodality of Gaussian coefficients: a constructive proof, J. of Comb. Theory, Ser. A, 53 (1990) 29-52.
Comment: Thank you so much!


TCP load balancer recommendation

Question: I need to load balance between 2 or 3 TCP servers. Any recommendations ? The TCP servers use their own proprietary protocol over the connection
Comment: Product and service recommendations are specifically off topic for ServerFault (see point 4 in the NOT About section of the [FAQ](http://serverfault.com/faq))
Answer: On the software side there's LVS.
Comment: I'm also prefering the LVS. Easy to use. It runs on normal hardware. this makes it to a cheat solution.
Answer: For a broadly applicable platform F5 load-balancers have done us wonders. We have a pair in a fail-over configuration and they're handling quite a lot of load-balancing. Even multiple protocols. Over the last several years we've load-balanced:

HTTP, lots of http
HTTPS, which they can terminate, saving server resources
SSH/SFTP
LDAP, handy for AD Global Address Book addresses for Entourage, as well as LDAP-enabled web-app Authn.
IMAP
SMTP

This device-pair was purchased explicitly to load-balance a certain critical http service, but the devices have proven so useful that they're now doing more traffic not on that service than they are on it. They also have the handy benefit of a rich rules system that allows you to do very interesting things, the smallest among them being the ability to serve up a different pool/address when the main load-balanced pool is down.
Yes, they are expensive. They made sense in our case because we had one critical service that was worth the expense, and we had enough add-on usage waiting in the wings to make the investment pay off even more. If you can afford it, go for it. I haven't seen the Cisco load-balancers, but they're undoubtedly equivalent in price.
Comment: +1 for F5. Excellent products running (mostly) on open source but providing a very nice GUI for tuning things.
Answer: Have a look at HAProxy: its very quick, and with some decent hardware, can handle > 10k connections.
Answer: I would prefer (of course it depends from budget) to have redundant hardware load balancers.
Almost it 99% it will be more reliable and with better performance than software solution.
Comment: Why do you say that? Can you give me more details?
Comment: What you mean I did I say that ? I said because it is the best practice.
Answer: I think you'll want to evaluate how much traffic you'll actually be receiving first.  You can get a "hardware" load balancer from either Cisco or F5, but if you only have 2 or 3 servers in the pool the performance and capacity of a software load balancer will almost certainly be more than adequate.  HAProxy does support failover pairs, and if you choose quality hardware the reliability should be about equal to the hardware solutions.
The main benefit at your scale (as opposed to hundreds or thousands of servers in a pool) to buying "hardware" load balancers is the ability to escalate to a vendor to get them to fix whatever the problem is.  This doesn't always work out any better in practice.  The downside to buying commercial "hardware" load balancers is that they will be drastically more expensive.  The F5s start at something like $30,000 for a pair of the lower-end 1600s and go up rapidly from there.  I assume Cisco's prices are comparable.

TCP load balancer recommendation


PHP Session Expiration - When does it refresh?

Question: I'm using Zend with a session expiration set to 1,800 seconds. I was wondering if this session expiration time refreshes back to 1,800 seconds every time I make a request from the browser to the server on behalf of the user and also when the user loads a new page, or does it just refresh when the user loads a new page?
Comment: you could set it to 5 seconds and test it.
Comment: It will likely depend on how your are using the session and what options and configurations you are using.
Answer: When a user loads a new page, that is the browser making a request to the server on behalf of the user. So the two scenarios you painted above are the same thing.
When a session is started, the session ID is sent to the browser which usually stores it in a cookie. The browser then uses the cookie to pass the session ID to the server with each request to identify the user. The server keeps track of when the session expires and this area can get a little tricky (read How do I expire a PHP session after 30 minutes?)
But as long as you are using the same browser to make the requests, then the session expiration will refresh in the two scenarios you've given.
Answer: The cookie that holds the session id (and all other cookies originating from the target server) travels alongside every request you make to the server, be it a page refresh or an ajax call.
So yes, the session refreshes upon any interaction with the server.
Answer: Basically it depends upon many things. Largely upon the browser and the version of the browser. You can read this post : How do I expire a PHP session after 30 minutes?
Answer: When you do session_start() if it is is the first call, the server saves session information in a file in /tmp folder, and send to your browser a cookie with this file identifier, else the server get cookie identifier and loads the file information. The duration of this cookie by default in php configuration is 30 minutes.
You can increase the time of this cookie in php.ini or manually setting directive with ini_set function or in .htacces file. You only setting the directive session.cookie_lifetime. The values are number of seconds or if set to the cookie are valid until you are close the browser
Another posible solution is make a token system for users, for example you manually sends a cookie to the browser that expires after 2 months width a token (large randomly key, saved in a database table with a user id field). When the session isn't available you check if the cookie exists and you can recreate session login finding a user manually with the cookie token.


Access from external network safely to raspberry

Question: I am implementing a home alarm system with raspberry and I need to access it from the external network. The initial idea was to use cascade VPN and ssh (in my university to connect to the cluster I had to first connect to the University network and then use ssh). But if via VPN I connect to the raspberry address then I cannot give commands via ssh because I'm in 'local', no? ... So I should either use ssh more fail2ban or use VPN. But could I be calm with one of these two methods? Can I use ACL somewhere? It would not be nice if someone could open the gate or access the cameras...
Comment: Welcome to the site. Could you explain why this is security related? It seems to me, that this is rather a question about setting up and controlling a raspberry.
Comment: Hi, it's not a problem of how to control the raspberry. I can choose the way to control Raspberry. My problem is to create an architecture that is not vulnerable to attack ...
Answer: I will assume you mentioned a university as a point of the environment and are not considering censorship. But an OpenSSH server will work well here. While not advisable I assume you will use the root user, do ensure a respectable password is used, this goes for any user allowed for SSH login. If concerns that password authentication (interactive-keyboard) is not for you, look at public key authentication, using ED25519 521-bits or RSA 4096-bits.
Regarding /etc/ssh/sshd_config harden the following:
  Port 30000
  LogLevel VERBOSE
  LoginGraceTime 120
  PermitRootLogin yes
  PermitEmptyPasswords no
  # Ideal session timeout
  ClientAliveInterval 600
  ClientAliveCountMax 0
  # Enhanced Authentication
  KexAlgorithms diffie-hellman-group-exchange-sha256,ecdh-sha2-nistp521
  Ciphers aes256-ctr,aes128-ctr
  MACs hmac-sha2-512,hmac-sha2-256
  AllowUsers root

I make a point to mention, CTR is preferred over CBC for OpenSSH exclusive, see: 'Plaintext Recovery Attacks Against SSH'. The port used for the SSH is your choice if exposed to the Internet use a non-standard port, because of botnets.
Fail2Ban is a viable choice for brute force protection. Consider the following configuration:
[ssh]
enabled = true
filter = sshd
port    = 3000
bantime = 600
findtime = 120
maxretry = 5
logpath = /var/log/auth.log

Of course adjust based on your needs, as I long bantimes can be a problem if you accidentally lock yourself out. Furthermore, I would advise keeping Fail2Ban enabled if public key authentication is enabled. As it will reduce traffic in the event of a botnet brute force, and hence CPU consumption.
Test your configuration with $ hydra -l root -P /root/rockyou.txt 192.168.1.100 -t 4 ssh where rockyou.txt is a wordlist. This is to ensure brute force protection is working properly. You can generate a wordlist with john or crunch or download one. Also, using nmap ensure the only open ports are those you desire to be exposed to your network interface.
While I won't expand on it, OpenVPN is another viable option, but I only consider this over SSH when I need censorship circumvention.
Comment: Thanks for your esaustive reply. I'm not Expert about openssh. Can it be configured to use esclusively certificates without password? And if so, is it a better solution?
Comment: By certificate, I presume you are referring to a PKI, unfortunately, OpenSSH does not support X.509 officially. However, you can use public key authentication instead. This works by pre-authorising each machine's public key you are going to log in from. The user public key pair is often stored ~/.ssh/. You copy the public key onto your OpenSSH server and only *authorized keys* are authenticated on the server. The client will be expected to authenticate with the corresponding private key each login, this proves ownership. Public key authentication is the best for security, but not convenient.
Comment: So i can use esclusively private key and avoid brute Force attack or the System asks password if no key is detected ? Thanks
Comment: OpenSSH uses PAM. Hence, it supports single or multi-factor authentication. If you only want public key authentication without interactive-keyboard that is completely possible. You will never prevent a brute force attack, but rather mitigate it from happening. How viable is it using interactive-keyboard with an 80-bit password V. an RSA 4096-bit key-pair, then factor in the firewall restricting brute forcing to 5 attempts every 600 seconds? I am not saying when using Fail2Ban interactive-keyboard (password) is bad, it works well with a strong password, but public key authentication is better.
Comment: Never enter any password you intend to use into an online service, but uses these to better understand strong password generation and entropy: [The Password Meter](http://www.passwordmeter.com/) and [Cygnius Password Strength Test](https://apps.cygnius.net/passtest/). Opinion varies about what a strong password is, so I will be simple, use alphanumeric (lower case, upper case and numeric values) with special characters, with a length of 15-32 characters.


Terraform plan does not update AWS Task Definition with last active revision value

Question: I would like your help on a situation that I'm facing with terrafom. My company recently launched a new website whose wordpress is hosted in an AWS ECS container. I had to make some adjustments to the site's infrastructure and I noticed that, when making the terraform plan, I get a message that there were changes outside the terraform, one of which is the revision number of the ECS Task Definition. But looking further down, when terraform plans the ECS Task Definition, instead of keeping the most recent revision number (31), he goes back to the last version that was applied by terraform (19). I suppose that this number is recorded in the TF state. My question is: is there any way (parameter or attribute) to perform the terraform plan and make it plan the ECS Task Definition with the latest active version deployed in the ECS container, in this case 31? The deployment is done through a bitbucket pipeline and the image is stored in the ECR.
This is the steps we run in bitbucket:
- step:
      oidc: true
      name: Get task-definition
      image: amazon/aws-cli:2.5.0
      artifacts:
        - task-definition.json
      script:
        - yum install jq -y
        - export AWS_REGION=us-east-1
        - export AWS_ROLE_ARN=arn:aws:iam::my-account:role/ci-ecs
        - export AWS_WEB_IDENTITY_TOKEN_FILE=$(pwd)/web-identity-token
        - echo $BITBUCKET_STEP_OIDC_TOKEN > $(pwd)/web-identity-token
        - TASK_DEFINITION=$(aws ecs describe-task-definition --task-definition site-institucional-prd)
        - ECR_IMAGE_TAG=145497587889.dkr.ecr.us-east-1.amazonaws.com/site-institucional-prd:${BITBUCKET_COMMIT}
        - NEW_TASK_DEFINTIION=$(echo "$TASK_DEFINITION" | jq --arg IMAGE "$ECR_IMAGE_TAG" '.taskDefinition | .containerDefinitions[0].image = $IMAGE | del(.taskDefinitionArn) | del(.revision) | del(.status) | del(.requiresAttributes) | del(.compatibilities) | del(.registeredAt) | del(.registeredBy)')
        - echo $NEW_TASK_DEFINTIION > task-definition.json

  - step:
      oidc: true
      name: Deploy to ECS
      script:
        - pipe: atlassian/aws-ecs-deploy:1.6.1
          variables:
            AWS_DEFAULT_REGION: 'us-east-1'
            AWS_OIDC_ROLE_ARN: 'arn:aws:iam::my-account:role/ci-ecs'
            CLUSTER_NAME: 'emprc-fgt-prd'
            SERVICE_NAME: 'site-institucional-prd-fgt'
            TASK_DEFINITION: 'task-definition.json'

I'm using the internal terraform module.
This is the part of my terraform where we provision the ECS Sevice based on the module we have created:
################################################################################
# ECS FARGATE
################################################################################

module "wp" {
 source = "git::firstname.lastname@example.com:my-repo//terraform/aws-ecs/modules/fargate-service"

  environment = var.environment

  enabled = var.enabled

  // variables task definition

  container_name = var.container_name

  enable_execute_command = var.enable_execute_command

  task_container_image = var.task_container_image

  task_definition_cpu    = var.task_definition_cpu
  task_definition_memory = var.task_definition_memory

  task_container_environment = var.task_container_environment

  extra_container_defs = var.extra_container_defs

  // variables service

  vpc_id          = var.vpc_id
  subnet_ids      = var.subnet_ids
  security_groups = var.security_groups
  service_name    = var.service_name

  cluster_id = var.cluster_id

  desired_count = var.desired_count

  capacity_provider_strategy = var.capacity_provider_strategy

  target_groups = var.target_groups

  health_check = var.health_check

  http_header = var.http_header

  lb_arn       = var.lb_arn
  host_header  = var.host_header

  autoscale = var.autoscale

  tags = var.tags
}

Here is the result of my terraform plan with only the problem theme (I will mask some values in the plan below):
Terraform detected the following changes made outside of Terraform since the
last "terraform apply":

# module.wp.aws_ecs_service.service[0] has been changed
  ~ resource "aws_ecs_service" "service" {
        id                                 = "arn:aws:ecs:us-east-1:my-account:service/emprc-fgt-prd/my-name"
        name                               = "my-name"
        tags                               = {
            "Environment" = "prd"
            "Name"        = "my-name"
            "Owner"       = "Owner"
            "Project"     = "project-name"
            "Provider"    = "Terraform"
        }
      ~ task_definition                    = "arn:aws:ecs:us-east-1:my-account:task-definition/site-institucional-prd:19" -> "arn:aws:ecs:us-east-1:my-account:task-definition/site-institucional-prd:31"
        # (14 unchanged attributes hidden)

Unless you have made equivalent changes to your configuration, or ignored the
relevant attributes using ignore_changes, the following plan may include
actions to undo or respond to these changes.
───────────────────────

Terraform used the selected providers to generate the following execution
plan. Resource actions are indicated with the following symbols:
  + create
  ~ update in-place
 <= read (data resources)

Terraform will perform the following actions:
 # module.wp.aws_ecs_service.service[0] will be updated in-place
  ~ resource "aws_ecs_service" "service" {
        id                                 = "arn:aws:ecs:us-east-1:my-account:service/emprc-fgt-prd/site-institucional-prd-fgt"
        name                               = "my-name"
        tags                               = {
            "Environment" = "prd"
            "Name"        = "my-name"
            "Owner"       = "Owner"
            "Project"     = "project-name"
            "Provider"    = "Terraform"
        }
      ~ task_definition                    = "arn:aws:ecs:us-east-1:my-account:task-definition/site-institucional-prd:31" -> "arn:aws:ecs:us-east-1:my-account:task-definition/site-institucional-prd:19"
        # (14 unchanged attributes hidden)

So new version deployment (wordpress) is always done by the bitbucket pipeline once the infrastructure is in place. In theory we do not change the infra, but when we need to change something on it, the task definition revision number is changed by terraform trying to assume the revision in TF state which is out dated. I understand that this is the correct behavior once the deployment is done by the bitbucket pipeline, but I would like to know if there is a way to keep the current revision active in ECS during the plan/apply.
Thank you for your time and support.
Answer: From what I see in your terraform plan, terraform apply will indeed set the latest task definition version and probably run redeploy of your ECS.
You can keep your state file up-to-date with terraform plan --refresh-only to see the possible changes in infrastructure done manually, and if you are ok with it, terraform apply --refresh-only will save those changes in your terraform state file.
Here is some more info on that subject.
Hope it helps


Advanced "skip page" logic in Cognito Forms

Question: Is there a way to skip from one page and have the user go to another? Example: Page 1 has yes/no field, if yes goto page 2 and if no goto page 3 and so on.
Answer: Absolutely!  When you add Page Breaks in Cognito Forms, you can select Show Next Page - When to specify whether the page following a page break should be available.  This will allow you to enter conditional logic such that when the answer to the question on Page 1 is Yes, then Page 2 is shown when the user clicks Next. This also affects the pages that appear in the progress bar and what pages are included in printed documents.

Advanced “skip page” logic in Cognito Forms


image map area unable to fire click event.afer maximize the widow or restore the window click event firing

Question: I am working with image map  i am taken two buttons in my image. in button click one popup(div)displaying .in that div i am taken image one map with areas . i am trying to click (close button and on and off button)) but not responding .after maximize the browser window  it is working . could any one solve this problem.and i want make all images responsive i used JQuery Image Map it is working but . when i given  div position is absolute.
it is not working. can any one provide solution for this problem
(press tab key for identify image map area's)
Answer: Although your question is hard to understand, i will try my best for 50 reps (I am young and needed the money ;)
You are using a JQuery Library from here:
https://raw.github.com/stowball/jQuery-rwdImageMaps/master/jquery.rwdImageMaps.min.js
The readme of it prints in large letters:
"Allows image maps to be used in a responsive design by recalculating the area coordinates to match the actual image size on load and window.resize"
So, your close handler doesnt trigger, because the area coords were only calculated by that "rwd" once you resize your browser window, and the readme tells us, that it is designed to do so.
Btw to make your code work:
add $('img[usemap]').rwdImageMaps(); below line 20 in your javascript code.
Comment: Hi, finally i understand the problem with your help.but i added that code in the line 20 it is not working still i am getting same problem... May be your young in rep but your too old in problem understanding :)
Comment: Your click handlers are triggering correctly for me: see here http://codepen.io/anon/pen/LuspK. At least i can open those Popups and can close it right away without a window resize.
Comment: yes for your it's working fine. but some where i get problem in my image. but i need a help form you . how can make responsive displaying maintenance panel and hydraulic panel could you suggest me. thanks in advance.


Why does cold kill humans but not bacteria?

Question: Bacteria can continue like nothing happened after being exposed to low temperatures why doesn't this happen to humans as well? Why can't our metabolic machinery continue as normal?
Comment: I think a better question would be something along the lines of "Do human cell lines tolerate cold temperatures?" The question as is is quite trivial - we are multicellular organs that rely on systemic functional integrity, whereas generally bacteria are single-cellular organisms. It's comparing apples and oranges at the minute. I think there is an interesting question in there, but major edits would be required.
Comment: @James Why would this be a homework question?
Answer: Let's look at what happens when a single cell within a cell wall freezes. We end up with a little drop of ice, within which are encased all the cellular structures. Thaw this ice, and all is well - provided neither freezing nor thawing happen too rapidly.
Now take what happens in a human being.
First, the blood in the extremities gets colder, and cools the interior somewhat. But we have mechanisms to conserve heat in the core, at least for a little while. This doesn't help the extremities much. If the blood freezes there, we get frostbite - the tissues die for lack of blood supply. Fingers and toes and the end of the nose, and other extremities, are compromised.
Now let the core temperature drop. Below a certain temperature, conduction in the heart slows and eventually stops. This is fatal.
There are many other effects, all of them related to the relative vulnerability of different tissues to cold. Freezing is generally bad for animal cells, which will rupture because of the mechanical effects of the expansion of water as it forms ice. Frozen body fluids can't do their jobs. Frozen nerves can't conduct impulses, so muscles won't contract once their temperature drops below the shivering point. And so on.
Comment: But why can't our cells resume normal activity after being frozen? Once that blood reaches the cells again why can't it function normally? What structures in our body or cells prohibits this from happening?
Comment: I edited to make clear that ice formation will rupture the cells. If the heart has stopped, the body dies. And when the formerly frozen body thaws, the cells do function normally by decaying, which is normal function for dead cells.


Creating publication-quality geometric figures in Python

Question: I am a mathematician. Recently, I became the editor of the puzzles and problems column for a well-known magazine. Occasionally, I need to create a figure to accompany a problem or solution. These figures mostly relate to 2D (occasionally, 3D) euclidean geometry (lines, polygons, circles, plus the occasional ellipse or other conic section). The goal is obtaining figures of very high quality (press-ready), with Computer Modern ("TeX") textual labels. My hope is finding (or perhaps helping write!) a relatively high-level Python library that "knows" euclidean geometry in the sense that natural operations (e.g., drawing a perpendicular line to a given one passing through a given point,  bisecting a given angle, or reflecting a figure A on a line L to obtain a new figure A') are already defined in the library. Of course, the ability to create figures after their elements are defined is a crucial goal (e.g., as Encapsulated Postscript).
I know multiple sub-optimal solutions to this problem (some partial), but I don't know of any that is both simple and flexible. Let me explain:

Asymptote (similar to/based on Metapost) allows creating extremely high-quality figures of great complexity, but knows almost nothing about geometric constructions (it is a rather low-level language) and thus any nontrivial construction requires quite a long script.
TikZ with package tkz-euclide is high-level, flexible and also generates quality figures, but its syntax is so heavy that I just cry for Python's simplicity in comparison. (Some programs actually export to TikZ---see below.)
Dynamic Geometry programs, of which I'm most familiar with Geogebra, often have figure-exporting features (EPS, TikZ, etc.), but are meant to be used interactively. Sometimes, what one needs is a figure based on hard specs (e.g., exact side lengths)---defining objects in a script is ultimately more flexible (if correspondingly less convenient).
Two programs, Eukleides and GCLC, are closest to what I'm looking for: They generate figures (EPS format; GCLC also exports to TikZ). Eukleides has the prettiest, simplest syntax of all the options (see the examples), but it happens to be written in C (with source available, though I'm not sure about the license), rather limited/non-customizable, and no longer maintained. GCLC is still maintained but it is closed-source, its syntax is significantly worse than Eukleides's, and has certain other unnatural quirks. Besides, it is not available for Mac OS (my laptop is a Mac).

Python has:

Matplotlib, which produces extremely high-quality figures (particularly of functions or numerical data), but does not seem to know about geometric constructions, and
Sympy has a geometry module which does know about geometric objects and constructions, all accessible in delightful Python syntax, but seems to have no figure-exporting (or even displaying?) capabilities.

Finally, a question: Is there a library, something like "Figures for Sympy/geometry", that uses Python syntax to describe geometric objects and constructions, allowing to generate high-quality figures (primarily for printing, say EPS)?
If a library with such functionality does not exist, I would consider helping to write one (perhaps an extension to Sympy?). I will appreciate pointers.
Comment: This is a very interesting and clear question, but unfortunately requests for library recommendations are explicitly off-topic here on SO. :-/
Comment: SymPy seems to provide some support for plotting the figures based on their [documentation here](https://docs.sympy.org/latest/modules/plotting.html#plot-geom). It uses `matplotlib` as its backend, so you may be able to utilise that.
Comment: There are lots of examples of plotting `shapely` geometries out there with `matplotlib`, so if you are constructing geometries by specifying points and vertices,  `shapely` may be easier than `SymPy`. If you are using symbolic expressions to generate your geometries, you could consider building `shapely` geometries from the `SymPy` expressions that you then plot with `matplotlib`.
Comment: Maybe you could try Manim, i.e., Mathematical ANIMation engine. You've probably not heard of it but you would've definitely heard of Grant Sanderson or 3Blue1Brown. It's the engine he uses(and designed) to create stunning mathematical illustrations.
Answer: There is a way to generate vector images with matplotlob, outputting with the library io to a vector image (SVG) with this approach.
I personally tried to run the code of the approach (generate a vectorial histogram) in that webpage as a python file, and it worked.
The code:

    import numpy as np
    import matplotlib.pyplot as plt
    import xml.etree.ElementTree as ET
    from io import BytesIO
    import json
    plt.rcParams['svg.fonttype'] = 'none'
    # Apparently, this `register_namespace` method is necessary to avoid garbling
    # the XML namespace with ns0.
    ET.register_namespace("", "http://www.w3.org/2000/svg")
    # Fixing random state for reproducibility
    np.random.seed(19680801)
    # --- Create histogram, legend and title ---
    plt.figure()
    r = np.random.randn(100)
    r1 = r + 1
    labels = ['Rabbits', 'Frogs']
    H = plt.hist([r, r1], label=labels)
    containers = H[-1]
    leg = plt.legend(frameon=False)
    plt.title("From a web browser, click on the legend\n"
            "marker to toggle the corresponding histogram.")
    # --- Add ids to the svg objects we'll modify
    hist_patches = {}
    for ic, c in enumerate(containers):
        hist_patches['hist_%d' % ic] = []
        for il, element in enumerate(c):
            element.set_gid('hist_%d_patch_%d' % (ic, il))
            hist_patches['hist_%d' % ic].append('hist_%d_patch_%d' % (ic, il))
    # Set ids for the legend patches
    for i, t in enumerate(leg.get_patches()):
        t.set_gid('leg_patch_%d' % i)
    # Set ids for the text patches
    for i, t in enumerate(leg.get_texts()):
        t.set_gid('leg_text_%d' % i)
    # Save SVG in a fake file object.
    f = BytesIO()
    plt.savefig(f, format="svg")
    # Create XML tree from the SVG file.
    tree, xmlid = ET.XMLID(f.getvalue())
    # --- Add interactivity ---
    # Add attributes to the patch objects.
    for i, t in enumerate(leg.get_patches()):
        el = xmlid['leg_patch_%d' % i]
        el.set('cursor', 'pointer')
        el.set('onclick', "toggle_hist(this)")
    # Add attributes to the text objects.
    for i, t in enumerate(leg.get_texts()):
        el = xmlid['leg_text_%d' % i]
        el.set('cursor', 'pointer')
        el.set('onclick', "toggle_hist(this)")
    # Create script defining the function `toggle_hist`.
    # We create a global variable `container` that stores the patches id
    # belonging to each histogram. Then a function "toggle_element" sets the
    # visibility attribute of all patches of each histogram and the opacity
    # of the marker itself.
    script = """

    """ % json.dumps(hist_patches)
    # Add a transition effect
    css = tree.getchildren()[0][0]
    css.text = css.text + "g {-webkit-transition:opacity 0.4s ease-out;" + \
        "-moz-transition:opacity 0.4s ease-out;}"
    # Insert the script and save to file.
    tree.insert(0, ET.XML(script))
    ET.ElementTree(tree).write("svg_histogram.svg")

Previously, you need to pip install the required libraries on the top lines, and it successfully saved a SVG file with a plot (you can read the file and zoomwant in the histogram and you will get no pixels, as the image is generated with mathematicals functions).
It (obviously for our time) uses python 3.
You then could import the SVG image within your TeX document for the publication rendering.
I hope it may help.
Greetings,
Javier.


Why would LDA have performed much better than SVM and Naive Bayes in diagnosing ADHD?

Question: In a final project in diagnosing Attention deficit hyperactivity disorder (ADHD) using Machine Learning, we obtained parameters from real patients. We used this data and got much higher success rates with LDA than with SVM and Naive Bayes. We had only 100 examples in our training set. We are wondering why LDA specifically succeeded much more than the others?
Comment: By LDA, you mean "linear discriminant analysis", right? Feel free to edit this post to add the tag [tag:linear-discriminant-analysis] if that's the case.
Answer: It would be hard to tell if you don't provide what kind of data/problem you are working on, but LDA works well when data that are grouped in gaussian blobs surrounding centroids while vanilla SVM works well when the data is almost linearly separable and naive bayes works well when your features are relatively independent of each other.
Answer: If I had to guess(and it is nothing more), I would say it has quite a bit to do with the problem itself and the architectures involved. Simply, the problem is less suited to a bayesian approach(Highly dependent features, linear distribution).


What are some comparative studies on program termination verification tools?

Question: Comparative studies of tools like AProver, 2LS
Comment: The body of your question should be complete unto itself.
Comment: Did you mean [AProVE](http://aprove.informatik.rwth-aachen.de/)?
Answer: As mentioned by nekketsuuu, SV-COMP has a termination category, and the Termination Competition has been going on for quite some time (there is some overlap).
It depends on what kind of termination you are interested in. This paper on AProVE gives an overview of that tool, which covers many of the techniques involved in general program termination analysis and types of programs that can be handled, though it does not really analyze the comparative strengths of different tools.
Sadly, I'm not aware of any modern overview paper that does this, which is unfortunate. The tool description papers of the competition participants for your category of choice would be a good place to start.
Answer: How about looking at Competition on Software Verification (SV-COMP) held at TACAS? There is a category of termination. For example, here is a link to SV-COMP 2017.
Answer: As the other answerers I'm not aware of such a study although it would be nice to have some. Instead, I would point to several benchmarks that the authors of these tools produce. A comparative study should benefit from it. I will set this as a community wiki so that other people can add references to other benchmarks/studies:
Benchmarks
Stainless verification framework
Termination Problems Data Base
Comparative studies


Is this nonnegativity constraint convex?

Question: Clearly, a Linear quadratic regulator problem involves quadratic cost which is convex. And minimizations that involves convex objective functions have unique solution...or global minimum.
I understand that in general if the objective function is convex and the constraints are also convex, then the task of deriving optimal solution remains in the area of convex optimization.
 But, what if the LQR problem is constrained? such as the states are constrained to be nonnegative $x(t)\ge 0$? What can we say about the convexity of this constraint?
Comment: A convex function has a unique minimum (if it has one: this may be not attained and actually be an infimum), but not a unique *minimizer* in general. Additional assumptions may be needed to have that.
Comment: @LorenzoStella Can you mention those essential assumptions for the existence of unique minimizer. The problem  assumes that the system is controllable. Thanks
Comment: For example, strong convexity implies existence of a unique minimum point, but I guess that is rarely the case for this type of problems, right?
Answer: I'm assuming we are dealing with discrete-time systems.
Short answer: if the dynamics is linear then yes.
Long answer: the problem is to understand what are the decision variables of your problem, with respect to which you classify it as convex or nonconvex. The initial state $x_0 \in \mathbb{R}^{n_x}$ is usually considered as a parameter, and the inputs $u_0,u_1,\ldots,u_{N-1} \in \mathbb{R}^{n_u}$ as decision variables, as well as subsequent states in time, $x_1,\ldots,x_N \in \mathbb{R}^{n_x}$. States and inputs are bound to each other by the dynamics, which is a constraint in this setting: given that constraints on the $x$'s and the $u$'s are convex (like nonnegativity of the states, as you mentioned), the problem is certainly convex if the dynamics is linear, i.e.
$$ x^{k+1} = Ax^k+Bu^k,\quad k=0,1,\ldots,N-1$$
where $A$ and $B$ are linear maps (matrices). If instead the dynamics non nonlinear, the problem is nonconvex in general. This is simply because in this case the feasible set (with respect to the linear dynamics above) is an affine subspace, which is convex in particular. Intersecting this with convex constraints on the $x$'s and the $u$'s still yields a convex feasible set.
Another way to see this is to eliminate the states by expressing them as function of the inputs via the dynamics: if this is a linear relation, then box constraints on the states (like the ones you mentioned) become convex polyhedral constraints on the inputs, and the cost associated with states remains convex (as it is a convex function composed with a linear map).
Comment: Thank you @Lorenzo, can you please suggest an article that discuss the above, espcially in continuous time domain
Comment: Hi, you are right: given your question I immediately jumped on the discrete-time train of thought. I'll edit my answer to make it clear. For continuous time I wouldn't know, can you maybe be more specific and specify exactly how you formulate the optimization problem?
Comment: [http://math.stackexchange.com/questions/1874298/is-it-possible-to-represent-re-formulate-the-cost-of-constrained-optimization-pr] Please refer to this question for the exact formulation....Please post if you have a relevant suggestion there also thank you


How do I parent a single bone from a rigify metarig to a cube without it parenting the whole metarig?

Question: I'd like to parent a single bone within a Rigify human full skeleton metarig to a corresponding cube [which contains animation information], however I can't select a single bone for parenting without selecting the whole skeleton. Is it not possible to parent individual bones within a metarig?
Answer: Yes, I don't think you can parent an individual bone to a mesh object. You can constrain it tho, so maybe that could solve your problem.
Comment: thanks - that worked!


How to crawl foursquare check-in data?

Question: Is it possible to crawl check-in data from foursquare in a greedy way? (even if I don't have friendship with all the users)  Just like crawling publicly available twitter messages. If you have any experience or suggestions, please share. Thanks.
Comment: Because I want to analyze user spacial temporal mobility using check-in data
Answer: If you have publicly available tweets containing links to foursquare, you can resolve the foursquare short links (4sq.com/XXXXXX) by making a HEAD request. The head request will return a URL with a check-in ID and a signature. You can use those two values to retrieve a check-in object via the foursquare API /checkins/ endpoint. You're only allowed to access 500 of these per hour.
You must abide by both the Twitter and foursquare terms of service -- in fourquare's case, you may not display this information to anyone, nor may you retain any user information for more than 3 hours (since the user has not authorized your application).
Comment: This may seem obvious, but you can use the same HEAD request to dereference a t.co URL as well.
Answer: You can only get the check-in data for a location if the manager of the location gives you OAuth access to your application.  If you have that, you can use the real-time API defined here: https://developer.foursquare.com/docs/realtime.html
Answer: No, it is not possible to crawl check-in data similar to Twitter. This information is considered personal data and is not public.
Answer: You can crawl twitter data for foursquare data =)

How to crawl foursquare check-in data?


Can my car sit on raised Jack stands for 20 year?

Question: I have a 1992 dodge stealth that has been sitting on Jack stands  since I could walk, so more or less  14 years . I'm a junior in high school and my plans for the car are to get the car back in "running" state . Would this long term Jack stand period cause any body or chassis damage if jacked correctly ?
Answer: Time will be the real problem - fluids evaporating, degrading, leaving residues, metal rusting due to humidity etc etc
It depends on how, or if, it was prepared for storage...
But leaving on stands should not increase the issues.
Comment: Gasoline evaporating from a carburetor can plug it up in a few years. Nothing good can happen in the gas tank. I would try to drain gasoline from any item even now. Tires are another potential problem , letting air ( oxygen pressure) may help. i can't imagine any problem with the chassis.
Comment: Tires will be throw-away items after 14 years anyway, so there's no point doing anything with them till you are actively working on the car. Just be careful not to take the car off the jacks and onto flat tires! The only issue with the jacks may be that (depending where it is stored) the jacks may now have corroded themselves "stuck" onto the chassis, unless you put plenty of grease on the jacking points before you mothballed the car.


Number of ways to color the edges of a tetrahedron with two colors?

Question: Grogg colors of each of the edges of a tetrahedron either purple or orange. Two colorings are considered the same if you can rotate one to produce the other. How many distinct colorings can Grogg make?
Answer: By enumeration, there are $12$
There is one where all six edges are purple
There is one where five edges are purple and one is orange
There are two where four edges are purple and two are orange: either the orange edges are sharing a vertex or they are on opposite edges
Repeat all of these with the colours swapped over.
Finally, there are four possibilities when there are three of each colour: either one colour shares one vertex with the other colour forming a triangle, or each colour follows a single line of three edges with two different possible orientations.
With thanks to @Donald Splutterwit and @PM for their observations.
Comment: @Donald Splutterwit...Yes I think you are right. And note PM's comment.
Answer: The number of edge colourings of a tetrahedron with two colours is $\color{red}{12}$.

Edit: Note that the mirror image of the "central" configuration gives another one that I had initially overlooked, thanks to PM for bring this to my attention.
Comment: Can you not reflect in the vertical axis in your middle configuration to generate a further colouring?
Answer: [Some text is adapted from one of my other answers.]
Before we can answer this question, we need to understand the rotations of the tetrahedron. You can see the rotations in the video at https://vimeo.com/90519331 .
Basically,

$8$ rotations are of the forms: $120^\circ$ or $240^\circ$ around an axis through one vertex and the center of the face.
$3$ more rotations are $180^\circ$ around an axis through the centers of two opposite edges.
$1$ more "rotation" is doing nothing (rotating by $0^\circ$).

How do we know we aren't missing any in this list of $12$ rotations? Well, there are only $4!=24$ permutations of the faces (or vertices), and half of them would turn the tetrahedron into a mirrored version of itself, which you can't do with a rotation alone.

Now, how do we get the number of colorings? There's a great theorem about counting, often called Burnside's Lemma, which says "when you want to count things with symmetry, the answer the the average (across all the operations) of the numbers of things (ignoring symmetry) that don't change when you do the operation."
So for each type of rotation, we should count how many colorings don't change:

How many colorings don't change when you rotate a third of the way around a vertex? The three edges connected to the vertex must have the same color ($2$ possibilities), and the triangle of the three other edges must have the same color too ($2$ possibilities). Therefore, there are $2\times2$ colorings for each of the $8$ rotations of this type.
How many colorings don't change when you rotate half way around an appropriate axis? Well, two edges end up where they started, so each of those are free to vary. And the other four edges swap in two pairs, so each of those pairs can have an arbitrary color (but two edges of the same pair must have the same color). Therefore, there are $2^4=16$ colorings for each of the $3$ rotations of this type.
How many colorings don't change when you do nothing to the tetrahedron? All of them! With $2$ colors and $6$ edges, that's $2^6$.

By Burnside's Lemma, the answer is then $$\frac{8\times4+3\times16+64}{12}=\frac{144}{12}=12\text{.}$$

An aside for those who want more, Burnside's Lemma has a generalization called the Pólya enumeration theorem, which can be used to answer more specific questions like "if we had three colors, how many colorings use each color twice?", as in this midterm solution document from Professor Jacob Lurie.
Answer: The cycle index for the rotational symmetry group of the tetrahedron acting on the edges of the tetrahedron is
$$
\frac{1}{12}(x_1^6+8x_3^2+3x_1^2x_2^2)
$$
with $2$ colours yields
$$
\frac{1}{12}(2^6+8(2^2)+3(2^2)(2^2))=12
$$
Comment: Do you intend to add more to this answer? I was intending to post another answer but the final calculation would be essentially the same as yours (I would just be adding context/explanation), and wanted to give you priority.
Comment: I'm aware my answer is quite concise but was a bit sad to be downvoted, especially as it was the first correct answer to be added in the presence of 2 pre-existing but incorrect answers.
Comment: You also were the first to post an answer with reasoning behind it beyond "here's the list of all of them, just trust I didn't miss any".
Comment: Thank you but please feel free to expand.. I think a complete explanation could be very long & i wasn't planning investing that much additional  time on it. Thanks.


Are all hypotenuses irrational if the shorter sides are integers?

Question: Is it sufficient to say that providing the shorter two sides of a right triangle can be expressed as integers that work out to equal the value of the hypotenuse, then the value of the hypotenuse must be irrational?  For example, suppose I wish to prove that $\sqrt 5$ is irrational, if the shorter sides are 1 and 2 then the length of the hypotenuse $\sqrt 5$ must be irrational.  Please tell me if I've made a mistake.
Comment: Have you heard of Pythagorean triples? Such as 3,4,5
Comment: Can't say I have.
Comment: @MichaelLee Well, it should answer your question. $3^2+4^2=5^2$.
Comment: $$5^2+12^2=13^2, \;8^2+15^2=17^2,\;161^2+240^2=289^2,...$$
Comment: Oh! Now I follow you!  If the sides consist of 3,4,5 then the hypotenuse is indeed a rational number.  I can't thank you all enough for helping me here, it would have taken me ages to figure it out by myself.
Answer: Hint:
take two integer numbers $m>n>0$, than:
$$
a=m^2-n^2 \qquad b=2mn \qquad c=m^2+n^2
$$
are integers such that $a^2+b^2=c^2$ (which is easy to prove). These are called the Pythagorean triples.


Is there a way to cache snap packages?

Question: I'm currently running squid-deb-proxy to cache apt-related downloads, I was wondering if the same could be done with snaps as well.
Answer: The squid-deb-proxy works because the files are served over plain HTTP, and generally do not require authentication (ones that do are usually over HTTPS and tend to not be cached).
Snaps however, are served over HTTPS due to the inherent requirements of authenticating to the store, and the possibility that some snaps are for purchase, and similar situations. To cache the data via a proxy, you will need to break the TLS connection by creating a certificate which you own, and which can be seen as valid by snapd when it attempts to verify the certificate.
Comment: That's unfortunate, so that means aside from having a convoluted setup, there's no easy way to do this? I've had a working squid with ssl enabled before but success seem to be a hit 'n miss in most cases, decided to scrap it all together.
Comment: Well, it's HTTPS, and all traffic is end-to-end encrypted, so in order to cache it somewhere in the middle, you obviously need to break that encryption. You could cache chunks of encrypted data, but there's no way to know what the data contains, or if it will remain valid (even if it was valid, it'd only still be valid for the one client, not all clients in the network).
Answer: At the first glance Ubuntu has Snap Store Proxy but then if you'd look closer into it you'll realise they expect that:

you shall tinker with Postgresql
configure some un-explained "domain name"
generate keys and then register this proxy
wait till they approve it

and only then you'd be able to save time and traffic with caching… "For evaluation purposes, we automatically grant the use of up to 5 devices."
Comment: This last comment is gone now. It seems you can use unlimited number of devices

Is there a way to cache snap packages?


Dependency of dimension of Hilbert space of wavefunction on the chosen observable

Question: I am assuming that the wave functions contain all the possible information about the system, how is it then for some observables like spin, the wave function can be expressed as a linear combination of two eigenvectors, where as for observables like position, the wavefunction is an infinite dimensional vector?
Answer: Doing an experiment to measure spin in a certain direction (Stern-Gerlach) one only observes two results (spin-up, spin-down). Since for any state of the physical system (wave function) it must be possible to express it as a linear combination of the eigenstates corresponding to the observable (spin), the state (wave function) can be expressed as a sum of the two eigenvectors (spin-up,spin-down).
On the other hand, if the observable you're looking at is position, any vector $\vec{v} \in \mathbb{R}^3$ is a possible measurement, which are infinitely many. So in this case the wave-function is an infinite dimensional vector.
Comment: The question was more regarding the mathematical consistency, if we take the wavefuction as a mathematical object,then what will it's dimension be?Since It can't be two different dimensions at the same time, how do we reconcile the infinite dimensional representation with the two dimensional one mathematically.
Answer: It's not a matter of the choice of observable, but of the choice of system.
If you only plan to measure a particle's spin, and that spin is not coupled to the same particle's position, then you can treat the position as part of the environment. If you plan to measure the position, then you have to include the position in the system. Even if the particle is physically the same in both problems, you are splitting the world into system and environment in two different ways, so the Hilbert space is different.


How do you force someone to sue you?

Question: I have a bill from a health care provider that I did go to but they are charging me for services I did not receive. They will not agree that they did not provide these services and continue to bill me. I believe I would win in small claims court, but I am afraid that they will report me to the credit reporting agencies at just the wrong time and then take too long to sue me. How can I force them to either take it to court or drop the charges?
Comment: If you have insurance, talk to them. Otherwise, try contacting your state's insurance regulator. In California, it's the [California Department of Insurance](http://www.insurance.ca.gov/01-consumers/110-health/),
Answer: I doubt this is possible. They have exactly as long as the law allows for them to bring suit against you, and there's nothing you can do to shorten that window. If you could, you might stipulate that they sue you within the next 6 hours or drop the case entirely. The law stipulates a "reasonable" period of time for them to bring suit. If they do wind up suing you, damaging your credit, and ultimately losing the case, you might be able to recover some damages if it affected your ability to get a loan, for example.
Comment: You might even be able to sue them if they decide not to go to court but still damage your credit. However, that's uncertain in more than one way.
Answer: Depending on your jurisdiction, you may be able to file a declaratory judgment action in small claims court. You'd effectively be asking the court to conclude that the contract(s) you made with the provider entitle them to X amount rather than Y.
Comment: Most states allow you to file declaratory judgment actions, but usually not in small claims court. So, it would be prohibitively expensive unless the excess charges are huge. There may also be an arbitration and/or mediation clause in the contact with the insurer or the doctor.
Comment: Luckily, you can do it here in Ohio. More luckily, I have not needed to.
Answer: Write to them and state that you deny liability for the alleged charge. Advise them that they are not permitted by law to continue to contact you about the alleged debt or to refer the matter to a debt collector or credit reporting agency unless and until they prove the debt in a court of competent jurisdiction. If you fell provocative, suggest the courthouse that would be mist convenient for you.
If they do any of the things they are not permitted to do, refer them to your jurisdiction's consumer watchdog.
Comment: Is there a law that allows you to require them to prove the debt in court before contacting you?
Comment: @bdb484: Of course they may initiate contact. The point here is that once the debt is disputed, the claimant can indeed be referred to court.

How do you force someone to sue you?


Decay of real continuous algebraic functions at infinity

Question: Let $f$ be a real valued continuous algebraic function on $\mathbb R^n$. Suppose the zero set of $f$ is bounded, i.e., if $|x|$ is large enough, $f(x)\neq 0$. Is there any estimate of the sort $|f(x)|\ge c(1+|x|)^{-N}$ for some $c>0$ and $n\in\mathbb N$? A prototypical example of such an inequality is $\sqrt{1+x^2}-x\ge c(1+|x|)^{-1}$, but I would appreciate general estimates along this line that apply to algebraic functions of $n$ variables.
Comment: No, if there are no continuity assumptions. Otherwise, e.g.,  you may define $f(x,y)$ to be the root of $f^2+4(x^2+y^2)f+(x^2-y^2)=0$ of minimal absolute value if it is nonzero, and the other root otherwise.
Comment: Maybe you can have radial bounds on half-lines $x=\lambda x_0, ||x||>>1$, $x_0$ fixed, by looking at the corresponding Puiseux series in the variable $\lambda$ near $\infty$.
Comment: @LoïcTeyssier If I want to do it In several variables, I want to make the estimate uniform, but I am unable to see why the Puiseux expansion is continuous w.r.t. $x_0$.
Comment: I am well aware of that, I was only suggesting this in case it'd be sufficient for your purpose to have the estimate on lines. Yet, in my experience, there is a kind of «semi-continuity» arising in that problems.
Answer: Update: As pointed out by Igor, this is not convincing. I only show that if $p(x,f)=0$ and $p(x,0)\not=0$ for $|x|>R$, then the claim holds. However, the OP only assumes that $f\not=0$ for $|x|>R$ (I mixed up the two originally).
Original answer: Yes, this works. If we had $|f(x_N)|\lesssim |x_N|^{-N}$ for arbitrarily large $N$, then the constant coefficient $p=a_0$ in the equation $\sum a_jf^j=0$ solved by $f$ would have the same property.
So it suffices to show that if a polynomial satisfies $p(x)>0$ for $|x|>R$, then in fact $|p(x)|\gtrsim |x|^{-N}$ for some $N$. This follows from the Positivstellensatz, which says, in our setting, that
$$
p(x) = \frac{1 + (|x|^2-R^2)F(x)+G(x)}{(|x|^2-R^2)H(x)+K(x)} \ge \frac{1}{(|x|^2-R^2)H(x)+K(x)} \gtrsim |x|^{-N} ;
$$
here, $F,G, H, K$ are sums of squares of polynomials.
(I suspect there must be a much more elementary argument.)
Comment: Why is $p$ non-vanishing near infinity?
Comment: Ah, I see. I was thinking that if $y$ is a solution of $p(x, y) = 0,$ then it is also a solution of $y p(x, y)=0,$  without adding the $y=0$ component.
Answer: Well it's true in dimension $1$, and I think the following argument
should reduce the case $n>1$ to the $n=1$ statement.
Let $r_0 = \max_{f(x) = 0} \| f(x) \|$.  Then $f$ has constant sign on
$\| x \| > r_0$ (continuous function on a connected set),
and we may assume the sign is positive (else replace $f$ by $-f$).
For $r \geq r_0$, define
$$
F(r) := \min_{\|x\| = r} f(x).
$$
This is an algebraic function of $r$ because it is the value of
the algebraic function $f(x_1,\ldots,x_n)$ on the algebraic variety
(typically a curve) in ${\bf R}^{n+2}$ specified by the following
equations on $r$, $x_1,\ldots,x_n$, and $c$:
$$
\sum_{i=1}^n x_i^2 = r^2, \quad
\forall i: \frac{\partial f}{\partial x_i} = c x_i.
$$
But by hypothesis $F(r) \neq 0$ for $r > r_0$, so there exists $N<\infty$
such that $f(r) \gg |r|^{-N}$ for large r, as claimed.
Answer: Your function $f$ is, in particular, a continuous semi-algebraic function on $\mathbf R^n$, i.e., its graph is a semi-algebraic subset of $\mathbf R^{n+1}$. Such functions are known to have sub-polynomial growth. More precisely (cf. Bochnak, Coste, Roy: Real algebraic geometry, Proposition 2.6.2, p. 43):
Let $S\subseteq\mathbf R^n$ be a closed semi-algebraic subset, and let $f\colon S\rightarrow \mathbf R$ be a continuous semi-algebraic function. Then there are $c\in\mathbf R$ and $N\in\mathbf N$ such that
$$
|f(x)|\leq c(1+||x||^2)^N
$$
for all $x\in S$.
Apply this to the inverse $1/f$ of your function on the closed semi-algebraic subset $||x||\geq A$, where $A\in\mathbf R$ is such that all zeros of $f$ have norm $<A$.
Comment: A belated thank you: found the (very informative) reference.


Is it possible to modify Adobe Air's WebKit settings in the mx:HTML component?

Question: Adobe Air's (read: Flex) mx:HTML component uses WebKit to render webpages. As such, does anyone know of a way to tweak WebKit's settings via the Air application (or a Flex API)?  For example, I'd like to set WebKit's "enable-private-browsing" setting from "false" to "true".
Answer: That would be very interesting.
Sadly, judging by the source code of the HTML component and the AIR documentation, it doesn't seem that there's any way to do so.
Maybe something to propose to the Flex/AIR team on JIRA for the next version.
Comment: I've logged a ticket here: http://bugs.adobe.com/jira/browse/SDK-25585  Let's see what happens.
Answer: Since it's not possible, I've logged a ticket here: bugs.adobe.com/jira/browse/SDK-25585  Let's see what happens.
Answer: For standalone application (e.g. stand for exhibition) you can build your own WebKit.


Tense problem. Retelling a story and asking questions

Question: I am reading a story and I need to retell it and then to ask some questions about the plot. So I don't know what tense I should use. The author himself switches from Present Simple/Continuous to Past Simple from time to time. So I am absolutely confused. Here are some extracts for you to make my question more clear:
1. It was December 21st, I am 15 and I am living through a slump.
2. I went to school. Flash forward a few hours I am sitting in the Vice Principal's office.
Thank you!
Comment: Put everything into the present. For example, _John is 15 and living through a slump. On December 21 he goes to school. A few hours later he is sitting in the VP's office because he has hit another student..._ The same applies to the questions: _What does his mother say when he gets home?_
Comment: @Shoe thank you! Is it a mistake if I put everything into the past? As far as I understand the key is to use ONE tense and not mix it with others. Is it right?
Comment: Strictly speaking, English has only two tenses: past and present. So the present simple, present continuous and present perfect are all present tenses. It is common practice to summarize a story or film in the present. (But if you are doing this as a homework assignment, it would be best to ask your teacher.)
Answer: Suit yourself!
You are re-telling it, now it is almost your story, especially if you are telling it to children and not a formal audience like in a seminar.
In general, present tense works great, combined with past tense for "flash back" segments of the story.


Tutorial on Wall Borders?

Question: There are no tutorials anywhere on how to build Wall Borders, I have a picture here that I posted, I hope someone can help and guide me through the process on how to make this on Blender 2.8.
Comment: What have you tried and where, *specifically*,  are you stuck?
Comment: https://blender.stackexchange.com/questions/146282/how-do-i-add-floor-mouldings-with-archipack-pro-in-blender-2-8
Answer: A typical way would be simply to duplicate the bottom edge of the wall, and convert it to a curve, down which you can sweep a profile of the molding.

ShiftD Duplicate the bottom edge of the wall
P separate it into its own object, and Header > Object Menu > Convert it to a curve. (The 'Path'). Make the path a 2D curve, to ensure clean miters.
Construct a profile for the molding, either as a mesh which you convert to a curve, or as a curve in the first place. (The 'Profile')

Note the orientation of the profile curve with respect to its object axes, and the position of its origin at its bottom left corner (shown with the 3D Cursor). All this can be adjusted in Edit Mode.

Now just assign the 'Profile' curve as the Bevel Object of the 'Path' curve.

You might want to convert the 'Path' curve back to a mesh when you're done, to make Auto Smooth available for it. That way, you can keep the poly count down.
Comment: .. but as @Duarte points out, if you have to do a lot of this, Archipack would be a good idea.
Answer: Start by drawing the profile of the moulding.  The profile is what it looks like from the cut end.  Fill the profile with one of more faces, then extrude that face in the direction you want.  UV map it and you are off to the races.

Tutorial on Wall Borders?


Alternating group and normal properties

Question: I am trying to look at the alternating group $A_4$ and struggling to come up with any nice proofs and was wondering if anyone could help. I am trying to prove that   $A_4$ as a subgroup of $S_4$ is a normal subgroup and that the Klein four subgroup is a normal subgroup of $A_4$. I know these can be done by multiplying out and proving left and right corsets coincide but am sure there must be a more elegant solution. Any help would be much appreciated thanks.
Answer:
Prove that $A_4$ is a normal subgroup of $S_4$.

There is nothing special about $4$ here; it is true more generally that $A_n$ is a normal subgroup of $S_n$ for any $n$. As with many questions, yours is easy enough to answer if you reformulate it correctly. We would like to show that if $\sigma$ is a permutation in $A_4$ and $\tau$ is any permutation of $S_4$ then $\tau\sigma\tau^{-1}$ is a permutation of $A_4$. Two questions:

What is the definition of $A_4$?
Does the permutation $\tau\sigma\tau^{-1}$ satisfy the definition characterizing elements of $A_4$?

Show that $A_4$ contains a normal subgroup isomorphic to the Klein four group.

Your second question is much more computational than the previous one. I recommend looking for elements of order $2$ in $A_4$, as every element of the Klein group besides the identity has order $2$.
Answer: For the first part observe that $[S_4:A_4]=\frac{24}{12}=2$ Thus $A_4$ is normal in $S_4$.
For the second part see this.

Alternating group and normal properties


How much of a benefit does a changing landing page give in terms of SEO?

Question: I have a friend with a small business with a website. He asked me if he should make a put a section on his landing page under the fold that with his most recent review (or something along those lines). Specifically, he wants to know if that's the most efficient use of his time. Is there a list or such of things google values compared to each other, so that these kinds of answers could be easily answered?
Comment: The actual "review", or a link to it?
Comment: The text of the most recent review/testemonial he has received, and a link to all of them.
Comment: Would the change affect how many people continue from the landing page or purchase the product? Would the number of people who hit the back button go down? If no and no then it sounds like a waste of time; If no and yes, it may help google; If yes and yes, then it should be done.
Answer: Based on my own experience, I see no reason why changing part of the page periodically would have any benefit to rankings. There are other, much more important factors in how/why/where a site ranks.
Certainly, it's good to have new content added to the site regularly. But just shifting around one portion of one page doesn't present any real benefit IMO.
Some of my best ranking pages historically virtually never change.
Comment: Could you provide any references to google-published documents? Could you provide any examples of more important factors?
Comment: There may or may not be an SEO benefit in changing a portion of the landing page, but there might be a benefit to users if it is relevant/new information. By _linking_ to new content from the landing page you can help search engines find the new pages - so this could have a SEO benefit.
Answer: Yes it helps
Google tracks how recently a page has been updated and distinctly favors pages that have been updated more recently (especially within the past week).  I have multiple clients who consistently rank 1st-2nd in SERPs on weeks thier home page changes, and 3rd-4th place on weeks where we forget to do that. If you are in a particularly non-competitive area, then yes as the accepted answer says, it may not be necessary, but you can't compare 1 site to another when judging the effectiveness of an SEO technique, you have to compare it to itself because each site's competition is unique.
In most cases, the difference between ranking 1st and 3rd is enough to double your organic search traffic; so, unless you are actually ranking 1st without updating content, you should be updating your content (time/budget permitting).
The important part here though is to make your changes below the fold to something low priority in Google's eyes to make sure that you are not hurting your SEO with the changes.  If you change something like the H1 header, then you could do more harm than good, but doing this as something in, or just above your footer works great to boost SERPs with minimal risk.


What is the difference between the simple past and the passive voice?

Question: I always get confused trying to explain the difference between the past tense and the passive voice. If I say something like "The gym opened yesterday" or "The gym was opened yesterday", what would the difference be? Could you say the second example draws more emphasis on the gym itself? In that case, when would it be appropriate to use one of these instead of the other? What do you think?
Comment: In the second case the "gym" didn't do anything -- it was the object of "opened".
Comment: "Opened" is a special case because it can be used transitively or intransitively with different meanings that happen to create this similarity. But if I said "The Dodgers lost yesterday" and "The Dodgers were lost yesterday" there's a pretty obvious difference in meaning.  For verbs that are strictly transitive or strictly intransitive, you can't even produce both forms without one being incorrect.
Comment: Is it that the OP wants an interpretation of these two sentences, or that he wants to know more about passive voice of past simple? As commented by @ThePhoton, the verb open can be transitive and intransitive. Someone opened the gym - The gym was opened...(by someone) Transitive.  Else, like we say, the vehicle moved, the ball rolled, the gym opened.
Answer: Aside from their names sounding alike, there's no similarity at all between past and passive.
Almost every verb in English has several forms, two tensed and two untensed:

a present tense form (used for infinitive): go, see, learn, say, fold
a past tense form: went, saw, learned, said, folded
a present participle form (used for gerund): going, seeing, learning, saying, folding
a past participle form: gone, seen, learned, said, folded

The present tense is no. 1. The past tense is no. 2. Only. That's all the tenses there are. Every main clause in every English sentence has to have a tense form (either present or past) as the first auxiliary verb (if there is one), or otherwise as the main verb. And that's all there is for the past tense.
Passive, on the other hand, is not a verb form, and doesn't have anything to do with time, present or past. Passive is a Construction, which means it's not just one thing, but a whole bunch of things done together, like driving a car involves more than just turning the wheel.
Passive is something that happens only to transitive clauses, which means the verb has a direct object. So not every sentence can have a passive form; it has to be the right kind of verb and there has to be a direct object. You don't need a specific subject -- indeed, if you are using passive, you probly don't care or even know about the subject. That's the point of the passive construction -- it focusses on the direct object by promoting it to subject in a new sentence:

(Someone) has washed the floor --> The floor has been washed.
(Someone) gave beer to the guests --> Beer was given to the guests.
(Someone) gave the guests beer --> The guests were given beer.

In each passive example, the main verb is a type 4 form, immediately preceded by a form of auxiliary be. This auxiliary takes whatever form the main verb of the original transitive clause had: present perfect in the first, and simple past in the last two.
And the nouns move around, too. The object becomes subject, the old subject usually disappears (but it can hang around in a by-phrase if you want). So there's a lot going on, which is the norm with constructions. But not with tenses. Tenses are really simple.
Comment: Things are a lot more complicated than I make them seem; and I hope I make them seem pretty complicated. But with a distinction as broad as this, I'm painting with big brushes.
Comment: +1 But the subjects of passive clauses are not always objects of their active clause counterparts, of course. They might be dummy pronouns, the complements of prepositions or even clauses.


Running multiple remote access instances of IPython with different profiles on the same port but accessed with different urls

Question: I am currently running a single instance of a notebook set up for secure remote access on port 443 (https://example.com/ipython/). I would like to allow others to have access, but not to my main notebook. Is it possible to spawn multiple instances listening on the same port but with different url prefixes (such as /ipython-school/, /ipython-shared/, etc)? (as outlined here)
Answer: No it is a general technical limitation. You cannot have multiple app listening on the same port. You will have to rely on something that act as a proxy an forward request to multiple instance that listen on localhost on different port.


Examples of non-overt mixes

Question: What are some examples of mixes you've heard that are very emotionally powerful, don't knock you out of your chair because the concept, story telling & depth of character development makes all those action based blockbusters seem like they are aimed at 12 year olds? Beautiful performances captured with equally beautiful production sound & masterful dialogue/adr editing & mix... Films that make you glad to be a human, where you leave the theatre lost for words....
Answer: No Country For Old Men did it for me when I remember seeing that for the first time.
Comment: One of my favorites too.
Comment: The sound of the dialog in No Country For Old Men is the best I've ever heard.
Answer:
Once Upon a Time in the West
PlayTime
North By Northwest
The Black Stallion
The Conversation
Apocalypse Now
2001
Das Boot
Master and Commander
Toy Story
A River Runs Through It
The English Patient
Ratatouille
No Country For Old Men
The King's Speech
The Hurt Locker

To name a few. All superb sound jobs, where the sound work/sonic choices/mix support the narrative.
Answer: I remember feeling this way about Super 8 recently, but I'd have to re-watch it to really put my finger on it.
Answer: It's a tie for me:
Star Trek -> only movie I've ever seen and my analytical sound mind never kicked in, walked out of there and days later realized I never gave a single thought to the sound.
The other is 'Runaway Jury' - fully dialogue-driven film but highly creative, outstanding performances, brilliant story.  A lot of creative futzing in there and forced sonic masking against DX and BGz, more so than the average film.  Very well done.
However, the movie that actually had me leaving the theater with a loss for words was 'Book of Eli'.
Answer: Forrest Gump and The Thin Red Line left me speechless the most. (I didn't see Forrest Gump in theaters because I was too young to see PG-13, but I left my living room speechless!....)
Social Network was superb as well.
Also, Benjamin Button was extremely well done and I was thinking about that movie for days afterwards.
Answer:
Elephant
Uncle Boonmee
Let's Talk About Kevin
No Country For Old Men
Answer: True Grit was one for me among many others mentioned here. I really enjoy the work of Skip Lievsay, Craig Berkey and Greg Orloff, quite inspiring and cinematic while keeping things fresh and real if I may say so
Answer: Steve McQueen's 'Shame'
(you might be lost for words for other reasons with this one though.. )
Tinker, Tailor, Soldier, Spy
Answer:
no country for old men
district 9
ratatouille
the king's speech
the american
house of flying daggers
symbol
ip man
good will hunting

I'm positive I'm missing a few good horror and suspense flicks in there.
IMO asian cinema has always had a culturally important direct line to minimalism and emotion that puts them at the head of the pack wrt subtlety and meaning in a mix.  I'm positive i've missed dozens of great asian flicks in my list as well, but this was just off the top of my head.
I also believe that only in the last 20 years or so has the technology of sound reached the point to where that kind of a mix can be achieved consistently.  The old westerns used to take valiant swings at these types of mixes, but the limitations of the technology of the time sets the true emotional impact behind that of modern films that are on the same level creatively in my opinion.  I think this is because at the time you really had to crush the nagra with level when recording dialogue, and now that this is no longer the case you have much more low level space in which to play.
Answer: I´ve recently seen The Steam of Life, a finnish documentary that sounds really natural and. I liked  Magnolia and Morvern Callar (some mentioned We need to talk about Kevin) mixes too.
Answer: These are to my opinion the best three mixes and movies from europe in this category:

Katalin Varga : http://www.youtube.com/watch?v=8PTjObn2W5I
Can get trough skin : http://www.youtube.com/watch?v=F5iohh7c698
the Misfortunates: http://www.youtube.com/watch?v=5q5yH0P5oZw
Answer: Syndromes and a Century

Examples of non-overt mixes


Why do criminals always leave the front door ajar so cops can easily detect something is wrong?

Question: Why does it seem like in every cop based TV drama (CSI, Law and Order, etc.) that whenever something bad has happened that the front door is always left open or slightly ajar?  Do criminals not realize that this is a tip for cops to know something is wrong?
Comment: They also always run away when they see cops. Or they shoot at them or fight them. You know, like normal people do. (Wha...?)
Comment: Why do TV computers emit beeps when printing a message to the screen?  Why do TV combination locks make a clicking sound?  Answer: because TV-watchers are really stupid!
Answer: TvTropes calls this the OminouslyOpenDoor and files it as a death trope, meaning that usually the investigator will find a dead suspect or witness in the room:

The good guys are having a hard time finding a lead for the current investigation. They find a possible culprit or a vital link in the investigation. The team gets an address and find the door slightly open.
  Too bad whoever they find behind that door, be it a suspect, relative or complete stranger, can't help them close the case.

There are two sides to this:
In-universe explanation aka: Why would they leave the door open?
Of course this does not always make sense and quite often this is simply illogical behaviour from the bad guys.
However there are some valid reasons why the door would not be shut:

It won't stay shut anymore. The bad guy broke in, but not by lockpicking. Instead, he used brute force and damaged either the lock or the whole door. Now it won't close anymore, making anyone looking at the door aware that something fishy is going on.
They just don't care. The bad guy is long gone, leaving behind a major mess or even a dead body. (see above) He does not really care if anybody notices the scene of the crime because he thinks that no incriminating evidence was left behind or because he is already on the run.
They had to leave in a hurry. The bad guy simply had no time to clean up and close the door properly. Either he was disturbed and had to get away, or he is still on the scene and had to hide when he saw the investigator arrive.

Analytical point of view aka: What is the purpose of the scene?
Even if there is a valid plot explanation for the scene, this is still mainly used as a device by the director to build up tension. The investigator usually arrives at the door with the motive to speak to someone. Sometimes this happens at his own door when he comes home.
Before the ajar door is noticed, normally there is little to no suspense. Often two characters will be talking casually until they see the door.
Then suddenly: Excitement!
Something is wrong - this door should not be open! The viewer gets drawn into the action and knows that a surprise must be lurking behind this door. So basically the door acts as a gateway between different atmospheres and is used to quickly change the pace of the episode.
Comment: +1 but also if the door wasn't ajar, then upon getting to the door, knocking, not getting an answer... All they could then do is leave (after all, most of the time they were just going to talk to someone). By having the door open, there is reasonableness (in TV sense) to assume something is wrong and to enter. In the real world, it could just mean the person left it open while taking the shopping in!
Comment: @Madivad: A cop who encountered an open door would be reasonably entitled to investigate why it is open (they'd be even more entitled if they would respect what IIRC Miss Manners referred to as the "invisibility principle").  A full search would not be justified in the absence of real evidence of wrongdoing, but having the door open can set in place a chain of progressive discoveries that each justify further inquiry.
Comment: One more possible in-universe explanation is that leaving the door ajar might be quieter than closing it, thus making a distinctive noise if there are others in the house. Not always relevant, though.
Comment: +1 - I almost saw my worst fears with this question fulfilled when seeing the TVTropes link, but apart from that this really goes to great lengths to provide an actual answer.
Comment: Yeah, I was really surprised how short the tvtropes entry is, considering how common this trope is. I also don't quite agree with the article in that it's not always death-related. Sometimes the trope is even subverted for comic effect (e.g. instead of a dead body a surprise party waits behind the door)


Heegard genus of hyperbolic Haken 3-manifolds

Question: Is there an example of a closed Haken hyperbolic 3-manifold of Heegaard genus 2?
Comment: Try 0-surgery on some hyperbolic knots of tunnel number > 1 and genus > 1.  KnotInfo will give a list (http://www.indiana.edu/~knotinfo/), then check with SnapPy.  For example, SnapPy reports that 0 surgery on 6_2 is hyperbolic.
Comment: @KenBaker: I think you mean tunnel number =1?
Comment: @VandersonLima:   From [indiana.edu/~knotinfo](http://www.indiana.edu/~knotinfo/), click on Advanced Search then set Tunnel Number = 1, Three Genus > 1, and Volume > 0 before hitting submit. That should return a list of 135 knots.
Comment: @IanAgol:  Yes, of course.  That's a typo.   And indeed 6_2 has tunnel number = 1.
Comment: Thank you very much. But how i find this Knot on this link you posted?
Comment: http://www.ams.org/journals/bull/1990-23-01/S0273-0979-1990-15910-5/S0273-0979-1990-15910-5.pdf
Answer: Even better, there are hyperbolic surface bundles with Heegaard genus two.  These are all described in Jesse Johnson's paper, titled Surface bundles with genus two Heegaard splittings.  You will need to use some criterion to recognize pseudo-Anosov maps, however.
Comment: Thank you for the answer. These are very nice examples indeed.
Comment: @VandersonLima - After seeing your comment, I thought to check KnotInfo.  It says that 57 of the 135 knots (as in Ken Baker's comment) are fibered.  Jesse's construction will give you infinitely more examples of the kind you asked for, but they won't all be fillings of knots in the three-sphere.
Answer: I found other examples in the literature.
In http://link.springer.com/article/10.1007%2FBF02110720, A. Yu. Vesnin and A. D. Mednykh proved that the Fibonacci manifolds F_{n} have Heegaard genus 2, for n > 2. It is known that for n > 3 these manifolds are hyperbolic.
Moreover the results in http://journals.cambridge.org/action/displayAbstract?fromPage=online&aid=2093944&fileId=S0305004100063465, by María Teresa Lozano and Józef H. Przytycki,
and http://msp.org/pjm/2000/194-2/p13.xhtml, by Kevin P. Scannell,
imply that for n > 5, the manifolds F_n are Haken.
So, this gives infinitely many examples.


Freeze User who is logged in

Question: If I freeze a user and if he is already logged into Salesforce, does he lose access? Or can he access it as long as he doesn't logout?
Comment: you could just deactivate the user and then reactivate again, thus forcing a new SessionId and then freeze the user.
Comment: This particular scenario is not documented clearly. I will think the best way to confirm this is to test it out.
Comment: @akarnid the reason I didn't deactivated is because there are certain processes I need to follow before deactivating. So I freezed the user in the meantime. However, I don't want the user to access Salesforce while frozen.
Answer: Based on a quick test in my DE Org, if an admin Freezes a User while the User is already logged in and accessing Salesforce, the User session is immediately terminated. The User cannot navigate to any other page/tab within the application once Frozen. The User is presented with a message as below.

Incorporating @sfdcfox's comment: The behavior is same if a User is deactivated.
Comment: Same behavior if you deactivate the user, too.
Comment: Good to know, will add your feedback in the answer to make it more comprehensive.
Answer: Salesforce checks the session's validity with every transaction. This means that if the user tries to continue working outside their Login Hours, while Frozen or deactivated, or if the IP address changes and "Lock session to IP address" changes, they will not be able to access Salesforce. There's no way to continue using a session if you're not allowed in the system for any security policy.

Freeze User who is logged in