Change a character from a 'char' in c++

Question: Is there a way to change a single character in a char?
like this example
I have user input. The user should enter a number. If the number is float or double the user should enter a point. But if the User enters ',' (3,44 or 54,33)
my code doesn't work. Is there a general way to change the comma to point?
Like this:
char number1[50], number2[50];

number1 = 2,33;
number2 = 54,45;

turns into
number1 = 2.33;
number2= 54.34;

Thank you for any help!
Comment: I wouldn't expect that to compile with or without the missing `;`. Please expand on your true goal.
Comment: sure.  `number` is an array of characters so write to the correct place in the array: `char number[50] = "2,33"; number[1] = '.';`
Comment: Have a look at https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list
Comment: pineapple, we definitely need a better problem description and code example.
Comment: If on the other hand you do want to assign a number directly to a string, then that's what sprintf() is for (or a stringstream if you are using C++)
Comment: I edit my question, I hope my issue description is better.
Answer: Firstly you can not assign an int, double etc. to a char array.
So number[50] = 2,33; is meaningless.
You have to define the number as "array of char". What I mean? You should define the char array as char number[50] = "2,33";
#include <iostream>
int main()
{
char number[50] = "2,33";
number[1] = '.';
std::cout << number << std::endl;

    return 0;
}

The output should be: 2.33
Comment: ok I need this for user input and if the user enters, for example, the number 52,3 I need to change the ',' to '.'.
Comment: So you have to search for ',' in the char array. In modern C++ you can use just string for that. But if you want to manipulate whole array by yourself. You can use for loop and check each of the element of the array. When you find the position of the ',' you just stop and get the position. Then change the value of the number[position] as '.'
Answer: #include <iostream>
#include <algorithm>
#include <string>
using namespace std;

int main ()
{
  char valor;
  const char x = ',';
  const char y = '.';

  cout << "Please enter an char value: ";
  cin >> valor;

  /*Cast char to string*/
    std::stringstream auxiliar;
    std::string varfin;
    auxiliar << valor;
    auxiliar >> varfin;

  /*Replace*/
  std::replace(varfin.begin(), varfin.end(), x, y);
  std::cout << varfin;

  return 0;
}

Answer: Cast char to string for work methods of replace

Methods for replace
Comment: Text should be presented as text. There are [many, many good reasons](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question) why images should not be used in questions and answers unless the image being an image is important to the question or answer.
Comment: Hi. Excuse me. I did not know.
Comment: Easily fixed, so you might as well do it. I'd love to get the downvote back. I hate leaving them around where kids could find them.

Change a character from a 'char' in c++


Correlation of two autocorrelated time series

Question: Say I have two time series $x(t)$ and $y(t)$ that are autocorrelated and I want to compute correlation coefficient between them. I've heard that in case of a high autocorrelation (close to 1) the correlation coefficient will be inflated. I, however, can not find any good reference showing this fact mathematically. Let's assume that we are talking about stationary time series.
Comment: stationary time series have autocorrelation functions of the form $r(\tau)$, where $\tau$ is the time delay between samples of $x(t)$. So, what does it mean to have autocorrelation close to $1$?
Comment: @gunes I was keeping in mind autocorrelation of order $1$.
Comment: Ok @tosik, can you also specify what *inflated*  $r_{xy}(1)$ corresponds to mathematically?
Comment: @gunes No, this is basically what I am looking for. But intuitively, the statement is that autocorrelated random variables tend to have high correlation between them.
Comment: You may check if the [cross-correlated](https://en.wikipedia.org/wiki/Cross-correlation) between them inflated.
Answer: When correlation coefficient for two time series $X_t$ and $Y_t$ is calculated the time dependence structure of the vector $(X_t, Y_t)$ should be considered.
For correlation coefficient to make sense it should be assumed that $EX_tY_t=\rho$ does not depend on time. Otherwise the correlation changes in time and usual estimate of correlation coefficient will not make sense.
The correlation for two time series $X_t$, $Y_t$ is calculated with the following formula (assume that both series have zeroe means):
$$
\rho(X_t, Y_t) = \frac{\frac{1}{T}\sum_{s=1}^TX_tY_t}{\sqrt{\frac{1}{T}\sum_{s=1}^TX_s^2\frac{1}{T}\sum_{s=1}^TY_s^2}}
$$
For correlation coefficient to make sense, this estimate should tend to true correlation coefficient as sample size increases.
To show this, some assumptions are necessary. Assuming that $(X_t,Y_t)$ is a stationary vector, immediately gives us that denominator tends to product of true variances of $X_t$ and $Y_t$. The same applies for nominator and thus the correlation coefficient tends to a true value of $\rho$ as sample size increases.
In this derivation the individual time series structure did not come into play.
The impact of it could be seen in variance of the estimator. Let us consider only the variance of nominator:
$$
Var(\frac{1}{T}\sum_{t=1}^TX_tY_t) =
\frac{1}{T^2}\sum_{t=1}^T\sum_{s=1}^TEX_tX_sY_tY_s - (EX_tY_t)^2
$$
If $X_t$ and $Y_t$ are independent white noise then all of the terms $EX_tX_sY_tY_s$ would vanish for $t\neq s$. If $X_t$ and $Y_t$ are highly autocorrelated (or have any dependence structure) the terms do not vanish, which means that the variance of correlation coefficient would be higher.
This can be seen in the simple simulations
<code>set.seed(123)
ff<-function(n) {
o1 <- arima.sim(list(ar = 0.95), n)
o2 <- arima.sim(list(ar = 0.95), n)
cor(o1,o2)
}
plot(hist(sapply(rep(1000,1000), ff)))

plot(hist(sapply(rep(1000, 1000), function(n) cor(rnorm(n),rnorm(n)))))

</code>
Here I sampled two independent AR(1) processes with high autocorrelation and plotted histogram of the correlation coefficient compared to similar sample of independent white noise.
As you can see both histograms center on the true value of zero. But for AR(1) processes the range is wider.
Answer: You said that the time series have to be stationary, but the "inflated correlation coefficient" idea probably comes from the spurious regression concept introduced by Granger and Newbold in 1974. Unfortunately, the paper is behind a paywall.
A mathematical motivation, which I'll admit to not understanding very well, is here.
Comment: Here is one possible explanation about the spurious correlation. https://stats.stackexchange.com/questions/7376/does-correlation-assume-stationarity-of-data/7378#7378


Angularjs e2e testing past/future comparisons

Question: I'm currently trying to figure out if there is a way to do a simple future/past comparison ex.
1) Check state of list by getting list length
2) Perform action which if success increments the list
3) Compare the current list length to the past.
But the concepts of Futures seems to get in my way. One would think this is a pretty normal use case.
Q: How would you go about handling past/future comparisons in Angularjs Scenario?
Answer: It's kind of longwinded, but you can define custom matchers which understand futures. For example:
angular.scenario.matcher('toBeGreaterThanFuture', function(future) {
  return +this.actual > +future.value;
});

Use like:
listLengthBefore = repeater('.td').count();
// Do some stuff.
listLengthAfter = repeater('.td').count();
expect(listLengthAfter).toBeGreaterThanFuture(listLengthBefore);


AngularJS - Highlight specific table rows when using ngRepeat

Question: Sample Table

        Sender
        Subject
        Received
        Actions

    <tr data-ng-repeat="message in messages | filter:search" data-ng-class="<% message.read %>">

            <% message.sender.first_name %> <% message.sender.last_name %>

            <% message.subject %>

        [ TODO ]
        [ TODO ]

My API returns an array of messages, each message has a read boolean attribute. If message.read is false, I want the class for the row to be success to highlight all unread messages in the table.
My attempt is incorrect, however what I want to do is populate data-ng-class="<% message.read %>" with data-ng-class="success"
I have also attempted the following without luck: data-ng-class="rowClass(message)">
and in the controller:
var messageControllers = angular.module('messageControllers', []);

messageControllers.controller('MessageInboxCtrl', ['$scope', '$routeParams', 'Message',
    function ($scope, $routeParams, Message) {
        $scope.folder = 'Inbox';
        $scope.messages = Message.query();

        $scope.rowClass = (function(message) {
            if (!message.read) return 'success';
            else return '';
        });
    };
}]);

Answer: From angular documentation:
ngClass is an expression that will be evaluated. "The result of the evaluation can be a string representing space delimited class names, an array, or a map of class names to boolean values. In the case of a map, the names of the properties whose values are truthy will be added as css classes to the element."
Thus,
  data-ng-class="{success: !message.read}"

See for an example http://plnkr.co/edit/8zSo5c?p=preview


Compile .less file on save with SquishIt

