Unable to tap into the mongo shell using the "mongo" command

Question: Seeing this message when I hit the "mongo" command on the terminal :
"/c/Program Files/MongoDB/Server/6.0/bin/mongo.exe: No such file or directory"
It is true that mongo.exe is not present at that location. But MongoDB version 6.0 and newer apparently do not have the legacy mongo.exe file. So, in spite of a successful installation, I do not have a mongo.exe file.
In such a case, how do I tap into the shell ? Please note that the commands "mongos" and "mongosh" are not working (command not found). mongos.exe is present at the location (/c/Program Files/MongoDB/Server/6.0/bin) though.
Answer: Yes MongoDB version 6.0 and above don't have mongo.exe file. Command is mongod. After installing msi file you need to install MongoDB Shell . Go through this link which have step by step guide to install MongoDB.
https://hevodata.com/learn/windows-mongodb-shell/


matrix multiplication: $A^2 = A$?

Question: I am supposed to think something geometrically and come up with a matrix $ A $ that has no $0$ on it and satisfies the condition $A^2 = A$.
On a similar type of problem where I had to satisfy $A^4 = I$ when $A^2$ is not $I$, I used the rotation through the coordinate system as any matrix would come to itself after $4$ rotation i.e. through $90$ each time.
Is it something similar in this case as well?
// Here I thought maybe I can use reflection through $y=x$ axis twice but that didn't really work as I can't get $2  \times  2$ matrix.
Comment: The 'ideal' MathJax command for matrices is `\boldsymbol{}`.
Comment: @ChaseRyanTaylor: You really don't need to set matrices in bold. If you want to distinguish them from vectors or scalars, the case distinction is enough.
Comment: @anomaly Yeah, that's why I didn't suggest an edit and why I put 'ideal' in single quotation marks. Normally I share that tidbit, because that's what APA stylistic guide (I believe it's that one) recommends, and also because I've seen uppercase vectors and lowercase matrices.
Comment: Yeah, it's not a big deal either way. My main problem with it is that bold looks ugly. :)
Answer: This intuitively means that "doing it again" doesn't do anything new.  One geometrical example is:  Projecting onto a line.  If you take your space and map each point to a line, then if you do it again they're all still just on that line.

matrix multiplication: $A^2 = A$?


worldpay setup with spree

Question: I am trying to setup WorldPay with spree, I have created sandbox account also but could not found from where I found below details
INSTALLATION:
AMERICAN EXPRESS LOGIN:
DISCOVER LOGIN:
JCB LOGIN:
MASTERCARD LOGIN:
MAESTRO LOGIN:
VISA LOGIN:
please help if someone already setup this with the spree
Answer: I had the same issue, and my problem was that I was trying to integrate with Worldpay Online (not regular old Worldpay).
In the end I created my own gateway (very basic with only the options I needed, but you could extend this to add the functionality that you want):
class Spree::WorldpayOnlineGateway < Spree::Gateway

    preference :client_key, :string
    preference :service_key, :string

    def provider_class
        ActiveMerchant::Billing::WorldpayOnlinePaymentsGateway
    end

    def payment_source_class
        Spree::CreditCard
    end

    def purchase(money, credit_card, options = {})

      options[:client_key] = self.preferred_client_key
      options[:service_key] = self.preferred_service_key

      provider = provider_class.new(options)
      provider.purchase(money, credit_card, options)

    end

end

Then in your spree.rb initializer, add the gateway:
config = Rails.application.config
config.after_initialize do
     config.spree.payment_methods << Spree::WorldpayOnlineGateway
end

worldpay setup with spree


How can I understand when hook_form_alter() is called?

Question: In Drupal 8, hook_form_alter() is invoked multiple times: at page load, submission, after executing custom submission handlers, and back to form action.
How can I see at which stage hook_form_alter() is invoked?
Answer: The lifetime cycle of a form and its stages depends on whether the form is rebuilding and using Ajax. Most times you react then on the form action you find in:
$form_state->getTriggeringElement()
The two different calls between page load and before the first submit is because the original form build is not cached and then has to be built the same way as the first one. Normally you don't care and alter the form build the same way for each call. If you need to make a distinction between both calls you find the raw submitted values in $form_state->getUserInput()


Unstable Camera behaviour on Android

Question: I'm writing the camera application. I've started with using android.hardware.Camera and corresponded classes. But from time to time my application failed to connect to the camera. It depends on device model and Android version. But if application works on some device fine, after a day or two it start to failing. One more thing that I noticed - if my app fails to connect then build-in camera app fails to connect too.
I read almost all post related to Camera API and related exceptions on stackoverflow and decided to replace my code with CommonsGuy's library https://github.com/commonsguy/cwac-cam2. And, unfortunately, fails are still exists.
I discovered that after fail I can use Camera API again only after device reboot.
So I want to ask is it possible to do something programmatically for making possible to use camera again without rebooting device? Maybe there is a way to kill Camera Service or upload native Camera code?
Example of fail (Nexus 4, Android 5.1):
Fatal Exception: java.lang.RuntimeException: Fail to connect to camera service
   at android.hardware.Camera.<init>(Camera.java:497)
   at android.hardware.Camera.open(Camera.java:342)
   at com.commonsware.cwac.cam2.ClassicCameraEngine$1.run(ClassicCameraEngine.java:78)
   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
   at java.lang.Thread.run(Thread.java:818)

Comment: On a rooted device, it's trivial to kill the MediaServer. On non-rooted device, there is no known vulnerability that could force its restart, at least nothing that will work across all ROMs and models.
Comment: Release the camera in different cases like changing front to back or vise-versa, onDestroy() method etc. Do some code: `mCamera.stopPreview(); mCamera.release();`
Comment: i also face this issue in my phone because of broken front camera connector. where the solution was to reboot the device while pressing camera connector part
Comment: If this happens with your app more often than with the built-in Camera app, then your code has some bug, not releasing the camera when necessary. There may be some tricky thread collisions when the app stops, and it is easy to lose track of the camera.
Answer:
So I want to ask is it possible to do something programmatically for making possible to use camera again without rebooting device?

No, sorry.
Answer: check this ref: http://developer.android.com/training/camera/cameradirect.html
try this code:
try
{
    releaseCameraAndPreview();
    if (camId == 0) {
        mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
    } else {
        mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
    }
}

catch(Exception e)
{
    Log.e(getString(R.string.app_name), "failed to open Camera");
    e.printStackTrace();
}

Then add this function somewhere:
private void releaseCameraAndPreview() {
    myCameraPreview.setCamera(null);
    if (mCamera != null) {
        mCamera.release();
        mCamera = null;
    }
}

Unstable Camera behaviour on Android


Should we use train, validation, or test data when creating PR/AUC curves to optimize the decision threshold?

Question: It makes sense to me that we can use the ROC-AUC and PR-AP scores of the validation sets during CV to tune our model hyperparameter selection. And when reporting the models final performance, it makes sense to create a PR or ROC curve on the test data set to illustrate performance on unseen data. But in terms of selecting a decision threshold for the model probabilities, does it make the most sense to create the PR/ROC curve(s) from validation data during CV, or from test data after the final model is already tuned via CV? We generally try to avoid that the test data affects how the model is created/tuned, but the decision boundary is not technically part of the model's hyper-parameters (as elaborated on in Is decision threshold a hyperparameter in logistic regression?), so is it fine in this case and this would not count as test data leakage?
This question is similar to threshold choice for binary classifier: on training, validation or test set?, but specifically about creating the PR/AUC curves where the suggested approach in that answer would not lead to the creation of a PR/AUC curve. It is also similar to the question Why ROC Curve on test set?, but that does not explicitly address why this is not considered test data leakage (which would lead to an overly optimistic evaluation)
Answer: Use training data to choose the threshold.

selecting a decision threshold ... from test data ?

No.
We train a model to learn the shape of the data.
We choose a classification decision threshold to express how
we value precision versus recall,
and that threshold plays a large role in measured
performance of the business use case once the model is deployed.
It is a model parameter.

We generally try to avoid that the test data affects how the model is created / tuned ...

That's right.
We're training a classifier that should generalize,
that should perform well on tomorrow's unseen data,
and the next day after that.
Using test data to choose the parameter is cheating.
We use test data to evaluate the trained model, full stop.
Let me quote from Abu-Mostafa, et al., "Learning From Data",
§5.3:

Data snooping is the most common trap for practitioners in learning from data.
The principle involved is simple enough,
If a data set has affected any step in the learning process,
its ability to assess the outcome has been compromised.
Applying this principle, if you want an unbiased assessment of
your learning performance, you should keep a test set in a vault
and never use it for learning in any way.

