Incorrect syntax near the keyword 'select'. employees details with highest purchase value

Question: Code to create tables for customer name and order details:
CREATE TABLE customers_demo_1 (
    id INTEGER NOT NULL,
    name TEXT,
    email TEXT);

INSERT INTO customers_demo_1 (id, name, email) VALUES (1, 'Doctor Who', 'email@example.com');
INSERT INTO customers_demo_1  (id, name, email) VALUES (2, 'Harry Potter', 'firstname.lastname@example.com');
INSERT INTO customers_demo_1  (id, name, email) VALUES (3, 'Captain Awesome', 'email@example.com');

CREATE TABLE orders_demo_1 (
    id INTEGER NOT NULL,
    customer_id INTEGER,
    item TEXT,
    price REAL);

INSERT INTO orders_demo_1  (id, customer_id, item, price)
    VALUES (111, 1, 'Sonic Screwdriver', 1000.00);
INSERT INTO orders_demo_1  (id,customer_id, item, price)
    VALUES (211,2, 'High Quality Broomstick', 40.00);
INSERT INTO orders_demo_1  (id,customer_id, item, price)
    VALUES (311,3, 'TARDIS', 1000000.00);

INSERT INTO orders_demo_1  (id, customer_id, item, price)
    VALUES (111, 1, 'Item2', 1300.00);
INSERT INTO orders_demo_1  (id,customer_id, item, price)
    VALUES (112, 1, 'Item3', 400.00);
INSERT INTO orders_demo_1  (id,customer_id, item, price)
    VALUES (111,1, 'Item7', 1900000.00);

INSERT INTO orders_demo_1  (id,customer_id, item, price)
    VALUES (311,3, 'Item5', 1200.00);
INSERT INTO orders_demo_1  (id,customer_id, item, price)
    VALUES (312,3, 'Item4', 1990.00);
INSERT INTO orders_demo_1  (id,customer_id, item, price)
    VALUES (211,2, 'Item9', 2300.00);
INSERT INTO orders_demo_1  (id,customer_id, item, price)
    VALUES (212,2, 'Item10', 2400.00);
INSERT INTO orders_demo_1  (id,customer_id, item, price)
    VALUES (211,2, 'Item11', 5000.00);
INSERT INTO orders_demo_1  (id,customer_id, item, price)
    VALUES (212,2, 'Item12', 8000.00);

Code:
select * from(
select customer_id, id,
sum(price) as Order_price_overall,
RANK() over (partition by customer_id order by sum(price) desc) as rank_order_value,
count(*) over(partition by customer_id) as no_of_orders
from orders_demo_1 o
group by id, customer_id
) t
inner join
select name,email from customers_demo_1 c
on t.customer_id=c.id

where t.rank_order_value=1

I want the highest sales value per customer to be displayed.
Error:
Incorrect syntax near the keyword 'select'.
Msg 156, Level 15, State 1, Line 63
Incorrect syntax near the keyword 'on'.

Expected output
customer_id   Name                id     Order_price_overall   Rank_order_value     no_of_orders
1             Doctor who         111     1902300                    1                     2
2             Harry Potter       212     10400                    1                   2
3             Captain Awesome    311     1001200                      1                   2

Comment: Missing parentheses: `inner join (select name,email from customers_demo_1) c`
Comment: Thanks for asking such a good question - table definitions, sample data, expected results - just what we want!
Comment: not working still, im getting error: invalid id
Comment: @NevilleKuyt if you feel it is good, pls upvote the question
Answer: Corrected the syntax
    SELECT *
FROM (
    SELECT customer_id
        ,id
        ,sum(price) AS Order_price_overall
        ,RANK() OVER (
            PARTITION BY customer_id ORDER BY sum(price) DESC
            ) AS rank_order_value
        ,count(*) OVER (PARTITION BY customer_id) AS no_of_orders
    FROM orders_demo_1 o
    GROUP BY id
        ,customer_id
    ) t
INNER JOIN (
    SELECT id
        ,name
        ,email
    FROM customers_demo_1
    ) c ON t.customer_id = c.id
WHERE t.rank_order_value = 1

Answer: This works for me:
select t.customer_id, t.Order_price_overall,t.no_of_orders,t.id as OrderId, t.rank_order_value, c.name, c.email from(
select customer_id, id,
sum(price) as Order_price_overall,
RANK() over (partition by customer_id order by sum(price) desc) as rank_order_value,
count(*) over(partition by customer_id) as no_of_orders
from orders_demo_1 o
group by id, customer_id
) t
inner join
(select * from customers_demo_1) c
on t.customer_id=c.id

where t.rank_order_value=1


Filtro externo no ng-table

Question: Sou novo em usar o AngularJS e o ng-table e estou tendo um pequeno problema.
Quero aprender a criar filtros fora da tabela gerada, mas não encontrei nada a respeito no site deles "http://ng-table.com".
Se fizer diferença, o filtro que quero criar é um filtro do título, mas fora da tag "table".
O meu código está funcionando direitinho, mas quero fazer um filtro externo.
Código JS
TemasCtrl.$inject = ['$http', '$resource', 'ngTableParams', '$timeout'];

function TemasCtrl($http, $resource, ngTableParams, $timeout) {

    var temas = this;

    temas.carregarTabela = function () {

        var Api = $resource('/temas');

        temas.loading = true;

        temas.tableParams = new ngTableParams({
            page: 1,
            count: 10,
            sorting: {
                name: 'asc'
            },
            filter: {}
        }, {
            total: 0,
            getData: function ($defer, params) {
                Api.get(params.url(), function (data) {

                    $timeout(function () {

                        params.total(data.total);
                        $defer.resolve(data.itens);

                    }, 500);
                });
            }
        });
    }

}

Código HTML

                    {{ tema.id }}
                    {{ tema.slug }}
                    {{ tema.titulo }}

Agradeço desde já a ajuda!
Answer: Acredito que isto vai lhe ajudar bastante:
https://scotch.io/tutorials/sort-and-filter-a-table-using-angular

Filtro externo no ng-table


If X is limit point compact space,which is T1,then X is countably compact.

Question: Countably compact means : every countable open covering contains a finite subcollection that covers it.
Limit point compact means: every infinite set contained in it has a limit point.
In T1 space every singleton is closed and if x is a limit point of some subset A, then every neighborhood of x contains infinitely many points of A.
Can anyone prove :
If X is limit-point compact space,which is T1,then X is countably compact.
Answer: Let $\{U_n\}_{n}$ be a countable cover of $X$ and assume that this cover does not have a finite subcover. Then for every $n \in \mathbb{Z}_{>0}$ there exists $x_n\in X\setminus\bigcup_{k = 1}^n U_k$ and we can set $A = \{x_n \:|\: n \in \mathbb{Z}_{>0}\}$. This is an infinite set because every element of $X$ is contained in some $U_n$ and there are only finitely many $k$ such that $x_k \in U_n$ (because $x_k \notin U_n$ for $k \geq n$). This also shows that $A \cap U_n$ is finite for all $n$.
By limit-point compactness we get a limit point $x \in X$  of $A$. This is contained in $U_n$ for some $n$. But then $U_n$ contains infinitely many elements of $A$ in contradiction to $A \cap U_n$ being finite.


Custom Module: db_select title AND body?

Question: I'm a little confused by how the node data is stored in the database.  It seems like the title is stored in the db "node," while the body is stashed field_data_body, and custom fields are placed elsewhere.
I have create a custom module that pulls certain pieces of content, but I need to match up the title with the body.  I've been successful pulling my list of titles:
    function foo() {
      $query = db_select('node', 'n')
       ->fields('n', array('type','title', 'nid'))
       ->condition('type', 'fooBar')
       ->condition('status',1)
       ->execute();
          return $query;
      }
      $result=foo();
        foreach ($result as $node) {
         $id = $node->nid;
        }

How can I match each of these with their bodies?
Thanks!
-JB
Answer: If you want directly include the body within your result set, you can do a join on the field_data_body table.
$query = db_select('node', 'n');

$query->leftJoin('field_data_body', 'd', '(d.entity_id = n.nid AND d.entity_type = :node)', array(':node' => 'node'));

$query
    ->fields('n', array('type', 'title', 'nid'))
    ->fields('d', array('body_value', 'body_summary', 'body_format'))
    ->condition('type', 'fooBar')
    ->condition('status', 1)
    ->execute();

Answer: You are correct - Drupal stores the data for fields inside of separate tables.
Depending on your use case, you may find it easier to use node_load() which will load the entire node object with all the field data.


Choose model for time series forecasting with R

Question: I try to forecast my web visitors on the web site for 10 future days using time series.
I have used a auto.arima() model My time series is daily.
How can I choose between ets() model and auto.arima() model concidering that:
accuracy(auto.arima)

                   ME     RMSE      MAE        MPE    MAPE MASE      ACF1
Training set 26.84448 877.9984 697.2491 -0.7432541 9.72338  NaN -0.126274

and
accuracy(ets)

                   ME     RMSE      MAE      MPE     MAPE MASE       ACF1
Training set 10.38619 1039.264 833.8032 -1.01747 11.62925  NaN 0.02922446

Comment: i have tried to find the response but no solution thanks..
Comment: You can choose the best model based on lower MAPE value.
Comment: @Gaurav, why shoudh i choose ets model ?
Comment: @Sidhha, can you explaine me the meaning of MPAE
Comment: Becoz of lower RMSE and MAPE values for ets
Comment: @Gaurav, so i choose the auto.arima and not ets model
Comment: Yeah sorry auto.arima. The question earlier was not formatted so I saw 26.84448 under the RMSE header for auto.arima
Comment: @Gaurav, thanks did you know how can i export my predict output into excel file like this(3columns): Date pred  se consedering that my output is $pred
Time Series:
Start = c(2015, 1)
End = c(2015, 5)
Frequency = 365
[1] 5659.850 6425.983 7778.235 8749.321 8851.684

$se
Time Series:
Start = c(2015, 1)
End = c(2015, 5)
Frequency = 365
[1]  879.2036 1079.9762 1115.6224 1117.8931 1121.6338
Answer: You should use forecast and not predict to forecast your web visitors.
Here an example based on simulated data (I have no access to your data).
You may adapt this example to your data. Hope this may be of help.
Time series with daily data
Data simulation
data <- rnorm(3650, m=10, sd=2)

Use ts() to create time series
series <- ts(data, frequency=365, start=c(1919, 1))

attributes(series)
class(series)
length(series)

Plot the data
plot(series, col ="aquamarine")

The accuracy of forecasts can only be determined by considering how well a model performs on new data that were not used when fitting the model.
The size of the test set is typically about 20% of the total sample
Training set
Use data from 1919 to 1926 for forecasting
sr = window(series, start=c(1919,1), end=c(1926,365))

Test set
Use remaining data from 1927 to 1928 to test accuracy
ser = window(series, start=c(1927,1), end=c(1928, 365))

Herewith enclosed is an exercise I've done on the basis of the online book of Hyndman and Athanasopoulos: "Forecasting: principles and practice", a very good reading.You may find the book here: https://www.otexts.org/fpp
Since this is a very simply simulation, there is no real trend in it, so the two models produce similar forecasting of a linera trend. Your data in all likelihood will have a seasonal component.