Question: I'm using SquishIt and have a .less file which I add to a CSS bundle with the following line
.Add("~/content/styles/dev.less")
This compiles as dev.less.debug.css when I build the solution, however I'd like to be able to just save the .less file and it automatically compiles the css (so I see the change instantly in my browser as I would with a traditional CSS file).
I have looked at a number of extensions to achieve this (such as LessExtension and LessCssForVisualStudio) but these require the file to be added to the bundle as dev.css rather than dev.less. Mindscape Web Workbench does not compile LESS files in its free version so I do not know if it also requires dev.css.
I can't change the link to the file as the project will be worked on across teams, where some won't install an extension and will be happy to build the solution to compile.
Is there and extension that automatically compiles LESS that is built to work with SquishIt?
Answer: Squishit uses dotless under the hood, so you could use that directly.. either set it up so that you request the less file and a handler returns CSS or you can use the exe to compile on build and also the watch mode... I'm not sure what's best for you, but you can find more information on the dotless wiki (https://github.com/dotless/dotless/wiki/Using-.less)
Comment: Can you give any more details about *how* to compile with the handler or the exe?
Answer: If you use it on non-production site, I would suggest using less.js (It will render css with js on client-side).
Comment: It is a production site unfortunately.
Answer: Web essentials does this job perfectly and its free.
http://vswebessentials.com/


Comparing Group and Expert Result

Question: Say I am predicting swimming times. I get a group of 20 to make predictions on the fastest to slowest swimmers from 1 to 6. I then ask a single expert in swimming to make the same predictions. Is there a way to test statistical significance between the group's predictions versus the expert's?
"significant" would mean if I were to select a random person from the group there's a very low percent he would predict in the same order as the expert.
ex.
We rank 1 to 6 the swimmers who received the highest to lowest average predictions (10 people predict swimmer 1 to get first, 10 predict swimmer 1 to get second, no one predicts swimmer to get other; his average is then 1.5, average of the predictions. We do this for every swimmer and rank the first 6 according to average). Now we have our top 6 from the group, how would I determine significance (as defined above) of an expert's prediction on the same swimmers.
Comment: Different in what sense? Can you give an example of a "significant" and a "nonsignificant" difference? That might help clarify your intention here
Comment: Different in the sense that if I were to choose 1 person from my group randomly what are the chances his prediction would match the expert's prediction given the distribution of the entire group. I guess "significant" would mean if I were to  select a random person from the group there's a very low percent  he would predict in the same order as the expert.
Comment: Thanks for clarifying. You should edit that into the body of the question itself; comments are not searchable, linkable, or archived in the same way that question text is.
Comment: "Significance" does not seem to be an applicable concept.  You seem to be asking for a way of *measuring* or *assessing* the discrepancy between the actual outcome and any particular prediction of it.  Since there are an abundance of solutions, what additional information can you supply to narrow them down?  Could you explain how you plan to use this measure of predictive accuracy, for instance?
Comment: The goal of the problem is to find if there is a difference between the amateur group and the expert. There is no actual outcome yet, we are just checking if there is a difference. We want a score that can tell us how different an expert's result is compared with the amateur group's predictions. In a sense it is a classification problem, but I'm not sure how to go about it, since rankings are dependent of one another.
Comment: Do you also have actual race results? Or are you doing something more like lumping the expert's ratings in with the (amateur) crowd, and then doing a "which one doesn't fit?" and seeing how often the one that doesn't fit is the expert?
Comment: The second one, lumping the expert's ratings in.
Answer: It depends on the question. Interrater agreement has been studied extensively, so there is not one single way to do this. I'll pose a question to you: if rater 1 predicts Swimmer A will take 6th place and Swimmer B will take 1st place whereas rater 2 predicts Swimmer A will take 1st place and swimmer B will take 6th place, would you or should you consider that a worse ranking than a similar setting where the disagreement is over 1st versus 2nd place? I can say with some confidence it would be er
I would think that a weighted kappa is the best approach to evaluating rater agreement for ranks. The choice of weight is determined by the problem. A higher weight considers adjacent ranks to be "ball park" close so that the second scenario of my example is considered an "okay" agreement but the first scenario is considered "awful". Unweighted kappas classify any ranking disagreement as a complete miss, regardless of how close it was. Confidence intervals and hypothesis tests are available for kappas using standard software. However, it would require that you actually produce an experiment for this question, and simulate examples from many types of races/events.
Comment: Thanks for the answer. It got me looking more into comparing ordinal results. One thing I found that looked interesting was Kendell's tau. I understand both of them deal with the problem, but I'm confused on the exact difference and when to use which.

Comparing Group and Expert Result


Nuxt content Shiki plugin returns : ERROR /home not found

Question: I'm trying to use syntax highlighter with @nuxt/content and Shiki.
After installing the shiki package in my nuxt.config.js project file.
import shiki from 'shiki'

...

export default {
  modules: ['@nuxt/content'],

  content: {
    markdown: {
      async highlighter() {
        const highlighter = await shiki.getHighlighter({
          theme: 'nord'
        })
        return (rawCode, lang) => {
          return highlighter.codeToHtml(rawCode, lang)
        }
      }
    }
  }
}

I got
Error
/home not found

But when I remove the highlighter method in the content, everything works fine. Can anyone help me please?
Answer: Instead of adding the import and await shiki, use the require method of using it.
  content: {
    markdown: {
      async highlighter () {
        const highlighter = await require('shiki').getHighlighter({
          theme: 'github-dark'
        })

        return (rawCode, lang) => {
          return highlighter.codeToHtml(rawCode, lang)
        }
      }
    }
  },

This is what I did to get it working.
An alternative solution to the above that also works would be:
import { getHighlighter } from 'shiki';

// ...

  content: {
    markdown: {
      async highlighter () {
        const highlighter = await getHighlighter({
          theme: 'github-dark'
        })

        return (rawCode, lang) => {
          return highlighter.codeToHtml(rawCode, lang)
        }
      }
    }
  },


Taxes in ubercart

Question: I'm trying to charge cali sales tax in my ubercart store. I have taxes turned on, and have it set up with
"and: California Sales Tax conditions"
Taxes don't show up at any point in the checkout process.
What am I doing wrong?
Answer: I do not know what the California Sales Tax conditions was. I think it might be some kind of stub for generating a custom condition somehow. Anyway, what I ended up doing was using the custom PHP code condition and calling this from it:
<code>function check_california_tax($order) {
    $state = uc_get_zone_code($order->delivery_zone);
    if ($state == 'CA') {
        return true;
    } else {
        return false;
    }
}
</code>
Answer: California Sales Tax has three elements. A state tax, a county tax and a district tax.
There are products that are exempt of all three taxes, like digital downloaded goods. State and County sales tax are always charged for a taxable good shipped in the state. The district tax is based on the shipping address of the goods.
There are over 400 district taxes, and multiple taxes can apply to a single address. Being districts, like a school catchment area for a school tax, or a hospital service area fro a hospital tax, the boundaries are not based on zip codes.
Further it is important that the correct districts and amounts are recorded for reporting the tax when paid over. In addition to correct reporting being a requirement of the business license, the districts get 50% of the monies for these taxes (50% to the state) and depend on them being correctly paid over to fund the costs of the local services.
It is not possible to do this using rules, one does need a table of districts, rates and how to determine what districts an address is in. The best way I have found is to use a commercial service from Avalara, Inc. The costs to them are a fraction of the development costs, let alone costs of maintaining the rates table, and eliminate audit issues later in the life of the business.
Google "ubercart avatax" - the results will be obvious.

Taxes in ubercart


Error after migrating site

Question: I get this error after I have migrated my site from local to live.

Notice: unserialize() [function.unserialize]: Error at offset 718 of
  1340 bytes in views_db_object->load_row() (line 2251 of
  /storage/content/16/184116/.com/public_html/sites/all/modules/views/includes/view.inc)

And this results in my site not showing my views. I suspect that this could have something to do with me changing "mylocalsitedirectory" to "mylivesite" in DB before importing DB to live site and ending up having a different serialization in Views than what it expects. But how do I solve this?
Comment: Go to `admin/config/development/performance` and purge the cache. Maybe it will help you.
Comment: Change the serialised string back to its original state, use `unserialize` to get the php array, change the array value you need to **in PHP**, then `serialize` it up again before pasting into the relevant db field. Simple as that :)
Comment: Or, even simpler, change the identifier preceding that value, e.g. `s:123:` to match the char count of the string after its been changed.
Answer: You don't have to delete everything.  Using database viewing/querying software (phpMyAdmin, dbForge Express, etc.), you can identify exactly which view is causing problems allowing you to remove only one view or attempt to fix it.
It is detailed in this answer: https://drupal.stackexchange.com/a/105393/8506
Answer: This is a painful process, but gets the job done.

Delete the two tables views_display and views_views
Export all views manually using Drupal export view from development
environment
Import all views manually using Drupal import view in production
environment
Comment: Should I not TRUNCATE the two tables and then export data? Or do the import also create the tables?
Comment: The import should create the tables. So truncate the tables
Comment: what if i've got hundreds of views? Any other solution?(
Answer: I've had some success with this script:
http://davidcoveney.com/782/mysql-database-search-replace-with-serialized-php/

Error after migrating site


IAM user with DeleteObject permissions cannot delete from S3 bucket

Question: Guys there's something I really don't understand. The GitLab runner at the bottom cannot delete objects in the bucket at the top. He should have permissions to do that, but instead I get the following:

delete failed: s3://bucket.domain.com/file.png An error occurred (AccessDenied) when calling the DeleteObject operation: Access Denied

S3 permissions bucket policy:
<code>   {
       "Version": "2012-10-17",
       "Statement": [
           {
               "Sid": "Stmt1412062044000",
               "Effect": "Allow",
               "Principal": {
                   "AWS": "arn:aws:iam::321570121925:root"
               },
               "Action": [
                   "s3:GetObject",
                   "s3:PutObject",
                   "s3:PutObjectAcl",
                   "s3:DeleteObject"
               ],
               "Resource": [
                   "arn:aws:s3:::bucket.domain.com/*",
                   "arn:aws:s3:::bucket.domain.com"
               ]
           },
           {
               "Sid": "Stmt1721016931TBA",
               "Effect": "Allow",
               "Principal": {
                   "AWS": "arn:aws:iam::321570121925:root"
               },
               "Action": [
                   "s3:ListBucket",
                   "s3:GetBucketLocation"
               ],
               "Resource": "arn:aws:s3:::bucket.domain.com"
           }
       ]
   }
</code>
GitLab runner result for "aws sts get-called-identity":
<code>   {
       "Account": "321570121925",
       "UserId": "AROAJZ6FNUZ33NL3XQVYK:i-0394709c2c1742643",
       "Arn": "arn:aws:sts::321570121925:assumed-role/gitlab-runner-20180419190331730700000002/i-0394709c2c1742643"
   }
</code>
I've been investigating for hours and this doesn't make sense to me. Help please.
Comment: Does the account 321570121925 own this bucket?  I'm guessing not, but don't want to start making incorrect assumptions.  What do you believe granting permissions to the account root should accomplish, here, and why?
Comment: @Michael Nope - the account doesn't own the bucket, and I'm trying to give it permissions so it can DeleteObject in it. It can Get and Put, but when it tries to Delete through the pipeline, it gets "permission denied".
Comment: Okay, so the bucket policy is probably fine, as is, but all this is doing is saying that the root of the specified account is *allowed to delegate* access to the bucket via user or role policy... but I don't believe you're doing that.  The gitlab runner role needs a policy statement allowing the same things.
Comment: @Michael Yeah you're correct - the GitLab runner assumes an IAM role that also needs matching permissions - they need to be both in the bucket policy and role policy. It doesn't work if DeleteObject isn't present in both places, and I had it only in the bucket. You can submit this as the answer btw.
Answer: S3 allows cross-account delegation of permissions, so that principals (users, roles) in one account can access resources in anothet account.
But, to do this, both accounts must grant the necessary permissions: the account that owns the bucket must delegate the permission and the account that owns the principal must also grant the permission.
<code> "Principal": {
      "AWS": "arn:aws:iam::xxxxxxxxxxxx:root"
  },
</code>
In the bucket policy, this delegates the permission to the root of foreign account xxxxxxxxxxxx... but that account must further delegate the permission to its users/roles with the appropriate IAM policy.

Note
To perform a specific operation on a resource, an IAM user needs permission from both the parent AWS account to which it belongs and the AWS account that owns the resource.
https://docs.aws.amazon.com/AmazonS3/latest/dev/how-s3-evaluates-access-control.html

The document referenced above privides an extensive overview of how S3 handles privilege checks.


Find a probability given specific cdf values

Question: Given $X$ is uniform random variable, $P\{X>1\} = 0.6$ and $F(2) = 0.5$.
Find $P\{-1\leq X < 3\}$.
My solution is: $P\{X>1\} = F(\infty) - F(1) = 0.6$. So $F(1) = 0.4$
And now I assume that F grows linearly. I need to find $F(3) - F(-1)$. Using fact of linearity I can say that $F(3) - F(-1) = 4 * [F(2) - F(1)]$.
My answer is $4\times(0.5 - 0.4) = 0.4$.
Am I right?
Comment: In this case, yes, but for example the same reasoning for $P\{ -1 \le X\le 8 \}$ does not hold
Comment: So, in the case of -1 to 10 I need to say that P = 1 if I get answer more then 1? UPD: Ok, let me think for a second
Comment: No, that's also false
Answer: If $X$ is uniform on some support $a \le X \le b$, then the density is $$f_X(x) = \begin{cases} \frac{1}{b-a}, & a \le x \le b, \\ 0, & \text{otherwise}. \end{cases}$$ The CDF is then $$F_X(x) = \begin{cases} 0, & x < a \\ \frac{x-a}{b-a}, & a \le x \le b \\ 1, & b < x. \end{cases}$$  We are given $$F_X(1) = 1 - \Pr[X > 1] = 1 - 0.6 = 0.4,$$ and $$F_X(2) = 0.5.$$  From these, we determine $$\frac{1 - a}{b-a} = 0.4, \\ \frac{2 - a}{b-a} = 0.5.$$  Hence $$\frac{0.4}{0.5} = \frac{1-a}{2-a},$$ so $a = -3$; we then substitute back to obtain $b = 7$, and $$\Pr[-1 \le X < 3] = F_X(3) - F_X(-1) = \frac{3-(-3)}{7-(-3)} - \frac{-1-(-3)}{7-(-3)} = \frac{2}{5}.$$