Or, if you do peek into the vault,
there should be another vault available with
additional unseen data for next week's tuning.
Or you should be able to collect fresh data,
perhaps via daily collection of transaction logs.
Comment: Thank you for the reply! It makes sense to me to not look at the test data at all, not even for the decision boundary. One thing that has me confused with the approach of using validation data, is if we create one PR/ROC curve per CV fold and then average them, or concatenate all the predictions and then create a single PR/ROC curve to choose the threshold. Since every fold can be thought of having its own model, I'm not sure about the best way of aggregating them (although the hyperparams are the same per fold, the regular params vary as the model learns from the data)
Comment: [This post](https://stats.stackexchange.com/questions/34611/meanscores-vs-scoreconcatenation-in-cross-validation) and the linked paper in one of the answers argues that is shouldn't matter much and that if anything the concatenated CV set is better.

So I guess something like [this example in sklearn](https://scikit-learn.org/stable/auto_examples/model_selection/plot_cv_predict.html#sphx-glr-auto-examples-model-selection-plot-cv-predict-py), but for the PR/ROC curve, would you agree with that?
Comment: I agree with that.


Geometric Algebra Grade Projection

Question: I was reading through the book Geometric Algebra for Physicist, and, although I find it pretty useful, there are steps that I find missing and haven't been able to find in any other GA books.
I was hopping someone could explain the steps to me:
The equation (3.126) states, $x$ is a vector and $A,B$ are bi-vectors:
$$ A ·(x\wedge(x·B))=\langle Ax(x·B) \rangle = \langle (A·x)xB \rangle=B·(x\wedge(x·A)) $$
In equation (4.154), $f_{1,2}$ are vectors and $A_r,B_r$ are $r$-blades:
$$ \alpha \langle A_r(B_r·f_1)\wedge f_2\rangle =\alpha \langle f_2·A_rB_rf_1\rangle$$
Could someone explain with detail the steps followed?
Best regards.
Answer: For the first decomposition,
since $ x \cdot B $ is a vector, $ x \wedge ( x \cdot B ) $ must be a bivector (grade 2).  The product of the bivector $ A $ with another bivector is a multivector with grades that may include 0, 2, 4, and the dot product of those two is the grade-0 selection.  That is
$$\begin{aligned}   A \cdot \left( { x \wedge (x \cdot B) } \right)   &=   \left\langle{{ A \left( { x \wedge (x \cdot B) } \right) }}\right\rangle \\    &=   \left\langle{{ A \left( { x (x \cdot B) - x \cdot (x \cdot B) } \right) }}\right\rangle.\end{aligned}$$
Here we used $ x y = x \cdot y + x \wedge y $, which leaves us a with a scalar factor $ x \cdot (x\cdot B) $, that has no contribution to the grade-0 selection, which leaves us with
$$\begin{aligned}   A \cdot \left( { x \wedge (x \cdot B) } \right)   &=   \left\langle{{ A x (x \cdot B) }}\right\rangle \\    &=   \left\langle{{ (A \cdot x) (x \cdot B) }}\right\rangle \\    &=   \left\langle{{ (A \cdot x) (x B - x \wedge B) }}\right\rangle \\    &=   \left\langle{{ (A \cdot x) x B }}\right\rangle.\end{aligned}$$
Here we made use of the fact that $ A x = A \cdot x + A \wedge x $, a vector and trivector, of which only the vector component contributes to the scalar selection.  Then we are free to rewrite $ x \cdot B $ in terms of $ x B $ and a trivector that also has no contritution to the scalar selection.  The final result follows from the fact that reversion of a scalar leaves it unchanged, so
$$\begin{aligned}   \left\langle{{ (A \cdot x) x B }}\right\rangle   &=   \left\langle{{ B x (x \cdot A) }}\right\rangle \\    &=   B \cdot \left( { x \wedge (x \cdot A) } \right),\end{aligned}$$
where we are able to use the very first step to write the scalar selection back in terms of dots and wedges.
The result of 4.154 probably requires similar logic.
Comment: That scalar factor is $x\cdot(x\cdot B)=(x\wedge x)\cdot B=0$.

Geometric Algebra Grade Projection


legitimacy of the tasks in the task scheduler

Question: Is there a way to know the source and legitimacy of the tasks in the task scheduler in windows server 2008 and 2003? Can I check if the task was added by Microsoft (ie: from sccm) or by a 3rd party application?
For each task in the task scheduler, I want to verify that the task has not been created by a third party application. I only want to allow standards Microsoft Tasks and disable all other non-standards tasks.
I have created a PowerShell script that goes through all the xml files in the C:\Windows\System32\Tasks directory and I was able to read all the xml task files successfully but I am stuck on how to validate the tasks.
Here is the script for your reference:
Function TaskSniper()
{
   #Getting all the fils in the Tasks folder
   $files = Get-ChildItem "C:\Windows\System32\Tasks" -Recurse | Where-Object {!$_.PSIsContainer};
   [Xml] $StandardXmlFile = Get-Content "Edit Me";

   foreach($file in $files)
   {
       #constructing the file path
       $path = $file.DirectoryName + "\" + $file.Name

       #reading the file as an XML doc
       [Xml] $xmlFile = Get-Content $path

       #DS SEE: http://social.technet.microsoft.com/Forums/en-US/w7itprogeneral/thread/caa8422f-6397-4510-ba6e-e28f2d2ee0d2/
       #(get-authenticodesignature C:\Windows\System32\appidpolicyconverter.exe).status -eq "valid"

       #Display something
       $xmlFile.Task.Settings.Hidden

   }

}

Answer: Legitimacy sounds vague.
If by source you are referring to the Author, that is available in the Principals node:
$xmlFile.Task.Principals.ChildNodes

id                                      GroupId                                 RunLevel
--                                      -------                                 --------
Author                                  S-1-5-32-545                            LeastPrivilege

An alternative approach may be to audit when and who creates a scheduled task.  Hera are the Security event id's for Windows 2008 R2:
4698    A scheduled task was created.
4700    A scheduled task was enabled.
4702    A scheduled task was updated.


net c# lock statement in data access layer

Question: I saw a code where they have the data access layer like this:
public class CustomerDA{

    private static readonly object _sync = new object();
    private static readonly CustomerDA _mutex = new CustomerDA();

    private CustomerDA(){
    }

    public CustomerDA GetInstance(){

        lock(_sync){
            return _mutex;
        }
    }

    public DataSet GetCustomers(){
        //database SELECT
        //return a DataSet
    }

    public int UpdateCustomer(some parameters){

        //update some user
    }

}

public class CustomerBO{

    public DataSet GetCustomers(){

        //some bussiness logic
        return CustomerDA.GetInstance().GetCustomers();
    }
}

I was using it, but start thinking... "and what if had to build a facebook like application where there are hundreds of thousands of concurrent users? would I be blocking each user from doing his things until the previous user ends his database stuff? and for the Update method, is it useful to LOCK THREADS in the app when database engines already manage concurrency at database server level?"
Then I started to think about moving the lock to the GetCustomers and UpdateCustomer methods, but think again: "is it useful at all?"
Edit on January 03:
you're all right, I missed the "static" keyword in the "GetInstance" method.
Antoher thing: I was in the idea that no thread could access the _mutex variable if there was another thread working in the same data access class. I mean, I thought that since the _mutex variable is being returned from inside the lock statement, no thread could access the _mutex until the ";" was reached in the following sentence:
return CustomerDA.GetInstance().GetCustomer();
After doing some tracing, I realize I was making the wrong assumption. Could you please confirm that I was making the wrong assumption?
So... Can I say for sure that my Data Access layer does not need any lock statement (even on INSERT, UPDATE, DELETE) and that it does not matter if methods in my DataAccess are static or instance methods?
Thanks again... your comments are so useful to me
Comment: Wherever you saw that code, don't ever look there again. This is simply bad code. Ignore it.
Comment: I think the one who wrote the code meant to have a singleton of CustomerDA.  The lock at GetInstance() isn't really necessary because _mutex is readonly.  You won't be blocked when you are running the SQL statements because there is no lock at GetCustomer() and UpdateCustomer().
Answer: The lock in that code is completely pointless. It locks around code that returns a value that never changes, so there is no reason to have a lock there. The purpose of the lock in the code is to make the object a singleton, but as it's not using lazy initialisation, the lock is not needed at all.
Making the data access layer a singleton is a really bad idea, that means that only one thread at a time can access the database. It also means that the methods in the class have to use locks to make sure that only one thread at a time accesses the database, or the code won't work properly.
Instead, each thread should get their own instance of the data access layer, with their own connection to the database. That way the database takes care of the concurrency issues, and the theads doesn't have to do any locking at all.
Comment: I'm not sure I agree with much of this. There are quite a few assumptions. A singleton for a DAL doesn't mean it can't use a connection pool to allow multiple threads concurrent connections. Not to mention the code doesn't look transcribed properly. GetInstance() should be static but isn't. They either thought the lock would only allow one user access to the database, or it used to be a incorrect implementation of Double-Checked Locking to ensure only one instance was created ever.
Comment: @Andrew Finnell: Yes, a singleton class with a connection pool would also work, but from the description in the question it doesn't sound like there is anything like that at present.
Answer: Set your lock where it is needed, so where concurrent accesses happen. Put in only as much code inside lock/critical section as much really need.
That GetInstance shouldn't be static ?
the following pseudo code explains how GetInstance operates:

LOCK
rval = _mutex
UNLOCK
Return rval

_mutex is readonly, refers to a non-null object, so it can't be changed, why lock ?
If your database provides concurrency management, but in your program you create two thread writing the same data in the same time in your own domain while waiting for the data,
how could your database help ?
Comment: What do you mean with the last part of your answer (how could database help if there are 2 threads writing same data at the same time)? So, is it a good idea if I take the lock to the method level? something like: "public int UpdateCustomer(){lock{ //some code here }}"
Comment: Do not think in this way :"I am locking things always here". For example if you want to use only one connection to database due to memory spare purposes, you have to lock only that statements, which are using that connection, not others. Always sink the locks to as deep function level as you can, and do not lock statements, that can run in the same time. "public int UpdateCustomer(){ /*local computings*/ .. lock{ /*using global variables, calling non-thread safe functions of global objects, etc. */ } /*more local computing*// } }"
Comment: So again in general: narrow locks as much as possible! if you think you cant go deeper, ask yourself which statements would cause interference in that function call. then go inside that function, and repeat. you will reach a point (like file.write(a) and write is in a library), when you cant narrow more. you see the point ? this is a good tactic to avoid some deadlocks, cause you release immediatly locked objects, so noone have to wait for an unnecessary lock). this 3 thing must strictly follow each other: 1)LOCK 2)GET_DATA_FROM_LOCKED 3)UNLOCK_IMMEDIATELY
Comment: Ok, I removed the lock from the GetInstance method, and I understand that I can take the lock to the UpdateCustomer level when needed... Do you think that "Making the data access layer a singleton is a really bad idea"? Should I remove the singleton and return a new instance each time? or maybe I should remove instances at all and call static methods like "CustomerDA.GetCustomers()"?
Comment: Static and singleton in your case is equal. The reason we prefer singleton is that its lifetime is simpler to handle, and avoiding satic/global data as much as possible makes your code easier to maintain. If you want to store informations about every connection, like username,password,time of connection,permission, etc., then use new instances. I wouldn't say that using a singleton as data access layer is always a bad idea, but if you want to think about the future and to make modifications later in your code, then separate the database accessor and the client data.
Comment: This is a good way to go: Create lightweight connector object for every new request. From these objects call the singleton methods, which handles the connections to the database, therefore you can limit for example the maximum connections. If you know memory pools, this singleton would do something similar like those. With this solution you can also easily use more databases in the same time. The clients should not know about the structure of the database, from their point it can be either a text file, an MDB file or an SQL database, put the database handling inside the singleton.


Is it invalid to adjust my independent variable based on a regression model fit?

Question: I have a dataset and I want to visualize the relationship between Outcome and Variable1, after adjustment for Variable2 and Variable3.  So I've created a linear model in R to obtain fitted values based on Variable2 and Variable3:
model   <- lm(Outcome~Variable2+Variable3, data=dat)
fitted  <- model$fitted.values
average <- mean(dat$Outcome)

Where fitted is the model fit values, and average is the overall average value for my Outcome.  I can then create adj.Outcome like so:
adj.Outcome <- Outcome*(average/fitted)