Assign the data to a vector of convenience
trainData <- sr     ### Training set (8 years, daily data)
testData <- ser     ### Test set    (2 years, daily data)

Auto-arima without stepwise (more precise)
library(fpp)

The default value in auto.arima() is test="kpss".
A KPSS test has a null hypothesis of stationarity
In general, all the defaults are set to the values that give the best forecasts on average.
Caution, takes a while to compute
arimaMod <- auto.arima(trainData, stepwise=FALSE, approximation=FALSE)
arimaMod.Fr <-forecast(arimaMod,h=730)      ### h is the length of the forecast, in this case 2 years = 365*2

Plot of the prediction and the test set
plot(arimaMod.Fr, plot.conf=FALSE)
lines(testData, col="red")
legend("topleft",lty=1,bty = "n",col=c("red","blue"),c("testData","ARIMAPred"))

Only the prediction
Plot the test set
plot(ser, main="Daily data", ylab="", xlab="Months", col = "red")

Plot the forecast on the training set
lines(arimaMod.Fr$mean, col="blue", lwd=3)

Accuracy
Accuracy for forecasting of sr (forecasted data) on ser (original data used as test set)
The best model had the lowest error (particularly the MAPE, Mean absolute percentage error)
accuracy(arimaMod.Fr,testData)

Test residues of arima
tsdisplay(residuals(arimaMod))

ETS
fit.ets <- ets(trainData)

fr.ets <- forecast(fit.ets,h=730)

plot(forecast(fit.ets,h=730))

Compare accuracy of ETS vs ARIMA
There is an overlap between the ETS and the ARIMA forecasting,
So I've plotted the ETS forecasting with a wider line
plot(testData)

lines(fr.ets$mean, col="red", lwd=5)
    lines(arimaMod.Fr$mean, col="green")
legend("topleft",lty=1,cex=1,y.intersp=0.6,bty = "n",col=c("black","red","green"),c("data","ETS","ARIMA"))

Accuracy test
accuracy(fr.ets,testData)
accuracy(arimaMod.Fr,testData)

Comment: hello and thank you very much for sharing your knowldge,i just have a question, for information i have a daily data witch containe 2 columns date and numbre of visitor 's site.my data from 01/6/2011 to 24/08/2015.(how can i send you or show you my data ).according to these information can i use the same script like you ?
Comment: i have used the same script but i have always the same value predected! why? i have write this arimaMod.Fr <-forecast(arimaMod,h=365) but always the same value predected by the arimaMod
Comment: I think you need to rearrange your data.   A time series is a sequence of measurements made over a time interval. So, your first column is the "time interval", and the number of visitors is your "measurement".   Essentially, you should have a sequence of measurements for each day of the year, form January 1st to December 31th.    When there was no visitor, your measurement is 0.
Comment: At the end, your should have a sequence of 365 measurements, a column with values that may go from 0 (no visitors) to any number your site had registered.   At this point your must create a ts object, as indicated, then plot your data to see whether there is any trend: no trend, no forecast.
Comment: thanks , so i can not use data for 01/06/2011 until 23/08/2015 ? or must i remplace missing value by zero ? another question how can I test the presence of trend in my time sereis using R? thanks
Answer: The best model is the model with the the lowest error (particularly the MAPE, Mean absolute percentage error).
However, the accuracy of forecasts can only be determined by considering how well a model performs on new data that were not used when fitting the model.
The size of the test set is typically about 20% of the total sample.
So, you need to split the series in a training set and a test set.
You may consult this tutorial, which is based on the online book of Hyndman and Athanasopoulos "Forecasting: principles and practice", a very good reading. The book explains with details what MAPE and the other measures of error are.
You may find the book here: https://www.otexts.org/fpp
The tutorial is here: https://rpubs.com/RatherBit/90267
I hope this is helpful.
Comment: ,thank you very much,  in my case i have a daily time series (frequecy=365) so this my R code myts <- ts(inputData$visites, frequency=335, start=c(2014, 1)) arimaOut <- auto.arima(myts)
predicteds <- predict(arimaOut, 30)
accuracy(arimaOut)  accuracy(auto.arima)

                   ME     RMSE      MAE        MPE    MAPE MASE      ACF1
Training set 26.84448 877.9984 697.2491 -0.7432541 9.72338  NaN -0.126274  is this true ? thanks
Comment: frequency should be 365 not 335 (a typo?)    You should split the series in a training set and a test set and use the 'forecast' command to get what you want.    Some of the error measures will turn to be NaN, since they are specific to some models and are not valid for other models.
Comment: yes sorry , its is an error,for information, my data contain 2           columns date visites
1 2014-01-01    3114
2 2014-01-02    5954
3 2014-01-03    5342
4 2014-01-04    4929
5 2014-01-05    5633
6 2014-01-06    5890 this my  R code:myts <- ts(inputData$visites[1:335], frequency=365, start=c(2014, 1)) arimaOut <- auto.arima(myts)
predicteds <- predict(arimaOut, 30) is it true now ? thanks
Comment: any help please ?


php-fpm not running as user specified in pool

Question: I have an Ubuntu18.04 web server with nginx and php-fpm (7.2) installed.
There are 6 pools, each with their own user and group:
/etc/php/7.2/fpm# grep -r ^user *
php.ini:user_dir =
pool.d/dev3.website.com.conf:user = dev3_app
pool.d/dev1.website.com.conf:user = dev1_app
pool.d/dev4.website.com.conf:user = dev4_app
pool.d/dev6.website.com.conf:user = dev6_app
pool.d/dev5.website.com.conf:user = dev5_app
pool.d/dev2.website.com.conf:user = dev2_app

/etc/php/7.2/fpm# grep -r ^group *
pool.d/dev3.website.com.conf:group = dev3_app
pool.d/dev1.website.com.conf:group = dev1_app
pool.d/dev4.website.com.conf:group = dev4_app
pool.d/dev6.website.com.conf:group = dev6_app
pool.d/dev5.website.com.conf:group = dev5_app
pool.d/dev2.website.com.conf:group = dev2_app

Each site runs a laravel app, with the storage directory made group writable:
/var/www/dev3.website.com# ls -la
total 2236
drwxr-xr-x  20 root dev3_app    4096 Jul 17 21:39 .
drwxr-xr-x   9 root root        4096 Jul 17 21:33 ..
...
drwxrwxr-x   7 root dev3_app    4096 Jul 17 21:29 storage

nginx connects via TCP port:
server {
    listen         80;
    server_name    dev3.website.com;

    root /var/www/dev3.website.com/public;
    index index.php index.html index.htm;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ [^/]\.php(/|$) {
        fastcgi_split_path_info ^(.+?\.php)(/.*)$;
        if (!-f $document_root$fastcgi_script_name) {
            return 404;
        }

        fastcgi_pass 127.0.0.1:9001;
        fastcgi_index index.php;

        # include the fastcgi_param setting
        include fastcgi_params;

        # SCRIPT_FILENAME parameter is used for PHP FPM determining
        #  the script name. If it is not set in fastcgi_params file,
        # i.e. /etc/nginx/fastcgi_params or in the parent contexts,
        # please comment off following line:
        fastcgi_param  SCRIPT_FILENAME
        $document_root$fastcgi_script_name;
    }
}

With this configuration I get
The stream or file "/var/www/dev3.website.com/storage/logs/laravel-2019-07-17.log" could not be opened: failed to open stream: Permission denied

When I run chmod a+w on the storage directory it works.
I have also run ps -ef |grep php:
root      2468     1  0 00:53 ?        00:00:05 php-fpm: master process (/etc/php/7.2/fpm/php-fpm.conf)
root     11897 10961  0 22:12 pts/0    00:00:00 grep --color=auto php

Answer: I am suspecting that it is running the "master process" as the root user but for each of the pools it runs the "worker" processes as the specified user. This is further supported by the fact that you had to chmod the logs directory in order to get it to work.
A troubleshooting step you could take is to have one of the sites write a file to /tmp/test and then check to see what user owns it.
You could also write a loop that sleeps for a couple of minutes inside one of the pool and then run your ps -ef | grep php command to see if the "master process" has spawn a process as the user you expect.
Comment: Thank you. Excellent way to diagnose it. Cause of my issue is that I copied a changed nginx host configuration file to my ansible script and overlooked to put the placeholder for the tcp port back in. So all sites connected to the same fpm process.


How can I override the canvas in my View?

Question: I am using Android 2.1 and Eclipse.
I have defined a LinearLayout with two components that have dimensions: 250 x 250.
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);

LinearLayout.LayoutParams llp =
  new llp.LayoutParams(250, 250);

meter1View = new MeterView(this, "Meter 1");
ll.addView(meter1View, llp);
meter2View = new MeterView(this, "Meter 2");
ll.addView(meter2View, llp);
ScrollView scrollView = new ScrollView(this);
scrollView.addView(ll);
setContentView(scrollView);

So far, so good.  I see two vertical compoments on my emulator screen.
However, in my Meter View class, the size of the canvas in onDraw is the size of my emulator screen, which is 480 by 800.
@Override
protected void onDraw(Canvas canvas) {
    int w = canvas.getWidth();
    int h = canvas.getHeight();
    Log.i(TAG, "  onDraw, w: " + w + ", h: " + h);
}

I would like a canvas size to be 250 x 250, so that I can pass this canvas to drawing routines. Right now, my drawing routines are drawing outside the 250 x 250 bitmap that was defined by my LinearLayout.
I realize that I can make my canvas drawing routine to work by translating the canvas, but it would be cleaner if I could temporarily override the original canvas with a new one.
I understand that I can define my own canvas by:
Bitmap b = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);

How can I replace the canvas that is created by the View class with my new canvas?
Any help will be greatly appreciated.
Charles
Answer: you should use the width and height of the view, not the canvas, both available via getWidth() and getHeight().  Then pass these dimensions to your drawing routine.
Answer: Don't replace the Canvas, just use the clip rect instead.


A good way to combine three graphs with the same Y axis but different X axis.