The reason why your solution works is that it so happens that the given probabilities result in the support $[a,b]$ to be "large enough" to contain the desired outcome $-3 \le X < 1$.  For example, now that we know $[a,b] = [-3,7]$, if I asked you for $\Pr[-5 < X < 0]$, you could neither say this is $1$ nor $0.5$.  The answer is $0.3$ because $\Pr[-5 < X < 0] = \Pr[-3 < X < 0]$, since the intersection $$(-5,0) \cap [-3,7] = [-3, 0).$$  So you need an extra step to justify that the "shortcut" you used is valid.
Comment: Thank you very much :)


Survival analysis using cox returns "The truth value of a Series is ambiguous."

Question: So I'm working with a dataset of Stroke cases from an hospital, and I would like to use Cox regression to make a survival analysis using time of arrival in the hospital, time of leave and survival or not. I have also lab data, sex, and age of the patient. processing the data is pretty straight forward but the I'm trying to use lifelines CoxPHFitter and fit it to the data I get the error : "ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()."
I will paste down here some info about the data I'm using :
X.info()
X.head()

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4552 entries, 0 to 4551
Data columns (total 3 columns):
 #   Column  Non-Null Count  Dtype
---  ------  --------------  -----
 0   CHOL    4552 non-null   float64
 1   sex     4552 non-null   int64
 2   age     4552 non-null   int64
dtypes: float64(1), int64(2)

CHOL
Sex
Age

0
4.9
1
95

1
4.9
1
91

2
4.1
0
50

3
5.6
0
79

4
4.9
0
57

I use T and E as:
T = df['survival_time']  # Time-to-event data
E = df['event_occurred']  # Censoring indicator

where T is leave date of the hospital - admission to the hospital date in days
and E is 1 for Death as a result or 0 for survival (also tried True and False)
And this is how I use the CoxPHfitter :
from lifelines import CoxPHFitter

# Fit Cox proportional hazards model
coxph = CoxPHFitter()
coxph.fit(X, duration_col=T, event_col=E)

print(coxph.summary())

The line coxph.fit(X, duration_col=T, event_col=E) generates this error : ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
Anyone has an idea of why I get this error ?
full error log:
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[150], line 5
      3 # Fit Cox proportional hazards model
      4 coxph = CoxPHFitter()
----> 5 coxph.fit(X, duration_col=T, event_col=E)
      7 print(coxph.summary())

File ~/anaconda3/lib/python3.11/site-packages/lifelines/utils/__init__.py:56, in CensoringType.right_censoring.<locals>.f(model, *args, **kwargs)
     53 @wraps(function)
     54 def f(model, *args, **kwargs):
     55     cls.set_censoring_type(model, cls.RIGHT)
---> 56     return function(model, *args, **kwargs)

File ~/anaconda3/lib/python3.11/site-packages/lifelines/fitters/coxph_fitter.py:290, in CoxPHFitter.fit(self, df, duration_col, event_col, show_progress, initial_point, strata, weights_col, cluster_col, robust, batch_mode, timeline, formula, entry_col, fit_options)
    184 """
    185 Fit the Cox proportional hazard model to a right-censored dataset. Alias of `fit_right_censoring`.
    186
   (...)
    287
    288 """
    289 self.strata = utils._to_list_or_singleton(utils.coalesce(strata, self.strata))
--> 290 self._model = self._fit_model(
    291     df,
    292     duration_col,
    293     event_col=event_col,
    294     show_progress=show_progress,
    295     initial_point=initial_point,
    296     strata=self.strata,
    297     weights_col=weights_col,
    298     cluster_col=cluster_col,
    299     robust=robust,
    300     batch_mode=batch_mode,
    301     timeline=timeline,
    302     formula=formula,
    303     entry_col=entry_col,
    304     fit_options=fit_options,
    305 )
    306 return self

File ~/anaconda3/lib/python3.11/site-packages/lifelines/fitters/coxph_fitter.py:610, in CoxPHFitter._fit_model(self, *args, **kwargs)
    608 def _fit_model(self, *args, **kwargs):
    609     if self.baseline_estimation_method == "breslow":
--> 610         return self._fit_model_breslow(*args, **kwargs)
    611     elif self.baseline_estimation_method == "spline":
    612         return self._fit_model_spline(*args, **kwargs)

File ~/anaconda3/lib/python3.11/site-packages/lifelines/fitters/coxph_fitter.py:623, in CoxPHFitter._fit_model_breslow(self, *args, **kwargs)
    619 model = SemiParametricPHFitter(
    620     penalizer=self.penalizer, l1_ratio=self.l1_ratio, strata=self.strata, alpha=self.alpha, label=self._label
    621 )
    622 if utils.CensoringType.is_right_censoring(self):
--> 623     model.fit(*args, **kwargs)
    624     return model
    625 else:

File ~/anaconda3/lib/python3.11/site-packages/lifelines/utils/__init__.py:56, in CensoringType.right_censoring.<locals>.f(model, *args, **kwargs)
     53 @wraps(function)
     54 def f(model, *args, **kwargs):
     55     cls.set_censoring_type(model, cls.RIGHT)
---> 56     return function(model, *args, **kwargs)

File ~/anaconda3/lib/python3.11/site-packages/lifelines/fitters/coxph_fitter.py:1229, in SemiParametricPHFitter.fit(self, df, duration_col, event_col, show_progress, initial_point, strata, weights_col, cluster_col, robust, batch_mode, timeline, formula, entry_col, fit_options)
   1226 self.formula = formula
   1227 self.entry_col = entry_col
-> 1229 X, T, E, weights, entries, original_index, self._clusters = self._preprocess_dataframe(df)
   1231 self.durations = T.copy()
   1232 self.event_observed = E.copy()

File ~/anaconda3/lib/python3.11/site-packages/lifelines/fitters/coxph_fitter.py:1305, in SemiParametricPHFitter._preprocess_dataframe(self, df)
   1303     df = df.set_index(self.strata)
   1304 else:
-> 1305     sort_by = [self.duration_col, self.event_col] if self.event_col else [self.duration_col]
   1306     df = df.sort_values(by=sort_by)
   1307     original_index = df.index.copy()

File ~/anaconda3/lib/python3.11/site-packages/pandas/core/generic.py:1527, in NDFrame.__nonzero__(self)
   1525 @final
   1526 def __nonzero__(self) -> NoReturn:
-> 1527     raise ValueError(
   1528         f"The truth value of a {type(self).__name__} is ambiguous. "
   1529         "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
   1530     )

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Comment: Can you include the full text of the error traceback? This suggests that the `fit` function is incorrectly using the shorthand (for example) `if s` to test whether a Pandas series `s` is empty or not, but if you're supplying the right types of input then that suggests that someone needs to update the package that that function came from.
Comment: @LucyJanssens try `T.values` and `E.values`
Comment: OK, I had a quick look at the `lifelines` library and it seems up-to-date and well maintained so it's probably that you need to change how you pass the data to it - try what @TinoD suggests and if that doesn't work I suggest seeking further help from the package author or any user community for that package.
Answer: When you use the fit method of the CoxPHFitter class, it expects the datato include all necessary columns like CHOL, sex, and age) as well as the duration and event indicator columns.You are not doing this. you can solve it this way:
from lifelines import CoxPHFitter
import pandas as pd

data = {
    'CHOL': [4.9, 4.9, 4.1, 5.6, 4.9],
    'sex': [1, 1, 0, 0, 0],
    'age': [95, 91, 50, 79, 57],
    'survival_time': [20, 40, 15, 10, 30],
    'event_occurred': [1, 0, 1, 0, 1]
}

df = pd.DataFrame(data)
coxph = CoxPHFitter()
coxph.fit(df, duration_col='survival_time', event_col='event_occurred')
summary = coxph.summary
print(summary)

which gives you what you wanted:
               coef  exp(coef)   se(coef)  coef lower 95%  coef upper 95%  \
covariate
CHOL      -1.067889   0.343734   5.069700      -11.004319        8.868542
sex       -2.123784   0.119578  15.619846      -32.738120       28.490551
age        0.059477   1.061282   0.440625       -0.804131        0.923086

           exp(coef) lower 95%  exp(coef) upper 95%  cmp to         z  \
covariate
CHOL              1.662972e-05         7.104912e+03     0.0 -0.210641
sex               6.053620e-15         2.362051e+12     0.0 -0.135967
age               4.474764e-01         2.517045e+00     0.0  0.134984

                  p  -log2(p)
covariate
CHOL       0.833167  0.263322
sex        0.891847  0.165131
age        0.892625  0.163874


Baker-Campbell-Hausdorff/Zassenhaus formula to first order in one matrix