Am I doing something invalid here?  This makes sense to me but I cannot find a reference anywhere.  I realize the adj.Outcome values don't have a real tangible meaning per se, but I think a plot of adj.Outcome vs. Variable1 would show the relationship I'm interested in.
Answer: In a simple linear regression with just one predictor variable, the visualization is easy to do with a scatterplot. When you have two predictors, such a graph has to move to three dimensions and creates challenges when it comes to visualization, but there are good software packages for doing 3D plots. Then there are serious issues when it comes to visualization when you have many predictor variables, so some alternative must be developed.
While it might be viable to plot your points in three dimensions to examine for patterns and strength of a relationship, even that can be challenging compared to the 2D case. However, a plot of interest to you might be a scatterplot of the true and predicted outcomes. This exists in just two dimensions. However, the predictions contain information about how all of the predictors work together to make a prediction. Despite the fact that correlation between true and predicted values has some serious issues, such as those I discuss here and demonstrate visually here, seeing a strong relationship between the true and predicted value is a good sign that you have captured something about the relationship (subject to all the usual caveats in predictive modeling related to overfitting).
For instance, in the graph below, it is easy to tell which model captures a stronger relationship between the predictor variables and the observed outcomes. If you modify my code, you can do this same kind of plot with hundreds (or more) of predictor variables, and you still would get a visualization in two dimensions.

library(ggplot2)
set.seed(2023)
N <- 500
x1 <- runif(N)
x2 <- runif(N)
y <- x1 + x2 + 7*x1*x2
L1 <- lm(y ~ x1 + x2)
L2 <- lm(y ~ x1 + x2 + x1:x2)
d1 <- data.frame(
    predictions = predict(L1),
    observations = y,
    Model = "No Interaction Term"
)
d2 <- data.frame(
    predictions = predict(L2),
    observations = y,
    Model = "With Interaction Term"
)
d <- rbind(d1, d2)
ggplot(d, aes(x = predictions, y = observations, col = Model)) +
    geom_point()


Integrating Qt Framework, Netbeans IDE, Visual Studio C++ Compiler