Question: I have three graphs as show below (the last one is split because I couldn't take a screenshot with everything together)

What's a good approach (from a UX standpoint) to combining all three graphs into a single visualization? What kind of visualization should I be looking at?
Comment: Is it cumulative, then? That might explain why you seem to have seven times as many page views on Sunday as on Monday.
Comment: Could you explain the *purposes* of these visualizations?  It is impossible to design a graphic intelligently without having a clear objective.  For instance, for year-over-year comparisons the third graphic is awful--it's impossible see the data--but if the point is to show that the cumulative page views are very small compared to the range of the vertical axis, it is a plausible solution.
Comment: @whuber I agree the third graphic is awful. The Y scale should have come down.
The idea here is to show the user how their website traffic is comparing to the previous week, month and year.
Comment: This isn't real data, is it? It doesn't look realistic.
Comment: @Kodiologist It is real data.
Comment: Yes. Sorry, I should have mentioned that.
Comment: Do you want an interactive or a static visualisation ?
Answer: I don't think you should try to combine these. The year, the day of the month, and the day of the week are all orthogonal concerns. If you layered them into a single plot with a three-layer stack of $x$-labels or something, you'd just have a more cluttered presentation.
Here's some more miscellaneous advice:

Don't cumulate. The cumulative display stretches the $y$-axis and makes it hard to make comparisons across $x$-values, since the reader needs to eyeball the difference on the $y$-axis rather than being able to read off the $y$-axis directly.
Remove the fill under the lines, and remove the vertical gridlines. These add a lot of visual noise for little information.
Present $y$-values as per-day means rather than sums. This will make the numbers smaller and easier to interpret, and it will let you put the $y$-axes of the three figures on the same scale.
Add thousands separators to the $y$-labels to make them more legible.

I recommend the popular book The Visual Display of Quantitative Information, by Edward R. Tufte, for guidance on making easy-to-read data graphics.
Answer: Here below you will find some suggestions, each one depending on the purpose and on the prior knowledge of the users.
Just show the actual data and let the user pick up from there
Plot the actual number of visits per period (day or month), instead of the cumulated data, and use line as an encoding mark. In terms of granularity, you can continue to stick with the multiple approach, one for each zoom level, or alternatively, one for each aggregation measure (total, average, min, max, etc.).
Let the user configure the period
Interactive displays offer the advantage that the user can zoom in and out or filter on the go to focus on a smaller period. Here is one example that pretty much speaks for itself: overview+detail based on vega.js
Reveal the underlying trend to the user
A convenient and okay-to-understand approach is to calculate moving averages and plot those as a layer over the original daily or monthly data. Based on the number of data points involved in the moving average calculation, you can visualise long or short term trends.
At what time of the day/week/month/year does the user's site have most visits?
One way to answer this question is to draw the data on a heatmap with a time scale on the x axis, e.g. months (or day numbers), and an ordinal scale on the y axis, e.g. day number (or even intra-day time). The number of visits should be encoded with grey tones (brightness) on a continuous scale. Here is such a heatmap based on vega.js.
How do the site's daily visits compare to the prior year average?
A simple way of comparing data in time is to transform the daily or monthly data into index values, base 100 being e.g the average number of daily or monthly visits during the previous year. Obviously, the choice of the base 100 requires careful consideration: it should be easily understood by the users on one hand and be meaningful on the other.


Personal Contact Forms

Question: What is the best way to get a 'Contact User' form on nodes like an ebay-ish 'Contact Seller' simple form?
I tried Contact / Contact Forms module, but I do not want a Sitewide Contact form to be accessible (don't want to use it) and I want Mollom/Captcha integration and sending limits for anonymous users.
I thought maybe I could do Webform, but I can't see a way to make the recipient dynamic (node author, for example).
Answer: Take a look at the Privatemsg module

Personal Contact Forms


Construct Derived Class in Base Class' Constructor in C++

Question: Suppose I have a class derived from a base class.  Polymorphism allows me to call the derived class' functions through a pointer to the base class (using virtual functions).  In other words, I can have a member of the derived class "pretending" to be a member of the base class.  Keeping that in mind, is it possible for the base class, in its constructor, to actually construct a member of the derived class (which then "pretends" to be a member of the base class, so nothing breaks)?  Logically , I see no reason that this should not work, but I cannot figure out how to do it syntactically.  If this is not possible, why not?
I know that I can have a separate function that constructs a member of the derived class and returns it as a member of the base class.  That is what I will do if this ends up being impossible, but it would be cleaner to have it as a constructor (because that is what this separate function basically is).
EDIT: Here is an example of what I am looking for:
class base
{
  base()
  {
    this=new derived(); //This is what I am looking for
  }

  virtual func();
};

class derived : public base
{
  derived() : base()
    {}

  func()
  {
    ...
  }
};

As mentioned above, this could be achieved with the following:
base *fake_base_constructor()
{
  return new derived();
}

In practice, there would be multiple derived classes, and the base class constructor would choose between them based on parameters, but conceptually, you only need one.
Comment: Please add some "what I want" code. What does it mean to "pretend to be a member of the base class" (Do you also include member data?)? What does it mean to "return it as a member of the base class"?
Comment: Do you have any code, broken or otherwise, that at least *attempts* to demonstrate what you're trying to describe? And polymorphism doesn't "pretend" anything. A *cast* pretends to be something it isn't; polymorphism is behavior modification via derivation override. You can also static-polymorph via templates, but it doesn't sound like that is what you want either.
Comment: What do you mean by "nothing breaks"?  It sounds like you're talking about guaranteeing that a subclass does not break the parent's invariant (which should be maintained by all subclasses).  Is this so?
Comment: @pmr: "Pretending to be a member of the base class" was an informal way of stating that a pointer to the derived class can be cast to a pointer to the base class (it was supposed to make it less wordy).  "Returning it as a member of the base class" also meant casting it to the base class in order to return it.
Comment: @RonaldBarzell: I just meant that it could be cast into the base class, so that type-checking would pass.
Comment: `this=new derived`? [Time to read a C++ book](http://jcatki.no-ip.org/fncpp/Resources). Like, _really_ thoroughly.
Comment: you can use integers (or even better an `enum`) to denote the relevant classes, and a `switch` statement in your function.
Comment: @LightnessRacesinOrbit: Yes, I know that does not work.  That is to show what I am trying to accomplish.
Comment: @Cheersandhth.-Alf: I know how to do that; I was asking if there is a way to do it directly in the constructor of the base class.
Comment: Thank you to @Cheersandhth.-Alf for the term "factory function".  Knowing that, my question can be rephrased as follows: Can the constructor of a base class act as a factory function function for its derived classes?  Sorry for the confusion I caused by not knowing that term.
Comment: @bugmenot: not directly. in theory you could let the base class have a pointer-to-derived member and let its methods forward to that derived instance. but it's just added complexity, obfuscation and inefficiency, not to mention additional ways that this could go wrong (that is, added opportunities to introduce bugs). not a good idea. forget it
Comment: @Cheersandhth.-Alf: That is what I figured.  I was planning on using what I now know is called a factory function, but I wanted to check if there were a better way.
Answer: Sounds like you want the curiously recurring template pattern. It allows the base class to know which type is being derived from it by giving it a template parameter which is the derived type:
template <class D>
class Base
{ };

class Derived : public Base<Derived>
{ };

Now you can use the template parameter Derived in the definition of Base. For example, the constructor of Base could do:
template <class D>
void Base<D>::some_base_member()
{
  D d;
};

In fact, an important result of this pattern is that you can call a Derived member from the Base class. For example:
template <class D>
void Base<D>::some_base_member()
{
  static_cast<D*>(this)->some_derived_member();
};

Comment: Of course doing that in the constructor of `Base` would be _Undefined Behavior_, as `Derived` does not exist until its constructor finishes.
Comment: A crucial piece of _CRTP_ is `static_cast< Derived* >( this )`
Comment: What you are showing is static polymorphism. I have no idea if this is what OP actually wants given how vague the question is.
Comment: Forgetting accessing via static cast (which I agree with), the one thing you should NOT do in the Base constructor is *instance* an object of type Derived (middle code snippet). Doing so recuses the "curiously recurring" into "blatant-recursion", which will eventually stack-fault.
Comment: @K-ballo Thanks! I was just adding that.
Comment: Sorry, that is not what I was looking for.  I need to be able to have different derived classes at run-time, not just at compile-time.  Hopefully the edit I made to the question will help.
Answer: It sounds like you want to select the type of thing that you get by passing something into the constructor?  Your example gives a static selection but the text implies that there will be multiple choices.  I'm curious how you intend to use this, specifically.
Say you wanted to do something like this:
enum Types
{
    Type_A,
    Type_B,
};

class Base
{
public:
    Base(Types t)
    {
        switch (t)
        {
        case Type_A:
            this = <magic> A;
            break;

        case Type_B:
            this = <magic> B;
            break;
        }
    }
};

but the problem is that this isn't how C++ works; your object's space is already allocated by the time the constructor is hit so you can't just stuff a derived item into that space.  For instance, imagine you had this as a class member variable:
struct SomeStruct
{
    int i;
    Base b;
    float f;

    SomeStruct();
}

SomeStruct::SomeStruct() : i(4), b(Type_A), f(3.14f)
{
}

This just can't work.  It really sounds like the most straight forward solution will be for you to use a factory function; it makes it explicit that you have to deal with pointers and it's something that programmers are used to seeing:
Base* BaseFactory(Types t)
{
    switch (t)
    {
    case Type_A:
        return new A;

    case Type_B:
        return new B;
    }
}

You could do something similar with the curiously recurring template pattern but it's not as straight forward as suggested in another answer (in part because you presumably want runtime polymorphism which isn't addressed in the Wikipedia article) but it's not really necessary; regardless of your solution the code module that does the construction of these things will have to have knowledge of everything that can be created and considering that a constraint it's probably best to have that bundle of knowledge somewhere other than in the base class.  Just my opinion but I think it's safest for the long haul to avoid building big bundles of string.
Comment: This is what I was looking for; thank you.  I was forgetting about non-dynamically allocated objects!  Great explanation, and sorry again to everyone else for my lack of communication skills.
Answer: You ask:

"is it possible for the base class, in its constructor, to actually construct a member of the derived class (which then "pretends" to be a member of the base class, so nothing breaks)?"

Yes, there are many ways to do derived class specific initialization in a base class.
Here's one example from a blog posting that I wrote about it, entitled "How to avoid post-construction by using Parts Factories":
#include <stdio.h>

namespace apiLevel {
    enum Handle {};

    Handle newButton( char const title[] )
    {
        printf( "apiLevel::newButton(\"%s\")\n", title );
        return Handle();
    }

    Handle newListbox( char const [] = "" )  { return Handle(); }
    Handle newStatic( char const [] = "" )   { return Handle(); }
}  // namespace apiLevel

class Widget
{
private:
    apiLevel::Handle    handle_;

protected:
    struct ApiWidgetFactory
    {
        virtual apiLevel::Handle newWidget( char const title[] ) const
        {
            return apiLevel::newStatic( title );  // Reasonable.
        }
    };

public:
    explicit Widget(
        char const                  title[] = "\"? (unspecified)\"",
        ApiWidgetFactory const&     factory = ApiWidgetFactory()
        )
        : handle_( factory.newWidget( title ) )
    {}
};

class Button
    : public Widget
{
protected:
    struct ApiWidgetFactory: Widget::ApiWidgetFactory
    {
        virtual apiLevel::Handle newWidget( char const title[] ) const
        {
            return apiLevel::newButton( title );    // Derived class specific.
        }
    };

public:
    explicit Button(
        char const                  title[],
        ApiWidgetFactory const&     factory = ApiWidgetFactory()
        )
        : Widget( title, factory )
    {}
};

int main()
{
    Button  button( "Just a button" );
}

The main advantage of the above approach is that it presents a type safe interface to the client code, with ordinary RAII-oriented construction (i.e., makes good use of class invariants).
The main disadvantage is that it requires maintaining two parallel class hierarchies, even though that is mainly a question of where to put the code.
For more info see that blog posting, which also links further to the FAQ, which also presents a few other approaches. The blog posting is sort of straight from the horse's mouth, namely mine. The FAQ item is the result of me convincing Marshall to write up that issue & solution for the FAQ.
Comment: I do not think that is what I am looking for.  Please correct me if I am wrong, but it seems to be functionally the same as the external function solution that I mentioned (see my edit if I did not explain myself well the first time).
Comment: @bugmenot: The function you showed, a simple factory function, is very different. Tthere is ordinarily *no need* for such a function, since it doesn't add anything (e.g. if you want to prevent non-dynamic allocation, simply make the destructor protected). The pattern above supports multiple derived classes such as `Button` and `Listbox`, with the common derived-specific data, here a handle to the API-level widget, initialized by the base class constructor.
Comment: I know that it would be useless for just one derived class, but I would actually be using multiple, and the constructor (or factory function) would choose between them based on its parameters.  Could you explain how yours is different?
Comment: @bugmenot: the function you showed, when amended to take a result-type indication argument, would still simply be a factory function. instead of calling the function to produce a `D` instance, you can just say `new D()`, which is also more clear and efficient! so apparently it serves no purpose. there is, apparently, no derived class specific initialization in the base class, for that function. the scheme above does derived class specific initialization, with a common concrete example where this is usually done. i suggest that you **study** that code. try it out, add a `Listbox` class. so on.
Comment: I see what you mean.  However, that is still not what I am looking for.  Essentially, if I have several derived classes (say, D1, D2, and D3), I want a way to get an instance of one of them, determined at run-time, based on other parameters.  For instance, given an integer value of 1, 2, or 3, it would return an instance of D1, D2, or D3, respectively, all cast to a B.  I do not need to do anything in the base class specific to which derived class was chosen; the base class is simply an abstract class to unify all of the derived classes.
Comment: @bugmenot: okay, that is indeed a factory function. and that's a very different question! it does *not* involve "for the base class, in its constructor, to actually construct a member of the derived class".


String declaration by character "A" + "B" vs "AB"

Question: Instead of
string someString = "AB";

I stumbled upon
string someString = "A" + "B";

Is there any technical explanation which renders the second way more advantageous?
Comment: The compiler will compile both to identical IL, so there is no difference.
Comment: There is no difference because the compiler can do a lot of optimisation of literal strings in code. My best guess is this code used to read something like `string someString = "A" + integerValue + "B";` and was subsequently edited to remove the non-literal part, and they did a lazy job of it.
Comment: Does this question belong on SO?  Where is the specific problem?
Comment: Note that this topic is already covered couple times on SO - like http://stackoverflow.com/questions/5164436/string-concat-using-constants-performance (somewhat different comparison, but answers this question too)
Answer: var answer = "The only thing advantageous is readability, if you have large " +
             "amounts of text it can be useful to break up the text inside the " +
             "source code for better readability. The compiler will turn it " +
             "in to a single string at compile time anyway";

Comment: @HenkHolterman But if you don't *want* the rendered string to have those newlines, then it's a problem.
Comment: Meh, a string that long should be a localised resource somewhere, but now I'm just trolling ;-)
Comment: The @"verbatim strings" are even more readable. They can include newlines without any fuss.
Comment: Doesn't really apply to any C# standard that I can think of, but also one of Python's main code standard (Pep8) likes you to make your lines of code only less than a certain length (80 chars I believe)
Comment: @AdamHouldsworth actually that is not a troll at all but good advice. Had this been a real program I would have made that string a resource too.
Comment: @ScottChamberlain Yeah, it's half and half. We localise all our display strings by default because You Never Know(tm), but localising it purely because it's long is the troll bit. We don't localise our exception messages, for example.


Equals method of Object and Object in Array

Question: I'm simply trying to find the position of an object in a Customer List, although it's constantly returning false when I use the equals() method.
I now understand that you have to create your own equals method to override the automatic one, yet I can't understand how to create one when I'm comparing a Customer inside a Customer array.
Here are my instance variables:
private Customer[] data;
private int size;
private final static int INITIAL_SIZE = 20;

Here is my method to find the position of the object:
public int findCustomerLocation(String name)
{
int spot = -1;
Customer cus = new Customer(name);
  for(int i = 0; i < size ; i++)
  {
    if((data[i].equals(cus)))
    {
      spot = i;
      System.out.println("spot is:"  + spot);
    }
    else
    {
      System.out.println("spot not found");
    }
  }
 return spot;
}//findCustomerLocation

(It's returning spot not found)
I'm trying to rewrite the equals method, but I'm a bit stuck, I'm trying to use if it's an instance of another, but it's still returning false
Comment: Show your `Customer` class.
Comment: Use [`Arrays.equals(Object[], Object[])`](http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#equals%28java.lang.Object[],%20java.lang.Object[]%29)?
Comment: @ElliottFrisch No, he's trying to implement `contains()` for an array. The issue is that his `equals()` method is broken.
Answer: Your equals method just uses the same identity operator (==) as the default Object#equals(). Presumably you intend for Customer objects to be considered equal when some particular information inside them, such as an ID field, is equal. If so, you need to compare those fields inside your equals() (and you should always include every field involved in equals() in your hashCode()).
Something like this might be what you're looking for:
public boolean equals(Object other) {
    if(!other instanceof Customer) {
        return false;
    }

    Customer that = (Customer) other;
    return this.name.equals(that.name);
}

Comment: I included my `Customer` class,  customers are just names, so I'm trying to see if a certain customer is already in the list, i.e. if their names are the same. I've never done `hashCode()` though.
Comment: @hello As described in [the Javadoc](http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#hashCode--), you should always override `hashCode()` when you override `equals()`, or Bad Things can happen. In the case where you only have one field, such as this, you can just use its hash code: `return name.hashCode()`.
Comment: If this.name is null, it fails.  You should use `java.util.Objects.equals(Object  a, Object b)`
Answer: The equals method should implement the logic that dictates whether a given object is "equal to" the current (this) object. Logically it should not rely on fields or parameters that are not members of the class. In your case, you should not be using the data array or the size field in the equals method. Just add the check on the appropriate fields of Customer.
For example, assuming Customer has a field called name, then the following equals checks if two Customers are equal if they have the same name:
@Override
public boolean equals(Object obj) {
    if (this == obj) {
        return true;
    }

    if (obj == null) {
        return false;
    }

    if (getClass() != obj.getClass()) {
        return false;
    }

    Customer other = (Customer) obj;
    if (name == null) {
        if (other.name != null) {
            return false;
        }
    } else if (!name.equals(other.name)) {
        return false;
    }
    return true;
}

If you're using an IDE like Eclipse, there are shortcuts for automatically overriding both equals() and hashCode() methods in a consistent way. Usually, both methods should use the same class members so that if two objects are equal, their hashcode values are identical.
Answer: You are comparing the Customer objects, not their names. Since they are not the same object, equals() will return false. To fix this add the following code to Customer:
public boolean equals(Object obj){
    if(obj instanceof Customer){
        Customer c = (Customer)obj;
        if(c.name.equals(this.name)
            return true;
    }
    return false;
}

EDIT: Sorry for the duplicate post, look at the post by chrylis, and insert obj != null before the instanceof statement

Good luck!
Answer: Note that you have to implement hashCode when you implement equals. There are some things to consider to write these methods correctly. To be on the safe side it's best to let an IDE generate these methods. For example, in Eclipse, go Source > Generate hashCode() and equals()...
Comment: He's actually wanting an `equals` for `Customer`.


Why can't I send a Twilio Verify SMS to caller in Mexico?

Question: Setup
I have been testing my Twilio app successfully for a while now using two USA-based numbers (+1 country code). The Verify tokens have been delivered successfully via SMS and the verification check statuses come back 'approved'. Life is good!
Problem
This morning I tried to testing my app with a caller from Mexico (+52 country code), and it totally failed. The caller did not receive the Verify SMS.
<code>Twilio::REST::RestError ([HTTP 403] 60605 : Unable to create record
The destination phone number has been blocked by Twilio. MX is blocked for sms channel in all services
https://www.twilio.com/docs/errors/60605
</code>
Aside from the "Unable to create record" message (I don't know what kind of record it is referring to), the message:

The destination phone number has been blocked by Twilio

makes me think my caller's number specifically has been blocked (is he on some dark web Internet's Most Wanted list!?).  The latter message:

MX is blocked for sms channel in all services

made my heart sink like all of Mexico was barred from receiving any kind of sms whatsoever.
Possible Cause
Visiting the URL from the error message led me to believe that perhaps somehow my Twilio account had been flagged (maybe I was manually testing too much in the preceding days):

The destination has been disabled due to suspected fraudulent activity or for possible security reasons.

Question
Why wasn't Twilio able to deliver the Verify SMS to the caller from Mexico?
Answer: I contacted Twilio Support and they promptly pointed me in the right direction. Apparently, only a handful of countries are enabled to receive Verify SMS by default. There are some bad dudes out there who abuse the communications network/system, so this is why we can't have nice things. Twilio Support to the rescue!

In order to send Verification SMS to phone numbers in a specific country, please ensure the destination country's Verify geo-permissions are enabled. You can enable them here: https://console.twilio.com/us1/develop/verify/geopermissions

For more information, please see https://www.twilio.com/docs/verify/preventing-toll-fraud/verify-geo-permissions

Screenshot of what to expect (search for country and check the box)
Comment: Recent update as well - https://www.twilio.com/changelog/verify-geopermissions-available-in-console-now


Interesting identity $\sum_{A\subseteq X\\B\subseteq X}|A\cap B|=n4^{n-1}$

Question:
Let $X = \{1,2,\dots,n\}$. Prove that the following identity holds:
  $$\sum_{A,B\subseteq X}|A\cap B|=n4^{n-1}$$

I noticed by using Inclusion-Exclusion formula that
$$
\begin{aligned}
\sum_{A\subseteq X\\B\subseteq X}|A\cap B|
&=\sum_{A\subseteq X\\B\subseteq X}|A|+\sum_{A\subseteq X\\B\subseteq X}|B|-\sum_{A\subseteq X\\B\subseteq X}|A\cup B|\\
&=\sum_{A\subseteq X}|A|2^{n}+\sum_{B\subseteq X}|B|2^{n}-\sum_{A\subseteq X\\B\subseteq X}|A\cup B|\\
&=2^n\sum_{A\subseteq X}|A|+2^{n}\sum_{B\subseteq X}|B|-\sum_{A\subseteq X\\B\subseteq X}|A\cup B|\\
&=2^{n+1}\sum_{k=1}^nk\binom{n}{k}-\sum_{A\subseteq X\\B\subseteq X}|A\cup B|
\end{aligned}
$$
By using identity $\sum_{k=1}^nk\binom{n}{k}=n2^{n-1}$, we get:
$$
\sum_{A\subseteq X\\B\subseteq X}|A\cap B|=n4^{n}-\sum_{A\subseteq X\\B\subseteq X}|A\cup B|$$
But now i am stuck.
Comment: Alternatively, you can use probability. Fix $A$. Then the expected intersection of $B$ with $A$ where $B$ is randomly chosen is clearly $|A|/2$. So the contribution from a fixed $|A|$ is $2^n|A|/2$. Now sum over all $|A|$ (and the choices for $|A|$)
Answer: You've written the sum in terms of an equally difficult sum, so it's not clear how to progress there.
To compute the sum directly, try writing it this way: $$\sum_{A\subseteq X\\B\subseteq X}|A\cap B| = \sum_{x\in X}\sum_{x\in A\cap B}1$$
For any $x$, there are exactly $2^{n-1}$ subsets of $X$ containing $x$, and we need to pick two of them, so there are $2^{n-1} \cdot 2^{n-1} = 4^{n-1}$ nonzero terms in the inner sum.  So we get: $$\sum_{x\in X}\sum_{x\in A\cap B}1 = \sum_{x\in X} 4^{n-1} = n 4^{n-1}$$
Answer: Choose two sets $A$ and $B$ at random and independent. Let $X$ be $|A\cap B|$. Then $X = X_1+X_2+...+X_n$ where $X_i$ is indicator variable for element $i$, i.e. $X_i=1$ if $i\in A\cap B$ else $X_i=0$. So we have $$E(X) = E(X_1) +...+E(X_n) =n\cdot {(2^{n-1})^2\over (2^n)^2} ={n\over 4}$$
But $$E(X) = \sum{|A\cap B|\over (2^n)^2}$$ and thus a conclusion.


Tangent lines of a projective curve

Question: I am solving this exercise and I don't know if I did the last step in a correct way:

Prove that the projective curve $(X+Y+Z)^{3}=27XYZ$ is irreducible and compute its singular points with their multiplicities and tangent lines.

Let $F=(X+Y+Z)^{3}-27XYZ$. As $Z$ does not divide $F$, dehomogenizing is reversible. The dehomogenized polynomial is: $$F_{*}=(X+Y+1)^{3}-27XY$$ $F_{*}$ is the substraction of two forms of consecutive degrees without common divisors, so it it irreducible. If $F_{*}$ is irreducible, then $(F_{*})^{*}=F$ is irreducible too.
I have computed the singularities using Maple and I get that $P=(1:1:1)$ is a double point.
Now there is the question. Have I computed well the tangent lines? I have done the following:
First I find the derivatives:$$F_{X}=3(X+Y+Z)^{2}-27YZ,\quad F_{Y}=3(X+Y+Z)^{2}-27XZ,\quad F_{Z}=3(X+Y+Z)^{2}-27XY$$ $$F_{XX}=6(X+Y+Z),\quad F_{XY}=6(X+Y+Z)-27Z,\quad F_{XZ}=6(X+Y+Z)-27Y$$ $$F_{YY}=6(X+Y+Z),\quad F_{YZ}=6(X+Y+Z)-27X,\quad F_{ZZ}=6(X+Y+Z)$$
And I will use the equation of the tangent lines: $$\sum_{i+j+k=m}\frac{1}{i!j!k!}\frac{\partial^{m}F}{\partial X^{i}\partial Y^{j}\partial Z^{k}}(P)X^{i}Y^{j}Z^{k}=0$$
Then: $$\frac{1}{2!}(F_{XX}(P)X^{2}+F_{YY}(P)Y^{2}+F_{ZZ}(P)Z^{2})+\frac{1}{1!}(2F_{XY}(P)XY+2F_{YZ}(P)YZ+2F_{XZ}(P)XZ)=0$$
So I get that: $$3X^{2}+3Y^{2}+3Z^{2}-18XY-18YZ-18XZ=0$$
Is this the equation of the tangent lines?
Comment: Clearly not, as $(1:1:1)$ is not on that conic. This should factor into two linear forms, but I'm not sure it does.
Comment: I don't quite get the irreducibility argument. How is $F_*$ the difference of two forms of consecutive degrees? $(X+Y+1)^3$ is not even a form.
Answer: $F_{XX}(P)=18\ne 3$ etc. The final conic should be
$$18X^2+18Y^2+18Z^2-18XY-18XZ-18YZ=0,$$
equivalently,
$$X^2+Y^2+Z^2-XY-XZ-YZ=0,$$
which is
$$(X+\omega Y+\omega^2 Z)(X+\omega^2 Y+\omega Z)=0$$
with $\omega=\exp(2\pi i/3)$.
Comment: But there is a $\frac{1}{2}$ multiplying the first three terms. Wouldn't it be $9X^2+9Y^2+9Z^2-18XY-18XZ-18YZ=0$?
Comment: @mkspk I'm not sure that $\frac12$ should be there...
Comment: @JyrkiLahtonen But if I do that, I don't count the YX, ZX and ZY terms.
Answer: Notice that
$$\{ (i, j, k) \mid i + j + k = 2 \} = \{(2, 0, 0), (0, 2, 0), (0, 0, 2), (1, 1, 0), (0, 1, 1), (1, 0, 1) \}$$
Thus we have
$$\frac{1}{2}(F_{XX}(P)X^{2}+F_{YY}(P)Y^{2}+F_{ZZ}(P)Z^{2})+(F_{XY}(P)XY+F_{YZ}(P)YZ+F_{XZ}(P)XZ) = 0$$
without the coefficient $2$ multiplying the mixed partial derivatives. It might be easier to understand why the coefficient $\frac 1 2$ must be there instead if you write the equation as:
$$(F_{XX}(P)X^{2}+F_{YY}(P)Y^{2}+F_{ZZ}(P)Z^{2})+2(F_{XY}(P)XY+F_{YZ}(P)YZ+F_{XZ}(P)XZ) = 0$$
because in this way one sees that the coefficient $2$ is there exactly to account for both $F_{XY}(P)XY$ and $F_{YX}(P)YX$, etc.
Anyway, a different approach is the following. Since $P$ belongs to the affine open subset given by $Z \neq 0$, we can dehomogenize with $Z = 1$ and identify $P$ with $(1, 1)$. Then, we consider the affinity:
$$\begin{cases} x = X - 1 \\ y = Y - 1 \end{cases} \quad\Longleftrightarrow\quad \begin{cases}X = x + 1 \\ Y = y + 1 \end{cases}$$
which maps $P = (1, 1)$ to $O = (0, 0)$. Applying the affinity to $F_*$ gives us:
$$(x + y + 3)^3 - 27(x + 1)(y + 1) = x^3 + 3x^2y + 3xy^2 + y^3 + 9x^2 - 9xy + 9y^2.$$
The homogeneous component with the lowest degree is:
$$9(x^2 - xy + y^2) = 9 (x - \omega y)(x - \omega^2 y)$$
where $\omega$ is a primitive sixth root of $1$. Thus the tangent lines to the transformed curve in $O$ have equations:
$$x - \omega y = 0 \qquad x - \omega^2 y = 0.$$
We apply the inverse affinity to obtain the equations of the tangent lines to the initial curve in $P$:
$$(X - 1) - \omega (Y - 1) = 0 \quad\longrightarrow\quad X - \omega Y - \omega^2 = 0$$
$$(X - 1) - \omega^2 (Y - 1) = 0 \quad\longrightarrow\quad X - \omega^2 Y - \omega = 0$$
Finally, we homogenize the equations:
$$X - \omega Y - \omega^2 Z = 0 \qquad X - \omega^2 Y - \omega Z = 0.$$

Tangent lines of a projective curve


UDP packets to IP addresses other than specific ones not arriving and not shown in Wireshark

Question: I'm writing a service using UDP, but I can't manage to reply to the client.
When sending to the client via the DHCP-assigned IP (192.168.1.143) Wireshark shows no sent packets. The server receives and Wireshark shows any packet sent by the client (broadcasted).
If I send to a random, unassigned IP Wireshark doesn't show it. I thought the NIC would happily send it, since there is a router in the way - shouldn't Wireshark show it, even though it cannot possibly be received by a remote endpoint?
If I send to either the router IP or another (specific, there is only one other) computer, the packet is shown in Wireshark.
I am running Windows 7, the firewall is turned off using the control panel.
Does the fact that wireshark doesn't show these packets mean that they aren't sent? What reason could there be for showing packets to one IP, but not another, on the same subnet?
Comment: When you say "there is a router in the way", you mean that the destination IP address is not inside the sending machine's subnet?
Comment: No, all devices are in the same subnet, 192.168.1.x, but the router  does DHCP for all devices.
Answer: The NIC cannot happily send a packet to an unassigned IP address in the same subnet, since it would have no idea what hardware address to send it to. Since the address is in the same subnet, the router is not in the way. Routers route between subnets.
Update 1: I see you're thinking that the machine is "wired directly to the router", but this is confusing terminology. Your "router" has a built-in switch in addition to a router. This machine is in fact connected to the router's switch, as is the actual part of the router that routes.
Update 2: It seems wired devices cannot communicate with wireless devices on your LAN at all, since wired devices are not getting ARP replies from wireless devices. The next step in troubleshooting is to make sure wired and wireless machines are connected to the same router and that you don't have some other device in-between them.
Comment: But there is only a wired connection to the router? So the local NIC on my host computer would send the packet to the router, which would drop it, but it would still be sent from my local computer? Am I completely wrong? The issue is though that I can send to one existing device (Windows 7 PC using a wired connection) and not another (Android 4.1 device using wireless). The packets don't arrive and wireshark shows no outbound packets.
Comment: You're completely wrong. Whatever argument you're using to conclude that you should send the traffic to something other than the machine directly would equally well apply to packets you were trying to send to the router. And clearly those are sent directly. (Both the router and this other machine are devices whose IP address are inside this machine's subnet, and thus should be sent directly. That's what the subnet mask is for -- to tell a machine which addresses it can reach directly.)
Comment: Well, I'm addressing it directly to the devices (192.168.1.2 and 192.168.1.143, respectively). One of them shows outbound packets in Wireshark, the other does not. Both devices actually exist, but one is wireless and the other is wired. The silly thing with sending to no endpoint (say 192.168.1.50) was just because I thought Wireshark would show me the outbound packet (addressed to 192.168.1.50) but sent through the router. But that might be completely stupid :p
Comment: Okay, not sending packets to a local IP that does not exist is expected, there's no way to know what hardware address to send them to, so they can't be put on the wire. So is your actual issue packets not being sent wireless machines? Presumably, it's for the same reason -- the machine is not getting the wireless machine's hardware address. You can check by running `arp -a` from a command prompt (after trying to send).
Comment: I'm using python sockets, and `sendto` is returning the amount of bytes sent, which is 20. It does tell me that whichever address I send to though. `arp -a` indeed doesn't show the `192.168.1.143` address, but I know it is connected by DHCP (I can receive packets from it). Do you know what could cause this?
Comment: Can you `ping` these IP addresses?
Comment: No, not from my current local host at least. "Destination host unreachable". My router shows this in "Available LAN hosts" though: `unknown  192.168.1.143  1C:B0:94:D5:DC:A0  Dynamic  Wireless` I guess the MAC address is what my local host is lacking?
Comment: So your actual problem is that your wired and wireless machines can't communicate with each other. Are you sure they're connected to the same router? Can they all reach the Internet?
Comment: I just tested; other wireless devices can be reached fine. All devices are shown correctly in the LAN hosts entry in the router interface though. So it's a single device, that is shown as an available host in the router, that can't be reached (isn't listed in the ARP table in any of my windows machines). Could the problem be with the router or the device? I don't know how the ARP table is populated...
Comment: It could be either. One way to check is to monitor the network at the device and see if it's receiving ARP queries.
Comment: Hi, I thought you might want to know how it worked out: Rebooted the router (not a cheapo one either, cisco small business) and I could ping it. I feel both stupid and cheated, because I didn't just start with restarting every device, and because it´s still necessary 2012.


Drupal 7: How to create a slideshow using Twitter Bootstrap Carousel?

Question: I'm a newbie when it comes to Drupal. But I know HTML/CSS, jQuery and Twitter Bootstrap quite well. I already have Bootstrap and jQuery installed and working fine.
I want to take advantage of Twitter Bootstrap responsive features and create a Twitter Bootstrap Carousel (photo slideshow) on the homepage. http://twitter.github.com/bootstrap/javascript.html#carousel
How can I set that up so that the photos and article links can be setup from Drupal 7 admin?
Comment: i dont know if there is any module to provide twitter bootstrap slideshow with Drupal, but what can you try is to create slideshow with  `views_slideshow` module and get all the styles from  twitter bootstrap, and style it by yourself etc. if you need more information, comment here, i will create a full answer
Comment: that's exactly what i want to do, to style it by myself. i already have twitter bootstrap and jquery working, all i need is the proper markup, and i do have the mark up, just don't know how to 1) add the slideshow to the homepage and 2) how to customize the markup. i think you have pointed me in the right direction, lemme try something...
Comment: are you trying to put image from article and you need a link to this article on your slideshow right?
Comment: yes, to look just like this but with different dimensions: http://twitter.github.com/bootstrap/javascript.html#carousel i'm almost there, but it seems i'm going to have to write several tpl files to remove a lot of the markup
Answer: It's very late to answer this question, but I guess it will be helpful to any other like me who seeks for assistance in creating a carousel with the use of TB(Twitter Bootstrap).
Drupal community has come up with a module called views_bootstrap or bootstrap_carousel
which will help you create a responsive carousel powered by TB and Drupal.
The instructions given in the project page should almost give you what you want cheers!


Can not use realm with object mapper swift 3.0

Question: I'm using Realm with Object Mapper for JSON Parsing. When I create a model class that Use both Object Mapper and Realm than I get compilation error
error:must call a designated initializer of the superclass 'QuestionSet'
import ObjectMapper
import RealmSwift

class QuestionSet: Object, Mappable {

    //MARK:- Properties
    dynamic var id:Int = 0
    dynamic var title:String?
    dynamic var shortTitle:String?
    dynamic var desc:String?
    dynamic var isOriginalExam:Bool = false
    dynamic var isMCQ:Bool = false
    dynamic var url:String?

    //Impl. of Mappable protocol
    required convenience init?(map: Map) {
        self.init()
    }

    //mapping the json keys with properties
    public func mapping(map: Map) {
        id          <- map["id"]
        title       <- map["title"]
        shortTitle  <- map["short_title"]
        desc        <- map["description"]
        isMCQ   <- map["mc"]
        url     <- map["url"]
        isOriginalExam <- map["original_pruefung"]
    }
}

if I use super.init() in init method than I get the compilation error
Case 1:
//Impl. of Mappable protocol
 required convenience init?(map: Map) {
    self.init()
}

error:must call a designated initializer of the superclass 'QuestionSet'
Case 2:
 //Impl. of Mappable protocol
 required convenience init?(map: Map) {
    super.init()
}

Convenience initializer for 'QuestionSet' must delegate (with 'self.init') rather than chaining to a superclass initializer (with 'super.init')
Case 3:
//Impl. of Mappable protocol
 required convenience init?(map: Map) {
    super.init()
    self.init()
}

error 1: must call a designated initializer of the superclass 'QuestionSet'
Initializer cannot both delegate ('self.init') and chain to a superclass initializer ('super.init')
Convenience initializer for 'QuestionSet' must delegate (with 'self.init') rather than chaining to a superclass initializer (with 'super.init')
Comment: You need a default constructor or whatever your language (Swift) calls it.
Comment: @EpicPandaForce If I use default init() method than I have to implement remaining init methods of Object. That I don't want to implement. So here convenience init() is used
Comment: Hmm... then I'm not sure. Ignore me, Swift is not my forte :D
Comment: "the superclass 'QuestionSet'", you are creating sub class inherit from QuestionSet?
Comment: @YunCHEN Yes Im subclassing the QuestionSet
Comment: Case 1 is working for me without Mappable protocol. I don't have ObjectMapper to test them together.
Comment: @YunCHEN The issue is that I m subclassing the QuestionSet. Without subclassing case 1 is also work fine with ObjectMapper as well.
Comment: got the same issue exactly, when i subclass my User model to any class like LoginResponse: User for the example, i got this error, what should i do in my extends class?
Answer: I use this pattern:
I have a BaseObject that all my Realm objects inherit from
open class BaseObject: Object, StaticMappable {

    public class func objectForMapping(map: Map) -> BaseMappable? {
        return self.init()
    }

    public func mapping(map: Map) {
        //for subclasses
    }
 }

Then your class would look like this:
import ObjectMapper
import RealmSwift

class QuestionSet: BaseObject {

    //MARK:- Properties
    dynamic var id:Int = 0
    dynamic var title:String?
    dynamic var shortTitle:String?
    dynamic var desc:String?
    dynamic var isOriginalExam:Bool = false
    dynamic var isMCQ:Bool = false
    dynamic var url:String?

    //mapping the json keys with properties
    public func mapping(map: Map) {
        id          <- map["id"]
        title       <- map["title"]
        shortTitle  <- map["short_title"]
        desc        <- map["description"]
        isMCQ   <- map["mc"]
        url     <- map["url"]
        isOriginalExam <- map["original_pruefung"]
    }
}


what is the correct way of using not:() function for RTL and LTR rules in CSS

Question: I applied a global div { direction: rtl ; } to my teachable school because the school is in Arabic language. but I also want to exclude certain elements from that rule (english texts, video players, sign up forms .etc)
so I tried using the not:() function to exclude those elements and here's the code:
div:not(.spc):not(.lecture-attachment-type-video):not(.quiz-content):not(.lecture-sidebar) {
    direction: rtl;
}
the global div {direction: rtl; } is working correctly but the :not() isn't. these classes are still in rtl.
any ideas?
thanks in advance
Comment: Why do you not "overwrite" the property with additional selectors like `#block-... { direction: ltr; }`? So you define the default direction and switch it for specific elements.
Answer: It's an inherited property, so not applying a rule with direction to those elements will just let them inherit that same direction from their parents. So to do it with CSS,
/* set it for the document: */
body {
    direction: rtl;
}

/* then reset it for the appropriate elements: */
.spc, .lecture-attachment-type-video, .quiz-content, .lecture-sidebar {
    direction: ltr;
}

… but if the text direction is a property of the content, which it usually is, HTML tends to be the better place to note that:

    ⋮

…

    ⋮

Comment: so using { direction: rtl; } alot won't cause too much trouble?
Comment: @AhmedDhahir: A lot how? Isn't it just once?
Comment: sorry for the unclear question.
my site has both RTL and LTR texts and they are interconnected (German language course for Arabic speakers )
I've set the direction to be RTL because there's more RTL text than LTR but where I have LTR elements I have to overwrite the global css rule (RTL).
therefore I have to use that "alot".
My question is, can this approach be harmful?
my first post here, still a n00b. thanks in advance
Comment: @AhmedDhahir: No, you don't have to worry – the way browsers apply CSS makes it not very different.


hadoop - java.lang.RuntimeException: java.lang.InstantiationException

Question: I am trying to run a map-reduce program from client side(widows-7), this is the map-reduce class :
Configuration conf =  new Configuration();

    conf.addResource(new Path("C:\\app\\hadoop-2.0.0-cdh4.3.0\\etc\\hadoop\\core-site.xml"));
    conf.addResource(new Path("C:\\app\\hadoop-2.0.0-cdh4.3.0\\etc\\hadoop\\hdfs-site.xml"));

    conf.set("fs.defaultFS", "hdfs://host:8020");
    conf.set("mapred.job.tracker", "host:8021");

    Job job = new Job(conf, "mapRed");
    job.setMapperClass(MapClass.class);
    //job.setInputFormatClass(org.apache.hadoop.mapreduce.lib.input.TextInputFormat.class);
    int numreducers = 1;

    job.setNumReduceTasks(numreducers);
    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(Text.class);

    Path inp = new Path("/data/test");
    FileInputFormat.addInputPath(job, inp);
    FileOutputFormat.setOutputPath(job, new Path("/data"));
    System.exit(job.waitForCompletion(true) ? 0 : 1);

This program is throwing exception :
    13/12/14 08:27:52 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
Exception in thread "main" java.lang.RuntimeException: java.lang.InstantiationException
    at org.apache.hadoop.util.ReflectionUtils.newInstance(ReflectionUtils.java:128)
    at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:2307)
    at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:87)
    at org.apache.hadoop.fs.FileSystem$Cache.getInternal(FileSystem.java:2342)
    at org.apache.hadoop.fs.FileSystem$Cache.get(FileSystem.java:2324)
    at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:351)
    at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:163)
    at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:335)
    at org.apache.hadoop.fs.Path.getFileSystem(Path.java:194)
    at org.apache.hadoop.mapreduce.lib.input.FileInputFormat.addInputPath(FileInputFormat.java:368)
    at org.gridedge.finalytics.MRTemplate.main(MRTemplate.java:55)
Caused by: java.lang.InstantiationException
    at sun.reflect.InstantiationExceptionConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.apache.hadoop.util.ReflectionUtils.newInstance(ReflectionUtils.java:126)
    ... 10 more

I found a simlilar question asked here InstantiationException in hadoop map reduce program and i changed FileInputFormat to TextInputFormat :
 TextInputFormat.addInputPath(job, inp);
 TextOutputFormat.setOutputPath(job, new Path("/data"));

Error remains same and its thrown at line FileInputFormat.addInputPath(job, inp);
Answer: The proper configuration is to set TextInputFormat at in setInputFormat method. That line seems to be commented in your code. Please comment it out and then try to use the
FileInputFormat.addInputPaths.
To set the input and output formats, you could see the below lines.
job.setInputFormatClass(TextInputFormat.class);
job.setOutputFormatClass(TextOutputFormat.class);
Let me know if you still face any error.


WMI Querying Thread Events - No results

Question: I`m investigating the WMI classes: Win32_Thread, Win32_ThreadTrace, Win32_ThreadStartTrace, Win32_ThreadStopTrace for possible usage.
The only one that returns any data is Win32_Thread. The rest do not return anything, no matter how I tried to execute it (as Administrator, with PowerShell, with ready to use tools, with code).
Is there any specific reason as to why this is happening? My OS is latest Win 10 Pro x64.
Example tool for testing: https://www.nirsoft.net/utils/simple_wmi_view.html
It would be really interesting and useful to see Win32_ThreadTrace working.
Any advice/help is much appreciated.
Comment: "The rest do not return anything, no matter how I tried to execute it" - the rest are _event_ classes - they can't be queried for instances, you [have to _subscribe_ to them and wait for WMI to call back](https://learn.microsoft.com/en-us/windows/win32/wmisdk/receiving-a-wmi-event).
Comment: @MathiasR.Jessen I see, then why doesn't the tool work to get notifications? It seems that it subscribes to most events.
Comment: Because the tool you're using is designed to browse WMI instances and class/schema data, not consume WMI events. What are you trying to accomplish with this? Write some sort of monitoring script in PowerShell?
Comment: I sincerely think that the tool is designed to subscribe as well, but maybe I am wrong so thanks for that. What I am trying to accomplish is far beyond my question... but to give you an idea: I want to trace threads created in process A by process B. I will do so using code, PowerShell was just for testing.
Answer: After investigation it seems that @Mathias was correct and you need to "subscribe" for certain events, even though "some" websites state that you can manually query these...
In any case, and answer is here for anyone else that hits this in the future:
<code>$query = "SELECT * FROM Win32_ThreadTrace"

Register-WmiEvent -Source Demo -Query $query -Action {
$global:myevent = $event
Write-Host 'ProcessID:' $event.SourceEventArgs.NewEvent.ProcessID
Write-Host 'ThreadID:' $event.SourceEventArgs.NewEvent.ThreadID
Write-Host 'TimeCreated:' $event.SourceEventArgs.NewEvent.TIME_CREATED }
</code>

WMI Querying Thread Events - No results


Is a normal distribution a good model of stock market returns across time?

Question: I'd like to use something like numpy.random.normal to model random stock market returns for a given year, with mean of 7.25% and standard deviation of 19.8% (found using Excel), using numbers for the S&P 500 acquired here:
http://pages.stern.nyu.edu/~adamodar/New_Home_Page/datafile/histretSP.html
Is a normal distribution a good model of stock market returns across time?
Comment: You can flag this for the moderators to migrate the thread to whichever you prefer. Since this has now been answered, it doesn't seem fair to me to delete. Note that only the moderators can migrate this thread to either of those sites.
Comment: This is probably a better question for the [quant.SE] or [economics.SE] sites than here.
Comment: OK, should I delete and move there, or leave this one open?
Answer: The short answer is no.  That is because stock returns exhibit what is called 'fat tails'.  Google "fat tails" + "stock returns" and you will get lots of information.  I think that understanding analytically the returns of the market is a superb question that is obviously not know - at least not known publicly !


How to resolve WIFI issues on Arduino YUN

Question: I have recently upgraded the open wrt of my Arduino YUN to version 3.18.23. After the upgrade, I have lost the WIFI access point of the YUN. I have also tried to reset the WIFI using the WIFI reset button but that seems not to work. Moreover, I have also tried to flash it but this has not solved the issue. Is there a way to revert back to the previous version of open-wrt? Downgrading the open-wrt, kernel and bootloader to the previous version more specifically?
Comment: Did you enable your wifi in settings (it is disabled by default)?
Comment: what do you mean by enabling wifi in settings? I cannot access the YUN web panel itself. And i have tried to wifi reset the yun also but i did not work either.
Comment: Can you access it via Ethernet or UART?
Answer: The openwrt img doesn't activate wifi by default. To revert, you can use the image provided on the arduino.org website.


How do I find a template?

Question: How I determine which template or form is responsible for processing node of page with this URL: mysite.com/node/node-number/edit ?
I think, that Drupal find the template of edit in this files:
page-node-edit.tpl.php
page-node- node-number.tpl.php
page-node.tpl.php
page.tpl.php

However, in my theme folder I have only page.tpl.php without the code of edit template, but edit template is worked.
And in template.php i heve this preprodsse_node:
function my_theme_preprocess_node(&$vars) {
    $node = $vars['node'];
    switch ($node->type) {
        case 'page':
            break;
    }
}

Now I think that the CCK module to generate this form. I can change one field or a behavior of the form?
P.S.
I need to change some input in edit form. And I can't use a different version of Drupal :(
Comment: The true answer of my question is: CCK module create a template for edit node
Answer: If you want to change the default value of fields in node edit form. You should looking on any *.tpl.php files. You have to define your own custom module and use hook_form_alter
You can use this if-statement inside the hook function.
// remember change [nodetype] to the one you want to alter.
if($form_id == 'nodetype_node_form'){
    // your code here
}

Comment: Thanks! How i can to change form action after user click submit?
Comment: You can define a new submit function and append into the form submit array.
`$form['#submit'][] = 'your_form_submit_function'`
Comment: Now if the form is submitted, CCK update some field in mysql database. I need to change this, because  in one form input contains three values, and this values need to be recorded in three fields in databse.
Comment: You can retrieve the submitted value in `$form_state['#values']`. You can do whatever you want then.
Comment: I would recommend you post a new question with more details of your case. Comment is not a good place for answering long question with lack of information.
Comment: Ok! I create this question [link] (http://drupal.stackexchange.com/questions/203368/how-to-edit-cck-form-at-drupal-6). And I thank you for your answer

How do I find a template?


The name: `Algebra' over a field/ring.

Question: An algebra over a field $F$ is a vector space over $F$, equipped with bilinear multiplication. i.e. $(v_1 + v_2) \cdot v_3 = v_1 \cdot v_3 + v_2 \cdot v_3$.
Why have our maths ancestors overloaded the name 'algebra' to also mean this structure? Is it just coincidental that this name has stuck?
In the theorems that I have seen, only examples of algebras are used. Has any theorem been proven using just the fact that the underlying structure is an algebra?
Comment: Are you asking if there are any theorems about algebras, or in your case rings which are vector spaces over a field? Because there are plenty.
Comment: @IanColey I meant to ask if there are any theorems about algebras. Not for specific algebras like the complex numbers, or the polynomials. But theorems which which go like "If A is an algebra, then ...".

According to Wikipedia, [link]http://en.wikipedia.org/wiki/Algebra_over_a_field[link], an algebra is almost a ring which is a vector space over a field, except that it need not be associative or have an identity. Do algebras have any easy properties?
Answer: There was once a persian mathematician that wrote an important book on rules of computations. His name, "al-Khwarizmi" was made eternal in "algorithm", the book title containing "ḥisāb al-jabr wa-l-muqābala" gave the word "algebra".
In the renaissance, algebra was everything that surpassed simple accountancy. Most prominently, solving polynomial equations and computations with roots.
Until the middle-end of the 19th century, mathematics was largely without structures. The idea of vector spaces and even of the set of real numbers started only in that period. The systematic use of structures is a side effect of axiomatic mathematics. Thus it is natural that the structure of polynomials, which were called "(entire (rational)) algebraic functions" at that time, is called "algebra". Because you need polynomials and their arithmetic to do "algebra".
That this was then generalized to the definition that you gave is due to the economy of words, why invent a new word when you can just re-purpose the name of the most prominent example.
To pinpoint this more precisely, one would have to find out when "Matrizenkalkül" or "matrix calculus" became "matrix algebra" and when the structure of infinitesimal symmetries was first named "Lie algebra", and if it had a different name before.

The name: `Algebra' over a field/ring.


Confidence interval for the ratio of two related proportions (glass ceiling index)

Question: I would like to compute the confidence interval of the glass ceiling index (GCI), which aims to measure gender inequality in Academia. According to "She Figures", the GCI is defined as follow:

The GCI measures the relative chance for women, as compared with men, of reaching a top position. The GCI compares the proportion of women in grade A positions (equivalent to Full Professors in most countries) to the proportion of women in academia (grade A, B, and C), indicating the opportunity, or lack of it, for women to move up the hierarchical ladder in their profession.

Hence it is defined $GCI=\frac{p_{W, A}}{p_W}$ where $p_{W,A}=n_{W, A}/n_A$ is the proportion of women in grade A, and $p_{W}=n_W/n=\frac{n_{W, A}+n_{W, B}+n_{W, C}}{n}$ the proportion of women in academia.
I have seen here a solution for computing the confidence interval for two independant proportion: Confidence interval around the ratio of two proportions
But in this case, the proportions are not independent. Do you know any method to approximate an interval of such kind of ratio? Thanks for your answer!
Comment: it is really easy to calculate a Bayesian credible interval for the measure you are looking for. Would that be of interest? Otherwise you could approximate a confidence interval, quick and dirty, using bootstrap.
Comment: Thanks for your comment. I can not use bootstrap. I am looking for an analytical solution. The reason is that in the end, it won't be computed by me, but by a service that only have access to SPSS.
Comment: I believe you can do bootstrapping in SPSS using the command syntax language. If you have limitations, such that the procedure should be possible to run using (the rather limited) SPSS, then you should state that in your question.
Answer: A quick and dirty solution using parametric bootstrap that will give you a confidence interval would look like the following in R:
<code># Made up numbers, substitute with your own
n_wa <- 50
n_wb <- 50
n_wc <- 50
n_a <- 100
n_b <- 100
n_c <- 100

# Parametric bootstrap
no_boot_samp <- 10000
n_wa_boot <- rbinom(no_boot_samp, size = n_a, prob = n_wa / n_a)
n_wb_boot <- rbinom(no_boot_samp, size = n_b, prob = n_wb / n_b)
n_wc_boot <- rbinom(no_boot_samp, size = n_c, prob = n_wc / n_c)
p_wa_boot <- n_wa_boot / n_a
p_w_boot <- (n_wa_boot + n_wb_boot + n_wc_boot) / (n_a + n_b + n_c)
gci_boot <- p_wa_boot / p_w_boot

# Calculating the 95% quantile bootstrap confidence intervall
quantile(gci_boot, c(0.025, 0.975))
</code>
Using these made up data the output is here:
<code>  2.5%  97.5%
0.8382 1.1600
</code>


Rails 3.1 assets pipeline in production

Question: I am using the assets pipeline (in Rails 3.1.3) and am kind of struggling to make it work in production.
Situation
In my /app/assets/stylesheets directory I have the following files:
application.css --> this is the default rails one
stylesheet.css --> This is my custom stylesheet

I spent a lot of time getting my stylesheet.css included in the /public/assets/directory in production (by running rake assets:precompile) and I finally made it by adding the following line into in my application.rb file:
    config.assets.precompile += ['stylesheet.css']

I know have the right precompiled stylesheet.css file in production.
My Problem
The problem I have is when using stylesheet_link_tag with my stylesheet.css file. It turns out:
<%= stylesheet_link_tag "stylesheet" %> is resolved into <link href="/stylesheets/stylesheet.css" media="screen" rel="stylesheet" type="text/css"> in production I would expect the path to be resolved into /assets/stylesheet.css just like it does in development.
What is even more surprising is that application.css behaves perfectly even though <%= stylesheet_link_tag "application"%> resolves into <link href="/stylesheets/stylesheet.css" media="screen" rel="stylesheet" type="text/css">. What I don't understand is that the public/stylesheets/ directory does not exist in rails 3.1.
Any idea ?
Comment: The only solution I have found so far is using `<%= stylesheet_link_tag "/assets/stylesheet.css" %>`. It is not satisfying but it works !
Answer: Richard Hulse answers pointed me to the right direction. What happens is really subtle..
The answer to my question is Rails 3.1 assets has no fingerprint in production.
Basically, my project use mongoid instead of ActiveRecord. According to Mongoid documentation about configuration, the application.rb file can be modified to not include ActiveRecord which means removing:
require railties/all

And replacing it with:
require "action_controller/railtie"
require "action_mailer/railtie"
require "active_resource/railtie"
require "rails/test_unit/railtie"
# require "sprockets/railtie" # Uncomment this line for Rails 3.1+

I was so used to doing this manipulation with rails 3.0.x that I did not pay attention to the comment related to Rails 3.1
My problem was that I was not requiring sprockets !
Thank you all for your help !
Answer: The reason you can access stylesheet.css in development is because of how Sprockets works.
In development mode ALL requests to anything under /assets are sent to Sprockets to process. Sprockets will directly map requests to paths, one-to-one, so you can access any assets stored in app/assets/etc.
All requests go through Sprockets; it is serving the files to your browser.
In production things are different. A fingerprint is added to filenames, and the expectation is that you'll precompile your assets to static files. This is for performance reasons - Sprockets is not fast enough to serve lots of requests.
Only those CSS and JS files referenced by the default manifests are compiled into application.css and application.js. Other files that you reference are not precompiled unless they are added to the config.assets.precompile array in your config file.
You say that the files resolve to /stylesheets/stylesheet.css. The pipeline should generate a path like this in development: /assets/applicaton.css. In production there should be a fingerprint in the filename. What you have posted suggested that the pipeline is not enabled (these are the old, pre 3.1, locations for the files).
If this is an upgraded app, it is likely that you have missed some crucial config option. This is the main cause of dev->production issues. Check that the pipeline options are set exactly as they are in the last section of the pipeline guide. (My guess is that you are missing config.assets.enabled = true in application.rb)
And for clarity I would suggest changing the name of stylesheet.css to admin.css, while including this in the precompile array (as you already had done).
With the config options set correctly, and your admin manifest included in precompile, you should have application.css available for the front end and admin.css available for the back-end, both linkable via the helper methods.
Comment: Ok I got it ! Wrote another answer about this. I am using mongoid and I was actually not including sprockets ! This question pouted me to the right direction: http://stackoverflow.com/questions/7648349/rails-3-1-assets-has-no-fingerprint-in-production
Comment: Yeah, that one will get you every time! ;-)
Comment: What you are saying makes a lot of sense. However, I do have the `config.assets.enabled = true` instruction in my application.rb file. And this app is fresh rails 3.1.3 app. I will try to further investigate my issue since as you are saying it really looks like the assets pipeline is not enabled in production (fingerprint missing)
Answer: You application.css should be a manifest file, meaning that your when you run your program it should include your stylesheet.css automatically.
make sure it has these two lines.
application.css:
/*
 *= require_self
 *= require_tree .
*/

If it does then something else isn't working properly, you shouldn't need the line:
config.assets.precompile += ['stylesheet.css']

If that isn't working either make sure you have all the settings enabled from this Asset Pipeline guide.
Comment: What I am looking for is to **not** include the `application.css` file. This is the reason why I am using another css file. The reason for that is that I want to have different css files depending on whether  I am in the front office or the back-office
Comment: Then I'm a little confused, does your `application.css` still have the manifest above? Or does `stylesheet.css`? If either do can you post the manifest?
Comment: application.css does not have such a broad manifest. It does not have the require_tree . directive. Instead it has a require_tree ./admin because I am only using it for my back office
Answer: While I was looking around actionpack to see what might be causing this problem I found this little gem in the 3.1.1 changelog:
javascript_path and stylesheet_path now refer to /assets if asset pipelining is on.

Soooo, If you're using 3.1.0 upgrade to 3.1.1 and see if it fixes it. If you've already upgraded then were back to square one. But it does seem to describe your problem since stylesheet_link_tag uses stylesheet_path interally.
Comment: I updated my question. This app is a rails 3.1.3 app. Thank you for the tip anyway

Rails 3.1 assets pipeline in production


Very poor VPS performance: my problem or the host?

Question: I have a Linux (CentOS 5.6) VPS which I use for hosting a few unimportant projects, but am currently really struggling with the performance. What can I do to find out if the problem is my configuration, or my host overloading the server I'm on?
If I ping the server right now:
Ping statistics for x.x.x.x:
  Packets: Sent = 100, Received = 73, Lost = 27 (27% loss),
Approximate round trip times in milli-seconds:
  Minimum = 161ms, Maximum = 207ms, Average = 167ms

The websites on the server are very very slow to load. I can connect via SSH, but there is a 2-20 second lag between me pressing the keyboard and anything appearing on screen.
Load is low (0.18 (1 min) 0.15 (5 mins) 0.09 (15 mins)), memory usage is low, the network interface is hardly being used... I've included some further information below.
# vmstat
procs -----------memory---------- ---swap-- -----io---- --system-- -----cpu------
r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st
0  0      0 728372      0      0    0    0   161   252    0 1440 11  0 89  0  0

# free
             total       used       free     shared    buffers     cached
Mem:       1048576     320208     728368          0          0          0
-/+ buffers/cache:     320208     728368
Swap:            0          0          0

iftop shows me as the only thing with a connection open to the server.
Is there anything else to look at, or should I get in contact with my VPS provider?
Comment: This looks suspiciously like the kinds of things I was experiencing on a regular basis on my previous VPS provider. Their support was no help at all. I finally changed providers, and haven't had any problems since (despite the new VPS living in a datacenter in the same city as the old one!).
Comment: Hmm, interesting! Do you mind specifying which provider you were with?
Comment: I was with GoDaddy. Still get my domains from them, but I now have a Linode VPS, and I couldn't be happier with it (well, unless it was free, of course...).
Comment: Ahh, well I'm not with them! Have heard good things about Linode, but are a little out of my price range. Have submitted a support ticket requesting to be moved to a quieter node.
Comment: can you tell us which services are you running there? I guess you're running apache.. but *sql? are all those thing with the default config?
Comment: All the standard web services: apache, BIND, Postfix, Dovecot, ProFTPd, SSH, MySQL. All installed and managed via Virtualmin. Having spoken to my host, it appears their network was suffering a DDOS last night: would have been good to have been notified about this, but it does account for things really going downhill then. I think the residual slowness is probably a combination of geography, and me paying $4 a month! Thanks for all the help.
Answer: Your stats in general look sane. The only worrying thing are connectivity issues (RTT - depending on how far you are it may look acceptable - and especially packet loss).
To start with, try switching all services down and test your connection to the server with repeated ping and traceroute. It can be that you're having issues with your end of the link (ISP), the data centre has some problems or both.
Only after having coped with those issues should you start looking for other possible causes.
Comment: The dropped packets seem to have resolved with a bit of time, though things are still going more slowly than I'd expect. The RTT isn't worrying me *too* much: I'm in the UK and the server is in the US. I was having no problems with my local connectivity when the issues were at their worst. Thanks for the help!
Answer: I would get in contact with your VPS provider.  If nothing else to get them working on the problem simultaneously as yourself to resolve it faster.
How is your connection at the client you are trying to connect from?
The stats you provided look OK.  Most VPS's use shared hosts so it likely another virtual server on your host is having issues.  Its also possible another server on your node is being DDOS'd - affecting your bandwidth.
Comment: I'm on a 50Mbit cable connection here which is fast and stable. The server is a cheap VPS, so I guess the node being overloaded is a plausible explanation. Thanks for the help!
Comment: Who are you using?  I use a cheap VPS as well through a company called Webexxpurts.  Its $15/month from 50GB of HDD 1.5GB of RAM and 1500GB/month of bandwidth.  Ive been using for about 3 months now and have had zero problems.  Speed has always been great.


Find the string subtract matching values

Question:
I want to calculate J column cells automatically based on A , C and I cells, as shown in screenshot for contract ID 111 total value is 800 and in C column  there are total 600 values against 111 contract ID, I want to to auto calculate the remaining amount in J cells against each contract.
Answer: Use SUMIFS and simple subtraction.
=I2-SUMIFS(C:C,A:A,H2)


Referencing Associated Object Returns Nil

Question: I have two models.
class User < ActiveRecord::Base
  has_one :message
end

class Message < ActiveRecord::Base
  belongs_to :user
end

If I have a created user with an associated Message and I delete that message and create a new one like, user.message returns nil. For example.
user = User.create

message = Message.create(user_id: user.id)

Message.where(user_id: user.id).destroy_all

Message.create(user_id: user.id)

# Now if I call this below, it always returns nil
user.message

Why does this occur? Shouldn't Rails 3 pick up on that change? How do I fix this?
Answer: Just load the object again before doing user.message like, user.reload.
reload - Reloads the record from the database.


Harmonic conjugates in geometry

Question: In geometry, points $P$ and $Q$ are said to be the harmonic conjugate with respect to points $A$ and $B$ if they divide $AB$ internally and externally in the same ratio.
One of my books specifies the formula $$\frac{2}{AB} =\frac{1} {AP}+ \frac{1} {AQ}.$$
Trying to derive this, you see that there are three cases; one for $P$ and two for $Q$ depending on which of $A$ or $B$ it's closer to. This formula works out if you consider the case when $Q$ is closer to $B$, but not in the other case.
Is it just that the formula is derived with $A$ being defined as the point $Q$ is farther from in the case of external division, and they just left it out? That's the only way it makes sense, unless the book's talking about signed distance, which I don't think is the case here.
Answer: So consider the case where $Q$ is closer to $A$ than $B$.
Suppose $A=(0,0), B=(x,0), P=(p,0), Q=(q,0)$. Here $x,p$ are positive but $q$ is negative.
The definition of harmonic conjugates says that
$$\frac{AP}{PB}=\frac{AQ}{BQ}$$
that is
$$\frac{p}{x-p}=\frac{-q}{x-q}$$
$$\Rightarrow \frac{1}{p}+\frac{1}{q}=\frac{2}{x}$$
One can conclude that the book is indeed using the signed lengths.

Harmonic conjugates in geometry


On guitar music, what does a number and a horizontal line underneath the notes mean?

Question: In the picture we can see two cases of horizontal lines underneath a group of notes, on the first one there is only one line with a number 1 beside it and on the second one there are two lines, the longer one with a number 1 and the shorter one with a number 3.
So what do these lines mean? What do the numbers beside them mean? And what does their length mean?
Thank you
Answer: It means that you should leave your first (and later third) fingers where they are throughout the underlined measures (or as long as the line reaches), because you will need them again on the same frets, and this minimizes unnecessary left hand movement. These numbered lines are recommendations and are purely for didactical purposes.