Question: Is there a closed-form expression for the term of $e^{t(c \hat{X} + d \hat{Y})}$ that is first-order in $d$, where $t$, $c$, and $d$ are scalars and $\hat{X}$ and $\hat{Y}$ are finite-dimensional linear operators?  I guess that to calculate this, you would use the Zassenhaus formula to expand the exponential, then collect all the terms proportional to $d^1$.  Unfortunately, so far as I can find the Zassenhaus formula is usually presented organized in powers of $t$, and each power of $t$ has a term proportional to $d^1$, so you would need to consider every term in the $t$ expansion just to get the first term in the $d$ expansion.
(A general expression for the Zassenhaus formula reorganized in powers of $d$ would be even better, but that's probably too much to ask for!)
Comment: @ tparker , my friend, did you take the trouble to read the answers to your question ?
Comment: @loupblanc I'm sorry, I've been quite busy since asking that question and I haven't had time to carefully read and digest the answers.  But I will, and mark the question answered, some time this week!  Sorry for the long delay.
Comment: Aug 9 -- Sep 6 : All the same week.
Answer: I don't know about using the Zassenhaus formula, but I did obtain the following expression for the terms that are first-order in $d$:
$$\sum_{n\geq1}\frac{c^{n-1}t^n}{n!}\sum\limits_{r,s\geq0,\ \ r+s=n-1}\hat{X}^r\hat{Y}\hat{X}^s. $$
Basically, expand $e^{t(c \hat{X} + d \hat{Y})}$ as a power series:
$$e^{t(c \hat{X} + d \hat{Y})}=\sum_{n=0}^\infty \frac{t^n}{n!}(c \hat{X} + d \hat{Y})^n. $$
Then, for each term $(c \hat{X} + d \hat{Y})^n$, we get a single $d$ whenever we obtain one copy of $d\hat{Y}$ and $n-1$ copies of $c\hat{X}$. For example, when $n=2$ we get
$$cd(\hat{X}\hat{Y}+\hat{Y}\hat{X}),$$
and for $n=3$ we get
$$ c^2d(\hat{X}\hat{X}\hat{Y}+\hat{X}\hat{Y}\hat{X}+\hat{Y}\hat{X}\hat{X}). $$
Summing over all $n$, we obtain the result.
Answer:
The Baker-Campbell-Hausdorff (BCH) formulas to linear order in one of the operators $X$ and $Y$ are given by
$$ Z ~=~ \ln (e^Xe^Y) ~=~\left\{\begin{array}{l}
X+B(-{\rm ad}_X)Y +{\cal O}(Y^2), \cr\cr
Y+B({\rm ad}_Y)X +{\cal O}(X^2), \end{array} \right. \tag{1}$$
where
$$ B(x)~:=~\frac{x}{e^x-1}~=~1 -\frac{x}{2} +\frac{x^2}{12}-\frac{x^4}{720} +{\cal O}(x^6)\tag{2}$$
is the generating function of Bernoulli numbers.
The first order Zassenhaus formulas are given by
$$ e^{-X}e^{X+Y} ~=~  \exp\left\{ E(-{\rm ad}_X)Y +{\cal O}(Y^2)\right\}
~=~  1+ E(-{\rm ad}_X)Y +{\cal O}(Y^2)$$
$$~=~  \prod_{n=0}^{\infty}\exp\left\{ \frac{(-{\rm ad}_X)^nY}{(n+1)!}\right\} +{\cal O}(Y^2)  , \tag{3}$$
$$  e^{X+Y}e^{-Y}~=~\exp\left\{  E({\rm ad}_Y)X+{\cal O}(X^2)\right\}
~=~1+ E({\rm ad}_Y)X+{\cal O}(X^2)$$
$$~=~  \prod_{n=0}^{\infty}\exp\left\{ \frac{({\rm ad}_Y)^nX}{(n+1)!}\right\} +{\cal O}(X^2) , \tag{4}$$
where we have defined the reciprocal function
$$ E(x)~=~\frac{1}{B(x)}~=~\frac{e^x-1}{x}~=~\sum_{n=0}^{\infty}\frac{x^n}{(n+1)!}  .\tag{5}$$
Note that the operator ordering of the infinite product $\prod_{n=0}^{\infty}$ on the rhs. of eqs. (3) and (4) only matters beyond linear order.
Answer: Let $f:d\rightarrow e^{tcX+tdY}$. Then $f(d)=f(0)+Df_0(d)+O(d^2)$ when $t,c,X,Y$ are fixed. We can write the result in two different forms:

Let $ad_U:Z\rightarrow UZ-ZU$. $f(d)=e^{tcX}+e^{tcX}\sum_{k=0}^{\infty}\dfrac{(-1)^k}{(k+1)!}(ad_{tcX})^k(tYd)+O(d^2)$

or $f(d)=e^{tcX}(I+d\sum_{k=0}^{\infty}\dfrac{(-1)^k}{(k+1)!}t^{k+1}c^k(ad_{X})^k(Y))+O(d^2)$.

$f(d)=e^{tcX}+dt\int_0^1 e^{\alpha tcX}Ye^{(1-\alpha)tcX}d\alpha+O(d^2)$.


More simplified way of creating page links dynamically?

Question: well I have a working script (see below) but it seems quite clunky and redundant; in my defense I wrote this code many moons ago, but that's not the point. I was curious if anyone has an idea on a more efficient way of writing this code, with less loops and conditionals and, well, noise in the code.
Code in question:
private function pageLinks($num, $page = 1, $search = false, $ne = false) {
    $query = ($search) ? '&query='.$search : null;
    $by = (is_numeric($ne)) ? '&by='.$ne : null;
    $links = 'Page(s):1';
    $count = 1;
    $npp = $this->numPerPage;
    $buttons = 9;
    $half = 4;
    for($i = 1; $i <= $num; $i++) {
        if(($i%$npp) === 0) {
            $count++;
        }
    }
    if($count < $buttons) {
        for($i = 2; $i <= $count; $i++) {
            $links .= '' . $i . '';
        }
    } elseif($page <= ($half + 2)) {
        for($i = 2; $i <= $buttons; $i++) {
            $links .= '' . $i . '';
        }
        $links .= '...' . $count . '';
    } elseif($page <= ($count - ($half + 2))) {
        $links .= '...';
        for($i = $half; $i > 0; $i--) {
            $links .= '' . ($page - $i) . '';
        }
        $links .= '' . ($page - $i) . '';
        for($i = 1; $i <= $half; $i++) {
            $links .= '' . ($page + $i) . '';
        }
        $links .= '...' . $count . '';
    } else {
        $links .= '...';
        for($i = $buttons - 1; $i >= 0; $i--) {
            $links .= '' . ($count - $i) . '';
        }
    }
    return($links);
}

The method is called like so:
$links = $this->pageLinks($count, $page, $url, $ne);

And the variables are as such:
$count = total number of clients in database (int)
$page = current page to build from (int)
$url = the name or email for the search (String)
$ne = is for the search string either by name (1) or email (2) (int)
And the output is something like (as links):
Page(s):1 2 3 4 5 6 7 8 9...33
Or if you're in the middle (page 20):
Page(s):1...16 17 18 19 20 21 22 23 24...33
Now this isn't always called through a search function, hence the default values for $url and $ne, but that's not very important. My question is there a cleaner way to handle building of these links? Or am I stuck with this cluster of loops?
Comment: You should ask this on http://codereview.stackexchange.com/.
Comment: @JaredFarrish thanks for the heads up, I just did.
Answer: With the help of the people at codereview.stackexchange.com I found exactly what I needed. You can find the answer here for a more in-depth approach, but here is the updated code if anyone comes across this and is curious:
private function pageLinks($num, $page = 1, $search = false, $ne = false) {
    $query = ($search && is_numeric($ne)) ? "&query=" . $search . "&by=" . $ne : null;
    $links = "Page(s):" . $this->page_link(1, $query);
    $npp = $this->numPerPage;
    $half = 4;
    $count = floor($num / $npp) + 1;
    $from = $page - $half;
    if($from <= 2) {
        $from = 2;
    }
    $to = $page + $half;
    if($to >= $count - 1) {
        $to = $count - 1;
    }
    if($from > 2) {
        $links .= "...";
    }
    for($i = $from; $i <= $to; $i++) {
        $links .= $this->page_link($i, $query);
    }
    if($i < $count) {
        $links .= "...";
    }
    $links .= $this->page_link($count, $query);
    return($links);
}
private function page_link($num, $query) {
    return("" . $num . "");
}


Summation Bounds When Finding Transformation of 2 Poisson Random Variables

Question: I am reviewing some material on functions of several random variables from Section 7.4 of John E. Freund's Mathematical Statistics, 6th Edition, and I'm stumped on how the author gets the upper bound of a summation during a transformation, so I'm hoping someone could help me understand this.  The particular worked example is on page 249 and 250.  Here is the question:

If $X_1$ and $X_2$ are independent random variables having Poisson
  distributions with the parameters $\lambda_1$ and $\lambda_2$, find
  the probability distribution of the random variable $Y=X_1+X_2$.

The question is straight forward, and I fully understand every step until the author shows the upper bound for $X_2$ (and in fact, I can derive the answer through other methods, but I'm interested in working through this method).  Here is the solution the author provides and then I'll explain exactly what my issue is:

Since $X_1$ and $X_2$ are independent, their joint distribution is
  given by:
\begin{eqnarray*} f(x_{1},x_{2}) & = &
 \frac{e^{-\lambda_{1}}\left(\lambda_{1}\right)^{x_{1}}}{x_{1}!}\cdotp\frac{e^{-\lambda_{2}}\left(\lambda_{2}\right)^{x_{2}}}{x_{2}!}\\
 & = &
 \frac{e^{-\left(\lambda_{1}+\lambda_{2}\right)}\left(\lambda_{1}\right)^{x_{1}}\left(\lambda_{2}\right)^{x_{2}}}{x_{1}!x_{2}!}
 \end{eqnarray*}
for $x_{1}=0,1,2,\ldots$ and $x_{2}=0,1,2,\ldots$ . Since
   $y=x_{1}+x_{2}$ and hence $x_{1}=y-x_{1}$, we can substitute $y-x_{2}$
  for $x_{1}$, getting
\begin{eqnarray*} g(y,x_{2}) & = &
 \frac{e^{-\left(\lambda_{1}+\lambda_{2}\right)}\left(\lambda_{2}\right)^{x_{2}}\left(\lambda_{1}\right)^{y-x_{2}}}{x_{2}!\left(y-x_{2}\right)!}
 \end{eqnarray*}
for $y=0,1,2,\ldots$ and $x_{2}=0,1,2,\ldots,y$, for the joint
  distribution of $Y$ and $X_{2}$. Then summing on $x_{2}$ from $0$ to
  $y$, we get
\begin{eqnarray*} h(y) & = &
 \sum_{x_{2}=0}^{y}\frac{e^{-\left(\lambda_{1}+\lambda_{2}\right)}\left(\lambda_{2}\right)^{x_{2}}\left(\lambda_{1}\right)^{y-x_{2}}}{x_{2}!\left(y-x_{2}\right)!}\,\,\,\,\,\,\,(*)\\  & = &
 \frac{e^{-\left(\lambda_{1}+\lambda_{2}\right)}}{y!}\cdotp\sum_{x_{2}=0}^{y}\frac{y!}{x_{2}!\left(y-x_{2}\right)!}\left(\lambda_{2}\right)^{x_{2}}\left(\lambda_{1}\right)^{y-x_{2}}
 \end{eqnarray*}

Now, what I don't understand is how we obtain an upper bound of $y$ on the summation for $x_2$ on the last two lines, denoted with $(*)$?  Since $x_2$ is poisson, shouldn't the upper bound be infinity?  Can someone help me understand where "$y$" comes from?  Thanks.
Comment: $x_1>y$ would imply $x_2$ was negative.
Answer: You have to recall that $X_1$ and $X_2$ are Poisson random variables and this means the support for $X_1$ and $X_2$ is 0, 1, 2, etc. for each.  In other words, $x_1$ and $x_2$ are integers such that $x_1\ge 0$ and $x_2\ge 0$.  Then, combine these facts with the fact that $x_1=y-x_2$ and substituting this value for $x_1$ into $x_1\ge 0$ reveals $y-x_{2} \ge 0 \implies y\ge x_{2}$.  Obviously, this means $x_2$ the upper bound cannot exceed $y$.


call to undefined function fatal error - weird problem

Question: I have a custom module which calls a custom function. I created this function longback working fine till yesterday. today it says call to undefined function
fatal error. Does anyone know what the reason could be. I tried all the possibility to make it work, but it crashes!
using drupal 7 , php 5.2
Comment: Did you try uninstalling and reinstalling the module?
Comment: Is this function in main module or some inc file?
Comment: Please add more info to your question. Where is the custom function written ? Where are you calling this from ? Are the custom modules enabled ?
Comment: Welcome to Drupal Answers :) in its current form this isn't a reasonable question. It's impossible to speculate as to what's causing errors in code we can't see. Please add the code and exact error message(s) to the question, and flag it to be reviewed for re-opening
Answer: The reasons maybe:

Either the module is disabled.
Typo error in the function call.
The module has been removed.


ActionCreator Dispatch not Rerendering component

Question: I have a simple drop-down menu for selecting a language, attached to a card that fires off an action languageSelected() onClick that should, in turn, re-render the component with the updated language.
The action is definitely firing onClick and I can see the state "change" with redux devtools.

However, the container component is not rerendering. Still new to Redux so I'm sure it's something silly I'm overlooking.
container/question

import React, { Component } from 'react';
import { languageSelected } from '../../actions/language';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { LANGUAGE_ENGLISH } from '../../actions/actionsTypes';
import { LANGUAGE_SPANISH } from '../../actions/actionsTypes';
import { LANGUAGE_CHINESE } from '../../actions/actionsTypes';
import '../../styles/Main.css';

class Question extends Component {
 render() {
  const {question, language, languageSelected} = this.props;
  let selectedQuestion = language;
  switch (selectedQuestion) {
   case LANGUAGE_SPANISH:
    selectedQuestion = question.q_spanish;
    break;
   case LANGUAGE_CHINESE:
    selectedQuestion = question.q_chinese;
    break;
   default:
    selectedQuestion = question.q_english;
    break;
  }
  return (

{question.category}

       <button
        className="btn language-btn dropdown-toggle pull-right"
        type="button"
        data-toggle="dropdown"
        aria-haspopup="true"
        aria-expanded="false">
        Language
       </button>

        <button className="dropdown-item white-link"
          type="button"
          onClick={() => languageSelected(LANGUAGE_ENGLISH)}>
         English
        </button>
        <button className="dropdown-item white-link"
          type="button"
          onClick={() => languageSelected(LANGUAGE_SPANISH)}>
         Spanish
        </button>
        <button className="dropdown-item white-link"
          type="button"
          onClick={() => languageSelected(LANGUAGE_CHINESE)}>
         Chinese
        </button>

{selectedQuestion}

  );
 }
}

function mapStateToProps(state) {
 return {
  question: state.question.selectedQuestion,
  language: state.language,
  languageSelected: state.language.languageSelected
 };
}

function mapDispatchToProps(dispatch) {
 return bindActionCreators({languageSelected}, dispatch)
}

export default connect(mapStateToProps, mapDispatchToProps)(Question);

action/language

import { LANGUAGE_SELECTED } from './actionsTypes';

export function languageSelected(language){
 return {
  type: LANGUAGE_SELECTED,
  payload: language
 }
}

reducer/language

import { LANGUAGE_SELECTED } from '../actions/actionsTypes';
import { LANGUAGE_ENGLISH } from '../actions/actionsTypes';
const initialState = {
 selectedLanguage: LANGUAGE_ENGLISH,
};

export default function(state = initialState, action) {
 switch(action.type) {
  case LANGUAGE_SELECTED:
   return {...state, selectedLanguage: action.payload};
  default:
   return state;
 }
}

rootreducer

import { combineReducers } from 'redux';
import questions from './questions';
import question from './question';
import language from './language';

const rootReducer = combineReducers({
 question,
 questions,
 language
});

export default rootReducer;
Answer: I think you have languageSelected in both mapStateToProps and mapDispatchToProps.. it looks like you should be using selectedLanguage from the state, but I can't find it in your render code:
function mapStateToProps(state) {
    return {
        question: state.question.selectedQuestion,
        language: state.language,
        // change from `languageSelected`
        selectedLanguage: state.language.selectedLanguage
    };
}

Comment: You just cured my headache. Thank you sir!


Fabric-karaf, Apache Camel, fabric-camel: "Component is not started"

Question: I have a problem with fabric-camel component.
It detects my camel endpoints from blueprint:
2014-10-02 15:27:43,598 | INFO  | 26c-351-thread-2 | FabricPublisherEndpoint          | 204 - io.fabric8.fabric-camel - 1.1.0.CR5 | Child: jetty:https://127.0.0.1:1221/https/incontrol?matchOnUriPrefix=true
2014-10-02 15:27:43,598 | INFO  | 26c-351-thread-2 | FabricPublisherEndpoint          | 204 - io.fabric8.fabric-camel - 1.1.0.CR5 | Consumer: jetty:https://127.0.0.1:1221/https/incontrol?matchOnUriPrefix=true

But then I get "Caused by: java.lang.IllegalStateException: Component is not started"
2014-10-02 15:27:43,602 | ERROR | 26c-351-thread-2 | BlueprintContainerImpl           | 197 - org.apache.aries.blueprint.core - 1.4.0 | Unable to start blueprint container for bundle pl.com.xxxxxx.esb.esb-incontrol-proxy
org.osgi.service.blueprint.container.ComponentDefinitionException: Unable to initialize bean .camelBlueprint.factory.inControlProxyContext
...
Caused by: org.apache.camel.ResolveEndpointFailedException: Failed to resolve endpoint: fabric://incontrol:jetty:https://127.0.0.1:1221/https/incontrol?matchOnUriPrefix=true due to: Component is not started
...
Caused by: java.lang.IllegalStateException: Component is not started
    at io.fabric8.camel.ZKComponentSupport.createGroup(ZKComponentSupport.java:53)

More detailed stacktrace http://pastebin.com/BFrPBarp
My blueprint.xml (relevant parts):

<bean id="httpsRouteBuilder" class="pl.com.xxxxxxx.camel.builder.HttpsRouteBuilder">
    ...

    <property name="incomingUri" value="fabric:incontrol:jetty:${endpoint.https.incoming.url}?matchOnUriPrefix=true"/>
    <property name="outgoingUri" value="${endpoint.https.outgoing.url}?bridgeEndpoint=true&throwExceptionOnFailure=false"/>

    ...
</bean>
...
<camelContext id="inControlProxyContext" trace="false" streamCache="true"
              xmlns="http://camel.apache.org/schema/blueprint"
              xsi:schemaLocation="http://camel.apache.org/schema/blueprint http://camel.apache.org/schema/blueprint/camel-blueprint-2.10.0.xsd">
    ...
    <routeBuilder ref="httpsRouteBuilder"/>
    ...
</camelContext>

My pom.xml (relevant parts):

<dependency>
    <groupId>io.fabric8</groupId>
    <artifactId>fabric-camel</artifactId>
    <scope>provided</scope>
</dependency>

I'll try to enable debug logging and see what else I can find. Unfortunately I still don't understand the underlying issue: why the component was not started?
Version info:

Karaf: 2.3.0.redhat-610379
Fabric: 1.1.0.CR5
Answer: You can try to enforce the component to be manually instantiated and started before the route is started: Try something like this:
<endpoint xmlns="http://camel.apache.org/schema/blueprint" id="fakeFabricEndpoint" uri="fabric:fake:jetty:${endpoint.https.incoming.url}?matchOnUriPrefix=true"/>


decreasing and concavity of function

Question:
If $g(x)=x-\sqrt{x}.$ Then the interval in which function is decressing and also find the interval in which function $g(x)$ is concave upward,is

My trial way
Dpmain of function is $x\geq 0$
$\displaystyle g'(x)=1-\frac{1}{2\sqrt{x}}$ and $\displaystyle g''(x)=\frac{1}{4x\sqrt{x}}$
For decreasing function $g'(x)<0$ and concave upward $g''(x)>0$
Function is decreasing in $\displaystyle \bigg(0,\frac{1}{4}\bigg)$ and concave upward in $x>0$
My doubt is whether we include $x=0$ in the interval or not
Means can we say function decreasing in $[0,1/4)$ and concave upward in $[0,\infty)$
Please clearfy me . Thanks
Answer: Yes you can. Take any interval $[0,t]$, where $t<1/4$. Then $g$ is continuous on $[0,t]$ and differentiable on $(0,t)$. For $x\in[0,t]$, what can you say about $g(t)-g(0)$?
Comment: So what should be the final answer. Means $[0,1/4)$ and $[0,\infty)$
Answer: Talking about a point in context of increasing/decreasing of a function is vague. The question boils down to asking whether $g$ is decreasing at $x=0$. So one may or may not choose to write it that way, either way is correct.
Comment: I would restrain myself from including $x=0$ for interval where $g$ is concave upward. Otherwise it would be an inflection point but since the curve does not exist for $x\lt 0$, it does not satisfy the condition of being called an inflection point.
Comment: Thanks so much.
Comment: And what we can say about concavity. Can we include $x=0$

decreasing and concavity of function


VS2012 and SQL Server Express

Question: I learnt that VS2012 comes with a version of SQL Server Express named LocalDb that works a little bit different from the usual SQL Server Express, the latter one works as a service.
What if I was interested in using the database as a service, can I have both installed, the new one that comes with VS2012 and SQL Server Express 2008?
Answer: I think you have this slightly wrong. It doesn't come with a local database, it comes with a built in GUI to access SQL Server (what ever version). You can use any database you like (multiple databases) and connect to the SQL Server using the Visual Studio version of SSMS.
So, yes, you can install multiple versions of SQL Server on your machine. I currently have 2005 express, 2008 developer edition, 2012 developer edition and express.
Comment: I'm starting a project and I don't know exactly what I'll need in the future, I'm trying to figure out my preferred environment, I know that it has a Visual Studio (2012 for now), Sql Server Express (I don't know why the name change), Silverlight, Azure, Wpf, etc.. and development for small businesses.  Knowing that, do you think that the current Sql Server 2012 Express will suffice?
Comment: @Rafael It is too hard to answer, but, if you're just starting then yes. I've only had to use SQL SERVER for large enterprise jobs with work. For my own websites and software projects, I use SQL express and it's fine. All of these things are confusing when you start, my advice is to start small and don't use the biggest and most powerful; typically they exist to solve a problem but can come with their own problems. I suggest start with Sql Server Express and only if it doesn't do something then think about moving, and Google SQL Server Express Limitations to understand it better.
Comment: Hi dave. When you say SQL Server Express, are you referring to SQL Server Express 2008 or the SQL Server Local DB that ships with VS2012?. I'm trying to standardize the development towards VS2012 as my dev env, but with respect to Silverlight projects, I think (maybe I'm wrong) that SQL Server Express 2008 is a better option. Don't you think?
Comment: Remember, SQL typically is backward compatible, just not forward compatible. Personally, I'd install SQL Server 2012 on your machine and point your connections from within Visual Studio to that.

VS2012 and SQL Server Express


MongoDB aggregation skip null value key

Question: I am trying to remove duplicate value from array which I am able to successfully achieve with below query however having difficulties skip key where values is null. I am using following code
db.mobile_data.aggregate([{$unwind: '$All_Participants'},
{$group: {_id:'$_id',All_Participants: {$addToSet: '$All_Participants'},
  Chat_group: {$first: '$Chat_group'}, Message_id: {$first: '$Message_id'} }}]);

my output result as follow
{
    "_id" : ObjectId("5856b1e39a47e6d13dab370b"),
    "All_Participants" : [
        "user1",
        "user4"
    ],
    "Chat_group" : 67.0,
    "Message_id" : Null
}

How can ignore Message_id if value is null? Expected output should be
{
    "_id" : ObjectId("5856b1e39a47e6d13dab370b"),
    "All_Participants" : [
        "user1",
        "user4"
    ],
    "Chat_group" : 67.0
}

Comment: I think this can help: http://stackoverflow.com/questions/33123396/group-in-mongo-excluding-null-values
Comment: I have tried following link command but did not work for me
Answer: Unfortunately, there is no way to remove 'null' fields during $group stage. We would need to add an additional $project stage after the $group stage to remove the null fields:
db.mobile_data.aggregate([
{$unwind: '$All_Participants'},
{$group: {_id:'$_id',All_Participants: {$addToSet: '$All_Participants'},
  Chat_group: {$max: '$Chat_group'}, Message_id: {$first: '$Message_id'} }},

{$project: {'All_Participants': 1, 'Chat_group': 1, 'Message_id': {
            $cond: {
               if: { $ifNull: [ "$Message_id", true ] },
               then: "$$REMOVE",
               else: "$Message_id"
            }}}}]);

If any other attributes (like 'Chat_group') can be null, then again a similar conditional projection would be required for it.
Also note that I have used $max to group 'Chat_group' instead of $first so that it doesn't consider null values but it could lead to degraded performance.
Answer: While unwinding 'All_Participants' you can use -> preserveNullAndEmptyArrays which will not unwind the null field if set to false.
You can refer this link->
https://docs.mongodb.com/v3.2/reference/operator/aggregation/unwind/
Comment: This answer is not completely correct as it can happen that the data doesn't have 'Message_id' attribute itself. Then in $group stage it would result in showing "Message_id" : Null. Therefore, we need to add a $project stage after the $group stage.

MongoDB aggregation skip null value key


Can Playing Cause Back Pain In Right Shoulder Blade?

Question: At first I thought this injury was related to golf, because it's painful to swing a golf club as well.  But I'm beginning to think that playing sitting down for long stretches (4-6 hours) is pulling a muscle in my back.  I have a sharp pain that is near the center of my back between my spine and my shoulder blade.  It hurts to sit up, wipe a counter, or swing a golf club.
Has anyone else had this problem?  If so, anyone no how to fix/prevent this?  I also have a bad case of tennis elbow that I know is related to playing but that seems to be clearing up with a little ice/heat treatment.
Comment: In "The Inner Game of Music", physical comfort is discussed at some length (as a form of "interference"/impediment to achieving your best performance). If memory serves, their suggestion is to bring your focus and attention to that body part that is hurting, and you will subconsciously adjust your technique. Sounds mystical, but I assure you the book is anything but!
Comment: Are you sitting in a classical position with one leg raised on a step or something?
Answer: It absolutely, absolutely can! You need to get a set of stretches specific for your issues to try to make sure the awkward muscle balance you're developing doesn't throw your body off so much that it becomes a long term problem. Proper posture and proper activation of postural muscles is KEY to making sure you don't get pain in your back and shoulders.
As you noticed, asymmetry on one side of your body can lead to all kinds of issues. Misalignment in your shoulder often leads to pain in the elbow, and we see it at my office all the time. Working on the finishing touches of a book of stretches for guitarists to do to help keep things balanced based on observations of clients I've worked with and my own guitar-playing experience.
Comment: Yes, stretching is the Right Answer.
Answer: It definitely can; it really depends how you are crouching over the guitar whilst playing.
If your playing for long periods it doesn't hurt to stretch off during and after your practice; you should be taking 15 minute breaks every 60-90 minutes anyway; try some arm and back stretching during this time, and at the end of your practice.
You could also look at your posture whilst playing, you should try and keep your back pretty straight, if your leaning over the guitar then this is one of the problems. Also look at the chair your sitting on,  any chair that is sat on for a long time should be well cushioned and comfortable, especially while playing an instrument.  Try using a foot-stool to bring the guitar closer to you by raising your knee, this will mean that you don't have to crouch over the guitar.
As for the elbow trouble; its not unusual; I tend get that in my shoulder more than anything, not so much in my elbow, but everyone sits slightly differently.  The same things apply to this, good posture and chair/stool will help, stretching the arm will never do any harm if done properly and may help.
Depending on your style of play; you might want also to try classical posture, there are plently of rock/metal/jazz men out there that also prefer this posture.  In fact it is necessary if practising with a V shaped guitar.
Comment: Thanks for the link -- I'll have to give some different sitting positions a try.  I definitely hunch over which is something I need to change.
Answer: Regardless of which instrument or style you are playing, playing in a relaxed position is a key to playing well and avoiding injury. With the various things you are concentrating on while playing, it can be very easy to simply not notice tension in your back, shoulders, arms, etc...
Maintain a focus on easy and free movement while playing, especially more difficult sections. In addition, it is good to take regular short breaks, such as 5 minutes half hour, to help relax the muscles and keep the mind focused.
Answer: For me personally, stretching solves all these problems.
You can follow a course, but the jist of it is to stretch every muscle in your arms and back, chest etc until it is completely loose.
The secret is not to overstretch, you should only take the stretch to just before the pain, and then back off.  Hold each stretch for a minimum of 30 seconds.
You can start with a standard Bob Anderson book but eventually you will develop your own stretches that really stretch the tense muscles.
Stretch regularly and often.  Yes it takes a lot of time.  And yes it is worth it.
Answer: Another thing to consider; besides the postures you adopt while doing various things, pay some attention to your normal posture.
You mention "wiping counters". I've worked nearly 10 years in food service and wiping counters can have a cumulative adverse effect on posture. Constantly leaning forward can give you "hunchback", if you're not careful.
You have to fix this from the lumbar, up!

Practice sitting on the very edge of a chair to make sure your lumbar is properly curved (if you're right on the edge of the chair one of three things will happen: you'll slip off onto the floor (if you've ruled-out beginner's luck, then this is a sign of a problem); it very quickly becomes uncomfortable or painful to continue sitting (this is also the sign of a problem); you can balance properly and could sit that way indefinitely (good)).
Practice standing "at ease". From the hips, up, your posture should be exactly the same as the sitting exercise: you're "sitting" on your legs. Your knees should be "straight" but not "locked". You should feel pressure in both the ball and heel of each foot (for bonus points, "roll" the pressure around the four contact).

Also helpful is raising the head slightly, eyes just above the horizon, for both of these.
Then, try it with the guitar (golfclub, wiping cloth, etc.).
Answer: Might me shape and size of your guitar which is the issue.  If you have a small frame and are playing a dreadnought acoustic or jumbo size, you're arm is forced into a stretch which pulls you shoulder plate out wards into an awkward position.  Your right arm should be able to comfortable wrap around the body of the guitar without stretching your shoulder blade.  Width of the body is important too, the thicker the body the more you have to stretch your right arm round to reach the strings at the soundhole
Answer: Yes, it can. Even sleeping can, swimming, biking too. You can stimulate any trigger point of any muscle by any movement. You can't even say that there was an abusus or a wrong movement. I couldn't tell whether my pain came from swimming or sleeping. It was so hard that I couldn't walk any more or stand up from the bed or go to the toilet in autumn 2017. But I healed it myself like I use to do when I have cramp in the leg: Standing with full weight of the hurting part of the body.
Answer: You might have one of your shoulders rounded off and the other more squared off as it's possible that you do what I do and slouch with just your left side. It's painful and causes neck problems. I try to play left handed to try to even things out, but if you are playing guitar 4-6 hrs daily that'd probably take a lot of effort... To stop the pain maybe just hold the guitar the lefty way when you're not practicing. Kinda sucks but playing guitar's fun and kind of makes it worth it.


Prove that it is a metric

Question: Hello I have problems with this exercises:
Denote by ${\mathbb{R}}^\infty$ the set of all sequences in $\mathbb{R}$. For $x,y$ define $d$
$d(x,y)= \displaystyle\sum_{i=1}^\infty{} \displaystyle\frac{1}{n!} \displaystyle\frac{|x_n-y_n|}{1+|x_n-y_n|}$
Prove that $d$ is a metric
I have to prove the following axioms:
i) $ d(x,x)=0 $
ii) If $ x \neq y $, then $ d(x,y) > 0 $
iii) $ d(x,y)=d(y,x) $
iv) $ d(x,z)\leqslant d(x,y)+d(y,z) $
$d(x,y)= \displaystyle\sum_{i=1}^\infty{} \displaystyle\frac{1}{n!} \displaystyle\frac{|x_n-y_n|}{1+|x_n-y_n|} \rightarrow{0}$ as $n\rightarrow{\infty}$
This means that, for $\epsilon > 0$ there exists an integer $ n_0(\epsilon$ such that:
$\displaystyle\sum_{i=1}^\infty{} \displaystyle\frac{1}{n!} \displaystyle\frac{|x_n-y_n|}{1+|x_n-y_n|} < \epsilon $
and so
$\displaystyle\frac{1}{n!} \displaystyle\frac{|x_n-y_n|}{1+|x_n-y_n|} < \epsilon$
I don't know how to continue
Thanks
Comment: Do you mean $\sum_{n=1}^{\infty}?$
Comment: What is meaning of $\sum_{i=1}^n{\infty}$?
Comment: $i$ doesn't appear anywhere.  This must be a mistake.
Comment: The correct is $d(x,y)= \displaystyle\sum_{i=1}^\infty{} \displaystyle\frac{1}{n!} \displaystyle\frac{|x_n-y_n|}{1+|x_n-y_n|}$
Comment: Just checking: Can you show that the expression in each summand defines a bounded metric on the reals?
Answer: The proofs of i), ii) and iii) are trivial (very easy), so we are going to prove iv).
Since $\;\left|x_n-z_n\right|\leqslant\left|x_n-y_n\right|+\left|y_n-z_n\right|\;,\;$ it results that
\begin{align}\dfrac{\left|x_n-z_n\right|}{1+\left|x_n-z_n\right|}&=1-\dfrac1{1+\left|x_n-z_n\right|}\leqslant\\&\leqslant1-\dfrac1{1+\left|x_n-y_n\right|+\left|y_n-z_n\right|}=\\&=\dfrac{\left|x_n+y_n\right|+\left|y_n-z_n\right|}{1+\left|x_n+y_n\right|+\left|y_n-z_n\right|}=\\&=\dfrac{\left|x_n+y_n\right|}{1+\left|x_n+y_n\right|+\left|y_n-z_n\right|}+\dfrac{\left|y_n-z_n\right|}{1+\left|x_n+y_n\right|+\left|y_n-z_n\right|}\leqslant\\&\leqslant\dfrac{\left|x_n+y_n\right|}{1+\left|x_n+y_n\right|}+\dfrac{\left|y_n-z_n\right|}{1+\left|y_n-z_n\right|}\;.\end{align}
Consequently,
\begin{align}\sum\limits_{i=1}^\infty\dfrac1{n!}\dfrac{|x_n-z_n|}{1+|x_n-z_n|}&\leqslant\sum\limits_{i=1}^\infty\dfrac1{n!}\dfrac{|x_n-y_n|}{1+|x_n-y_n|}+\sum\limits_{i=1}^\infty\dfrac1{n!}\dfrac{|y_n-z_n|}{1+|y_n-z_n|}\end{align}
that is
$d(x,z)\leqslant d(x,y)+d(y,z)\;.$