Question: I'm using Qt 4.7.4 as C++ framework, Netbeans 7.0 as IDE and MinGW as C++ compiler.
These are integrated well due to Netbeans ability and I'm coding my projects with them easily.
I know in Qt Creator, we can switch to Visual Studio as C++ compiler very easy.
But, how can we use Visual Studio as C++ compiler in Netbeans which works with Qt framework?
Is there any Netbeans plugin or some configuration for it (then, Only F6 to run)?
Note: As mentioned in comments (Cat Plus Plus), it's related to QMAKESPEC or -spec. and i'm searching for a solution via Project > Properties > Qt > ...
Comment: If the integration means it's using `qmake`, then it's a matter of choosing another makespec (via -spec or QMAKESPEC environment variable).
Comment: As Cat says, qmake is the way to go.  I would point out that you don't want to compile with Visual Studio, it's Visual Studio's C++ compiler which you're after ([see this link](http://msdn.microsoft.com/en-us/library/f35ctcxw(v=VS.100).aspx) for options available)
Answer: You might try using qmake -spec win32-msvcXXXX where XXXX is from {2003, 2005, 2008, 2010} and matches your version of Visual Studio.
I would, however, expect that you will have to rebuild Qt for Visual Studio.  The MingW libraries will not work with Visual Studio.  The answers to How to Build Qt for Visual Studio may help here.  [I freely admit to never trying this.]


Conditional probability calculation

Question: This is a homework question about probability that I do not understand, even after discussing it with my teacher. I understand the correct answer, but don't understand why my answer is wrong.
A company buys rejected devices from two manufacturers. 60% of the devices are made by manufacturer A, 40% are made by manufacturer B. 10% of A's devices are defective. 30% of B's devices are defective.
A new shipment arrived. Due to sloppy handling, we don't know which device comes from which manufacturer.
We take a sample of 20 devices. They are tested thorougly. 2 devices are defective.
Question: What is the probability of finding two defects if we don't know who the manufacturer was?
My answer: general probability of finding a defect is $0.6\cdot0.1 + 0.4 \cdot 0.3 = 0.18$. Probability of finding two defects in a sample of 20 is then $\binom{20}{2} \cdot 0.18^2 \cdot 0.82^{18} = 0.1730$
This is not correct. The correct answer is to first find the probability of two defects when we know that the devices are made by A ($0.2852$) or B ($0.0278$). We then do $0.6\cdot 0.2852+0.4\cdot 0.0278=0.18224$.
I would like to understand why my method is wrong, what my error in thinking is.
Answer: Your method would be correct if (assumes that) each of the 20 devices in the sample could be from either manufacturer, independently of all the others in the sample, i.e., that the number of devices from manufacturer A is Binomial with parameters 20 and 0.6, with the remaining devices being from manufacturer B.
Based on the "correct" answer, it is apparently the case, although not explicitly stated, that all 20 devices in the sample are from the same manufacturer (A or B). I.e., with probability 0.6, all 20 are from manufacturer A, and with probability 0.4, all 20 are from manufacturer B.
Comment: But the question actually states: "Due to sloppy handling, we don't know which device comes from which manufacturer". Why would a random subset of 20 samples all happen to be from the same manufacturer?
Comment: That's why I wrote 'Based on the "correct" answer, it is apparently the case, although not explicitly stated ...'  I.e., there seems to be an assumption that the entire shipment, form which 20 devices are selected, is from a single manufacturer, we just don't know which manufacturer. I grant you that it is a sloppily written question, requiring you to use the answer to determine what the complete problem statement (assumptions) must be.
Comment: You'll notice I put correct in quotes.
Comment: Yes I noticed it. My comment was not meant as a critique but rather to highlight that the wording of the question actually gives enough reason to assume the contrary.
Comment: Aaaah! Thanks so much, this has been bugging me for days. English is not my native language and I translated the question. The original question is (in hindsight) clear about this assumption. I do wonder now if technically the answer is wrong because the conditional probabilities are calculated with the binomial formula, but this is a finite population and we explicitly learned that if n=10N n is not big enough to assume it doesn't matter (n should be > 10N). So, shouldn't P(2D|A) be 20*0.1^2*0.9^18+19*0.1*0.9^18=0.3152 instead of 0.2852?
Comment: Binomial probabilities apply to finite populations, and only to finite populations.
Comment: Of course, thanks again! What I meant was that it seems to me that this is a without-replacement situation.

Conditional probability calculation


How to create a reference to the base service methods?

Question: I have service classes hierarchy like this:
base service:
[ServiceContract()]
public interface IServiceBase
{
    [OperationContract]
    void BaseMethod();
}

public class ServiceBase : IServiceBase
{
    public void BaseMethod()
    {}
}

service A:
[ServiceContract()]
public interface IServiceA : IServiceBase
{}

public class ServiceA : ServiceBase, IServiceA
{}

service B:
[ServiceContract()]
public interface IServiceB : IServiceBase
{}

public class ServiceB : ServiceBase, IServiceB
{}

On the client side I create two proxy classes for ServiceA and ServiceB through Visual Studio's "Add service reference" tool:
ProxyA proxyServiceA;
ProxyB proxyServiceB;

These are references on TWO DIFFERENT SERVICES (although with a base class on the server side).
I want to call methods from the BaseService through these proxies in identical way. For example I want to pass these proxies as a parameter to a method and call its BaseService method, like this:
// somewhere on the client side
WorkMethod(proxyServiceA);
WorkMethod(proxyServiceB);

// Something like this, BUT I DON'T REALLY KNOW WHAT TYPE OF PARAMETER TO USE
void WorkMethod(ProxyBase proxyBase)
{
    proxyBase.BaseMethod();
}

But how to do it, what type of parameter to use (remember that these proxies are different classes without BaseService common ancestor)?
In another words, on the server side it is known that ServiceA and ServiceB has a common ancestor and it is possible to call a base method, but how to do it on the client side?
Is it possible to obtain some class on the client that is recognized as a base class for these two proxies? (except System.ServiceModel.ClientBase of course)
Comment: The problem is almost the same as in [this case](http://stackoverflow.com/questions/3422567/wcf-service-inheritance) - creating a base proxy that implements the base service.
Answer: You need to use ServiceKnownTypeAttribute Class. The KnownType attribute allows you to designate acceptable subclasses for the data contract (Your base service). This sample show how it use. Whithout KnowType you will always get exception like

CommunicationException was unhandled

[DataContract]
[KnownType( typeof( Student ) )]
[KnownType( typeof(Teacher) )]
public abstract class BaseService
    {
        [DataMember]
        public int Code { get; set; }

        [DataMember]
        public string Name { get; set; }
    }
[DataContract]
public class Student : BaseService
    {
        [DataMember]
        public int StudentId { get; set; }
    }
[DataContract]
public class Teacher : BaseService
    {
        [DataMember]
        public int TeacherId { get; set; }
    }

Here is MSDN doc
Comment: I added more clarity to my question with code samples. I think the known types is not the key or only a part of the key. I don't understand the part of my code where I have to call WorkMethod - how can I pass any of these proxies (proxyServiceA or proxyServiceB) to the WorkMethod method and call BaseMethod? The known types aren't enough I think.
Comment: The known types concept is related to data contracts. There are no data contracts in my question. My question is about sharing the base implementation of the base interface and trying to use this base functionality on the client. Sorry, I think your answer is not relative.


Absolute values don't work

Question: I don't understand, how absolute valued could possibly be considered well defined.
As shown here,
$|a| = |-a| , ||a|| = |-|a||$
So lets take $a=-2, |a| = -2 = |-a|,$  but $|-a| = |2| = 2$
But it doesn't just stop here:$ ||-a|| = |-|-a|| = -|-a| = --|a|=---a=-a$
It doesn't even matter how many times you do it, it always inverts, when it shouldn't. Hence $|a| \ne |-a|$
Answer: The absolute value is never negative, by definition. Hence, for any $a>0$, $|-a|=|a|=a$.
Answer: Just to add that $|x|$ is never negative, take a look at the graph of $|x|$.

As you can see, if you have $x<0$, then $|-x|=x$ and for $x\ge 0$, $|x|=x$.
This is because by definition of absolute value, we have
$$|x|=\begin{cases}x&x\ge 0\\-x&x<0\end{cases}$$
Answer: Let's look at the standard definition of $|x|$
$$|x|=\begin{cases}x&x\ge 0\\-x&x<0\end{cases}$$
That is:
 - $|x|=x$ when $x \ge 0$
 - $|x|=-x$ when $x < 0$
For any real number $a$ it is either greater than zero, equal to zero, or less than zero.

So lets take $a=-2, |a| = -2 = |-a|, but |-a| = |2| = 2$

Since $a=-2$ is less than zero, $|a|=-(-2)=2$
this also gives $-a=2$ is greater than zero so $|-a|=2$.
Looks consistent to me. We can also do this in general.

Whenever $a \ge 0$ we have $-a \le 0$ hence $|a|=a$ and $|-a|=-(-a)=a$
Whenever $a < 0$ we have $-a > 0$ hence $|a|=-a$ and $|-a|=-a$

The only possible point that could be not well-defined is zero but since $\pm 0 = 0$ it's not an issue.
Now let's look at the double absolute value problem (work like an onion one layer at a time):

$||a||$ since $|a|>0$ $||a||=|a|$
$|-|a||$ since $|a|>0$ we have $-|a|<0$. Then $|-|a||=-(-|a|)=|a|$

Absolute values don't work


A multiple choice question on topology regrading continuity of identity function with different topologies.

Question: Let $X$ be a set with at least two elements. Let $\tau, \tau'$ be two topologies on $X$ such that $\tau'\neq\{\emptyset,X\}$. Which of the following condition is necessary for the identity function to be continuous.
$id: (X,\tau)\rightarrow (X,\tau')$
(1) $\tau \subseteq \tau'$
(2) $\tau'\subseteq\tau$
(3) no condition on $\tau$ and $\tau'$
(4) $\tau \cap \tau'=\{\emptyset, X\}$
My Efforts
(1) False
Let $U$ be an open set in $\tau'$, that is not in $\tau$. Inverse image of $U$ is $U$ but the preimage is not open.
(2) True.
Every open set in $\tau'$ is already open in $\tau$ so identity function is continuous.
How should I approve or reject other two option.
What if the topologies are not comparable;?
Comment: Please notice the difference between `\phi` and `\emptyset`.
Comment: You have already identified the correct answer.
Comment: @LordSharktheUnknown What if the topologies are not comparable, how do I show that result in option 2 is actually an if and only if statement
Comment: You can prove 2. is an if and only if by applying the definition of continuity @StammeringMathematician
Answer: Given two topologies $\tau,\tau'$ on the same set $X$, the identity function $id:(X,\tau)\to(X,\tau')$ is continuous exactly when $\tau'\subseteq\tau$ for the reason you gave. This forces comparability between the topologies. Thus, the identity function is never continuous when $\tau$ and $\tau'$ are not comparable.
As for why $4)$ is incorrect, think about the continuity condition. We want for every set $U\in\tau'$ that $U\in\tau$. However, if $\tau\cap\tau' = \{\emptyset, X\}$, then this condition fails on every nontrivial open set. It is (in a sense) the 'worst case scenario' for continuity.
Comment: Thanks for the help and clear explanation.


Prove $\sqrt{\frac{a^2+b^2+c^2+d^2}{4}}\geq\sqrt[3]{\frac{abc+abd+acd+bcd}{4}}$

Question: For real numbers $a, b, c, d >0$ I have to prove that  $$\sqrt{\frac{a^2+b^2+c^2+d^2}{4}}\geq\sqrt[3]{\frac{abc+abd+acd+bcd}{4}}$$ always holds. I tried using the mean inequalities for multiple numbers but I always get in trouble with the different orders of the two roots. And in case I make an estimate that can handle the orders of the roots, it is too strong. Can anyone help?
Comment: i have an ugly proof, powring by $6$, setting $$b=a+u,c=a+u+v,d=a+u+v+w$$ and after the polynomial in $$a,u,v,w$$ is positive
Answer: Use this inequality:
$\frac{1}{16}(a+b+c+d)^3 \geq abc+bcd+cda+dab$ equivalent $\frac{1}{4}(a+b+c+d) \geq \sqrt[3]{\frac{abc+abd+acd+bcd}{4}}$ Now just prove$\sqrt{\frac{a^2+b^2+c^2+d^2}{4}}\geq \frac{1}{4}(a+b+c+d)$ equivalent $4(a^2+b^2+c^2+d^2)\geq (a+b+c+d)^2$ equivalent $3(a^2+b^2+c^2+d^2)\geq 2(ab+ac+ad+ bc + bd + cd)$ equivalent $(a-b)^2 + (a-c)^2 + (a-d)^2 + (b-c)^2 + (b-d)^2  + (c-d)^2 \ge 0$
Comment: Proving $\sqrt{\frac{a^2+b^2+c^2+d^2}{4}}\geq \frac{1}{4}(a+b+c+d)$ then is really easy since this is just the inequality between the quadratic and the arithmetic mean.
Comment: @mxian See my updated answer
Answer: Since
$$\frac{a^2+b^2+c^2+d^2}{4}\geq\frac{ab+ac+bc+ad+bd+cd}{6}$$
it's just
$$(a-b)^2+(a-c)^2+(a-d)^2+(b-c)^2+(b-d)^2+(c-d)^2\geq0,$$ it's enough to prove that
$$\sqrt{\frac{ab+ac+bc+ad+bd+cd}{6}}\geq\sqrt[3]{\frac{abc+abd+acd+bcd}{4}},$$
which I proved here:
How to prove this inequality $\sqrt{\frac{ab+bc+cd+da+ac+bd}{6}}\geq \sqrt[3]{{\frac{abc+bcd+cda+dab}{4}}}$


does the following dynamic system converge to a steady state?

Question: This is an economics problem, but I'm pretty sure this kind of thing comes up elsewhere. I've used dynamic programming to find the optimal path of a system (law of motion), which is:
$k_{t+1}=\beta\alpha k_t^\alpha$,
where $\alpha,\beta \in R(0,1)$
now I want to find out if this expression converges to a steady state, defined as
$\lim_{t\to\infty} k_{t+1}=k_t=k^*.$
I thought about trying to tackle it as an eigenvalue problem, of the form
$\left[ \begin{matrix} \log k(t+1)\\ \log k(t+2) \end{matrix} \right] = \left[ \begin{matrix} 0 &1\\ 0 &\alpha \end{matrix}\right] \left[ \begin{matrix} \log k(t)\\ \log k(t+1)\end{matrix} \right] + \left[ \begin{matrix} 0\\ \log\beta + \log\alpha \end{matrix} \right]$
or
$U_{t+1} = AU_t +B$
My question is this: will the system converge as long as the eigenvalues of A are inside the unit circle? I'm concerned about how the contribution of B behaves over time. Am I on the right track with this thing at all?
Answer: This dynamical system is explicitly solvable.
Let $x_t=\log k_t$, then $x_{t+1}=\alpha x_t+b$ with $b=\log(\alpha\beta)$. Since $\alpha\ne1$, this is equivalent to $x_{t+1}-x^*=\alpha (x_t-x^*)$ with $x^*=b/(1-\alpha)$, hence $x_t=x^*+\alpha^t(x_0-x^*)$ is the explicit solution of your dynamical system. Since  $|\alpha|<1$, $x_t\to x^*$ for every starting point $x_0=\log k_0$, which means that $k_t\to k^*$ with $k^*=\exp(x^*)=(\alpha\beta)^{1/(1-\alpha)}$.
Comment: Thank you very much. I think $a=\alpha$ though, not $\log\alpha$.
Comment: Yes. Corrected.


Reading Excel Sheet Using C# Where the Table has Merged Cells

Question: I am trying to read an Excel sheet that has some merged cells using C#.  I read in another post that merged cells still existed from the code's point of view but they just had null values.  So I have tried skipping null values but I am still getting wonky results.  Here is the code I am using.  It is supposed to populate an HTML table with values from the spreadsheet:
private void Output_Excel_File()
{
    string inputFileLocation = AppDomain.CurrentDomain.BaseDirectory + "/dashboard.xls";
    DataSet ds = Get_Spreadsheet_Data(inputFileLocation, "Dashboard Statistics");
    if (ds.Tables.Count > 0)
    {
        foreach (DataTable dt in ds.Tables)
        {
            int row = 0;
            foreach (DataRow dr in dt.Rows)
            {
                int col = 0;
                foreach (DataColumn dc in dt.Columns)
                {
                    string cellValue = dr[dc].ToString();
                    cellValue = Regex.Replace(cellValue, "\n", "<br /");
                    if (cellValue == "X" || cellValue == null)
                    {
                        col++;
                        continue;
                    }
                    string index = "r" + row.ToString() + "c" + col.ToString();
                    Literal cellTarget = (Literal)form1.FindControl(index);
                    cellTarget.Text = cellValue;
                    col++;
                }
                row++;
            }
        }
    }
}

In particular my indexing is off and the line:
cellTarget.Text = cellValue;

always ends up throwing a null reference exception when the indexing becomes mismatched with the indexing in the HTML.
I've Googled and Googled but I'm stumped.  Any advice is appreciated.
Comment: What does `Get_Spreadsheet_Data` do? Is this a library? Which one?
Comment: This code was given to me by someone with experience doing this sort of thing.  I just assumed that it worked.  When I debug I do see values from the spreadsheet in the variables but the indexing is off and I can't figure out why.
Answer: From what I remember, The upper left most cell of merged cells will carry the data. Every other cell reference in the merged group will be empty.
EDIT:
If you want to skip processing r0c1 (Because I assume it doesnt exist) if it is "X" or Null, then you would have to do something like this:
foreach (DataColumn dc in dt.Columns)
{
    string cellValue = dr[dc].ToString();
    cellValue = Regex.Replace(cellValue, "\n", "<br /");
    if (cellValue != "X" | cellValue != null)
    {
        string index = "r" + row.ToString() + "c" + col.ToString();
        Literal cellTarget = (Literal)form1.FindControl(index);
        cellTarget.Text = cellValue;
    }

    col++;
}

Also I think cellValue will not ever be null, but it may be empty "" so I like to use:
if (cellValue != "X" | cellValue.Length == 0)

EDIT2:
You may be a bit confused with the NullRefference exception that you are recieving. From what I see it not because the cellValue is null, it's from:
(Literal)form1.FindControl(index);

trying to find r0c1 which I assume doesn't exist and returns a null control(Literal). So when you go to use
cellTarget.Text = cellValue;

you get a NullReference error because the object itself cellTarget is null.
Comment: That's why I am skipping cells that return a null value.  But my indexing is still off.
Comment: It looks like the first time through on the loop your `index` is at R0C0 `string index = "r" + row.ToString() + "c" + col.ToString();` from `int col = 0;` and `int row = 0;`
Comment: The Literal control I am replacing in the HTML table has id="r0c0".  For some reason my index advances to r0c1 even though there is only one value in the first row of the table -- all of its cells being merged.
Comment: Hmm.  My table is 5x5 and the first row is 5 merged columns that just contains a title.  My understanding is that to traverse this row I still must iterate over the merged cells but they will have a null value.  Therefore skipping nulls should work, no?
Comment: Yes, but you are still hitting the line `Literal cellTarget = (Literal)form1.FindControl(index);` every time. I edited my answer to help.


Examples of elementary substructures of $(\mathbb{C},0,1,+,-, \times)$

Question: I wonder what are some examples of elementary substructures of $(\mathbb{C},0,1,+,-, \times)$. I know that $(\mathbb{R},0,1,+,-, \times)$, $(\mathbb{Q},0,1,+,-, \times)$ are not since they don't satisfy $x^2=-1$.
Thanks!
Comment: Possibly the algebraic closure of $\mathbb{Q}$ in $\mathbb{C}$?
Comment: The theory of $(\mathbb{C}, 0, 1, +, -, \cdot)$ is precisely the theory of characteristic 0 algebraically complete fields, since the latter is complete...
Answer: As commenters have mentioned, any elementary substructure of $\mathbb{C}$ must satisfy the same first order properties. But it is well known that $\mathsf{ACF}_0$ (the theory of Algebraically Closed Fields of characteristic $0$) is model complete. This follows, for instance, from quantifier elimination.
How is this helpful?
Any elementary substructure of $\mathbb{C}$ must, in particular, model $\mathsf{ACF}_0$, since it is clear that $\text{Th}(\mathbb{C}) \supseteq \mathsf{ACF}_0$. But by model completeness, we get the converse: any submodel $\mathfrak{M}$ of $\mathbb{C}$ that models $\mathsf{ACF}_0$ must be elementary!
So we're looking for the subrings of $\mathbb{C}$ which are themselves algebraically closed fields of characteristic $0$.
We see one obvious elementary substructure: $\overline{\mathbb{Q}}$. However, there are lots more! For a more detailed discussion about the algebraically closed subfields of $\mathbb{C}$, see here for instance.

I hope this helps ^_^
Comment: Nice answer. But I wouldn't call the issue of formulas with parameters a "minor detail". In general, a structure may have elementarily equivalent substructures which are not elementary substructures! The fact that this does not happen for models of ACF$_0$ is the statement that ACF$_0$ is model complete, which follows from elimination of quantifiers.
Comment: I agree - I was actually in the middle of changing that when you both commented :P
Comment: @NoahSchweber you beat me by 10 seconds!
Comment: @AlexKruckman Yours was more accurate though :P


2-coloring of R(m,m) with no monochromatic $K_m$

Question: I am working on a pset question on Ramsey numbers and trying to prove the following question:
Let $m \ge 3$ be a positive integer. Construct a red/blue coloring of $K_{(m-1)^2}$ which has no monochromatic $K_m$ (i.e. show that $R_{m,m} \ge (m-1)^{2} + 1$.
Here is my rough draft where I am trying to conceptualize the answer. However, I am new to the subject of graph theory and would appreciate any feedback on how to proceed.
=========================
To construct a $K_{(m - 1)^2}$ that does not have a monochromatic $K_m$, we need to show that there is a 2-coloring of $K_m$ that contains neither a red monochromatic $K_m$, nor a blue monochromatic $K_m$. We will count the colorings of $K_m$ that contain either a red or a blue monochromatic $K_m$. \
Let $S$ be a subset that has $\textit{m}$ vertices and Let $S_2$ be the set of 2-colorings of $K_m$ where the subgraph induced by \textit{S} is either all blue or all red. We can count the number of colorings in $S_2$ as we know that there are two ways to color the edges in the subgraph induced by $\textit{S}$ so that it is monochromatic. Then, we see that the number of 2-colorings containing either a red $K_m$ or a blue $K_m$ corresponds to the cardinality of the union of all the $S_2$'s for all possible subsets $textit{S}$ containing $\textit{m}$ vertices. We know that the union cannot be larger than the sum of the sizes of the sets. Then, the number of 2-colorings containing a monochromatic red or blue $K_m$.... (incomplete)
Then, there must be a 2-coloring of $K_m$ such that it contains no monochromatic coloring of $K_m$ and  we can conclude that $R(m,m) \ge (m - 1)^2 + 1$.
Comment: Generally, if the question says to "construct" they mean something like (in this case) "describe how to color the edges explicitly."  I haven't thought carefully about your sketch, but it seems like you are trying to prove the lower bound without producing the coloring (not necessarily wrong, but not what is being asked).
Comment: Thanks for the input. I appreciate it!    My next attempt was something like this:       Take the vertices of $K_{(m - 1)^2}$ and mark them with the ordered pairs of $(k -1)\ x\ (k-1)$. Consider the vertices $v, u, x, y$ such that $vu \in E$ and $xy \in E$. We see that these two edges are red if $v = x$ and they are blue otherwise. Then, we have constructed a coloring of $K_{(m - 1)^2}$ such that it has no monochromatic $K_m$.        === do you think this is how I should approach the question?
Comment: That seems reasonable except for the use of "we see". You are not being given a coloring or solving for one; you are defining a coloring.
Answer: You are trying to give a non-constructive proof that a legal coloring exists. Sometimes this is a useful method, but I do not see it working out here. You will probably be better off trying to find an explicit coloring.
Here is a (big) hint for finding a coloring. Arrange the vertices in a $(m-1)\times (m-1)$ grid, and color the edges so that every row is a red $K_{m-1}$.
Answer: Split the vertices into blocks of size $m-1$, color edges between vertices of the same block red and between vertices of different blocks blue.
If we select $m$ vertices there must be two of different blocks and thus a blue edge, there must also be a block with two or more vertices and thus a red edge.


Is there a way for code competition in Php for IDE's in case of "mixed" types?

Question: Lets check a Factory class. It can return any class, or it at least one fix class. Code competitions cant know its methods/properties, how to "tell" to IDE's its class?
Comment: Did you mean code completion? There's no way of telling object of which class is returned by a factory without executing the code.
Answer: You can use a PHPDoc, most IDEs support it.
/**
 * Factory::make()
 *
 * @param string $classname
 *
 * @return Object - The object being made.
 */


Android - Como chamar um método de outra class a partir do onCreate()?

Question: Eu sou bem novo em Android. Então se puder explicar a lógica por trás do problema eu agradeceria. Isso me ajudaria a entender o problema e ver como eu poderia resolve-lo se acontece-se de novo.
Na activity um eu tenho um método que é executado quando um certo botão é clicado. O mesmo botão está na outra activity, então, em vez de criar o mesmo método duas vezes e dizer tudo que o que ele tem que fazer, eu gostaria apenas de chamar o método que está dentro da activity1. Isso a partir do onCreate();
Qualquer ajuda é válida!
Activity 1 (trecho)
//Do intent on Button shopButton
public void buttonIntent(){
    Button buttonShop = findViewById(R.id.shopButton);
    if (buttonShop != null){
        buttonShop.setOnClickListener(new OnClickListener( ) {
            @Override
            public void onClick( View v ) {
                Intent i = new Intent(MainActivity.this,ShopActivity.class);
                startActivity(i);
            }
        });
    }
}

Activity 2
package com.example.android.musique;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

public class ListActivity extends AppCompatActivity {

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

        //Create an MainActivity Object
        MainActivity mainAct = new MainActivity();

        //Call methods what catches the button and do intent from MainActivity
        mainAct.buttonIntent();
    }

}

LOGCAT
01-10 22:24:16.514 8887-8956/com.example.android.musique D/OpenGLRenderer: ProgramCache.generateProgram: 34359738371
01-10 22:24:16.516 8887-8956/com.example.android.musique D/OpenGLRenderer: ProgramCache.generateProgram: 240518168576
01-10 22:24:16.518 8887-8956/com.example.android.musique D/OpenGLRenderer: ProgramCache.generateProgram: 68724719680
01-10 22:24:16.529 8887-8956/com.example.android.musique D/GraphicBuffer: register, handle(0x7a2b9b5780) (w:720 h:1280 s:720 f:0x1 u:0x000b00)
01-10 22:24:16.539 8887-8887/com.example.android.musique V/InputMethodManager: onWindowFocus: null softInputMode=272 first=true flags=#81810100
01-10 22:24:16.564 8887-8956/com.example.android.musique D/GraphicBuffer: register, handle(0x7a2b9b6200) (w:720 h:1280 s:720 f:0x1 u:0x000b00)
01-10 22:24:17.401 8887-8894/? I/art: Ignoring second debugger -- accepting and dropping
01-10 22:24:17.829 8887-8956/? D/OpenGLRenderer: ProgramCache.generateProgram: 34359738369
01-10 22:24:18.383 8887-8956/? D/OpenGLRenderer: CacheTexture 7 upload: x, y, width height = 72, 18, 28, 103
01-10 22:24:18.392 8887-8956/? D/OpenGLRenderer: CacheTexture 7 upload: x, y, width height = 84, 120, 17, 90
01-10 22:24:18.408 8887-8956/? D/OpenGLRenderer: CacheTexture 7 upload: x, y, width height = 84, 209, 15, 24
01-10 22:24:18.507 8887-8956/? D/OpenGLRenderer: ProgramCache.generateProgram: 103079215104
01-10 22:24:19.352 8887-8956/? D/OpenGLRenderer: ProgramCache.generateProgram: 103084458052
01-10 22:24:24.085 8887-8887/? D/AndroidRuntime: Shutting down VM
01-10 22:24:24.095 8887-8887/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                 Process: com.example.android.musique, PID: 8887
                                                 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.musique/com.example.android.musique.ListActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2745)
                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2810)
                                                     at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1529)
                                                     at android.os.Handler.dispatchMessage(Handler.java:110)
                                                     at android.os.Looper.loop(Looper.java:203)
                                                     at android.app.ActivityThread.main(ActivityThread.java:6275)
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)
                                                  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
                                                     at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:117)
                                                     at android.support.v7.app.AppCompatDelegateImplV9.<init>(AppCompatDelegateImplV9.java:149)
                                                     at android.support.v7.app.AppCompatDelegateImplV11.<init>(AppCompatDelegateImplV11.java:29)
                                                     at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:54)
                                                     at android.support.v7.app.AppCompatDelegateImplV23.<init>(AppCompatDelegateImplV23.java:31)
                                                     at android.support.v7.app.AppCompatDelegateImplN.<init>(AppCompatDelegateImplN.java:31)
                                                     at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:198)
                                                     at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:183)
                                                     at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:519)
                                                     at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:190)
                                                     at com.example.android.musique.MainActivity.buttonIntent(MainActivity.java:45)
                                                     at com.example.android.musique.ListActivity.onCreate(ListActivity.java:19)
                                                     at android.app.Activity.performCreate(Activity.java:6717)
                                                     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2698)
                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2810)
                                                     at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1529)
                                                     at android.os.Handler.dispatchMessage(Handler.java:110)
                                                     at android.os.Looper.loop(Looper.java:203)
                                                     at android.app.ActivityThread.main(ActivityThread.java:6275)
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)

