Create variable length array from string

Question: The string
$string = 'a.b.c.d';
should create an array like
array('a' => array('b' => array( ....
I managed to come up with this:
function create_array(&$arr, $string, $data){

  $parts = explode('.', $string);
  $key = array_shift($parts); // first key

  $new_arr = array();
  $have_empty_slot = false;

  if(!isset($arr[$key])){
    $arr[$key] = array();
    $have_empty_slot = true;
  }

  $new_arr = &$arr[$key];

  foreach($parts as $part){
    if(!isset($new_arr[$part])){
      $new_arr[$part] = array();
      $have_empty_slot = true;
    }

    $new_arr = &$new_arr[$part];
  }

  // last one
  if($have_empty_slot)
    $new_arr = $data;

}

$arr = array('a' => array('aa' => array('aaa' => 555)), 'b' => 55);

create_array($arr, 'c.cc.dd', 4545); // <-- works

create_array($arr, 'a.aa.aa2', 33); // <-- works

create_array($arr, 'a.aa.aaa.aaaaaaa', 4545); // <-- connection closed by remote server lol

print_r($arr);

So if I try to add a new element after the last element of an existing set of elements I get that connection closed by remote server error. What's wrong with it?
Comment: What is `$arr` and what is that number (3rd parameter)?
Comment: the 3rd parameter is not important, that's the value of the last child element
Answer: This should work:
function create_array(&$arr,$string,$data){
    $a=explode('.',$string);
    $last=count($a)-1;
    $p=&$arr;

    foreach($a as $k=>$key){
        if ($k==$last) {
            $p[$key]=$data;
        } else if (is_array($p)){
            $p[$key]=array();
        }
        $p=&$p[$key];
    }
}

Answer: It's still pretty unclear, but if you only want what you have asked for:
function convertToArray($string)
{
    $pos = strpos($string, '.');
    $key = substr($string, 0, $pos);

    $result = array($key => array());

    if ($pos === false) {
        return array($string=>array());
    } else {
        $result[$key] = convertToArray(substr($string, ($pos+1)));

        return $result;
    }
}

var_dump(convertToArray('a.b.c.d'));

Will ouput:
array(1) {
  ["a"]=>
  array(1) {
    ["b"]=>
    array(1) {
      ["c"]=>
      array(1) {
        ["d"]=>
        array(0) {
        }
      }
    }
  }
}


Down-sets of a finite ordered set are down Max.

Question: The following exercise comes from the book: Introduction to Lattices and order (second edition, B. A. Davey, H.A. Priestley).
Problem 1.14, pag. 27.
Let $P$ be a finite oredered set.
(1) Show that $Q=\downarrow\mbox{Max}(Q)$, for all $Q\in\mathcal{O}(P)$;
(2) Establish a one-to-one correspondence between the elemenents of $\mathcal{O}(P)$ and antichain in $P$.
(3) Hence show that, for all $x\in P$,
$$|\mathcal{O}(P)|=|\mathcal{O}(P\setminus\{x\})|+|\mathcal{O}(P\setminus (\downarrow x\ \cup \ \uparrow x))|$$
Some definitions
Definition 1 (antichain). Let $P$ an ordered set. $P$ is an antichain if $x\le y$ in $P$ only if $x=y$.
Definition 2 (maximal element). Let $P$ an ordered set, $Q\subseteq P$. Then $a\in Q$ is a maximal element of $Q$ if $a\le x$ and $x\in Q$ imply $a=x$. The set of all maximal element of $Q$ is $\mbox{Max}(Q)$.
Definition 3 (Down-set). Let $P$ be an ordered set, and $Q\subseteq P$. $Q$ is a down-set (of $P$) if, whenever $x\in Q,y\in P$ and $y\le x$, we have $y\in Q$.
Definition 4 (down Q, down x, up x). Given an arbitrary subset $Q$ of $P$ and $x\in P$, we define
$\\ \bullet \ \downarrow Q=\{y\in P \ | \ \exists x\in Q\ \mbox{s.t.} \ y\le x\} \ \ \ (\mbox{Down} \ Q)$
$\bullet \ \downarrow x=\{y\in P\ | \ y\le x\} \ \ \ (\mbox{Down} \ x)$
$\bullet \ \uparrow x=\{y\in P\ | \ y\ge x\}\ \ \ (\mbox{Up} \ x)$
Definition 5 (set of all down-set of P). The family of all down-set of a set $P$ is denoted by $\mathcal{O}(P)$.
$|A|$ is the cardinality of the set $A$.
My ideas
(1.a) I want to show that $\downarrow\mbox{Max}(Q)\subseteq Q,\, \forall Q\in\mathcal{O}(P)$.
Let $x\in\downarrow\mbox{Max}(Q)$, then $\exists q\in\mbox{Max}(Q)$ such that $x\le q\implies x\in Q$, because $Q$ is a down-set of $P$. Is it ok?
(1.b) Now I'll try to prove that $Q\subseteq\downarrow \mbox{Max}(Q)$.
Suppose, by contraddiction, that there exists $q\in Q\setminus\downarrow\mbox{Max}(Q)$, i.e. $q\in Q\wedge q\notin\downarrow\mbox{Max}(Q)$, so $\forall s\in\mbox{Max}(Q)$, we have that $(q>s)\vee q\ ||\ s$ ($q$ is not comparable with $s$).
If $q>s$, then $s\notin\mbox{Max}(Q)$, (contraddiction).
If $q\ || \ s$, then $q\in\mbox{Max}(Q)\implies q\in\downarrow\mbox{Max}(Q)$ (contraddiction).
Is this part ok?
(2) Let $\mathcal{A}(P)$ be the set of all antichains of $P$. I think that
$\begin{array}{ccccc}\phi&:&\mathcal{O}(P)&\longrightarrow&\mathcal{A}(P)\\ \\ &&Q=\downarrow\mbox{Max}(Q)&\longmapsto&\phi(Q)=\mbox{Max}(Q)\end{array}$
is a good one-to-one correspondence.
(3) I have no idea to solve this. I have to study this answer  to understand what to do.
Please, check my ideas and tell me if they are ok or not: the order theory is so insidous to me. Thank you.
Answer: (1) is OK, although the proof that $Q \subseteq {\downarrow}\mathrm{Max}Q$ has at least a minor problem: if $q||s$ for all $s \in \mathrm{Max}Q$, then $q \notin \mathrm{Max}Q$, because $q \leq q$.
But you can just say (I guess) that in a finite poset any element is below a maximal element, and proceed from there.
(2) is OK.
For (3), just note that the number of anti-chains in $P$ is the sum of the number of anti-chains in $P\setminus\{x\}$ with the number of anti-chains in $P \setminus ({\downarrow}x \cup {\uparrow}x)$.
Indeed, if $A$ is an anti-chain in $P$ and $x \in P$, then, if $x \in A$ it follows that $A$ is an anti-chain in $P \setminus ({\downarrow}x \cup {\uparrow}x)$;
otherwise (if $x \notin A$), then $A$ is an anti-chain in $P \setminus\{x\}$.
Hence, by (2) you get the desired result.
Comment: Thanks you! I need to writer the 1.b in a batter way. (3) Is clear now. I really appreciate Your help. Anyway, I think there Is a minor typo in your answer: $a\in P$ Is clearly $x\in P$ in (3). Thanks for Your time.
Comment: @Ixion Thanks! Corrected the typo.


Can i use pointers in and with template parameters?

Question: I'm trying to do someting like this:
template<typename FromType, typename ToType>
class TEncodingCache
{
public:
    ToType* Get(const FromType* Source)
    {
        return Data[Source];
    }

private:
    std::map<FromType*, ToType*> Data;
};

In main function:
TEncodingCache<char, char16_t> cache;
cache.Get("test");

I obtain this error:
binary '[': no operator found which takes a right-hand operand of type 'const FromType *' (or there is no acceptable conversion)
Comment: Your `Get` parameter is a `const FromType *`, but your map's key is a `FromType *`. Are you aware that in C++ you cannot convert a pointer to a constant object to a pointer to a non-constant object, and that you can only compare pointers to the same type, and, furthermore, pointer comparison is not portable, except in certain narrow situations? There are multiple reasons why the shown code will not work, and comprises undefined behavior. C++ simply does not work this way.
Comment: Notice that there are no guaranties in C++ to have `"test" == "test"`.
Answer:
Can i use pointers in and with template parameters?

Yes.

I obtain this error: binary '[': no operator found which takes a
  right-hand operand of type 'const FromType *' (or there is no
  acceptable conversion)

That error occurs because your std::map expects keys of type FromType*, and you are trying to pass it the Source argument of type const FromType *.  The compiler won't allow that because it would violate the const-correctness guarantee (i.e. when you declared Source to be of type const FromType * you effectively promised that the function wouldn't modify the object the pointer points to, and passing Source to std::map::operator[] as a FromType * would allow std::map::operator[] to modify it, if it wanted to).
The easy fix would be to change your member-variable to this:
std::map<const FromType*, ToType*> Data;


Pulumi GKE Ingress with SSL

Question: I am trying to use #Pulumi to setup

#Ingress for my #GKE service
with HTTPS loadbalancer
with Google managed SSL certificate.
For some reason, the Ingress creation is stuck forever at "Creating Ingress".

I am using GCE Ingress Controller.
Are there any working examples that I can refer to?
if you need more info, feel free to ask and I would be happy to provide.
Below is a code snippet of I have tried so far (arrived at this state after a zillion trials). What am I missing?
#kubernetes #gcp
const authDeploymentService = new k8s.core.v1.Service(authDeploymentName,
            {
                metadata: {
                    name: "auth-svc",
                    labels: authDeploymentAppLabels,
                    namespace: namespaceName,
                },
                spec: {
                    type: "LoadBalancer",
                    ports: [{ port: 80, targetPort: 8080 }],
                    selector: authDeploymentAppLabels,
                },
            },
            {
                provider: clusterProvider,
                dependsOn: [authDeployment]
            }
        );

        const authServiceManagedCert = new gcp.compute.ManagedSslCertificate("auth-cert-001", {
            name: "auth-cert-001",
            project: myGcpProject.projectId,
            description: "Managed SSL Certificate For auth service",
            managed: {
                domains: [
                    "mydomain.com"
                ]
            }
        });

        const managedCertConfigMap = new k8s.core.v1.ConfigMap("managed-certificate-config", {
            data: {
                "1": pulumi.interpolate`{"Key":{"Namespace":"${namespaceName}","Name":"${authServiceManagedCert.name}"},"Value":{"ExcludedFromSLO":false,"SoftDeleted":false,"SslCertificateName":"${authServiceManagedCert.id}","SslCertificateBindingReported":true,"SslCertificateCreationReported":true}}}`
            },
            metadata: {
                name: "managed-certificate-config",
                namespace: "kube-system",
            }
        })

        const ingress = new k8s.networking.v1beta1.Ingress(authDeploymentName + "-ingress", {
            metadata: {
                namespace: namespaceName,
                annotations: {
                    "ingress.gcp.kubernetes.io/pre-shared-cert": authServiceManagedCert.name,
                    "networking.gke.io/managed-certificates": authServiceManagedCert.name
                }
            },
            spec: {
                ingressClassName: "gce",
                backend: {
                    serviceName: authDeploymentService.metadata.name,
                    servicePort: 80
                },
                tls: [
                    {
                        hosts: ["mydomain.com"],
                    }
                ],
                rules: [
                    {
                        host: "mydomain.com",
                        http: {
                            paths: [
                                {
                                    path: "/",
                                    backend: {
                                        serviceName: authDeploymentService.metadata.name,
                                        servicePort: authDeploymentService.spec.ports[0].port,
                                    },
                                }
                            ],
                        },
                    },
                ]
            }
        },
            {
                provider: clusterProvider,
                dependsOn: [managedCertConfigMap]
            });

Answer: Ok in case anyone else stumbles across this, I found one key input thanks to this article  ... I was using networking/v1beta (which is deprecated apparently) instead of networking/v1. Once I changed to v1, I started seeing different behavior such as the backend,frontends, target proxies etc getting created automatically.
I only wish Pulumi updates its documentation to reflect this so people like me don't struggle.

Pulumi GKE Ingress with SSL


Change Event Within Date Range

Question: I am trying to write PHP code to check if a date/time falls within a certain range to render some HTML, and if it doesn't, render some other HTML. Below is my code. If I set the comparisons to a future date, it seems to work fine, & the flag status goes to half staff & then back to full staff according to the parameters. However the next day, about 2-3 hours after the status is set back to full staff, it automatically reverts back to half staff status.
if(date('Y-n-j-G-i') >= '2013-10-9-12-00' && date('Y-n-j-G-i') <= '2013-10-10-5-00' ) {

    echo "Governor's Flag Status:
 Half Staff";
}
else {
    echo "Governor's Flag Status:
 Full Staff";
}

I have tried to 'think' through the logic, but it appears I am missing something. Any help would be appreciated.
Comment: Where are you getting format like `'2013-10-10-5-00'` from?
Answer: Do not compare strings (as you actually do, because date() function returns formatted strings), compare UNIX timestamps instead.
Use time and strtotime with valid time format:
$currentTime = time();
if($currentTime >= strtotime('2013-10-9 12:00') &&
   $currentTime <= strtotime('2013-10-10 5:00')) {

Comment: Thanks. This appears to be working. It does make more sense to compare numerical values, than to compare strings. :)

Change Event Within Date Range


Command+K in Eshell (mac)

Question: Often I will have multiple buffers open in Emacs, including a few eshells, and using the muscle-memory from bash, I will Command+K to try and clear the buffer in eshell. However, using this in eshell just screws up all of my buffers and I have to close everything and open everything again.
I would like to re-bind Command+K while in eshell to clear the e-shell buffer. If this is not possible, I would like to simply disable the effect of Command+K while in eshell, so that my muscle memory doesn't cause me to screw up my other buffers. Are either of these tasks possible?
Answer: You can bind key to local map in your case is "eshell-mode-map"
<code>(define-key eshell-mode-map "\C-k" 'eshell/clear)
</code>
Comment: My notes indicate that I had problems adding keys to `eshell` and had to do something extra like use the `eshell-mode-hook`:  `(add-hook 'eshell-mode-hook (lambda () (define-key eshell-mode-map [return] 'eshell-send-input)))`.  In addition, the call of the question is for the `super` modifier key rather than the `control` key.
Comment: Hi, thanks for the reply, but I get the error "symbol's value as variable is void: eshell-mode-map". I tried adding what lawlist said, but I still get the same error.

Command+K in Eshell (mac)


String to Datetime regardless of DateTime Format

Question: I have a text file with DateTimes stored like this: 30/11/2013 1:18:36 PM
This is fine if you only run the program on one machine, as the DateTime is stored in the same format as the system uses. However I just encountered a problem where if I change user to one of my other accounts, who for some reason is using MM/DD/YYYY format, an error is thrown. How can I read the DateTime regardless of what the system format is? This is what I'm using right now:
RecieptList.Add(new Reciept
                {
                    ...
                    DateNTime = Convert.ToDateTime(stringArray[(i * 12) + 9]), // == 30/11/2013 1:18:36 PM
                    ...
                });

Thanks!
Comment: I was thinking that I'd want to know the time zone, and then I'd want to store the datetime as UTC. Not directly part of your question, just a common issue when doing something similar.
Comment: I think I should mention what the error was. It failed to convert the string into a datetime. +$exception {"String was not recognized as a valid DateTime."}
Comment: Do you have the option to store the data differently?
Comment: What way were you thinking?
Comment: It seems the problem start when you write the date. If you write the date according to the CultureInfo of the current machine and then try to read back in a different culture you are at a dead end. You should store your date in a CultureInfo indipendent way. How do you write these dates?
Comment: Found a good SO question/answer explaining what I was thinking: http://stackoverflow.com/questions/114983/given-a-datetime-object-how-do-i-get-a-iso-8601-date-in-string-format
Answer: you can use TryParseExact() to parse the Dates.
Try This:
String dt = "30/11/2013 1:18:36 PM";//or anydate
DateTime result;
if (DateTime.TryParseExact(dt, "dd/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture, DateTimeStyles.None,out result))
{
   //success use result
}

Edit: as per comments you mentioned that you are storing dates in system dependent culture.
I Strongly suggest you to use CultureInfo.InvarientCulture argument while storing the dates, to store them in Indepedent culture.
so that while reading it in different machines won't produce problems.
Try this: While storing Dates into TextFile
 String dt = DateObject.ToString(CultureInfo.InvariantCulture);

now you can write String dt into TextFile.
Comment: @Nathan:
Your task is impossible. How to determine if the date format is MM/dd/yyyy or dd/MM/yyyy.
Take this as an example: 12/11/2013.
Is this the 12th November 2013 or 11th Dezember 2013?
Comment: Sometimes the string is in dd/MM/YYYY, sometimes its MM/dd/yyyy, depeneding on what the system is set to when the date was written. Would your example read a date in MM/dd/YYYY format?
Comment: @Nathan so the Date format of the input string varies?  that isn't clear from your question.
Comment: @Nathan: my code assumes that your date is in the format of `dd/MM/yyyy` and it wont work if the date is in any other format.
Comment: Good point Janes, I guess the way I'm doing it now will have to do. Thanks!
Answer: You need to parse the date, with the correct settings of the computer. You can get the UI settings by calling Thread.CurrentUICulture .
CultureInfo ci = Thread.CurrentUICulture ; // ci refers to the current UI culture
Convert.ToDateTime(dateStr, ci);

Replace your code with the above , and it should work. You can find more examples below
Convert.ToDateTime Method (String, IFormatProvider)
DateTime.TryParse Method (String, IFormatProvider, DateTimeStyles, DateTime)
Comment: I have mentioned CurrentUICulture , there is difference between CurrentCulture and CurrentUICulture
Comment: Pardon me i overlooked it.


Drupal 7 hook_form_alter and submitting the form

Question: I added some custom field so that i can get more information when someone registers into the website but i want to alter one field on the form. I created a module which has a hook_form_alter function so that i can alter the field_first_name of the registration form. here is the code
function user_registration_form_alter(&$form, &$form_state, $form_id){
if ($form_id == 'user_register_form'){

    $form['field_first_name'] = array(
        '#type' => 'textfield',
        '#title' => t('First Name'),
        '#description' => t('Enter your first name.'),
        '#maxlength' => 255,
        '#required' => TRUE,
        );

}
if (isset($form['actions']['submit'])) {
 $form['actions']['submit']['#submit'][] ='user_registration_form_submit';
   }

}

I also created a the function which handles the form submission.
function user_registration_form_submit(&$form, &$form_state)
{

$fe_id = db_insert('field_revision_field_first_name')
    ->fields(array(
        'field_first_name_value' => $form_state['value']['field_first_name'],
        ))->execute();
    drupal_set_message(t('your form entry has been added'));
}

My problem is that when i submit the form and i check the user details. i find that the first name details does not exist in the database or when i login as the administrator and click on the 'people' link. i find that all information is are submitted except the first name field which i am trying to alter. I also tried to submit the form without the form submit function but it still doesn't work.
and i get the following error message if i add the form_submit function

Notice: Undefined index: value in user_registration_form_submit() (line 37 of /var/www/html/lite/sites/all/modules/user_regestration/user_registration.module).
PDOException: SQLSTATE[HY000]: General error: 1364 Field 'entity_id'
  doesn't have a default value: INSERT INTO
  {field_revision_field_first_name} (field_first_name_value) VALUES
  (:db_insert_placeholder_0); Array ( [:db_insert_placeholder_0] => ) in
  user_registration_form_submit() (line 38 of
  /var/www/html/lite/sites/all/modules/user_regestration/user_registration.module).

THIS IS LINE 37 AND 38 OF MY CODE
'field_first_name_value' => $form_state['value']['field_first_name'],
))->execute();

I am creating the module on localhost first before i push it to the live website
Comment: the second question is answered here http://drupal.stackexchange.com/questions/204068/how-do-i-programmatically-insert-the-entity-id or here http://stackoverflow.com/questions/37798980/drupal-7-hook-form-alter-and-submitting-the-form/37822904#37822904 ;)
Answer: There's a typo, change value to values
To get the user id use:
<?php
global $user;
print $user->uid;
?>

Comment: Thanks for that correction but know the error has changed and its as follows ................."PDOException: SQLSTATE[HY000]: General error: 1364 Field 'entity_id' doesn't have a default value: INSERT INTO {field_revision_field_first_name} (field_first_name_value) VALUES (:db_insert_placeholder_0); Array ( [:db_insert_placeholder_0] => john ) in user_registration_form_submit() (line 38 of /var/www/html/lite/sites/all/modules/user_regestration/user_registration.module)."
Comment: so - what entity are you trying to insert ? a field revision ???? something seems strange to me here ..
Comment: I looked into my database and found that drupal had made a table for the field first_name so i want to insert data into the first_name field but drupal is giving me an error of entity_id does not have a default value. the entity_id field is in that table.
Comment: the entity in this case refers to the user. so the entity_id will be the userid, see my edit to get the current user's id
Comment: It could be that the user is not created in your hook ...
Comment: thanks but now i am trying to figure out how do i generate the user_id so that it can be inserted into the entity_id field.
Comment: actually this is another question. maybe [profile2](https://www.drupal.org/project/profile2) will help you. if you want to do it yourself, add another question !


Can you please explain Simpson's paradox with equations, instead of contingency tables?

Question: I probably don't have a clear understanding of the Simpson's paradox. Informally I know that the average of response Y1, grouped over all possible levels of factor A, can be higher than the average of response Y2 over all levels of A, even if the average of Y1 for each level of A (each group) is always less than the corresponding average of Y2. I've read examples, but I still get surprised each time I see it, maybe because I don't learn well by specific examples: I have troubles generalizing them. I learn best, and would rather see, an explanation in formulas. Can you please explain the paradox relying on equations, instead than count tables?
Also, I think the reason for my surprise is that I could unconsciously be making some assumptions about the averages involved in the paradox, which may not be true in general. Maybe I forget to weight by the number of samples in each group? But then, I would like to see an equation which shows me that the estimate of the total average is more accurate if I weight each group average by the number of samples in each group, because (if this is true) it isn't obvious to me in general. Naively I would think that the estimate of $\mathbf{E}[Y_1]$ has a lower standard error when I have more samples, irrespective of weighting.
Comment: I have a related post [here](http://stats.stackexchange.com/questions/221711/is-stagewise-feature-discovery-an-invalid-approach) with simulations. The simulation may be helpful for you to understand simpson's paradox
Comment: [here](http://dagitty.net/learn/simpson/) is a machine producing Simpson's paradoxs on demand!
Answer: Suppose we have data on 2 variables, $x$ and $y$,  for 2 groups, A and B.
Data in group A are such that the fitted regression line is
$$y = 11  -  x$$
with mean values of $2$ and $9$ for $x$ and $y$ respectively.
Data in group B are such that the fitted regression line is
$$y = 25  -  x$$
with mean values of $11$ and $14$ for $x$ and $y$ respectively.
So the regression coefficient for $x$ is $-1$ in both groups.
Further, let there be equal numbers of observations in each group, with both and y distributed symmetrically.  We now wish to compute the overall regression line.  To keep matters simple we will assume that the overall regression line passes through the means of each group, that is $(2,9)$ for group A and $(11,14)$ for group B. Then it is easy to see that the overall regression line slope must be $(14-9)/(11-2) = 0.55$ which is the overall regression coefficient for $x$. Thus we see Simpson's paradox in action – we have a negative association of $x$ with $y$ in each group individually, but a positive association overall when the data are aggregated.
We can demonstrate this easily in R as follows:
<code>Xa <- c(1,2,3)
Ya <- c(10,9,8)
m0 <- lm(Ya~Xa)
plot(Xa,Ya, xlim=c(0,20), ylim=c(5,20), col="red")
abline(m0, col="red")

Xb <- c(10,11,12)
Yb <- c(15,14,13)
m1 <- lm(Yb~Xb)
points(Xb,Yb, col="blue")
abline(m1, col="blue")

X <- c(Xa,Xb)
Y <- c(Ya,Yb)
m2 <- lm(Y~X)
abline(m2, col="black")
</code>

The red points and regression line are group A, the blue points and regression line are group B and the black line is the overall regression line.
Comment: @DeltaIV I have written a new answer using purely algebraic arguments.
Comment: Hi, thanks for the answer, but this is yet another specific example of the Simpson's paradox. I specifically asked for something in the form of a theorem or a set of equations, a more abstract and general approach. Anyway, since there are no other answers, I'll study your example and if I feel that it helps me to generalize the concept, I'll accept the answer.
Answer: Here is a general approach to understanding Simpson's Paradox algebraically for count data.
Suppose that we have survival data for an exposure and we create a 2x2 contingency table. To keep things simple we will have the same counts in each cell. We could relax this, but it would make the algebra quite messy.
\begin{array}{|c|c|c|c|}
\hline
& \text{Died}   & \text{Survived} & \text{Death Rate} \\ \hline
\text{Exposed} & X &  X & 0.5 \\ \hline
 \text{Unexposed}& X & X & 0.5\\ \hline
\end{array}
In this case, the Death Rate is the same in both the Exposed and Unexposed groups.
Now, if we split the data, say into one group for females and another group for males, we obtain 2 tables, with the following counts:
Males:
\begin{array}{|c|c|c|c|}
\hline
& \text{Died}   & \text{Survived} & \text{Death Rate} \\ \hline
\text{Exposed} & Xa &  Xb & \frac{a}{a+b} \\ \hline
\text{Unexposed}& Xc & Xd & \frac{c}{c+d}\\ \hline
\end{array}
and for females:
\begin{array}{|c|c|c|c|}
\hline
& \text{Died} & \text{Survived} & \text{Death Rate} \\ \hline
\text{Exposed} & X(a-1) &  X(b-1) & \frac{a-1}{a+b-2} \\ \hline
 \text{Unexposed}& X(c-1) & X(d-1) & \frac{c-1}{c+d-2}\\ \hline
\end{array}
where $a,b,c,d \in [0,1]$ are the proportions of each cell in the aggregated data table that are male.
Simpson's Paradox will occur when the death rates for exposed males is greater than the death rate for unexposed males AND the death rate for exposed females is greater than the death rate for unexposed females. Alternatively, it will also occur when the death rates for exposed males is less than the death rate for unexposed males AND the death rate for exposed females is less than the death rate for unexposed females.
That is, when
$$\left(\frac{a}{a+b} < \frac{c}{c+d}\right) \text{   and   } \left(\frac{a-1}{a+b-2} < \frac{c-1}{c+d-2}\right)$$
$$ \text{Or  }$$
$$\left(\frac{a}{a+b} > \frac{c}{c+d}\right) \text{   and   } \left(\frac{a-1}{a+b-2} > \frac{c-1}{c+d-2}\right)$$
As a concrete example, let $X=100$, and $a=0.5, b=0.8, c=0.9$. Then we will have Simpson's paradox when:
$$\left(\frac{0.5}{0.8+0.9} < \frac{0.9}{0.9+d}\right) \text{   and   } \left(\frac{0.5-1}{0.5+0.8-2} < \frac{0.9-1}{0.9+d-2}\right)$$
$$ (-9 < d < 1.44) \text{   and   } (0.96 < d < 1.1) $$
From which we conclude that d must lie in $(0.96,1]$
The 2nd set of inequalities gives:
$$\left(\frac{0.5}{0.8+0.9} > \frac{0.9}{0.9+d}\right) \text{   and   } \left(\frac{0.5-1}{0.5+0.8-2} > \frac{0.9-1}{0.9+d-2}\right)$$
$$ (d < -0.9 \text{ or } d>1.44) \text{   and   } (0.96 < d \text{ or } d > 1.44) $$
which has no solution for $d \in [0,1]$
So for the three values that we chose for $a,b,$ and $c$, to invoke Simpson's paradox, $d$ must be greater than 0.96. In the case where the value was $0.99$ then we would obtain a Death Rate for Males of
$$  0.5/ (0.5+0.8) = 38 \text{% in the exposed group} $$
$$  0.9/ (0.9+0.99) = 48 \text{% in the unexposed group} $$
and for Females:
$$  (0.5-1)/ (0.5+0.8-2) = 71 \text{% in the exposed group} $$
$$  (0.9-1)/ (0.9+0.99-2) = 91 \text{% in the unexposed group} $$
So, males have a higher death rate in the unexposed group than in the exposed group, and females also have a higher death rate in the unexposed group than the exposed group, yet the death rates in the aggregated data are the same for exposed and unexposed.


How to disable/turn off Automatic URL alias

Question: Could anyone suggest how to disable/turn off automatic URL aliases?
Answer: Automatic URL aliasing? It will be the Pathauto module doing that. You can disable it, but you will need to delete your current aliases as well, which the Pathauto module provides an interface for if you check its settings.


A slightly complicated differential problems that needs help

Question: I have totally forgotten how to do calculus and recently I am taking a course that requires me to solves some differential problems and I am stuck at this:
$$
y = (x+1)^7 (2x+5)^2 (3x-4)^6
$$
find $dy/dx$
I am just not sure if I have to expand everything (which I believe I shouldn't) or is that just chain rule and product rule?
Comment: Hint: $y=2916x^{15}+11664x^{14}-20655x^{13}-121473x^{12}+28485x^11+516843x^{10}+160267x^9-1142835x^8-728589x^7+1349385x^6+1259592x^5-722832x^4-1036800x^3+9984x^2+337920x+102400$ :)
Answer: Just have a bit patience:
$$
(f g h)' = (fg)' h + fg h' = (f'g+fg') h + fgh' = f'gh + fg'h+fgh'
$$
and
$$
\left((a x + b)^c\right)' = c (ax+b)^{c-1} (ax+b)' = ac(ax+b)^{c-1}
$$
should suffice.
Comment: thanks! that's what I was trying to derive a few minutes and this confirms that!
Comment: And it follows inductively that you can do what you did on the first line for any number of factors
Answer: $$y = (x+1)^7 (2x+5)^2 (3x-4)^6\\
\ln y = 7\ln (x+1)+2\ln (2x+5)+6\ln (3x-4)\\
\frac {y'}y=7\frac1{x+1}+2\frac2{2x+5}+6\frac3{3x-4}\\
y'=(x+1)^7 (2x+5)^2 (3x-4)^6\left(7\frac1{x+1}+2\frac2{2x+5}+6\frac3{3x-4}\right)=??$$
In general:
$$\frac{d}{dx}\prod_kf_k(x)=\prod_kf_k(x)\sum_{k}\frac{f_k'(x)}{f_k(x)}$$
Comment: Nice shortcut!!
Comment: Is this valid for all $x \in \mathbb R$?
Comment: Once you complete the computation, how do you check the answer at the end?
Comment: I think assuming $\mathbb{C}$ as domain of calculation, there is no problem.
Comment: @UmbertoP. not required here actually, required in "find the roots type" where ln is also involved. Only the last step here matters.
Comment: Perhaps it's better to take the absolute value of both sides first?
Comment: @GFauxPas Oh forget everything between Umberto and me. It really doesn't matter for the final result, whatever x may be.
Answer: hint: Let $f = (x+1)^7\cdot (2x+5)^2, g = (3x-4)^6$, and use the product rule twice.
Answer: Derive every factor in turn
$$
y' = 7(x+1)^6 (2x+5)^2 (3x-4)^6\\+
2\cdot2(x+1)^7 (2x+5)^1 (3x-4)^6
\\+6\cdot3(x+1)^7 (2x+5)^2 (3x-4)^5
$$


assumptions made for a normal distribution- a interview question

Question: I was asked in my interview:
What assumptions can you make? Why and when? (i.e When is it safe to assume "normal").
Can some one answer this .
Answer: You can make any assumptions you like. Then you have to support them or show that they are not (grossly) violated or show that methods that don't use those biases give similar results.
For example, we can assume the errors from a ordinary least squares regression are normally distributed (note that OLS regression makes additional assumptions, e.g. independence and homoskedasticity).  We can then show evidence that they are, indeed, normal by looking at the residuals of the model in various ways (e.g. quantile normal plots, tests of normality, examination of skew and kurtosis). In addition, we can use robust regression on the same variables and see if the results are very different from the ones in OLS (e.g. by looking at the parameter estimates or by comparing the predicted values).
Or, we can assume that the relationship between x and y is linear and test that by looking at scatter plots or by adding a quadratic term to the model and seeing what it does or by using splines and seeing how "unstraight" they are.
Comment: @IrishStat Can you explain the context in which you intend "normality requires independence"? It's rather easy to state conditions where you have normality but not independence.
Comment: you might want to add that normality requires independence thus if you have time series data or spatial data this has to be validated.
Comment: Great Explanation!!
Comment: It is my understanding that tests invoking the central limit theorem require  n.i.i.d. meaning normal, independent and identically distributed random variables . You can have i.i.d. with or without normality. It appears that the term "normal" in my time series experiences implicitely carries with it the i.i.d. specification which is what I was ranting about.
Comment: It would be great if you could answer my other query as well. http://stats.stackexchange.com/questions/138734/bias-and-sampling


Empty sym array and double array not the same in Matlab

Question: I use matlab R2018b
These code are right:
a=0.336;
Ta=9.476;
Te=1.208;
Tw=1.498;
eqh=[0.661;0.619;0.568];
ex=[-1.24;-1.346;-1.441];
en=-ex;
ey=[0.376;0.705;0.968];
eqx=[-0.309;-0.357;-0.392];
eh=[1.594;1.583;1.545];
eyqh=[0.642;0.78;0.897];
a0=a*Ta*Te^2;
syms bt Td Ki Kp;
a1=[];a2=[];a3=[];a4=[];exqh=[];
for i=1:3
        Kp=1/bt;
        exqh(i)=en(i)*eqh(i)+eqx(i)*eh(i);
        Ki=1/(bt*Td);
        a1=Ta*Tw*eqh(i)+a*Te^2*en(i)+a*Te^2*ey(i)*Kp
        a1(i)=a1
end

But these code are wrong:
a=0.336;
Ta=9.476;
Te=1.208;
Tw=1.498;
eqh=[0.661;0.619;0.568];
ex=[-1.24;-1.346;-1.441];
en=-ex;
ey=[0.376;0.705;0.968];
eqx=[-0.309;-0.357;-0.392];
eh=[1.594;1.583;1.545];
eyqh=[0.642;0.78;0.897];
a0=a*Ta*Te^2;
syms bt Td Ki Kp;
a1=[];a2=[];a3=[];a4=[];exqh=[];
for i=1:3
        Kp=1/bt;
        exqh(i)=en(i)*eqh(i)+eqx(i)*eh(i);
        Ki=1/(bt*Td);
        a1(i)=Ta*Tw*eqh(i)+a*Te^2*en(i)+a*Te^2*ey(i)*Kp

end

The difference between them is :
a1=Ta*Tw*eqh(i)+a*Te^2*en(i)+a*Te^2*ey(i)*Kp
        a1(i)=a1

and
 a1(i)=Ta*Tw*eqh(i)+a*Te^2*en(i)+a*Te^2*ey(i)*Kp

I do not know why the second is wrong.
The following error occurred converting from sym to double:
Unable to convert expression into double array.

Error in Now3 (line 20)
        a1(i)=Ta*Tw*eqh(i)+a*Te^2*en(i)+a*Te^2*ey(i)*Kp

Comment: When you say "it's right" you mean that it doesn't generate an error message. I can't believe it does what you want it to do, because the result of the first two loop iterations are thrown away (overwritten).
Comment: @CrisLuengo The letter 'i' is changed, I tested it in my software, and I did not generate an error.
Comment: Yes, `i` is changed, but `a1` is overwritten, discarding the values it had in the previous loop iteration. When you do `a1=...` you throw away anything that `a1` has previously, and give it a new value. You are discarding the results for `i=1` and `i=2`.
Answer: a1 =[];

is an empty double array

while
Ta*Tw*eqh(i)+a*Te^2*en(i)+a*Te^2*ey(i)*Kp;

is a sym variable, can't be assigned directly to a double array

Alternative
a1 = sym([]);

is an empty sym  array
Comment: Ta*Tw*eqh(i)+a*Te^2*en(i)+a*Te^2*ey(i)*Kp;  is a sym variable. Why can it be assigned to a1 which should be double because a1=[] is an empty double array?
Comment: But why can it be assigned indirectly to a1(1)?
Comment: And can you tell me why a1(1) is a double variale?
Comment: And why a1 is a neutral matlab but a1(1) is a  double variable?
Comment: @Y.zeng: `a1 = ...` overwrites `a1`, its previous value and type are irrelevant. `a1(1) = ...` assigns something **into** the array `a1`, its type is relevant.
Comment: @CrisLuengo If I put Ta*Tw*eqh(i)+a*Te^2*en(i)+a*Te^2*ey(i)*Kp to a1, then I put a1 to a1(1), what is the difference to I putting Ta*Tw*eqh(i)+a*Te^2*en(i)+a*Te^2*ey(i)*Kp to a1(1) directly?
Comment: @Y.zeng: Please read my previous comment again. I explain exactly what the difference is.


Place a UIButton at bottom of UIScrollView with constraints

Question: I have a view with three textfield/textview fields in it, and in order to make the view scrollable when the keyboard appears, I have put all the elements inside a scrollview. The elements where not outside the frame before, so the contentSize should be the same size as the full screen size and then when the keyboard appears, so when the keyboard appears i update the bottom constraints for the scrollview to be -keyboardHeight from the view bottom and then it is scrollable above the keyboard..
This all works fine, the problem is adding a button to the bottom of the scrollview that leading/trailing to the sides and bottom of the view.
See pictures:
Current view, with button hidden behind navigation bar
Where i would like the button to be. Approx 20 margin to right.left.bottom
I am using SnapKit to set my constraints, and for the button I would like to do something like this:
    sharebutton.snp.makeConstraints { (make) in
        make.width.left.right.equalToSuperview()
        make.bottom.equalToSuperview().offset(-20)
    }

(The Superview/the scrollview is already set as 20 margin from sides)
//EDIT: Code added ->
override func viewDidLayoutSubviews() {
    scrollview.contentSize = CGSize(width: centerView.frame.width,      height: view.frame.height)
}

override func viewDidLoad() {
    super.viewDidLoad()

    self.title = "title"
    view.backgroundColor = .white

    view.addSubview(scrollview)

    scrollview.addSubview(sharebutton)
    scrollview.addSubview(subjectField)
    scrollview.addSubview(messageField)
    scrollview.addSubview(datepicker)
    scrollview.addSubview(addressTable)
    addressTable.dataSource = self
    addressTable.delegate = self
    addressTable.separatorStyle = .none
    addressTable.keyboardDismissMode = .onDrag
    addressTable.separatorStyle = .singleLineEtched

    subjectField.placeholder = "content"
    datepicker.setTitle("topbutton", for: .normal)
    datepicker.setTitleColor(.black, for: .normal)
    datepicker.setTitleColor(UIColor.ME.border, for: .highlighted)
    datepicker.titleLabel?.font = UIFont.ME.button
    datepicker.layer.borderWidth = 1
    datepicker.layer.cornerRadius = 3
    datepicker.layer.borderColor = UIColor.ME.border.cgColor
    datepicker.addTarget(self, action: #selector(showDates), for: .touchUpInside)

    sharebutton.setTitle("Share", for: .normal)
    sharebutton.backgroundColor = UIColor.ME.buttonMainBlue
    sharebutton.addTarget(self, action: #selector(shareClicked), for: .touchUpInside)

    scrollview.backgroundColor = .red
    scrollview.snp.makeConstraints { (make) in
        make.top.bottom.equalToSuperview()
        make.left.width.right.equalTo(centerView)
    }

    datepicker.snp.makeConstraints { (make) in
        make.top.equalToSuperview().offset(paddingGlobal)
        make.left.width.right.equalToSuperview()
        make.height.equalTo(50)
    }

    addressTable.snp.makeConstraints { (make) in
        make.top.equalTo(datepicker.snp.bottom)
        make.left.right.equalTo(datepicker)
        make.height.equalTo(200)
    }

    subjectField.snp.makeConstraints { (make) in
        make.top.equalTo(datepicker.snp.bottom).offset(20)
        make.left.right.equalToSuperview()
    }

    messageField.snp.makeConstraints { (make) in
        make.top.equalTo(subjectField.snp.bottom).offset(20)
        make.height.equalTo(200)
        make.left.right.equalToSuperview()
    }

    sharebutton.snp.makeConstraints { (make) in
        make.width.left.right.equalToSuperview()
        make.bottom.equalToSuperview().offset(-20)
    }
}

Any thoughts ?
Comment: show the code where you are adding button and other UIElement to subview.
Comment: I have added the code
Comment: you need to add a `uiview` (for ex name it `containerView`) inside a scroll view subview first then add all your uielement(eg.  textfield/textview, UIButton) to the subView of that containerView.
Comment: I solved it with a containerview :) Thank you
Answer: You need to add a UIView (for ex name it containerView) inside a scrollView subview first then add all your uielement(eg. textfield/textview, UIButton) to the subView of that containerView.
Answer: as Govind commented, I could solve it by placing my subviews in a container view.
Answer: Using StoryBoard and Constaint Xcode 11.5 iOS 13
StoryBoard View Controller Scene


Best way to represent 1/3rd of 100% in CSS?

Question: I have a big
 with three little
's inside of it, inline. They each have 33% width, but that causes some alignment problems because 3 * 33% != 100%. What is the best way to represent a perfect third in CSS like this? Maybe just 33.33%?
Comment: Just throw enough decimal places at it until it's unlikely someone has a desktop large enough to make sig.figs relevant to the calculation.
Comment: Useful info: [Sub-Pixel Rendering Problems in CSS](http://ejohn.org/blog/sub-pixel-problems-in-css/)
Comment: You can't specify fractions, so 33.33% is pretty much your only option.
Comment: This is why it would be awesome to count in base 12 rather than in base 10. Half=6, third=4, quarter=3, sixth=2. Two thirds=8, three quarters=9. Base 10 is a pain
Answer: Now that calc is widely supported among modern browsers, you can use:
#myDiv {
    width: calc(100% / 3);
}

Or you can use this as a fallback if your browser wouldn't support it:
#myDivWithFallback {
    width: 33.33%;
    width: calc(100% / 3);
}

Comment: Don't forget the fallback: `.column-one-third { width: 33.33%; width: calc(100%/3); }`. That way you can support non calc browsers.
Comment: I've found that 6 decimal places is often necessary for it to properly calculate the exact 1/3 of a div. `width: 33.333333%;`
Comment: side note, both `calc(200% / 3)` and `calc(100% / 1.5)` work nicely as 2/3rds
Answer: Are you making any allowance for margins? You could go 30% per column with 5% margin either side of the center column.
Quick example
Answer: .col_1_3 {
    width: 33%;
    float: left;
}

.col_1_3:nth-of-type(even) {
    width: 34%;
}

Comment: .col_1_3 {width: 33.33%; float: left;} is a better approach. Maybe some box-sizing: border-box and some padding.
Answer: The highest resolution screen is a non-production NEC LCD screen with a resolution of 2800x2100. Even at that size, one pixel is 0.0357% of the width of the screen. So 33.33% should be close enough until 5,000-pixel-wide screens become the norm.
John Resig did some research into sub-pixel rounding in different browsers, though, so depending on your three columns to equal exactly the width of the screen may never have a perfect solution.
Comment: This answer is not very future proof
Comment: 2021: Writing this comment from my 3840x2160 standard production monitor
Comment: That "high" sounds a little low for current non-production monitors. This looks a little more reasonable as a current technology ceiling.

http://en.wikipedia.org/wiki/Ultra_High_Definition_Television


multiple subnets on the same cisco switch port

Question: We have several servers on colocation and now trying to re-organize the network by utilizing Cisco ASA 5505 as a router and Cisco 3750x series switch.
Network topology is looking like that:
<code>    uplink
      |
+----------+
| ASA 5505 |
+----------+
      |
      |(trunk vlan10,101,102)
      |
+-----------+
|   3750x   |
+-----------+
      |
      |
      |
+--------------------------+
| Server N                 |
| 192.168.10.10  : vlan10  |
| 192.168.101.10 : vlan101 |
| 192.168.102.10 : vlan102 |
+--------------------------+
</code>
The problem with 3750x configuration as we need to deliver three different subnets (vlan 10,101,102) to the "Server N".
"Server N" has multiple IPs from different subnets (vlan101 and 102) assigned to the same NIC. Plus, it has Base Motherboard Controller on board with another IP from vlan10. BMC shares the NIC - thus there is only one physical link from the server to switch.
Since 3750x doesn't allow having multiple vlans allowed on the same port with out trunking - what is the best way to configure the switch to allow this configuration?
UPDATE 2014-02-24:
The original question was asked a long time ago, so let me post the solution i found working for me with out messing with trunks and recompiling the system.
I used static routes to deliver traffic over a vlan to a server secondary addresses.
for the configuration above, the NIC has three subnets. Let's consider one of them as primary and include into VLAN configuration. Other two are going to be a routed subnets.
Here is the simple config:
<code>    interface Vlan1
     ip address 192.168.10.1 255.255.255.0
    !
    ip route 192.168.101.0 255.255.255.0 192.168.10.10
    ip route 192.168.102.0 255.255.255.0 192.168.10.10
</code>
This way you can add multiple secondary subnets to your server.
However, i believe this is not the best way to configure it as it keeps secondary subnets out of VLANs - thus it's not as secure as we want it. But this is going my next questions to professionals.
Comment: "Trunking" is practically defined as "having multiple VLANs on the same port". Why don't you trunk to the server?
Comment: More likely, they just put each IP (other than the first) in its own subnet and routed them to the host as /32s. You can also put multiple subnets in the same VLAN. I'm not sure why you think that won't work in your environment.
Comment: This requires additional OS configuration (like bonding) which is undesired. Many dedicated server providers are able to add additional IPs with out having you to reconfigure your server. We would like to go the same way first and keep "trunk to the server" as the last resort.
Comment: Curious what OS you're running that tagging is enormous task? I can do this in Windows with a broadcom adapter in about 30 seconds.
Comment: @EugeneM: It doesn't require bonding, it just requires trunking. Providers add additional IPs without requiring you to reconfigure your server because the IPs are in the same subnet.
Comment: @DavidSchwartz SingleHop delivered 173.236.xxx.xxx 96.127.xxx.xxx and 107.6.xxx.xxx to the same server - which i believe is not in the same subnet. Same happens with our Softlayer servers - totally different IPs with out trunking. Do you think they merged all these subnets into one VLAN? I wonder if merging several subnets into one vlan is the only way to solve my problem and my ASA doesn't support that...
Comment: @SpacemanSpiff: i'm running Ubuntu on Dell R710 server. Tagging is not an enormous task at all, but rather the last thing i want to do. Since all known to me provides can deliver totally different subnets to my servers with out having me to change anything - i wonder how's that possible with all our hardware.
Comment: @DavidSchwartz: Actually that's was my question - how to get it working in my environment. Looks like asa 5505 doesn't allow to configure multiple subnets under one VLAN via ASDM. Is there a command to do this via serial port? like "#ip add xxx secondary" ?
Comment: @EugeneM: I discovered the same thing a couple weeks ago and it blew my mind. Never tried this workaround, but it might work: http://www.ducea.com/2008/05/31/adding-a-secondary-ip-address-on-a-cisco-asa-ethernet-interface/
Answer: Trunk the interface going to the server.
Comment: does it require additional server configuration (like re-building linux kernel with 802.1Q support) ?
Comment: you should be able to do a vconfig add [eth device] [vlan], this will create a [eth device].[vlan] interface you can work with.
Comment: take a look at this link http://www.cyberciti.biz/tips/howto-configure-linux-virtual-local-area-network-vlan.html
Answer: Although it is common to have a 1-to-1 Layer 2 to Layer 3 mapping (aka vlan to IP network mapping), you don't have to.
If you really don't want a trunk, it might be appropriate to have multiple L3 networks exist within a single vlan. However, keep in mind that this could be a security risk as all that is needed to bypass firewall rules between the L3 networks on the ASA is a host to change its IP settings since they are all in the same vlan.
You need to decide the appropriate solution on your own of course. However, if you get comfortable configuring vlan trunks on both switches servers then you can feel confident that your decision wasn't made due to a bias towards taking a shortcut.
Comment: thanks for the reply, that was my first thought to combine multiple subnets into the same vlan, but it looks like ASA 5505 doesn't support it. In our orifinal topology - all servers were connected through $30 dumb switch and everything worked just fine. I just can't believe that such complex devices for $4K cannot do what dumb switch does...
Answer: Well, I'm not going to waste time telling you you're doing it wrong, but there is a way to achieve what you want that's going to burn ports on your 3750 :)
Set the following:
Port 1 on VLAN10
Port 2 on VLAN101
Port 3 on VLAN102
Ports 4-7 on a fourth VLAN, let's call it 103.
Now... connected Port 1 to Port 4, Port 2 to Port 5, Port 3 to Port 6, Port 7 to your server.
Ta da... you have just bridged your three VLANs back together... YAY.
This is all sorts of the "wrong way to do it", but I suppose it does get you what you want, all three broadcast domains merged back together. Your ASA may get pissy with you, you've been warned.
Comment: Just another good reason for me to hate the Cisco ASA :)
Comment: that's a 1001st way to burn a switch ;) anyway, i wonder how every dedicated server provider can deliver different IP ranges (from totally different subnets) to the server with our having you reconfigure anything in the system...
Comment: It will not burn the switch, lol. You're not even going to come CLOSE to hitting the ASIC limitations of a 3750.


Laravel: eloquent relationship create multi

Question: i have a ParentItem model
$parentItem = ParentItem::get()->first();

I have this array
$items = array(
 array(
  'title' => 'test1',
  'desc' => 'test1'
 ),
 array(
  'title' => 'test2',
  'desc' => 'test2'
 )
);

i want to add it as a has many relationship.
so i can do:
foreach($items as $item) {
 $parentItem->items()->create($item)
}

is there any way way to create all at once..?
something like:
$parentItem->items()->createMany($items);

Comment: What's wrong with the `createMany` method? Also, you could get the parent model like this: `$parentItem = ParentItem::first();`. This will only retrieve one item from the database. The way you are doing it now gets all the entries in the database and then uses PHP to grab the first item in the collection.
Answer: You can tryout two path.
Using saveMany method:
$parentItem = ParentItem::first();
$items = array(
    new Item(['title' => 'test1','desc' => 'test1']),
    new Item(['title' => 'test2','desc' => 'test2'])
);
$parentItem->items()->saveMany($items)

For further info you can read here.

https://laravel.com/docs/5.1/eloquent-relationships#inserting-related-models

Using insert method:
$parentItem = ParentItem::first();
$items = array(
    array('title' => 'test1','desc' => 'test1','parent_item_id' => $parentItem->id),
    array('title' => 'test2','desc' => 'test2','parent_item_id' => $parentItem->id)
);
Item::insert($items);

Remember in insert created_at and updated_at won't be inserted automatically, you have to provide them in the array if you have them in your table. For further info you can read here.

https://laravel.com/docs/5.1/queries#inserts
Answer: As of right now, you may use the createMany Eloquent method to achieve this.
Details here: https://laravel.com/docs/9.x/eloquent-relationships#the-create-method


Mac OS X and Mercurial

Question: I recently acquired a MacBook. I compiled Mercurial 1.6.3, and set it all with NetBeans.
The thing is, whenever I try to commit, and since I'm writing the revision message and my name with accented characters (in Spanish), I'm getting an error like:
transaction abort!
rollback completed
abort: decoding near 'Naim? Batuta ': 'utf8' codec can't decode byte 0x8e in position 4: unexpected code byte!

I used locale on the console, and I got this:
LANG=
LC_COLLATE="C"
LC_CTYPE="UTF-8"
LC_MESSAGES="C"
LC_MONETARY="C"
LC_NUMERIC="C"
LC_TIME="C"
LC_ALL=

I tried setting LC_CTYPE="C.UTF-8", and now LC_CTYPE became ="C" as well, yet Mercurial keeps showing me the same message.
At first I thought it was NetBeans switching character encodings, but then I tried a simple hg commit, and it returned the same error.
I've read everywhere, and while such articles mention character encodings of Mercurial, Mac OS X, and Python, some patches to fix it (a while ago, so they should be already in Mercurial), I haven't found a real solution.
Has it happened to you before? How did you solve it? Please, help me. It works just fine on my desktop (Windows) machine, but sometimes I need to make modifications while I'm away, and this is driving me crazy.
Thanks in advance!
Answer: When I issue the locale command on my mac osx, I get the following
LANG="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_CTYPE="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_ALL="en_US.UTF-8"

For you it should be
LANG=es_ES.UTF-8
LC_ALL=es_ES.UTF-8

Are you exporting these? Because, your locale should have shown a different value after exporting.
export LC_ALL=es_ES.UTF-8
export LANG=es_ES.UTF-8

Comment: Nope, it didn't work. I tried switching locales to es_ES.UTF-8, to no avail. I just didn't want to use the MacPorts port, and just wanted to try compiling it myself. It looked liked as if it had worked, until I had to put it to work. What else do you think it might be? Switch to git? :s Thanks!
Comment: By the way, I just quit the Terminal. Should I also restart? I don't think, but you never know.
Comment: Yes and I would suggest adding the two lines in .bash_profile , quit terminal and then restart and check for locale command output
Answer: Your Spanish locale should be es_ES.UTF-8 (if your terminal does use UTF-8), or es_ES (which will use ISO-8859-1 encoding). "C" locale knows nothing about Spanish accentend characters.
Anyway, if properly setting locale in your terminal doesn't help, then you can try setting
[ui]
fallbackencoding=ISO-8859-1

in your .hgrc config file.
Comment: I tried all these suggestions, but none seemed to work. I keep getting the same error, whether it's an accented character in the username, or in the commit message. :'(
Answer: No idea what really happened. I deleted any file I had of Mercurial from my compilation, and just used the installation package.
Yes, it now works wonders. Thank you all!

Mac OS X and Mercurial


Using linear algebra to find constants in the equation of a circle which passes through given points.

Question: Find constants $a ,\ b ,\ c \ $ such that the equation of the circle, $x^2+y^2+ax+by=c$, contains the points $(6,8)$, $(8,4)$, and $(3,9)$.
Use the points to create a system:
$\begin{array}{rcrcrcrcr}
6^2 & + & 8^2 & + & 6a & + & 8b & = & c \\
8^2 & + & 4^2 & + & 8a & + & 4b & = & c \\
3^2 & + & 9^2 & + & 3a & + & 9b & = & c \\
\end{array}$
Place it into an augmented matrix and perform row operations to reduce:
$\displaystyle \left[
\begin{array}{rr|rcr}
8 & 6 & c &-& 100 \\
4 & 8 & c &-& 80  \\
3 & 9 & c &-& 90  \\
\end{array}
\right]
$ ($R_2-R_3$)
$\displaystyle \left[
\begin{array}{rr|rcr}
8 & 6 & c &-& 100 \\
1 & -1 & 10  \\
3 & 9 & c &-& 90  \\
\end{array}
\right]
$ ($R_1-R_3$)
$\displaystyle \left[
\begin{array}{rr|rcr}
5 & -3 & -10 \\
1 & -1 &  10 \\
3 & 9 & c &-& 90  \\
\end{array}
\right]
$ ($R_1-3R_2; \frac{1}{2}R_1; -R_2)$
$\displaystyle \left[
\begin{array}{rr|rcr}
 1 & 0 & -20 \\
-1 & 1 & -10 \\
 3 & 9 & c &-& 90  \\
\end{array}
\right]
$ ($R_2+R_1$)
$\displaystyle \left[
\begin{array}{rr|rcr}
1 & 0 & -20 \\
0 & 1 & -30 \\
3 & 9 & c &-& 90  \\
\end{array}
\right]
$  ($R_1-R_1$)
This gives $c$ such that the given circle has a negative radius, but surely that can't be. Where is my error?
Comment: The first column should contain the coefficients of $a$, i.e. $(6,8,3)^T$ and the second column the coefficients of $b$, i.e. $(8,4,9)^T$ or vice versa.
Comment: The $c$ in your equation is not the square of the radius. You need to complete the squares on the left-hand side first. What is left on the right-hand side after that is the square of your radius.
Answer: As noted in the comment of thanasissdr, the third row of your starting matrix is wrong. It must be $9,3,c-90$
Anyway, solving correctly the system, you find: $a=-6$,$b=-8$ and $c=0$.
This means that the circle has center $C=(\alpha,\beta)=(-a/2,-b/2)=(3,4)$ and radius $r=\sqrt{\alpha^2+\beta^2+c}=5$.
Answer: As Arthur said, once you have rearranged your initial equation into the form $$(x+\frac{a}{2})^2+(y+\frac{b}{2})^2=m^2$$ then m will be your radius. The fact that c is negative is irrelevant unless you find $m^2$ to be negative, them you should be worried


Comparing categorical data

Question: I'm comparing two groups in a large dataset. For some of the variables, the following 5 choices are available: 1, 2, 3, 4, 5 or more
This seems like categorical data- but would it be considered ordinal or nominal? Can I just use the 5 choices on their own to compare across groups, like doing a chi squared analysis and regression models? Or should I be doing any sort of dummy coding or watching out for anything else?
EDIT- the data is ordinal. one of the questions, for example, is # of arrests. how would I proceed if I want to compare across groups like in a regression model? dummy code?
Comment: You need to make the decision on the first question. For example, country, race,.. are nominal; level of pain, degree of like/dislike are ordinal. The following questions depend on the answer to the first question.
Comment: it would be ordinal data then
Comment: Then use Cochran-Mantel-Haenszel chi-square test.  I do not think you need model, given there is no other covariate.
Answer: It solely depends on your data. If they are just simple answers to some kind of multiple choice questionnaire, i.e. they can be replaced by $A$,..$E$ or can be shuffled, they are nominal. In this case, you should employ some sort of coding to use them, like one-hot. If they represent some kind of degree, e.g. movie ratings, votes etc. then the variable is ordinal and applying a transformation could be fatal.
Comment: yes, they represent some degree. one question for example is # of arrests

Comparing categorical data


Using Linq for copying/filtering produces a dynamic result in foreach loops?

Question: So I create this projection of a dictionary of items I would like to remove.
var toRemoveList =
    this.outputDic.Keys.Where(key =>
        this.removeDic.ContainsKey(key));

Then I iterate through the result removing from the actual dictionary
        foreach(var key in toRemoveList)
            this.outputDic.Remove(key);

However during that foreach an exception is thrown saying that the list was modified during the loop. But, how so? is the linq query somewhat dynamic and gets re evaluated every time the dictionary changes? A simple .ToArray() call on the end of the query solves the issues, but imo, it shouldn't even occur in the first place.
Comment: `foreach(var key in toRemoveList.toList())` What if you're adding things to the list in the loop? That could be an infinite loop right there.
Comment: ^ What he said.  The difference is that `Linq` queries are lazily executed (get the next one, stop working, check if there's another? Get the next one, stop working....check if there's another?) During the "stop working" step it defers to the content of the for loop (in this case).
Comment: I see, so in this case, the query is executed at each step of the foreach call?
Comment: Well...no: the expressions you use to generate your linq query are executed at every step of the way...Have you ever seen the 'yield' operator?
Comment: You might find it interesting to know what low level details causes the exception itself.  Your foreach loop calls `toRemoveList.MoveNext`, which calls `outputDicEnumerator.MoveNext()`.  `outputDicEnumerator` is a initialized with the code `outputDicEnumerator.version = outputDic.version;`.  Calling `outputDic.Remove` calls `outputDic.version++;`.  Calling `outputDicEnumerator.MoveNext()` runs `if (outputDicEnumerator.version != outputDic.version) throw ...;`.
Comment: I see, thanks for all the replies!
Answer:
So I create this projection of a dictionary of items I would like to remove.

var toRemoveList =
  this.outputDic.Keys.Where(key =>
    this.removeDic.ContainsKey(key));

As I have often said, if I can teach people one thing about LINQ it is this:  the result of a query expression is a query, not the results of executing the query.  You now have an object that means "the keys of a dictionary such that the key is... something". It is not the results of that query, it is that query. The query is an object unto itself; it does not give you a result set until you ask for one.
Then you do this:
    foreach(var key in toRemoveList)
        this.outputDic.Remove(key);

So what are you doing?  You are iterating over the query. Iterating over the query executes the query, so the query is iterating over the original dictionary.  But you then remove an item from the dictionary, while you are iterating over it, which is illegal.

imo, it shouldn't even occur in the first place.

Your opinion about how the world should be is a common one, but doing it your way leads to deep inefficiencies. Let us suppose that creating a query executes the query immediately rather than creates a query object.  What does this do?
var query = expensiveRemoteDatabase
    .Where(somefilter)
    .Where(someotherfilter)
    .OrderBy(something);

The first call to Where produces a query, which in your world is then executed, pulling down from the remote database all records which match that query.  The second call to Where then says "oh, sorry, I meant to also apply this filter here as well, can we do that whole query again, this time with the second filter?" and so then that whole record set is computed, and then we say "oh, no, wait, I forgot to tell you when you built that last query object, we're going to need to sort it, so database, can you run this query for me a third time?"
Now perhaps do you see why queries produce a query that then does not execute until it needs to?
Comment: "oh, sorry, I meant to also apply this filter here as well!" Good one.
Answer: The reason is that toRemoveList does not contain a list of things to be removed, it contains a description of how to get a list of things that can be removed.
If you step through this in a debugger using F11 you can see this quite clearly for yourself. The first point it stops is with the cursor on foreach which is what you would expect.
Next you stop at toRemoveList (the one in foreach(var key in toRemoveList)). This is where it is setting up the iterator.
When you step through var key (with F11) however it now jumps into the original definition of toRemoveList, specifically the this.removeDic.ContainsKey(key) part. Now you get an idea of what is really happening.
The foreach is calling the iterators Next method to move to the next point in the dictionary's keys and holds onto the list. When you call into this.outputDic.Remove(key); this detects that the iterator hasn't finished and therefore stops you with this error.
As everybody is saying on here, the correct way to solve this is to use ToArray()/ToList() as what these do is to give you another copy of the list. So the you have one to step through, and one to remove from.
Answer: The .ToArray() solves the issues because it forces you to evaluate the entire enumeration and cache the local values. Without doing so, when you enumerate through it the enumerable attempts to calculate the first index, return that, then return to the collection and calculate the next index. If the underlying collection you're iterating over changes, you can no longer guarantee that the enumeration will return the appropriate value.
In short: just force the evaluation with .ToArray() (or .ToList(), or whatever).
Comment: @KingKing are you the idiot who's downvoting all the answers and clearly doesn't understand how LINQ works? I don't care what the OP wants, the OP NEEDS `ToArray()` or `ToList()`, there is no other way to write the code.
Comment: I don't mind the ToArray, I just wanted to know why it is needed
Comment: The OP doesn't want `ToArray()`
Comment: @evanmcdonnal PLEASE read the OP's question carefully: He said `ToArray() call on the end of the query solves the issues, but imo, it shouldn't even occur in the first place`
Comment: @LukasTaves see my anser above, i have mentioned the reason fully.
Comment: @KingKing: I thought I did a pretty good job explaining why it doesn't really matter what OP wants. It's not possible and I've explained why.
Answer: The reason you are getting this error is because of deferred execution of linq. To explain it fully when  your loop runs is actually when the data is fetch from the dictionary. Thus modification in outputdic takes place at this point of time and it is not allowed to modify the collection you are looping upon. This is why you get this error. You can get rid of this error by asking the compiler to execute it before you run the loop.
var toRemoveList =
this.outputDic.Keys.Where(key =>
    this.removeDic.ContainsKey(key)).ToList();

Notice the ToList() in the above statement. It will make sure that your query has been executed and you have your list in toRemoveList.
Comment: The OP doesn't want something not `deferred`
Comment: @KingKing he is getting the error and he doesn't knows why it is happening. I have explained that. What is wrong with that? And i have explained in my answer why modification is taking place at this point
Comment: @evanmcdonnal well before passing our comments we should take his point of view.
Answer: The LINQ query uses deferred execution. It streams the items one by one, retruning them as they're requested. So yes, every time you try to remove a key it changes the result which is why it throws an exception. When you invoke ToArray() it forces execution of the query which is why it works.
EDIT: This is somewhat in response to your comments. Check out iterator blocks on msdn this is the mechanism being used when your for each executes. Your query just gets turned into an expression tree and the filter, projects, operation ect is applied to the elements one by one when they're retrieved unless it is not possible.
Comment: The OP doesn't want `ToArray()`
Comment: It's not the only option.  `var toRemoveList = removeDic.Keys.Where(key => outputDic.ContainsKey(key))` works just fine because the foreach loop then enumerates over `removeDic` instead of `outputDic`.


How to show conditional tab in webform 7.x-3.x

Question: I created an enquiry form using the webform 7.x-3.x module and I want to create condition on field, but not showing conditionals tab.

I also use webform_conditional 7.x-1.0-beta2 but conditional tab not  showing.
But,
I create again enquiry form from webform 7.x-4.x Module. In webform i show conditionals tabs.

My question is how to show conditions tabs in webform 7.x-3.x. I not want to upgrade module webform 3.x to 4.x.
Have any configuration or module to show conditional tab.
Answer: If you specifically want to use this within webform you need to use webform conditional to work smoothly.


Integrality and ring morphisms $f:R\to S$

Question: I am thinking about the following problem: Let $f:R\to S$ be a ring morphism and let $T$ in $R$ be a subring. If $r$ in $R$ is integral over $T$, then it is true that $f(r)$ is integral over the image subring $f(T)$: if $\sum t_i r^i=0$, then also $\sum f(t_i)f(r)^i=0$ by the properties of a ring morphism.
Now the question is: if $f(r)$ is integral over $f(T)$ for some $r$ in $R$, is then also $r$ integral over $T$? If $f(r)$ is integral over $f(T)$, then $\sum f(t_i)f(r)^i=0$ for some $t_i \in T$, i.e. $f(\sum t_i r^i)=0$, because $f$ is a ring morphism.
Now if $f$ is injective, then the statement is indeed true. But I do not think that the statement holds in general, so I was searching for a counterexample with a non injective morphism, but I could not think of a direct counterexample.
For example, $\mathbb{Z[}\frac{1+\sqrt3}{2}]$ is not an integral ring extension of the integers, whereas $\mathbb{Z[}\frac{1+\sqrt5}{2}]$ is. But how would we find a morhpism between these rings, if one is finitely generated and the other is not?
Another thing I tried was to chose $R= \mathbb{Z[\frac{1}{2}]} $ and $T=\mathbb{Z}$, but there for any ring morphism $f(\mathbb{Z})$ is the zero ring or the integers, so that $f(\frac{1}{2})$ is not integral over $f(T)$.
Answer: This is a stupid counterexample, but consider any non-integral ring extension $T\subset R$ and the unique morphism $R\rightarrow 0$.
Comment: I am not sure this is valid since the definition of integrality requires a non zero monic polynomial. This will be difficult in 0[X] ;)
Comment: That is a good point.
Answer: Let $T= \mathbb{Z}$, $$R = \{\frac{a}{b} \bigg\rvert a,b\in \mathbb{Z},3\nmid b,(a,b)=1\}$$ which is the localization of $\mathbb{Z}$ at the prime ideal $(3)$. $S = R/3R$. Let $f: R\to S$ be the canonical map. Then the element $f(1/2)$ is integral over $f(T)$. Indeed, we have
$$\overline{1/2} = \overline{1/2} + 3(\overline{1/2}) = \overline{2}$$
But $1/2$ is not integral over $T$.


On algorithm of iterating an array of arrays

Question: there are n arrays a_0, ..., a_n-1, each of l elements. how to write efficient code to iterate all combinations, in which each element is picked from a distinct array. for example, if two arrays are [0, 1]  and [3, 4], then the output should be
[0, 3]
[0, 4]
[1, 3]
[1, 4]

Comment: Is this homework?  What have you tried so far?
Comment: So do the values always hold their index position? That is, in the above example, the following are not possible combinations: [0,1], [3,1], [4,3], etc.?
Comment: @Janathan M [0,1], is not a elegible combination, since element 0 and 1 are both from array 0...
Comment: @Richard: ...and [3,0] is not eligible either because 3 comes from the 2nd array, and 0 from the first, right?
Comment: @Janathan it's eligible and that's what is wanted, the elements from different arrays.
Comment: Edited to show all possible permutations.
Comment: possible duplicate of [How do I compute the cartesian product of n sequences in F#?](http://stackoverflow.com/questions/3334429/how-do-i-compute-the-cartesian-product-of-n-sequences-in-f)
Answer: In an ideal mathematical environment there is no better algorithm then O(l^n), you are going to produce an output of l^n elements anyway.
If you give us context like programming language or architecture we can think of the algorithm closest to O(l^n).
Comment: puesudo code only,,, actually I thought about using stack to iterate, but still working on it...
Answer: You cannot do better than O(l^n), as nightcracker correctly points out. Here's one way that you can approach the problem.
Make a large array A whose ith entry is the array a_i, i.e.
A[i] = a_i
Now iterate through all words of length n on the alphabet {0,1,...,l}:
-(array*)nextWord:(array*)word {
    array *newWord = word;
    for (int i=n-1; i=>0; ++i) {
        if (word[i] < l) {
            newWord[i] = word[i]+1;
            for (int j=i+1; j<n; ++j) {
                newWord[i] = 0;
            }
            return newWord;
        }
    }
    return NULL;
}

Finally, select the entries based on the word by
word = [0, 0, ... , 0];
while (word != NULL) {
    A[0][word[0]], A[1][word[1]], ... , A[n-1][word[n-1]];
    word = nextWord(word);
}

Sorry for the inconsistencies in the pseudocode, but hopefully you can discern the logic here.

Incidentally, based on the example in the question, I am assuming that the first entry should come from the first array, the second entry from the second array, and so on. If this is not the case, then you can still use the idea above and then permute the entries. However, doing this may lead to repetitions if and only if two of the arrays have a common entry.


Solving $\frac{4x}{x+7}<x$

Question: I know how to solve the problem. The reason I post the problem here is to see whether there is a quick approach, rather than a traditional method, to solve the problem.

The problem is: find $x$ that satisfy $\frac{4x}{x+7}<x$
  I considered two cases: $x+7>0$ and $x+7<0$, and then went through details to find x. The process took me a few minutes. I wonder whether there is a simple way to find the answer.
Answer: Transform $\frac{4x}{x+7}<x$ into the equivalent $-\frac{x^2+3x}{x+7}=\frac{4x}{x+7}-x<0$ or $\frac{x^2+3x}{x+7}>0$.
This reduces to question to finding the sign of $\frac{x^2+3x}{x+7}$, which can be solved by making a simple table:
$$
\begin{array}{c|ccccc}
&  & -7 &  & -3 &  & 0 & \\
\hline
x & - & - & - & - & -& 0 & + \\
x+3 & - & - & - & 0 & + & + & + \\
x(x+3) & + & + & + & 0 & - & 0 & +\\
x+7 & - & 0 & + & + & + & + & +\\
\dfrac{x^2+3x}{x+7} & - & ! & + & 0 & -& 0 & +
\end{array}
$$
The answer is therefore $(-7,-3) \cup (0, +\infty)$.
Comment: @WillJagy, I forgot a minus sign. It's fixed now. Thanks.
Comment: I don't understand. If $x=1,$ then $4x/(x+7) = 1/2,$ and this is smaller than $x=1,$ as was requested. You and the other answer have the same outcome. Am I seeing the inequality backwards on the screen? I see $\frac{4x}{x+7}<x$
Answer: Here is another way--whether or not it is simpler depends on the problem and your previous experience.
First solve the equality
$$\frac{4x}{x+7}=x$$
I'm sure you can do that fairly quickly, getting $x=0$ or $x=-3$. Then find the values of $x$ where one or both of the sides of the equation are undefined. In your problem, that is $x=-7$.
Those finitely many values of $x$ break up the real number line into a finite number of intervals, two of them (the left-most and the right-most) infinitely large. Check each of those intervals to see if they make your initial equality true or false. You are guaranteed that any point in an interval will give the same answer as any other point in that interval.
Your final answer is the union of the intervals that made the equality true.
In your case examine the intervals:
$(-\infty,-7)$: Inequality is False
$(-7, -3)$: Inequality is True
$(-3, 0)$: Inequality is False
$(0, \infty)$: Inequality is True
So your final answer is
$x\in (-7, -3) \cup (0, \infty)$
NOTE: My first version of the answer had the Trues and Falses reversed so the answer was wrong. I now realize just what I did wrong--thanks for the corrections in the comments!
Comment: well, no. ..... I think your final line gives the hyperbola above the line, not below
Comment: For example, if $x=1,$ then $4x/(x+7) = 1/2,$ and this is below $x=1,$ as the question requested.
Comment: @Rory you might have made a mistake somewhere, the answer should be -70.
Answer: First of all, note that $x=0$ is not a solution. Thus we can consider two cases: $x$ is positive, or $x$ is negative.
If $x$ is positive, then we can divide by $x$ to obtain $\frac{4}{x+7}<1$. Since $x$ is positive, this is always true. Thus, $(0,\infty)$ is in our solution set.
If $x$ is negative, we get $\frac{4}{x+7}>1$. This works if $x$ is greater than $-7$, but less than $-3$. Thus, $(-7,-3)$ is in our solution set.
Answer: Reducing both sides to the same denominator, the inequality is equivalent to
$$\frac{x(x+3)}{x+7}>0\iff x(x+3)(x+7)>0\;\text{ AND }\; x\ne -7.$$
Now, by the I.V.T., the  polynomial has a constant sign between its roots, which determine 4 intervals and signs alternate when stepping from one interval to the next (or the previous) interval. As $\;\lim\limits_{x\to\infty}x(x+3)(x+7)=+\infty$, the successive signs are as follows:
$$\begin{array}{r}x\\\hline x(x+3)/(x+7)\end{array}\quad\begin{array}{rccccccc}
-\infty&&-7&&-3&&0&&+\infty\\\hline
&-&0&+&||&-&0&+
\end{array}$$
and we see at once the set of solutions is $\;(-7,-3)\cup(0,+\infty)$.
Comment: Is there really any need to say "AND $x\not=-7$" since it's implied by the strict inequality $x(x+3)(x+7)\gt0$?
Comment: Formally you're right, . I only wanted to insist on determining the domain of validity of ther inequation. . Besides, from this point of view, I should have written $x>7$ first.
Answer: This is not a faster way, it is an indication of how to get better at this. Learn how to sketch a graph of the hyperbola $y = 4x /(x+7).$ Draw $y=x$ on the same graph paper. Then explain what you see. You can get a pdf of graph paper, then print out as needed, from https://www.printablepaper.net/category/graph

Solving $\frac{4x}{x+7}<x$


Finding generating function for a given sequence

Question: The task is to find the generating function for the sequence $$d_n = (\sum_{k=0}^n \binom{n}{k})*(\sum_{k=0}^n \frac{(k-1)^2}{2^k})$$
let's call this function $D(x)$.
I marked $a_n = \frac{1}{2^n}$; $b_n = \frac{-2n}{2^n}$; $c_n = \frac{n^2}{2^n}$ with respective generating functions $A(x)$, $B(x)$, $C(x)$.
So I found $$A(x) = \frac{1}{1-\frac{x}{2}}$$ and
$$B(x) = \frac{-x}{(1-\frac{x}{2})^2}$$
$$C(x) = \frac{2x+3x^2}{4(1-\frac{x}{2})^3}$$
using derivatives.
now the generating function for $a_n + b_n +c_n$ should be $A(x)+B(x)+C(x)$ and it's $$\frac{x^2}{(1-\frac{x}{2})^3}$$.
Next by using convolution (with let's say $f_n = 1$) we'll get that the function for the series $$u_n = \sum_{k=0}^n \frac{(k-1)^2}{2^k})$$ is $$\frac{x^2}{(1-\frac{x}{2})^3(1-x)}$$
Now since $h_n = \sum_{k=0}^n \binom{n}{k} = 2^n$ the appropriate function is $$H(x) = \frac{1}{1-2x}$$.
Again with using convolution with $h_n$ and $u_n$ we'll get that $$D(x) = H(x)U(x) = \frac{x^2}{(1-\frac{x}{2})^3(1-x)(1-2x)}$$
Is my answer good? or shall i keep expanding it to partial fractions.
Answer: Hint: The situation is   somewhat different.

Write
  \begin{align*}
d_n &= \sum_{k=0}^n \binom{n}{k}\sum_{k=0}^n \frac{(k-1)^2}{2^k}\\
&=\sum_{k=0}^n(k-1)^22^{n-k}
\end{align*}
  and  consider the  Cauchy-product $\sum_{k=0}^na_kb_{n-k}$   when multiplying  generating  functions.
Comment: With all due respect, you might be interested in this [MSE link](https://math.stackexchange.com/questions/2425156/).
Comment: @MarkoRiedel: Many thanks for the hint. Answer provided.
Answer: I think you had to compute the sums first and then multiply. I mean, the sequence is:
$$d_n = \left(\sum_{k=0}^n \binom{n}{k}\right)\cdot\left(\sum_{k=0}^n \frac{(k-1)^2}{2^k}\right)$$
Which means
$$d_n=2^n\cdot\left(\sum _{k=0}^n \frac{k^2}{2^k}-2\sum _{k=0}^n \frac{k}{2^k}+\sum _{k=0}^n \frac{1}{2^k}\right)=\\=2^n\cdot\left[(6-2^{-n} n^2-2^{2-n} n-3\cdot 2^{1-n})-2(-2^{-n} n-2^{1-n}+2)+(2-2^{-n})\right]=\\=2^n\cdot\left[2^{-n} \left(2^{n+2}-n^2-2 n-3\right)\right]=2^{n+2}-n^2-2n-3$$
$d_n=2^{n+2}-n^2-2n-3$
And its generating function is
$$F(x)=\frac{4}{1-2 x}-\frac{-x^2-x}{(x-1)^3}-\frac{2 x}{(x-1)^2}-\frac{3}{1-x}=\\=\frac{4 x^2-3 x+1}{(x-1)^3 (2 x-1)}$$
Hope this answers to your question


Continuos functions in metric spaces

Question:
Let $F$ be the set of all continuous functions $[0,1]\to\mathbb{R}$ and
$d_\infty(f,g):=\sup_x |f(x)-g(x)|$
$d_2(f,g):=\sqrt{\int_0^1 (f(x)-g(x))^2\, dx}$
metrics on $F$. Check which of the following functions are continuous and which are not:
a) $\operatorname{id}: (F, d_\infty)\to (F, d_2)$
b) $\operatorname{id}: (F, d_2)\to (F, d_\infty)$
c) $\operatorname{ev_0}: (F, d_\infty)\to\mathbb{R}$
d) $\operatorname{ev_0}: (F, d_2)\to\mathbb{R}$

I think, that a) and c) are continuous and b) and d) are not continuous.
A function $f: X\to Y$ between metric spaces is continuous in $x\in X$, if for every $\varepsilon >0$ it exists $\delta>0$ such that for every $x'\in X$ holds, that $d(x,x')<\delta\Rightarrow d(f(x), f(x'))<\varepsilon$.
a):
Let $f,g\in F$ and let $\varepsilon >0$ be arbitrary. Choose $\delta:=\varepsilon$.
It is $d_\infty(f,g)=\sup_{x}|f(x)-g(x)|<\delta$.
Then
$d_2(\operatorname{id}(f),\operatorname{id}(g))=d_2(f,g)=\sqrt{\int_0^1 (f(x)-g(x))^2\, dx}\leq \sqrt{\int_0^1 (\sup_x |f(x)-g(x)|)^2\, dx}<\sqrt{\int_0^1 \delta^2\, dx}=\sqrt{\delta^2}=\delta=\varepsilon$.
$\square$
c) is pretty much the same:
Let $f,g\in F$ and let $\varepsilon >0$ be arbitrary. Choose $\delta:=\varepsilon$.
It is $d_\infty(f,g)<\delta\Leftrightarrow \sup_x |f(x)-g(x)|<\delta$.
Now $d(\operatorname{ev_0}(f), \operatorname{ev_0}(g))=d(f(0), g(0))=|f(0)-g(0)|\leq \sup_x |f(x)-g(x)|<\delta=\epsilon$. $\square$
Is this correct. Could it be improved, how I write the proof down?
Next I want to show, that b) and d) are not continuous.
But I am not exactly sure how to do it.
I choose some $f\in F$ and then try to show, that
$\exists\varepsilon >0\forall\delta >0\exists g\in F: d_2(f,g)<\delta\wedge d(\operatorname{ev_0}(f), \operatorname{ev_0}(g))\geq\varepsilon$
So I choose $\varepsilon$ and the function $g$ can depend on $\delta$.
But I just can not find suitable choices.
But I also can not proof that these functions are continuous...
For d), I thought it is best to choose $f:[0,1]\to\mathbb{R}, x\mapsto 0$ and $g: [0,1]\to\mathbb{R}, x\mapsto \delta x$
This does not work. When I choose something other than 0 for $f$ the integral
$\sqrt{\int_0^1 (f(x)-g(x))^2\, dx}$ gets out of control...
Do you have a hint?
Thanks in advance.
Comment: Have you tried using sequential cont.?
Comment: No. I wanted to go by definition.
Answer: For both b) and d) consider the functions $f_n(x)=1-n^{2}x$ for $ 0\leq x \leq \frac 1 {n^{2}}$ and $0$ for $ x > \frac 1 {n^{2}}$. Let $f(x)=0$ for all $x$. Since $0 \leq f_n(x) \leq 1$ we get $\int f_n^{2} =\int_0^{1/(n^{2})} f_n^{2} \leq \frac 1 {n^{2}} \to 0$ so $d_2(f_n,f) \to 0$. But $f_n(0)=1$ for all $n$ so $d_{\infty} (f_n,f)$ does not tend to $0$ and $f_n(0)$ does not tend to $f(0)$.

Continuos functions in metric spaces


Android HttpURLConnection uses SSL connection when usesCleartextTraffic is set to true and throws SSL handshake time out exception

Question: I am building an Android app and need to use HttpURLConnection to call a local web service. The URL is http://xxx.xxx.xxx.xxx:8080/webservice/movies/1. It gives correct response using Postman.
However, in Android Studio, I cannot get the connection working. I've added Internet permission <uses-permission android:name="android.permission.INTERNET" />, and already set       android:usesCleartextTraffic="true" in the manifest file. But when I test the following method, it throws SSL handshake timed out exception. Why it still tries to use an SSL connection when the usersCleartextTraffic is set to true? How should I workaround to fix this?
public static ArrayList<MovieViewModel> GetTop5Movies(int personId) {
        ArrayList<MovieViewModel> movieList = new ArrayList<MovieViewModel>();
        URL url = null;
        HttpURLConnection conn = null;
        String textResult = "";
        try {
            url = new URL(BaseURL.GET_TOP5_MOVIES_URL + personId);
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Accept", "application/json");
            //It throws expection when it gets to the following line
            Scanner inStream = new Scanner(conn.getInputStream());
            while (inStream.hasNextLine()) {
                textResult += inStream.nextLine();
            }
            Log.i("Movies", textResult);
            JSONArray jsonArray = new JSONArray(textResult);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                movieList.add(new MovieViewModel(jsonObject.getString("Name"), jsonObject.getString("ReleaseDate"), jsonObject.getInt("RatingScore")));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            conn.disconnect();
        }
        return movieList;
    }

Answer: SSL is for HTTPS not for HTTP. Why it is giving this? will tell you more if you post the logs.
Please post the manifest.xml too.


Configuration for RestKit in-memory Core Data store

Question: I need to split my Core Data persistent storage (managed by RestKit) into two parts. One part should persist only in memory and not be saved to disk, and the other part should be saved. Usually it is done by adding configurations to Core Data object model and creating two stores for each configuration. But RestKit's RKManagedObjectStore method - (NSPersistentStore )addInMemoryPersistentStore:(NSError *)error; doesn't take configuration name and adds persistent store with configuration nil:
- (NSPersistentStore *)addInMemoryPersistentStore:(NSError **)error
{
    if (! self.persistentStoreCoordinator) [self createPersistentStoreCoordinator];

    return [self.persistentStoreCoordinator addPersistentStoreWithType:NSInMemoryStoreType configuration:nil URL:nil options:nil error:error];
}

According to Core Data documentation, this prevents from using any configurations in persistent store coordinator.
I can reload this method and make it use configuration, but first I want to ask:
Are there any reasons for me to not to do this? There must be reasons why addInMemoryPersistentStore looks like it looks. May be someone had tried to make the same thing as I'm going to do and found that it doesn't work?
Answer: I would say that you should create your own version of the method which takes a configuration parameter. I don't think that you're missing anything, I just think that if RestKit was to offer support for 100% of the Core Data configuration API out of the box then there would be a lot of code to maintain and very few people would benefit from all of the extra effort.
Your best option is to subclass and add the method you want, calling super as appropriate, and then instantiate that subclass and pass it when you are configuring your Core Data stack (managed object store).


Create a user friendly workflow to create banners

Question: I'm looking for an easy way where my users can add banners on a page. There are many options here (View Slideshows, Rotating Banners,...) but what I want is a user to be able to do this as simple as possible.
The ideal scenario would be:
Create content - upload image - type a title and select the pages on which it should be displayed.
Basically, my (absolute n00b users) must be able to add a banner to any page available without any knowledge of views, panels,...
I've experimented with node references and templates, but no luck so far.
Is their anyone with the same situation and found out a great solution?
Comment: What version of Drupal are you using? What "pages" do you expect the user to be able to select? Will the banners be on the front page? on taxonomy pages? on specific sections of the site? on certain content types? on view pages? admin pages?
Comment: I'm using Drupal 7. The content managers should be able to add a banner to any page available on the site (front page, side pages, view pages,...) but they should be always be in the upper part of the site.
Answer: The simplest would be a content type with an image field and a text field. The image field would be the banner and the text field would be the path on your website where it should be displayed.
Create a view that filters on that content type and has the image as the field it displays.  Put the path field as an argument.  Configure it to return only 1 item.
In a block, call that view using $_GET['q'] as the argument.
Image is displayed in the block.  Display this block on your page where you want your banner.
Don't like blocks?  Put this in a page_preprocess() hook and assign the view output to a variable and put this in your page where ever you want it.
Get fancy?  Randomize the sort so if more than one of these content types has the same path a different image is displayed on each page load/reload.
Get fancier.  Use the views_nivo_slider module ( http://drupal.org/project/views_nivo_slider )
Comment: Great suggestion! Although, I'm not sure I get what you mean with the arguments... The way it's configured now. One node of the 'banner'-content type has a path `/nl`, `/en` and `/fr` (because I'm working with a multilingual site). I've set the contextual filter on `path`, but whenever I enter the `/nl`, `/fr` or `/en` filter in the view preview, nothing shows up. What do I do wrong?
Comment: Arguments are drupal6speak and I am not very up on drupal7 yet, but basically you want to filter on the full text of that field versus the full path.  Perhaps someone more fluent in drupal7 can tell you exactly how to do it as I was thinking you would put foo/bar/bazz/bing in the field, not individual components and nl en and fr look like just the language components to me.


Measuring Facebook/Twitter/Instagram activity times

Question: I recently got into a debate on how to best measure when my Facebook/Twitter/Instagram friends are most active. Imagine that I have the input data set that consists of (timestamp, user_id), where timestamp is the time when the user did something like posting a new status. Given this information, how would you measure when the most users would see your post? We can assume that we are going to quantize this to an hour or half hour interval.
My friend suggests that simply averaging the number of unique users engaged in any given hour isn't enough because not all users are active every day, but randomly during any given time of day, making all hours look the same in the long run. Thoughts?
Comment: I assume that data scientists at Facebook can just query directly the number of views a post has. That's probably the best way to answer this question. Outside of that, I don't see any practical way to answer this question.
Comment: Are you saying that given this data, this question is impossible to answer? What additional data would you need?
Comment: Social media companies don't serve content in time-series order, they serve it according to user interests and interactions. "Time of day" is only relevant if you also know the locations (i.e. local times) of potential consumers. Views are plausibly strongly correlated with follower/friend counts (because who else would see it?) etc etc
Comment: I mean hypothetically speaking, if we had the perfect time series dataset, and timezones where known.
Answer: The mean number of active users per time interval is indeed a simple but sensible way to approach this problem with this kind of data. Fancier approaches could involve modeling user activity as a Poisson process.
Your friend's suggestion boils down to the idea that people are overall no more likely to be active on a website at one time of day than another. This is unlikely, as you can tell from publicly available website usage data, and would be easy to check if you actually had the data you wanted to analyze.


Background VoiceOveraccessibility focus on a UICollectionView

Question: I have a problem with voiceover on a collectionview. I have a fullscreen (minus navigation bar) UICollectionView that contains 5 cells. Each cell contains a view with isAccessibilityElement=true.
When VoiceOver is activated the title in the navigation bar is focused. If I then move focus by left/right swiping each of the cell items is focused, one by one, just as one would expect. The problem is if I instead move focus by dragging my finger downwards on the screen. Then the background of the screen (i.e. the collection view's area) receive focus when the finger is outside of any of the cells.
Is there a way to turn this off?
I have tried:
class MyViewController: UICollectionViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        // A. This makes everything in the collection inaccessible, both
        // background and cell content.
        //collectionView?.accessibilityElementsHidden = true

        // B. This has no effect
        //collectionView?.isAccessibilityElement = false
    }
...

I would expect B to work, but it doesn't (nothing happens). I've also tried various other things like: self.view.isAccessibilityElement = false, self.view.superview.isAccessibilityElement = false without success.
Hope someone can help!
Comment: It's been quite a while, have you figured it out? I have the same problem, would be a huge help if you did...
Answer: Traversing a collection view with VoiceOver is like traversing an accessible element whose trait property is adjustable.
Each element of the collection view is an UIAccessibilityElement that must be redefined inside your code.
To understand how that should be implemented, I suggest you take a look at the WWDC 2018 - Deliver an exceptional accessibility experience video whose content is perfectly summarized here and whose presented example can be downloaded... following this kind of programing won't focus any object in the background.
Comment: In the demo they want 'UICollectionView' to have the 'adjustable' trait and receive focus. The point of this question however is not having the trait and avoiding 'UICollectionView' ever getting the focus on itself. I only need focus to appear on couple of its cells, and never on collection itself. And what I don't get is why setting 'collectionView?.isAccessibilityElement = false' doesn't achieve that.
Comment: Cells that need it already have the focus, and they work fine. The problem is that the collectionView itself receives the focus if you tap a place not containing any of the cells. It doesn't say anything since accessibilityLabel isn't set for it. But it still draws a frame around the whole thing even if I try explicitly removing the ability to have focus for it using isAccessibilityElement. And that frame is exactly what needs to go away.
Comment: The video as well as the summary is huge, could you please quote the relevant part?
Comment: @f3dm76 : each topic of the video is detailed and points at the timelapse that it refers to. Focus on the demo that lasts few minutes. Take time to understand each point of the video if you want to solve your problem... it's sometimes necessary.
Comment: It is, but the names of the points tell me nothing about UICollectionViews or unnecessary focus for them. Could you please point out the one relevant to the issue at hand?
Comment: @f3dm76 : if the demo looks like your app should work, download the available code to take a look at it. In my view, the problem deals with what you have implemented and the way it should be done as Apple explains. Follow their path step by step and that should definitely work.
Comment: Create each of your collection view cell as a new accessibility element and override the 'isAccessibilityElement' according to your focus specifications. If that doesn't fit, I haven't understood the problem and I'll pass, sorry.


Should drummers have blisters/calluses on their hands?

Question: Is it common for drummers to get blisters/calluses on his or her fingers? Whenever I play on an electric drum-kit, my fingers swell up with blisters. Could this be due to bad hand form?
Comment: Are you implying that when you play on  acoustic drums, you get no blisters?
Comment: [Ringo Star certainly did...](https://www.youtube.com/watch?v=pqUq2Da7d5c)
Comment: @Tim, I do not get blisters when playing on acoustic drums. I only get blisters when I play on an electric drum kit.
Answer: Sounds as if you're gripping the sticks too tightly and hitting the drums too hard!  Maybe it's worse on an electronic kit because the pads don't 'bounce' so much, it can be like hitting a lump of wood.
Comment: I think you're probably right. I'm probably holding my sticks too tightly and need to loosen up.
Answer: Don't worry about it. My fingers often get blistered, especially on my left hand. You might be gripping the sticks too hard but even if you aren't you'll might get blisters after a while. If they hurt but a band-aid on them or invest in a pair of drumming gloves which will improve grip and stop blisters.
Comment: Thanks for the input @Sam_Stone! I always found gloves difficult to drum with, but I'm going to try band-aids
Answer: Blisters are not good.  If a blister starts to develop, it may be helpful to put a special blister bandage ("second skin") on it.  But prevention would be better.  Hopefully Laurence's suggestion of the technique adjustment helps.  Also, you could try putting a small piece of athletic tape on the specific spot where you tend to get a blister, before you play.  I would take it off afterwards, to allow for good air circulation.
About callouses.  Speaking as a string player, I find it helpful to have some callous, because otherwise, playing for several hours a day can be painful.  (Also, playing with not enough callous in a very humid environment makes fingers feel too sticky.)
To build up some helpful callous, I find it helpful to play at least 30 minutes a day for a week or so prior to a day when I know I'll be playing for several hours.
There are times when callouses get a little too thick, and this can interfere with sensitivity of the fingers.  Also, sometimes a sharp edge of callous appears, which can snag on things.  The solution to both problems is the same: gentle filing with a fine grain nail file (emory board or metal, whichever you prefer).