Prove that it is a metric


Amazon S3 REST API; how is the API-key transferred firsttime between client and service?

Question: Within my research I came across many different sources, but somehow I fail to see, which side is generating the private API-key and how is the other side getting hold of it.
Many people recommend Amazon S3 Restful API as the role model, hence if I understand that, I could create something similar for my own purposes.
Amazon's S3 REST API.
e.g. this example here explains the process very nicely, however it fails to explain, which side is generating the API-key? So upon user signup, is it the service side that is generating the private API-key and assigns it to the user id in database?
If this is the case though, the client needs to know the API key in order to create the signature for each request, so that the service can actually verify it. So how do both sides get hold of the private API key?
In my case I would have a iPhone app and a AngularJS web app as my clients talking to the RESTful API service.
Many Thanks,
Answer: First, you don't want give out keys to your clients. In general, that's a security nightmare. (Also, key creation can take some hours to propagate. And you'll have to manage the permissions for each key, etc.)  So all the signing is done by your server, and your key doesn't leave your server.
You want your server to have the S3 key, but only return signed links that will give the client the power to do something (GET a particular file, or PUT a file).  It's a bit like the mother-may-I game: The client asks you for a "S3 signed link", then it can talk to S3 to do one thing.  Since your server is doing a trivial amount of work (checking request is authorized, then returning a signed URL), you will be able to scale pretty well.
For some things, like "list files" or "delete a file", it might be better for your server to call S3 (i.e. making a web request to S3 within the web request from the client) and return the results to the client (instead of messing with signed links). But if you do this, you may run into problems when scaling -- unless you are using the right technologies. (I.e. you want an evented server like node.js)
Note that for a PUT request, the signed link must specify a lot of stuff ahead of time (like the file type, etc). You have to read the AWS spec carefully.
Be careful of the Confused Deputy problem. Your code will have one key that can see all user's files, so you are responsible for the security between users.


Exchange 2016 Fresh Install HTTP ERROR 500

Question: After doing a new install of Exchange 2016 on Windows Server 2016 I go to https://ex1/ecp, attempt to log in and get:
This page isn't working ex1 is currently unable to handle this request.
HTTP ERROR 500

I have removed and create a new OwaVirtualDirectory, I have checked to make sure the groups that EX1 is a part of is not a part of Domain Admins, Schema Admins, Enterprise Admins, Organization Admins.
Running Get-OwaVirtualDirectory | FL Identity,auth,URL returns:
Identity                      : EX1\owa (Default Web Site)
ClientAuthCleanupLevel        : High
InternalAuthenticationMethods : {Basic, Fba}
BasicAuthentication           : True
WindowsAuthentication         : False
DigestAuthentication          : False
FormsAuthentication           : True
LiveIdAuthentication          : False
AdfsAuthentication            : False
OAuthAuthentication           : False
ExternalAuthenticationMethods : {Fba}
Url                           : {}
InternalSPMySiteHostURL       :
ExternalSPMySiteHostURL       :
SetPhotoURL                   :
Exchange2003Url               :
FailbackUrl                   :
InternalUrl                   :
ExternalUrl                   :

I can see that no internal or external URLs are showing which I think may be related to the problem, but don't know what to do for sure.
The only oddities in the install were:

During the first install there were errors that I had to fix (Windows Updates), after updates and reboot I attempted to reinstall through the GUI but it erred thinking it was already installed and I had to reinstall using cmd.
I manually added the domain administrator account (as well as my other admin account) to schema admins and enterprise admin groups for the install.
I unfortunately don't remember the error, but during install through cmd, there was some message that popped up saying that something in IIS wasn't setup, like a * http redirect I think? I don't know and I've since rebooted so can't scroll back to see it again. I feel like this is causing the issue.

EDIT:
I have now also tried running UpdateCas.ps1 with no success as well as the following:
Get-OwaVirtualDirectory | Set-OwaVirtualDirectory -FormsAuthentication $False -BasicAuthentication $True
Get-OwaVirtualDirectory | Set-OwaVirtualDirectory -FormsAuthentication $True -BasicAuthentication $True
Get-EcpVirtualDirectory | Set-EcpVirtualDirectory -FormsAuthentication $false -BasicAuthentication $true
Get-EcpVirtualDirectory | Set-EcpVirtualDirectory -FormsAuthentication $true -BasicAuthentication $true
iisreset

As well as:
Get-EcpVirtualDirectory | Set-EcpVirtualDirectory -FormsAuthentication $false -BasicAuthentication $true -WindowsAuthentication $true
Get-OWAVirtualDirectory | Set-OWAVirtualDirectory -FormsAuthentication $false -BasicAuthentication $true -WindowsAuthentication $true
iisreset
Recycle MSExchangeECPAppPool
Recycle MSExchangeOWAAppPool

Event Viewer shows Event ID 1023:
Exchange ActiveSync tried to access a mailbox on Mailbox server "EX1.mydomain". It could not access the mailbox because the Mailbox server is offline.

I feel that this must be the answer, I haven't had a chance to configure any mailbox datastores so the administrator would be in the default one. I cannot however locate how to find and mount this. Any ideas?
Answer: Figured it out. It was the mailbox datastore dismounted. Didn't know the name of the datastore so ran:
Get-MailboxDatabase -Server SERVERNAME | Mount-Database

I can access ECP now from the machine, although I now get 403 error when attempting to access the page from another PC on the network, but that's a separate issue.
Answer: I had a similar problem with exchange and I was able to fix it by following the directions here: https://support.microsoft.com/en-us/help/2779694/unable-to-open-owa-ecp-or-ems-after-a-self-signed-certificate-is-remov
Comment: Please do not post links as answers.  Links eventually die and then the answer disappears.


Update Your Amazon RDS SSL/TLS Certificates by October 31, 2019

Question: We recently received an email from AWS called "Update Your Amazon RDS SSL/TLS Certificates by October 31, 2019"
We have tried to follow the guidelines to get ready for the deadline in March 2020, however since our DB instance is in MySQL 5.6, it's unclear if we have to actually perform anything, since from the command line examples provided there is not for version 5.6
Could you please advise on the matter ?
Comment: if there is no SSL certificates already being in used, then what to do with the DB instances (RDS) using our web servers ?
means, currently we are not using any certificates for RDS to communicate.
please advise , is this the communication/ssl certificates related to AWS RDS and web servers on AWS also ?
Answer: It is my understanding that this will apply to all in-support MySQL instances regardless of version. Which would include 5.6, yes. The old CA expires uncomfortably soon, so AWS will not be leaving old MySQL versions behind on it. You will need to update your CA-files appropriately.


Reading pre-populated Sqlite.db in ios7

Question: I'm really new to ios world and I've got an app that was rejected by Apple because it takes to long to load data from an api (lots of records to save to my database). So I've decided to deliver my app with a prepopulated sqlite database to prevent from the initial load of objects.
First of all I've checked this site to understand how to insert my database in my project.
Site
I don't think the site is updated because in the ios7 the database created comes with 3 different files in the cache folder

database
database-wal
database-shm

Which one should I use to import?
And second of all how should I read the database file and copy/create my database from there?
My current database is created using CoreData, will that be a problem when i try to copy/create the imported database?
Tutorials and code snippets are welcome :)
Comment: It's not exactly a duplicate, but my answer here covers why those files are different and what you should do in this situation: http://stackoverflow.com/questions/20687547/nsmanagedobjectcontext-not-saving-properly-to-sqlite/20692638#20692638
Answer: First thing you need to remember is that you really should create this pre-populated database using Core Data.
To avoid having three files, the tool that creates the database needs to close it correctly. Here's what SQLite website for more info.
I don't know if Core Data does this if you properly tear down Core Data stack, but it probably should. If it won't do this, try to open and close the database that Core Data created using sqlite utility.
How you should use it in the app depends on your app. If this is some initial state from which the user is supposed to continue populating the database, you could just copy the file to the appropriate place (like Application Data subfolder) before initializing Core Data stack.
Another case is when this database is an example database like a photo library with photos that user is not supposed to keep when she starts using the app. In this case I would recommend separate this database and the user's database.
The third case is when this database is kind of a big catalog of something. And the user adds additional entries to it. You'll probably want to update this catalog from time to time without touching user's entries. In this case I would also recommend not to mix user's data with this catalog.
Answer: After a few researches and tests I managed to do it.
So I added the sqlite database to the project, according to the link in my question.
I've found this useful post that almost did the job. Post
So I've modified the persistentStoreCoordinator method on AppDelegate adding this code
and the database requests that I had with the old database worked with no problem.
<code>NSDictionary *options = @{ NSSQLitePragmasOption : @{@"journal_mode" : @"DELETE"} };