Answer: A menos que esse método seja static ou você crie uma classe da qual suas activity derivem, você precisara implementar esse método em ambas.
O erro do seu log é derivado do fato que você tentou instanciar a activity manualmente com MainActivity mainAct = new MainActivity();
O Android não vai simplesmente criar um objeto da activity, ele tentara "colocar para rodar" ela.
Mudar seu método para estático deve resolver seu problema.
public static void buttonIntent(final Activity activity){
    Button buttonShop = activity.findViewById(R.id.shopButton);
    if (buttonShop != null){
        buttonShop.setOnClickListener(new View.OnClickListener( ) {
            @Override
            public void onClick( View v ) {
                Intent i = new Intent(activity, ShopActivity.class);
                activity.startActivity(i);
            }
        });
    }
}

Comment: `MainActivity asd = new MainActivity();
asd.buttonIntent();`

buttonIntent (Activity) in MainActivity cannot be applied.

Fico preso nesse resultado
Comment: Você utilizara assim: `MainActivity.buttonIntent(this);` onde `this` é a referencia da Activity onde o método foi chamado. Você não precisa instanciar um novo objeto.


Dynamically Adding Parameters to CountIfs in VBA

Question: I'd like to use countifs in VBA without knowing the amount of criteria/ranges. So in the example below, my script would see that there were 2 criterias, and apply 2 sets of criteria/ranges.
How do I do this in VBA, I can do everything apart from put it in the countifs formula. I tried putting it in a string/variant, ie: Application.Worksheetfunctions.Countifs(stringvariable) but it has not worked, I understand why it has not worked but I can't find a way to do this.
Thanks in Advance for your help.
Comment: Hard to tell where your code is in error without seeing the code. It should be doable if you construct the formula appropriately.  Another approach would be to use the Advanced Filter and then the SubTotal "CountA" function, all of which can be implemented in VBA.
Answer: 1) Create the formula as a string
2) Use application.evaluate(var) to get the result