if (_persistentStoreCoordinator != nil) {
    return _persistentStoreCoordinator;
}

NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"MyDB.sqlite"];

NSError *error = nil;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];

if (![[NSFileManager defaultManager] fileExistsAtPath:[storeURL path]])
{
    NSURL *preloadURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"MyDB" ofType:@"sqlite"]];
    NSError* err = nil;

    if (![[NSFileManager defaultManager] copyItemAtURL:preloadURL toURL:storeURL error:&err])
    {
        NSLog (@"Error - Could not preload database.");
    }
}
</code>

Reading pre-populated Sqlite.db in ios7


Measures of effect size for chi-squared tests

Question: What are the different measures of effect size used for chi-squared tests / binomial data? I'm already at least somewhat familiar with the phi coefficient and odds ratio. I've heard of Cramer's V and relative risk as well. However, I'm still not sure how to decide which effect sizes to report in different circumstances. What are the arguments for / against the different measures of effect size and in what circumstances are each most informative?
Additionally, though I have resources for calculating confidence intervals for the odds ratio, I have struggled to find information regarding confidence intervals for the other effect size measures.
Answer: I think relative risk is the best index of effect size when using binomial data. Odds ratios are somewhat difficult to interpret (you can read the article entitled "Down with odds ratios!" by Sackett and colleagues). In contrast, relative risk provides an intuitive and easily interpretable value (e.g., one group has 40% greater risk of belonging to group X). Cramer's V is potentially useful, but is also difficult to interpret. Specifically, the meaning of the Cramer's V value is difficult to ascertain without knowledge of how it is calculated (and it is hard to explain in plain English).
I suggest presenting relative risk and absolute risk for maximum interpretability and transparency.
As for confidence intervals, I don't know how to calculate them by hand. Most websites that calculate them for odds ratios also do so for relative risk.
Comment: +1 Just a quick note that odds ratio has the property of "invertibility" if you change the level of the outcome -- e.g. if smoking (compared to not smoking) has an OR of 2 for having disease X, then smoking has an OR of 1/2 for NOT having disease X. This is not true of relative risks (whether this is trivial or not depends on the application.) For a worked example see [Wikipedia on odds ratios](http://en.wikipedia.org/wiki/Odds_ratio#Invertibility_and_invariance)


Can't access In-App Products in Play Store

Question: I'm working on an Android app developed on Titanium SDK 3.2.0.GA and I'm using the In-App Billing module by Appcelerator.
My implementation of the module it's as follows (omitting functions which only purpose is to display log info):
<code>var IdentifierProduct = '';
var InAppBilling = require('ti.inappbilling');
var publicKey = Alloy.Globals.Android.publicKey_1 + Alloy.Globals.Android.publicKey_2 + Alloy.Globals.Android.publicKey_3 + Alloy.Globals.Android.publicKey_4;
InAppBilling.setPublicKey(publicKey);

function initializeBilling()
{
    var synchronousResponse = InAppBilling.checkBillingSupported();
    displaySynchronousResponseCodes(synchronousResponse);
}

function requestPurchase(identifier, item_type)
{

    // Check if billing for current product type is supported before sending purchase request
    var checkBillingResponse = InAppBilling.checkBillingSupported(item_type);
    if (checkBillingResponse.responseCode == InAppBilling.RESULT_OK)
    {
        Ti.API.info('Current product type supported, continuing with request');

        var tmpArgs = {
            productId: identifier,
            productType: item_type,
            developerPayload: 'devPayload'
        };

        Ti.API.info('args for product request\n' + JSON.stringify(tmpArgs));
        var synchronousResponse = InAppBilling.requestPurchase({
            // productId: 'android.test.purchased',
            // productId: 'android.test.canceled',
            // productId: 'android.test.refunded',
            // productId: 'android.test.item_unavailable',
            productId: identifier,
            productType: item_type,
            developerPayload: 'devPayload'
        });
        displaySynchronousResponseCodes(synchronousResponse);
    }
    else
    {
        Ti.API.info('Current product type not supported, aborting request');
        displaySynchronousResponseCodes(checkBillingResponse);
    }
}

function ON_BIND_EVENT(e)
{
    if (e.result == InAppBilling.SUCCESS) {
        NotifyMe('Billing Service Bound');
        enableInAppPurchases(true);

        //Call
    } else {
        NotifyMe('Billing Service Bind Failed');
        enableInAppPurchases(false);
    }
}
InAppBilling.addEventListener(InAppBilling.ON_BIND_EVENT, ON_BIND_EVENT);

function ON_CONNECT_EVENT(e)
{
    NotifyMe('CONNECT CALLED');
    if(Ti.App.Properties.getBool('transactionsRestores') === null)
    {
        Ti.API.info('fresh install, lets restore the transactions');
        try
        {
            InAppBilling.restoreTransactions();
        }
        catch(err)
        {
            Ti.API.info('Error');
            Ti.API.info(JSON.stringify(err));
        }
    }
}
InAppBilling.addEventListener(InAppBilling.ON_CONNECT_EVENT, ON_CONNECT_EVENT);

function RESPONSE_EVENT(e)
{
    // Events with (e.sync == true) are deprecated and will be removed. Use the event object that the methods return.
    if(!e.sync){
        NotifyMe('RESPONSE CALLED ' + e.requestId + ' ' + e.responseCode);
        Ti.API.info('RESPONSE CALLED \n' + 'Request Id:\n' + e.requestId + ' ' + '\nResponse Code:' + ResponseString(e.responseCode));
        if(e.responseCode === InAppBilling.RESULT_ERROR)
        {
            // Error in request
            Ti.API.info('Response event error');
            Ti.API.info(JSON.stringify(e));

        }
        else if(e.responseCode === InAppBilling.RESULT_ITEM_UNAVAILABLE)
        {

            // Item unavailable in request
            Ti.API.info('Response event item unavailable');
            Ti.API.info(JSON.stringify(e));
        }

    }
}
InAppBilling.addEventListener(InAppBilling.RESPONSE_EVENT, RESPONSE_EVENT);

function PURCHASE_STATE_CHANGED_EVENT(e)
{
    Ti.API.info('PURCHASE_STATE_CHANGED_EVENT Parameters:\n' + JSON.stringify(e) );
    NotifyMe('PURCHASE STATE CHANGED CALLED ' + e.signedData + ' ' + e.signature+'\n'+ 'SECURITY RESULT ' + e.result);

    Ti.API.info('PURCHASE STATE CHANGED CALLED');
    Ti.API.info('Signature Verification Result:\n' + VerificationString(e.result));
    Ti.API.info('Signed Data:\n' + e.signedData);

    if (e.signedData != null) {
        var response = JSON.parse(e.signedData);
        /*
         * We are not guaranteed to have any orders returned so
         * we need to make sure that this one exists before using it.
         *
         * If there is no notificationId then there is no need to confirmNotifications().
         * This happens when restoreTransactions() triggers a PURCHASE_STATE_CHANGED_EVENT.
         */
        for(var i = 0; i < response.orders.length; i++)
        {
            if(typeof response.orders[i] !== 'undefined')
            {
                setPurchaseFlag(response.orders[i].productId);
            }
            if (response.orders[i] && response.orders[i].notificationId)
            {

                Ti.API.info('confirming notification for order ' + JSON.stringify(response.orders[i]));
                var synchronousResponse = InAppBilling.confirmNotifications({
                    notificationIds: [response.orders[i].notificationId]
                });
                displaySynchronousResponseCodes(synchronousResponse);
            }
        }
    }
}
InAppBilling.addEventListener(InAppBilling.PURCHASE_STATE_CHANGED_EVENT, PURCHASE_STATE_CHANGED_EVENT);

function NOTIFY_EVENT(e)
{
    Ti.API.info('NOTIFY CALLED \n' + 'Notify Id:\n' + e.notifyId);

    var synchronousResponse = InAppBilling.getPurchaseInformation({
        notificationIds: [e.notifyId]
    });
    displaySynchronousResponseCodes(synchronousResponse);
}
InAppBilling.addEventListener(InAppBilling.NOTIFY_EVENT, NOTIFY_EVENT);

InAppBilling.startBillingService();
</code>
The following is a list of the steps I've reviewed to look for errors:

I've checked that my package name is the same as the one in my application draft in Play Store
I checked that my license key is correct
all of my In-App products are in active state
the request sent to the Play Store are with product ids that correspond to my In-App products.
My device account is in registered as a test account so it should let me make a purchase.

I added the In-App Products around two weeks ago and every time I try to request a purchase, all of them are return a not found response, Play Store couldn't take this long to activate the, right?
And yet, I get as a response "the item you are attempting to purchase could not be found".
The response code I get is 2, which I thought it meant RESULT_SERVICE_UNAVAILABLE, but the dialog that appears clearly says the item was not found, am I interpreting the response code wrongly? Or should I look into why the service is unavailable?
I followed the guide to test In-App purchases and I'm getting this error with no clear cause.
EDIT
I've been searching around and found a few questions (here and here) were developers get RESULT_SERVICE_UNAVAILABLE when making too many restoreTransactions() calls. I checked my code and saw that, indeed, I was making a restoreTransactions() call every time I launched the app.
Now I have added a validation on the ON_CONNECT_EVENT to make sure if there were transactions to restore at all, in case it doesn't then I set a flag that prevents the app from making a restoreTransactions() call the next it launches.
The problem, though, still remains, can I contact Google in some way to ask for my In-App services to be enabled again? How long do I have to wait? The users on those questions mention it could take up to 3 weeks, can we accelerate this process?
Unfortunately without In-App Purchases we cannot release our app.
Comment: what will come when add products in inapp developer console..?#for me it is coming "to be activated"..
Answer: Try publishing your app in alpha or beta. They have changed the way of doing tests and now this is required.
Cheers
Comment: I contacted Google and they told me this too, I'm changing to alpha and seeing how it works.
Comment: Just a quick question: I already uploaded an APK to Production to test the In-App Billing logic, now that I have to publish in Alpha, will the APK in Production be published too?
Comment: Just checked and after I uploaded an APK to Alpha, the one in Production disappeared. Whew I was getting I little worried back there.
Comment: yes,you have to follow the new guidelines to test In-App Purchases with Google Play.
Answer: I'm a newbie myself, but the methods, properties and events you are using do not appear in the current documentation -- perhaps your code expects an earlier version of InAppBilling.


Covariance and correlation in multivariate random variables

Question: I have this experiment where there are two random vectors $P_1 = (x_1,y_1)$ and $P_2 = (x_2,y_2)$. These two vectors represents two measurements for the location of two nearby points ($10$ meters apart) using two independent sensors. I want to calculate the covariance matrix and correlation coefficient between $P1$ and $P2$ using $10,000$ measurements I have. I know how do this for two random variables but not in the case of two random vectors.
Comment: Pick two components at a time.  Apply what you know.
Comment: +1 for whuber's answer. That's the absolute most basic thing you can do.

Are you familiar and comfortable with matrix notation? What programming language/environment are you using? There are extremely concise ways to do this...
Comment: @whuber: I am not sure about what you mean by "two components at a time". would you elaborate?
Comment: @MatthewGunn: Yes I am totally fine with the matrix notation, and I am using Matlab.
Comment: You have four vector components: $x_1, y_1, x_2, y_2$.  Pick any two.  You know how to compute their covariance matrix and their correlation coefficient.  Do this for all $6$ pairs and you will be done.
Answer: Let $\mathbf{x}$ be a random column vector. In matrix notation, the covariance matrix for $\mathbf{x}$ can be expressed as:
$$ \Sigma = E\left[\left( \mathbf{x} - E[\mathbf{x}]\right) \left(\mathbf{x} - E[\mathbf{x}]\right)' \right] $$
The sample analogue is:
$$ \hat{\Sigma} = \frac{1}{n-1} \sum_i \left( \mathbf{x}_i - \hat{\boldsymbol{\mu}}\right) \left(\mathbf{x}_i - \hat{\boldsymbol{\mu}}\right)' \quad \quad \hat{\boldsymbol{\mu}} = \frac{1}{n} \sum_i \mathbf{x}_i $$
where each $\mathbf{x}_i$ is a column vector containing the $i$th observation.
Something standard is to put your $n$ observations in an $n$ by $k$ data matrix $X$ where each row is an observation. That's standard convention in statistical texts and something similar is standard practice in many programming environments.
$$ X = \left[ \begin{array}{c} \mathbf{x}_1' \\  \mathbf{x}_2' \\ \ldots \\  \mathbf{x}_n' \\  \end{array} \right] $$
Various operations can be expressed quite elegantly with matrix notation using the data matrix $X$. The sample covariance matrix can be written as
$$(X - \hat{\boldsymbol{\mu}}')'(X - \hat{\boldsymbol{\mu}}') / (n - 1)$$
where $X - \hat{\mathbf{u}}'$ means you subtract the row vector $\hat{\mathbf{u}}'$ from each row of $X$.
(Note: bold letters are vectors, upper case are matrices, lower case are scalars, and $'$ means taking the transpose.)
Matlab comment:
In Matlab, you can easily follow the formulas exactly: make a data matrix $X$, compute $\hat{\boldsymbol{\mu}}$, and compute $\hat{\Sigma}$. There are also built-in functions, mean and cov respectively, which will do it for you.