Function for drawing $\sin x$ with a maximum value of $360$ and minimum of $70$?

Question: I want a function to draw $\sin x$ between an upper limit of $360$ and a lower limit of $70$.
Attempt: I know how to handle the lower limit but I'm having trouble with the upper limit.
$$y = a(\sin(x)+1) + 70$$
Comment: The range of $\sin x$ is $[-1,1]$, which is a difference of $2$, so multiply that up to the desired range and then offset appropriately.
Comment: are you familiar with the techniques of single variable calculus? Simply take the derivative and solve for the zeros you want...  The constant should become clear
Answer: Since $\sin x$ goes from $-1$ to $+1$ you only need to make
$$f(x)=a\sin x+b$$ and solve the system $$\begin{cases}a+b=360\\-a+b=70\end{cases}$$ hence $$\color{red}{(a,b)=(145,215)}$$
Answer: I assume you want to find some shifted and scaled/stretched/compression version of $\sin x$ such that the upper limit is $360$ and the lower limit is $70$.
Then halfway between $y=360$ and $y=70$, we must have the midline of $y=215$. From $215$ we need to go up by an amplitude of $360-215=145$  to get to $360$ and down by $215-70=145$ to get to $70$. Hence, if we assume the point $(0,215)$, the equation your looking for is:
$$y=145\sin(x)+215$$
This follows from $-1 \leq \sin x \leq 1$, because then $145(1)+215$ will be our max and $145(-1)+215$ will be our minimum. You can add a horizontal stretch/compression if you wish.
If we have the more general point $(0,y(0))$ then using the same idea about the maximum value $\sin (u)$ to assume what you want is of the form:
$$y=145\sin(ax+b)+215$$
This assumption was made from begging (we want $\sin x$ stretched/compressed/shifted in such a way...). Anyways if you plug in $x=0$ you get:
$$c=145\sin(b)+215$$
You can solve for $b$. $a$ can be anything but if you don't want a horizontal stretch from our parent function $\sin x$, take $a=1$ because $a$ "scales" or stretches/ compresses your function in the horizontal direction.
Answer: Figured it out seconds after posting by luck. :)
$$y= \frac{290}{2}(\sin(x)+1)+70,$$
since $\sin (x)$ occupies a total height of $2$.
Comment: This does not work. The minimum is 70, but the maximum is $360+70=430$.
Comment: Indeed.  Replace $\frac{360}{2}$ with $\frac{290}{2}$ to fix the issue.


How do I add an image inside a rectangle or a circle in JavaFX?

Question: Suppose we have a rectangle called r
Rectangle r = new Rectangle(40, 20);

and an image called image
Image image = new Image("...src for image");

How do I fit the image inside the rectangle? Also, how can I make the image move if the rectangle moves too? How do I do the same thing for a circle? Code examples are greatly appreciated.
P.S. Jewelsea, I'm waiting for you, lol!
Comment: possible duplicate of [Border-Radius and Shadow on ImageView](http://stackoverflow.com/questions/20489908/border-radius-and-shadow-on-imageview)
Answer: if you want to fill Rectangle by image, you can follow this:-
in your fxml file add a Circle
<Rectangle fx:id="imgMenuUser" />

And in your Controller
@FXML
private Rectangle rectangle;
Image img = new Image("/image/rifat.jpg");
rectangle.setFill(new ImagePattern(img));

Answer:
How do I fit the image inside the rectangle?

Put the shape and the image in a StackPane.

Also, how can I make the image move if the rectangle moves too?

Just move the StackPane.
import javafx.application.Application;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.geometry.Point2D;
import javafx.stage.Stage;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;

public class Main extends Application {
    @Override
    public void start(Stage primaryStage) {
        try {
            Pane root = new Pane();

            StackPane imageContainer = new StackPane();
            ImageView image = new ImageView(...);
            imageContainer.getChildren().addAll(new Rectangle(64, 48, Color.CORNFLOWERBLUE), image);
            enableDragging(imageContainer);

            root.getChildren().add(imageContainer);

            Scene scene = new Scene(root,800,600);
            scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
            primaryStage.setScene(scene);
            primaryStage.show();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    private void enableDragging(Node node) {
        final ObjectProperty<Point2D> mouseAnchor = new SimpleObjectProperty<>();
        node.setOnMousePressed( event -> mouseAnchor.set(new Point2D(event.getSceneX(), event.getSceneY())));
        node.setOnMouseDragged( event -> {
            double deltaX = event.getSceneX() - mouseAnchor.get().getX();
            double deltaY = event.getSceneY() - mouseAnchor.get().getY();
            node.relocate(node.getLayoutX()+deltaX, node.getLayoutY()+deltaY);
            mouseAnchor.set(new Point2D(event.getSceneX(), event.getSceneY()));;
        });
    }

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


Herança de telas - Android

Question: Queria cria uma tela(Activity) base para o app android que estou desenvolvendo, para que todas as demais telas herdassem desta base. Assim sendo, a tela teria uma área reservada para o topo da página, uma região central onde o conteúdo vai ser variável e uma área de rodapé que conteria dois botões.
Como poderia fazer isso?
Comment: Creio que a ideia seria fazer uso de `Fragment` na área que fica variável. Mas detalhes de implementação pra isso não tenho. Eu pessoalmente evito usá-los.
Comment: Como o @mutlei disse `Fragments` é a melhor solução. Não vejo razão para não usa-los. Para melhor entendimento, recomendo dar uma olhada nessa pergunta: http://pt.stackoverflow.com/questions/17483/qual-a-diferen%C3%A7a-entre-desenhar-na-activity-e-no-fragment/17502#17502.
Comment: Eu evito usá-los pois as aplicações que fiz até agora, @Wakim, não precisavam deles e só me dava mais dor de cabeça. Mas se bem usados, podem ser uma mão na roda, creio.
Answer: Outras respostas já deram algumas alternativas, mas acho que posso acrescentar mais uma.
Minha sugestão seria criar um layout único como sendo um template de verdade e usar um ViewStub para definir o conteúdo dinâmico desse template durante a criação das Activity's.
Por exemplo:
template.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="5dp">

    <include ... />

    <ViewStub android:id="@+id/stub"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:weight="1" />

    <include ... />
</LinearLayout>

Para mudar dinamicamente o layout durante a criação da Activity é só fazer:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Pode "setar" normalmente seu layout
    setContentView(R.layout.template);

    ViewStub vs = findViewById(R.id.stub);

    // Define qual o layout a ser inflado
    vs.setLayoutResource(R.layout.seuLayoutAtual);
    View conteudoPrincipal = vs.inflate();
}

Lembrando que o ViewStub sairá da árvore e dará lugar a toda sub-árvore que está definido no layout que você passar no método ViewStub.setLayoutResource. O método inflate retorna a raiz do layout que você inflou.
Dessa forma você reaproveitar o mesmo layout apenas mudando o conteúdo que precisa.

Para a questão de função/comportamentos que pertencem ao template, você pode criar uma classe, podendo ser abstrata se preferir, que herde de alguma subclasse ou a própria Activity (FragmentActivity, ListActivity e assim em diante) que contenha esse comportamento que é comum a todos.
Você teria algo como:
public abstract class BaseActivity extends Activity {

    // Template method para retornar o conteudo
    // interno ao template.
    // Sendo abstrato para obrigar que a subclass forneca
    public abstract @LayoutRes int getContentLayoutId();

    // Metodo responsavel por configurar o conteudo do template
    public abstract void onCreateContent(View conteudo);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.template);

        ViewStub vs = findViewById(R.id.stub);

        // Define qual o layout a ser inflado
        vs.setLayoutResource(getContentLayoutId());
        View conteudoPrincipal = vs.inflate();

        // Configuracao de listener de eventos e etc

        // Deixa a subclasse configurar o conteudo
        onCreateContent(conteudoPrincipal);
    }

    // Metodos comuns
}

Onde cada Activity que irá usar o template definirá o conteúdo:
public class ActivityLoja extends BaseActivity {
    @Override
    public int getContentLayoutId() {
        return R.layout.loja;
    }

    @Override
    public void onCreateContent(View conteudo) {
        // Configuracao do conteudo
    }

    // Restante do codigo da sua Activity
}

public class ActivityCarrinho extends BaseActivity {
    @Override
    public int getContentLayoutId() {
        return R.layout.carrinho;
    }

    @Override
    public void onCreateContent(View conteudo) {
        // Configuracao do conteudo
    }

    // Restante do codigo da sua Activity
}

O registro é normal, como se não houvesse a herança:
<activity
    android:name=".activity.ActivityLoja"
    android:label="@string/loja" />

<activity
    android:name=".activity.ActivityCarrinho"
    android:name="@string/carrinho" />

Algumas referências:

http://developer.android.com/reference/android/view/ViewStub.html
http://android-developers.blogspot.com.br/2009/03/android-layout-tricks-3-optimize-with.html
Comment: essa sem dúvida é a melhor forma, menos trabalhosa e mais organizada, para realizar este trabalho!
Comment: No caso quero criar uma Activity "completa" como base, ou seja, ter métodos implementados na classe relacionados aos componentes do xml, teria como fazer a herança disso também?
Comment: Ah sim, é possível e bem comum. Você pode ter uma classe abstrata (abstrata ou não, dependendo da sua modelagem) que possui todos os métodos em comum. Ela deve herdar de `Activity` ou `ActionBarActivity` ou outra subclasse de `Activity`. Todas as outras `Activity's` que usarem o template podem herdar dessa classe comum que também é uma `Activity` válida.
Comment: No código da classe abstrata, onde temos  `vs.setLayoutResource(getContentResId());`  na verdade é:  `vs.setLayoutResource(getContentLayoutId());`  correto?
Comment: Isso @MuriloFechio, erro meu, vou corrigir, de resto está correto.
Comment: Muito boa sua solução, já havia utilizado a herança de activity, mas a ideia do template é genial!!!
Answer: Acredito que vc quer é um Designer de telas(XML) e não de Tela(activity) estou certo?
Se for esta a sua questão então , você quer saber como se faz uma velha prática de
reuso de layouts assim como é uma boa prática em páginas web.
Para fazer uma tela ou seja um layout xml que pode ser reusado em toda parte
do aplicativo, de forma que tenha um topo um corpo e um rodapé.
faça..
master_top.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffffff"
android:padding="5dp" >

<ImageView
    android:id="@+id/imageView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_margin="5dp"
    android:src="@drawable/my_logo" />

</RelativeLayout>

activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#f0f0f0" >

<include android:id="@+id/topo_view"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    layout="@layout/master_top" />

<LinearLayout
    android:id="@+id/linearLayout1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_margin="10dp"
    android:background="#ffffff"
    android:orientation="vertical"
    android:padding="5dp" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="$$$$$$$ CORPO $$$$$$$"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#1AA52F" />

</LinearLayout>

<include
    android:id="@+id/rodape_view"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    layout="@layout/master_footer" />

</RelativeLayout>

master_footer.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffffff"
android:padding="5dp" >

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:gravity="center"
    android:text="-----------RODAPE---------------"
    android:textColor="#EFEFEF" />

</RelativeLayout>

...
Você também pode usar  < merge >
REF oficial site.
http://developer.android.com/training/improving-layouts/reusing-layouts.html
Comment: Neste caso, em todas as telas que eu desenhar eu teria que fazer o include do top, do footer e criar um layout para o centro, correto? Não teria como eu dar o include em um xml tipo esse activity_main que você deu de exemplo e "desenhar" somente o conteúdo do interior do LinearLayout?
Answer: Tem como sim, seria como você fazer o inverso do exemplo!
No exemplo é só fazer uma cópia do (XML) e mudar o corpo e pronto.
Mas não tem como fugir, uma parte do layout você não vai conseguir sair
do trabalho de fazer.
Para fazer desse forma que você falou basta fazer o contrário.
Exemplo:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#ffffff"
    android:padding="5dp" >

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_margin="5dp"
        android:src="@drawable/my_logo" />

    <include android:id="@+id/topo_view"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        layout="@layout/my_body" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:gravity="center"
        android:text="-----------RODAPE---------------"
        android:textColor="#EFEFEF" />

    </RelativeLayout>

my_body.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:background="#f0f0f0" >

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:background="#ffffff"
        android:orientation="vertical"
        android:padding="5dp" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@@@@@@@ MY BODY @@@@@@@@"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="#1AA52F" />

    </LinearLayout>

    </RelativeLayout>

Herança de telas - Android


How to refactor .filter method on array so to pass one more variable needed for filtering?

Question: Given an array with a list of participants, some students, some teachers :
var participants = [
    {'name': 'G01a','email':'email@example.com','group': '1','role':'student'},
    {'name': 'G01b','email':'firstname.lastname@example.com','group': '1','role':'student'},
    {'name': 'G02a','email':'email@example.com','group': '2','role':'student'},
    {'name': 'G02b','email':'firstname.lastname@example.com','group': '2','role':'student'},
    {'name': 'P01', 'email':'email@example.com', 'group': 'teacher','role':'teacher'},
    {'name': 'P02', 'email':'firstname.lastname@example.com', 'group': 'teacher','role':'teacher'},
];

I currently write 2 highly similar filter functions to filters students, then teacher:
// DERIVATED INITIAL DATA
var checkRoleS = function (participant){
  console.log(participant.role== 'student')
  return participant.role == 'student';
}
var students = participants.filter(checkRoleS);
console.log(students)

// DERIVATED INITIAL DATA
var checkRoleTeachers = function (participant){
  console.log(participant.role== 'teacher')
  return participant.role == 'teacher';
}
var teachers = participants.filter(checkRoleTeachers);
console.log(teachers)

How to have a single checkRole function with one more parameter sot to pass forward the string "student" or "teacher" needed for the filtering ?
Thus getting something like :
var students = participants.filter(checkRole("students"));
var teachers = participants.filter(checkRole("teachers"));

EDIT : jsfiddle
Answer: you can use an anonymus function to call you check function with as many arguments as you want :

var participants = [
    {'name': 'G01a','email':'email@example.com','group': '1','role':'student'},
    {'name': 'G01b','email':'email@example.com','group': '1','role':'student'},
    {'name': 'G02a','email':'email@example.com','group': '2','role':'student'},
    {'name': 'G02b','email':'email@example.com','group': '2','role':'student'},
    {'name': 'P01', 'email':'firstname.lastname@example.com', 'group': 'teacher','role':'teacher'},
    {'name': 'P02', 'email':'email@example.com', 'group': 'teacher','role':'teacher'},
];

var checkRole = function (participant, role){
  console.log(participant.role === role)
  return participant.role === role;
}

var students = participants.filter(i => checkRole(i, "student"));
console.log(students)

var teachers = participants.filter(i => checkRole(i, "teacher"));
console.log(teachers)
Comment: Thanks, I now use `var getAllByRole = function(participantsArray,role) { return participantsArray.filter(function (i) {  return i.role == role; }) };` derivated from your answer. See http://jsfiddle.net/a6k3uvxj/17/
Answer: You could take a closure over key and value and return a function for getting an object.

const
    filterBy = (key, value) => object => object[key] === value,
    participants = [{ name: 'G01a', email: 'email@example.com', group: '1', role: 'student' }, { name: 'G01b', email: 'email@example.com', group: '1', role: 'student' }, { name: 'G02a', email: 'firstname.lastname@example.com', group: '2', role: 'student' }, { name: 'G02b', email: 'email@example.com', group: '2', role: 'student' }, {  name: 'P01', email: 'firstname.lastname@example.com', group: 'teacher', role: 'teacher' }, { name: 'P02', email: 'firstname.lastname@example.com', group: 'teacher', role: 'teacher' }],
    students = participants.filter(filterBy('role', 'student')),
    teachers = participants.filter(filterBy('role', 'teacher'));

console.log(students);
console.log(teachers)
.as-console-wrapper { max-height: 100% !important; top: 0; }


How to crop an UITextView

Question: I would like to have two UITextViews, one in the background and one in the front. Is there any possibility to crop 50% of the one in the foreground so that you can see 50% of the one in the background? I do not want to re-size the UITextView in the front, but merely to hide half of it.
I think an illustration is in place as this might sound rather confusing:

I thought I do this with two view controllers, one hidden, one visible:
<code>// Visible and Hidden View

VisibleView *visibleController = [[VisibleView alloc] initWithNibName:@"VisibleView" bundle:nil];
self.visibleView = visibleController;
[visibleController release];

HiddenView *hiddenController = [[HiddenView alloc] initWithNibName:@"HiddenView" bundle:nil];
self.hiddenView = hiddenController;
[hiddenController release];

[self.view insertSubview:visibleView.view atIndex:0]; // show visibleView
</code>
Ideally, I would like to animate the 'hiding' of the visibleView Controller, so that the hiddenViewController unveils in the background (like a sliding door - sliding in from the right). This is what I've come up so far, but I can't think of any transformation / cropping technique that will do:
<code>[UIView beginAnimations:@"Hide VisibleView" context:nil];
[UIView setAnimationDuration:0.5];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationTransition: ??
                       forView: self.view
                         cache: YES];
[visibleView.view removeFromSuperview];
[self.view insertSubview:hiddenView.view atIndex:0];

[UIView commitAnimations];
</code>
I guess this is quite basic, but I'm still a beginner and would be very happy over any suggestions of how to accomplish this.
Answer: I just created a new View-Based Application project and put this code in the viewDidLoad of the viewController to get the screen shown. It shows the theory of what you need to do. The main points to note are the 'clipsToBounds = true' and the negative x-position of textFrameRight.
- (void)viewDidLoad
{
    [super viewDidLoad];

    NSString* text = @"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
    UIFont* font = [UIFont fontWithName:@"Helvetica" size:20.0f];

    CGRect textFrameLeft = CGRectMake(0, 0, 320, 480);

    UITextView* textLeft = [[UITextView alloc] initWithFrame:textFrameLeft];
    textLeft.text = text;
    textLeft.font = font;
    textLeft.textColor = [UIColor blackColor];

    CGRect textFrameRight = textFrameLeft;
    textFrameRight.origin.x -= textFrameRight.size.width/2;

    UITextView* textRight = [[UITextView alloc] initWithFrame:textFrameRight];
    textRight.text = text;
    textRight.font = font;
    textRight.textColor = [UIColor redColor];

    CGRect leftFrame = self.view.frame;
    leftFrame.size.width /= 2;

    UIView* leftView = [[UIView alloc] initWithFrame:leftFrame];
    leftView.clipsToBounds = true;

    CGRect rightFrame = self.view.frame;
    rightFrame.size.width -= leftFrame.size.width;
    rightFrame.origin.x += leftFrame.size.width;

    UIView* rightView = [[UIView alloc] initWithFrame:rightFrame];
    rightView.clipsToBounds = true;

    [self.view addSubview:leftView];
    [leftView addSubview:textLeft];

    [self.view addSubview:rightView];
    [rightView addSubview:textRight];

    [leftView release];
    [textLeft release];
    [rightView release];
    [textRight release];
}

==================================
Realising the OP wanted this to animate; here is a revised version of the above method which does such. There are more hard-coded values in this version; but it serves as an example.
- (void)viewDidLoad
{
    [super viewDidLoad];

    NSString* text = @"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
    UIFont* font = [UIFont fontWithName:@"Helvetica" size:20.0f];

    CGRect leftFrame = CGRectMake(0, 0, 0, 480);
    CGRect textFrameLeft = CGRectMake(0, 0, 0, 480);

    CGRect rightFrame = CGRectMake(0, 0, 320, 480);
    CGRect textFrameRight = CGRectMake(0, 0, 320, 480);

    UITextView* textLeft = [[UITextView alloc] initWithFrame:textFrameLeft];
    textLeft.text = text;
    textLeft.font = font;
    textLeft.textColor = [UIColor redColor];

    UITextView* textRight = [[UITextView alloc] initWithFrame:textFrameRight];
    textRight.text = text;
    textRight.font = font;
    textRight.textColor = [UIColor blackColor];

    UIView* leftView = [[UIView alloc] initWithFrame:leftFrame];
    leftView.clipsToBounds = true;

    UIView* rightView = [[UIView alloc] initWithFrame:rightFrame];
    rightView.clipsToBounds = true;

    [self.view addSubview:leftView];
    [leftView addSubview:textLeft];

    [self.view addSubview:rightView];
    [rightView addSubview:textRight];

    [UIView beginAnimations:@"Hide VisibleView" context:nil];
    [UIView setAnimationDuration:3.0];
    rightView.frame = CGRectMake(320, 0, 0, 480);
    textRight.frame = CGRectMake(-320, 0, 320, 480);
    leftView.frame = CGRectMake(0, 0, 320, 480);
    textLeft.frame = CGRectMake(0, 0, 320, 480);
    [UIView commitAnimations];

    [leftView release];
    [textLeft release];
    [rightView release];
    [textRight release];
}
Comment: Updated the answer with another code example that has animation. I should also say: Notice you have to set the .frame property to get the animation to work.
Comment: @Wex: Wow, I am really impressed as well! Thanks for this very lucid and straightforward example. I was so confused about frames etc., but your code explains it better than 1000 words would do. I will try to animate it and post my results once I'm done. Thanks so much again!!
Comment: No problem guys :). I didn't realise you wanted it animated. That should be possible by manipulating leftView.frame and rightView.frame however you need.
Comment: @Wex: I had a go with getting it animated, but I guess I make life too difficult. If I understand the concept, I must change 4 values in order to get this animated from RIGHT TO LEFT (i.e. imagine the red comes from the left, i.e. the text becomes soaked with red/blood from the left). I would need to change the following in my animation:  textFrameRight.origin.x = -320 ----> 0;
 leftFrame.size.width = 320 -----> 0;
 rightFrame.size.width = 0 -----> 320;
 rightFrame.origin.x = 320 ------> 0;
Comment: @Wex: Or is there an easier solution manipulating the frames?
Comment: @Wex. Thanks so much. I've struggled with this, and no, mine didn't work. It does now because I did not realise that I needed to get set the .frame property. You saved my sanity (at least for today, don't know with what problems I will come up tomorrow). You have an extraordinary talent to explain things (with code) - I'm very impressed. Thanks for your time and help. I really, really appreciate it.
Answer: I usually use to mask view with other views. In your case I'll do something like this:

both of textviews has its own superview that act as a mask
animate the frame of each single mask to reveal/hide the children view
Comment: Thanks, that is really helpful! Sorry to ask this, but does a textview have a superview or the viewController (e.g. in my case the visibleController)? How do I access the mask of the superview in this instance? Will I need to call something like `mask superview.visibleController.UITextView1`? In other words, how do I access the frame of the mask of the superview of my textview1? Sorry if this is basic, but I'm really struggling. I had a look at the UIView docs, but can't make much sense of it.
Comment: - (textView) it's a textView

- (maskView) it's a basic uiview (clipToBounds:YES) and it has the textView (textView) as subview

Then:
in the viewController I'll do something like this:

[UIView beginAnimation.....]

maskView.frame = cgrectmake(.....)

[UIView commitAnim....]
Comment: I see! Will give this a try and let you know how it went. Thanks so much for your help, I appreciate your explanations.

How to crop an UITextView


Given a system of differential equations, how can one tell if $\textbf{x}_c = (0,0)^T$ is a unique critical point?

Question: I have:
$$\frac{d\textbf{x}}{dt}=\begin{bmatrix}
    -1       & 2 \\
    -2       & -1  \\
\end{bmatrix}\textbf{x}(t)$$ with $\textbf{x}(0)=(1,-1)^T$.
I am asked whether the critical point $\textbf{x}_c=(0,0)^T$ is unique or not.
I don't know how to go about answering this one.. Help please! :-)
Thanks!
Answer: The critical point(s) occur where
$\dfrac{d\mathbf x}{dt} = 0; \tag{1}$
since, as a vector field,
$\dfrac{d\textbf{x}}{dt}=\begin{bmatrix}
    -1       & 2 \\
    -2       & -1  \\
\end{bmatrix}\textbf{x}, \tag{2}$
the critical points occur wherever
$\begin{bmatrix}
    -1       & 2 \\
    -2       & -1  \\
\end{bmatrix}\textbf{x}_c = 0 \tag{3}$
has a solution.  We see that
$\det(\begin{bmatrix}
    -1       & 2 \\
    -2       & -1  \\
\end{bmatrix}) = 5 \ne 0; \tag{4}$
the coefficient matrix is thus non-singular; the only solution to (3) is
$\mathbf x_c = \begin{pmatrix} 0 \\ 0 \end{pmatrix}; \tag{5}$
thus this critical point is indeed unique.
Comment: That's it?? Okay, thank you!
Comment: That's it.   Glad to help out.  Cheers!
Comment: I looked at your website. You seem like an interesting dude.
Comment: Heh!  Thanks, I'd like to think so . . . by the way, not to put too fine a point on it, you can always upvote/accept my answer if you like it . . . or not!  Forgive me for saying this, but you know musicians:  shamelessly self-promoting.  Anyway, do what you feel . . . more Cheers!
Comment: So shameless! I'm aghast. Fellow musician, I understand!
Plus it was a top-notch answer, of course!
Comment: Hey, another musician, awesome!  Thanks for the understanding, musician to musician, and of course, the "acceptance"!  What do you play?  What instruments, what kind of music?
Comment: I'm good at guitar, acceptable at banjo, and dabble in just about anything else. Mostly my voice is my favorite instrument though! Right now I've been playing a lot of Van Morrison. After you stop hating the guy, you learn to love him!
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/23057/discussion-between-bliebervik-and-robert-lewis).


Orientation on a manifold as a sheaf

Question: I am thinking about orientation of a connected manifold $M$ of dim $n$ as a sheaf.
There are two definitions I could use, the first is the sheaf associated to the presheaf
$$U\mapsto H_n(M,M-U;R).$$
The second is the sheaf of sections of generators of the fibration $R^*\to \tilde{M}_R\to M$, where $R$ is a ring and $R^*$ is the discrete group of units of $R$ and $\tilde{M}_R$ is the $R$-orientable cover of $M$.

I have the following questions:
   1. Are the two definitions the same?
  2. Theorem 3.26 of Hatcher seems to translate to that if $M$ is closed, then it is orientable iff the orientation sheaf has a global section that generate stalk-wise, i.e. it is a principal $\underline{R}$-module.
  3. Lemma 3.27 seems to be saying if $M$ is closed, then the presheaf above is already a sheaf.

Are these correct? Feel free to tell me more things or give me references.
Comment: What is your definition of "the $R$-orientable cover of $M$"?
Comment: Not answering your question (not even for $R=\mathbb{Z}$), but a number of interesting comments about the orientation sheaf can be found here: http://mathoverflow.net/q/10966/17064
Comment: As a set, consists of pairs $(x,\mu_x)$ where $x\in M$ and $\mu_x$ is a generator of $H_n(M,M-\{x\};R)$ as an $R$-module. Topologize it so that it projects to $M$ in the first coordinate as a covering space map.
Answer: (1) Your two definitions can't be the same because one of them restricts to units in $R$ and the other does not.  To be more precise, let $F_0$ be the presheaf of $R$-modules $U\mapsto H_n(M,M-U;R)$ and let $F$ be its sheafification.  Let $G$ be the sheaf of continuous sections of the bundle of $R$-modules on $M$ whose fiber at $x$ is $H_n(M,M-\{x\};R)$, and let $G^*\subset G$ be the subsheaf of sections which generate every fiber.  Then $F$ is your first sheaf, and $G^*$ is your second sheaf.  But these are not isomorphic; rather, $F\cong G$.  To get this isomorphism, note that there is a canonical map $F_0\to G$ (given an element of $H_n(M,M-U;R)$, restrict it to $H_n(M,M-\{x\};R)$ for each $x\in U$), and this map induces an isomorphism on stalks (since any point has arbitrarily small neighborhoods on which both $F_0$ and $G$ evaluate to $R$, with the map being the identity).  This map thus induces an isomorphism after sheafifying, giving an isomorphism $F\to G$.  It is $G^*$ which is normally referred to as the "sheaf of $R$-orientations", not $F$.  If you like, you can identify $G^*$ as a subsheaf $F^*$ of $F$ via the isomorphism; it can be described as the subsheaf of sections which generate every stalk as an $R$-module (or, more elegantly, as sheaf of isomorphisms of $\underline{R}$-modules $\operatorname{Iso}_{\underline{R}}(\underline{R},F)$).  While $F\cong G$ canonically has the structure of a sheaf of $R$-modules, $F^*\cong G^*$ is merely a sheaf of $R^*$-sets.
(2) Theorem 2.36(a) says that if $M$ is closed, connected, and $R$-orientable, then there is a global section of $F_0$ that makes $F$ a principal $\underline{R}$-module, i.e. it is (noncanonically) isomorphic to the constant sheaf $\underline{R}$ as a sheaf of $R$-modules.  Note that Hatcher's definition of "$R$-orientable" is exactly that $G$ is a principal $\underline{R}$-module (or equivalently, that $G^*\cong\operatorname{Iso}_{\underline{R}}(\underline{R},G)$ has a global section), so it is trivial that in that case $F\cong G$ is also principal.  The nontrivial content of Theorem 2.36(a) is to say that the global generating section is actually already a section of the presheaf $F_0$.
(3) Lemma 2.37 doesn't quite say that $F_0$ is a sheaf if $M$ is closed, because $A$ is required to be a compact set, rather than an open set.  Here is an instructive example.  Take $M=S^1$ and let $U\subset M$ be an open set whose complement is countably infinite.  Then $U$ is a disjoint union of countably infinitely many open intervals, so $F(U)\cong R^\mathbb{N}$ (since $F(V)=R$ for any open interval $V\subset S^1$).  But $F_0(U)$ can be computed directly to be a direct sum of countably infinitely many copies of $R$ (the key point being that $H_0(M-U)$ is the free $R$-module on $M-U$, which is countable).  So $F_0(U)\not\cong F(U)$, so $F_0$ is not a sheaf.

Orientation on a manifold as a sheaf