Windows installer for Python module which includes dependencies

Question: I have a python module with an entry point in its setup.py which points to __ main__.py. I want to be able to distribute this module to my coworkers in such a way that they can install it using a windows installer, and execute the entry point from the command line. They already have Python installed on their computer.
The built-in python setup.py bdist_wininst functionality looked perfect, except that my module has a third party module dependency, and for some reason, bdist_wininst does not install dependencies even if they are specified in the setup's install_requires.
All-in-one windows exe solutions such as py2exe or pyinstaller are not suitable since the entry point requires input, and I want the user to be able to specify the input via the command line.
Of course, I could distribute the module source files and have my coworkers run python setup.py install, but they will be too afraid - they are not programmers.
Comment: could you include a batch file with the `python setup.py install` and just have them run th batch file?
Comment: I suppose I could. Good idea. But I am also wondering if there are more polished solutions.
Answer: Yes, it would be possible to use an application like Nullsoft NSIS to build an installer that would install your python package, but it will require more code and an extra build step.
Do your coworkers have pip and setuptools installed?  Are you able to distribute your package on pypi?  If so, it would be really simple for your coworkers to just do pip install mypackage.  It has the added benefit of handling dependencies and if you use python wheels, your users don't require a build environment to install your package.


In python elif statement is an invalid syntax in a while statement

Question: while True :

    print ("Do you like ice cream?")
    Icecream = input ()
    if Icecream == ('yes' or 'y' or 'ye'):
        print ("Damn right!")
    break;

    elif Icecream == ('no' or 'nah' or 'n' or 'No' or 'Nah' or 'N' or 'Nope' or 'nope'):
        print ("Why not??")
        break;

    else :
        print ('Command not recognised, please use yes or no')

SyntaxError: invalid syntax
When I run it through it says the Elif is an invalid syntax, How do i fix it?
Comment: Make sure your code snippet is indented correctly (looks the same as your actual code) - indentation matters a lot in Python.
Comment: break; resets the indentation, and ends the if block.
Comment: @Kursion not everyone is an American, Robbie is obviously using 'ye' for yes, so there's a tipoff for you, too.
Comment: Your comparisons aren't doing what you think they do. You really want `if Icecream in ('yes', 'y', 'ye'):` Otherwise `('yes' or 'y' or 'ye')` gets evaluated as a boolean statement, which will turn it into just `'yes'`. So you end up really doing `if Icecream == 'yes':`. Same issue with the second if block.
Comment: @Kursion it is, because you're wrong - in England and other places, they spell things differently. "Correcting" `colour` to `color` or `recognise` to `regonize` or `tyre` to `tire` is not a correction at all, just you choosing to apply American standards to other peoples' spelling. Do you ever wonder why sometimes software makes you click the little American flag vs, say, the British flag when you choose a language? This is why.
Comment: ok my bad, removed my comments.... wooouh what an aggression here ;) I'm french :D
Answer: The break statement under print ("Damn right") is not indented, so the if is then "finished" and the elif does not belong to any if.
Also, no need for a ; after break.
Answer: You need to tab the break for the if part. It isn't indented correctly.  Under print ("Damn right!") you need to properly add a tab or spaces.
while True :

print ("Do you like ice cream?")
Icecream = input ()
if Icecream == ('yes' or 'y' or 'ye'):
    print ("Damn right!")
    break;

elif Icecream == ('no' or 'nah' or 'n' or 'No' or 'Nah' or 'N' or 'Nope' or 'nope'):
    print ("Why not??")
    break;

else :
    print ('Command not recognised, please use yes or no')


How does including lags imply losing observations

Question:
My time series professor passed a comment today, that running this model implies losing k+1 observations. I think I have understood how the observations are wasted, but I am notorious for falsely believing that I have understood something(self-diagnosed). A simple explanation would be appreciated!
Answer: Imagine that you have ten periods of observation in your data set:
period : 1 2 3 4 5 6 7 8 9 10
var_t  : 7 6 7 8 9 4 4 3 6 5
Imagine that you wish to to include a lag of one period on some variables:
period : 1 2 3 4 5 6 7 8 9 10
var_t  : 7 6 7 8 9 4 4 3 6 5
var_t-1: . 7 6 7 8 9 4 4 3 6
Notice that you do not have a lagged value for var_t=1 because you did not observe the value of var_t in the period before t=1, and thus do not know its lagged value.
So with a lag of two:
period : 1 2 3 4 5 6 7 8 9 10
var_t  : 7 6 7 8 9 4 4 3 6 5
var_t-1: . 7 6 7 8 9 4 4 3 6
var_t-2: . . 7 6 7 8 9 4 4 3
So you see, adding additional lags to a fixed number of observations implies a loss of observations (e.g. with lag of two, you have only eight periods of observation for values of period, var_t, var_t-1 and var_t-2).
Comment: ahh!, my initial idea of it was very vague but something along these lines. this example cleared it up nicely, thank you!


Request a new password using username only

Question: We don't want to use email id for request a new password.
How can we accomplish this without customizing/touching to core module.
Comment: did you try this module https://drupal.org/project/logintoboggan
Comment: Did you try anything, before asking?
Answer: User module accepts either username or email to reset password.. Code goes below in user module...
<code>/**
 * Form builder; Request a password reset.
 *
 * @ingroup forms
 * @see user_pass_validate()
 * @see user_pass_submit()
 */
function user_pass() {
  global $user;

  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Username or e-mail address'),
    '#size' => 60,
    '#maxlength' => max(USERNAME_MAX_LENGTH, EMAIL_MAX_LENGTH),
    '#required' => TRUE,
    '#default_value' => isset($_GET['name']) ? $_GET['name'] : '',
  );
  // Allow logged in users to request this also.
  if ($user->uid > 0) {
    $form['name']['#type'] = 'value';
    $form['name']['#value'] = $user->mail;
    $form['mail'] = array(
      '#prefix' => '<p>',
      '#markup' =>  t('Password reset instructions will be mailed to %email. You must log out to use the password reset link in the e-mail.', array('%email' => $user->mail)),
      '#suffix' => '</p>',
    );
  }
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array('#type' => 'submit', '#value' => t('E-mail new password'));

  return $form;
}

function user_pass_validate($form, &$form_state) {
  $name = trim($form_state['values']['name']);
  // Try to load by email.
  $users = user_load_multiple(array(), array('mail' => $name, 'status' => '1'));
  $account = reset($users);
  if (!$account) {
    // No success, try to load by name.
    $users = user_load_multiple(array(), array('name' => $name, 'status' => '1'));
    $account = reset($users);
  }
  if (isset($account->uid)) {
    form_set_value(array('#parents' => array('account')), $account, $form_state);
  }
  else {
    form_set_error('name', t('Sorry, %name is not recognized as a user name or an e-mail address.', array('%name' => $name)));
  }
}
</code>
You need to implement hook_form_alter in your own custom module and alter above form validation to add your own which accepts only username... You can achieve using custom module with out touching Drupal core... In hook form alter check for form id user_pass and override validate handlers like below..
<code>$form['#validate'] = array('custom_module_user_pass_validation');

function custom_module_user_pass_validation(($form, &$form_state) {

}
</code>


Extensions by Adjoining elements and Extensions by quotient of a Principal Ideal

Question: Extensions can be constructed 2 ways to get an extension with roots of a polynomial

Adjoining an element to a field - i.e. $F(\sqrt 2)$ is an extension of $F$. You can also build a tower of extensions by adjoining another element to the first extension.

Extensions generated by a Principal ideal. For e.g. if $p(x)$ is a principal Ideal of $F(x)$, then you can construct an extension $F(x)/\langle p(x) \rangle$. The elements of this extension are cosets.

Though I am able to understand the 2 kinds of constructions, I am unable to understand which constructions is used when/where & if there is any relation between the extensions obtained by the 2 different kinds of constructions?
Comment: The first approach is used when we have two fields $F, K$ with $F\subseteq K, a\in K$ and then $F(a) $ is the intersection of all subfields of $K$ which contain $F$ and $a$.
Comment: @ParamanandSingh - so to decide which approach to use, you would have know to know that F(a) is in the intersection - is there a procedure which tells if it is in the intersection or not?
Comment: Well, the second approach is more fundamental and is the way to extend a field using an algebraic element. The first approach is more common when the field $K\supseteq F$ has been generated using non-algebraic methods (eg $\mathbb {R} \supseteq \mathbb {Q} $) or when $a$ is not algebraic over $F$.
Comment: Also my first comment was a definition of $F(a)$. Using it one can show that $F(a) $ is the set of all rational functions of $a$ with coefficients in $F$. So you don't really have to find an intersection of subfields every time.
Comment: @ParamanandSingh - I am a little confused with your use of the notation $F(a$) here. If $F$ is a field, the notation $F(a)$ or $F(\sqrt 2)$ is used to denote an extension formed by adjoining $a$ or $\sqrt 2$ to $F$ - similar to $R[a]$ or $R[\sqrt 2]$ for a Ring $R$. But you last comment seems to indicate that you are using $F(a)$ to denote a map/function and not an extension.
Comment: No, I haven't said that $F(a) $ is a function / map. My comments are just giving a precise meaning to the word "adjoin".
Comment: @ParamanandSingh  Also if you see the extension $\mathbb R[\sqrt 2]$, $\sqrt 2$ is algebraic over $\mathbb R$, right?
Comment: @ParamanandSingh - in your earlier comment, you wrote that $F(a)$ is the set of all rational functions.
Answer: Let us first try to deal with extensions via an algebraic element.
Let $F$ be a field and $p(x) \in F[x] $ be irreducible and let us ponder about a root of $p(x) $. A very simple approach is to assume that we can apply field operations ($+, -, \times, /$) on the root $x$ and combine it with elements of $F$. However in so doing we always keep track of the fact that it is a root of $$p(x) =a_0x^n+a_1x^{n-1}+\dots+a_n$$ and thus any powers of $x$ greater than or equal to $x^n$ can be replaced with an expression containing powers of $x$ upto $x^{n-1}$ via the equation $$x^n=-\frac{a_1x^{n-1}+\dots+a_n}{a_0}$$ Thus when we try to combine $x$ with elements of $F$ Using $+, -, \times$ we get polynomials in $x$ with coefficients in $F$ and the highest power of $x$ in such polynomials is $x^{n-1}$. Using the fact that $p(x) $ is irreducible one can show that ratio of such polynomials is also a similar expression (without any courses in abstract algebra the proof of this quite non-obvious).
Thus when we try to combine elements of $F$ with the root of $p(x) $ we are naturally led to polynomials in root $x$ with powers upto $x^{n-1}$ and these polynomials behave as elements of a field. Note further that all of this was achieved by replacing $x^n$ and higher powers by using the fact that $x$ is a root of $p(x) $. More abstractly the process can be understood in terms of modulo arithmetic. Let $a(x), b(x) $ be polynomials in $F[x] $ and we write $a(x) \equiv b(x) \pmod {p(x)} $ if $a(x) - b(x) $ is divisible by $p(x) $. This leads us to an equivalence relation on $F[x]$ and a set of equivalence classes say $K$.
Now given a polynomial $a(x) \in F[x] $ let $r(x) $ be the remainder when $a(x) $ is divided by $p(x) $. Then we have $a(x) \equiv r(x) \pmod {p(x)} $ and degree of $r(x) $ is less than $n$ (the degree of $p(x) $). Thus the set $K$ of equivalence classes can be written as $$K=\{[r(x)] \mid\text{degree of }r(x) <n, r(x) \in F[x] \} $$ This is what we denote as $F[x] /\langle p(x)\rangle $ and this set is a field if $p(x) $ is irreducible.
Another point to note here is that there is a subset of $K$ namely $$\{[a] \mid a\in F\} $$ which behaves exactly in the same manner as $F$ with respect to field operations and in this sense we say that $F$ is a subfield of $K$ or that $K$ is an extension of $F$. This is the procedure where one can extend a field by using an irreducible polynomial.
Another approach of "adjoining" assumes there is an extension $K/F$ of fields (obtained using any means, including the one involving an irreducible polynomial described earlier). Let $a\in K$ and the set $F(a) $ is defined to be the intersection of all subfields of $K$ which contain $F$ as well as $a$. Thus it is the smallest subfield containing $F$ and $a$. And it can be proved that it is the set of all expressions of the form $f(a) /g(a) $ where $f(x), g(x) \in F[x] $ and $g(a) \neq 0$.
If an element $a\in K$ is algebraic over $F$ it can be proved that $F(a) $ is isomorphic to $F[x] /\langle p(x)\rangle $ where $p(x) $ is the minimal polynomial for $a$ over $F$. And thus both approaches are same in case the field extension is done via an algebraic element.
Note further that there are other ways to extend a field and most notable among them is the field of fractions of $F[x] $ which leads to $F(x) $, the field of rational functions in an indeterminate $x$.  And we have the non-algebraic mechanism of extending from $\mathbb {Q} $ to $\mathbb{R} $ which involves order relations in a fundamental way and does not apply to general fields.
Comment: It's not clear what exactly is $a \in K$ here? Is $a$ the root?
Comment: @user93353: no, the notion of adjoining does not need the notion of a root of some polynomial, rather it assumes that we have a extension $K/F$ of fields and then one tries to define the meaning of adjoining an element $a$ of $K$ to $F$. So in this context $a$ can be any element of $K$.
Comment: @user93353: for example let us consider the extension $\mathbb {R} /\mathbb {Q} $ and we can consider $\mathbb {Q} (\pi) $ obtained by adjoining $\pi\in\mathbb {R} $ to $\mathbb {Q} $.


poedit doesn't recognize _x

Question: My .po file contains:
"X-Poedit-KeywordsList: __;_e;__ngettext:1,2;_n:1,2;__ngettext_noop:1,2;"
"_n_noop:1,2;_c,_nc:4c,1,2;_x:1,2c;_nx:4c,1,2;_nx_noop:4c,1,2;_ex:1,2c;"
"esc_attr__;esc_attr_e;esc_attr_x:1,2c;esc_html__;esc_html_e;esc_html_x:1,2c\n"

And my php/wordpress code contains:
_x( 'Add New', $this->post_type , $domain ),

I know that Poedit is scanning that file (all the other translatable strings are picked up on "update catalog", and share the same domain). And if I change _x to __ (and remove the context parameter) it picks that one as well. But as it is written, the "Add New" string simply wont show in PoEdit.
Even if I add manually the string to the po file, it will put it in the "obsolete strings" after trying to update to .po file from sources...
Would have thought that the "_x:1,2c;" bit would be enough to pick up the string, but it never does.
Is there something I'm doing wrong, or have I encountered an actual bug?
Answer: See the documentation for _x() at http://codex.wordpress.org/Function_Reference/_x — the second argument is context, which is a string included in the PO together with the source text to disambiguate otherwise identical strings with different meaning. The codex page above has an example; another one is e.g. "Open" that could be used in different context, so the programmer would use e.g. "File menu" as the context.
The important part is that it is handled the same way as the text to be translated. The text has to be a string literal for xgettext to extract it and so does the context (it has to be: it's something that goes into the PO file!).
$this->post_type is not a literal, which is why xgettext doesn't recognize it. There's no way it could know what the post_type value could be at runtime and so it couldn't possibly know what to write into the created PO file.
To fix this, you need to use _x() with at least the first two arguments string literals.

poedit doesn't recognize _x


How to select multiple values from a list block and perform search?

Question: I am a newbie to Drupal.
I have created a block that contains tags of the important topics on my website so how do I insert a search option for the user so that he can select multiple tags from that block and perform the search operation.
Comment: Welcome to the drupal.SE. Please find my answer below.
Answer: Assuming it's a view, you have to do a couple of things after constructing the view.

Click on the Filter Criteria as seen in the screenshot below:

Click on Expose this filter, Grouped filters and Allow multiple selections in this order (they will only appear if you click in this order). Please see the screenshot below:
Comment: Oh Thank you so much for this! Really helped a lot.


How to add programmatically region's class when region had block in D8?

Question: I have one row three column region. How can I add custom class on each region when one of region is not work?
When three regiosn work, classes will be below
|------------|-------------|--------------|
|            |             |              |
|  region 1  |   region 2  |    region 3  |
|            |             |              |
|------------|-------------|--------------|
  col-sm-4      col-sm-4       col-sm-4

When two regions work, classes will be below
|-------------------|---------------------|
|                   |                     |
|  region 1         |     region 2        |
|                   |                     |
|-------------------|---------------------|
      col-sm-6             col-sm6

When only one region work, class will be below
|-----------------------------------------|
|                                         |
|               region 1                  |
|                                         |
|-----------------------------------------|
               col-sm-12

I use in page.html.twig like below. It worked for me but not good code for more column.
{% if page.region_1 and page.region_2 %}

 {{ page.region_1 }}

 {{ page.region_2 }}

{% endif %}

{% if not page.region_1 and page.region_2 %}

 {{ page.region_2 }}

{% endif %}

{% if not page.region_2 and page.region_1 %}

 {{ page.region_1 }}

{% endif %}

I'm try using hook_preprocess_region() like below. Can I check regions condition in hook_preprocess_region?
function MYTHEME_preprocess_region(&$variables) {

  // Add class in header region.
  $region = $variables['elements']['#region'];
  $region_header = array(
    'region_1',
    'region_2',
    'region_3'
  );

  if (in_array($region, $region_header)) {
    $variables['attributes']['class'][] = 'col-sm-12';
  }

}

Answer: Check Block Class module for this
Block Class allows users to add classes to any block through the block's configuration interface. By adding a very short snippet of PHP to a theme's block.tpl.php file, classes can be added to the parent  element of a block. Hooray for more powerful block theming!
Comment: thank your answer. But I wanna make to programmatically change classes when region is has some block and not for `drpual 7`.


git and jgit committing difference: git requires email while jgit doesn't

Question: Working on a project, i am mixing Netbeans 7.3 integrated git client (that actually is jgit) and command line git client.
When committing with Netbeans, the IDE offers two fields: Author and Committer.

But when working on the same project via command line, i get:
$git commit

*** Please tell me who you are.

Run

  git config --global user.email "firstname.lastname@example.com"
  git config --global user.name "Your Name"

to set your account's default identity.
Omit --global to set the identity only in this repository.

fatal: unable to auto-detect email address (got 'agostinox@local-pc.(none)')

Consistently, git config --list returns a set of keys that doesn't contain user.email or user.name.
It would be easy to add the information reuqired, but the question is: since the auto-detection of eamil address has failed, which is the email address that has been used in the previous, successful commit performed by Netbeans (jgit)?
Answer: The best way to see what was used is probably to look at git log --pretty=fuller.  Judging by the above, jgit probably allowed agostinox@local-pc as the email address.
BTW, the difference here is probably that git is unhappy about the email address it found  (local-pc is not a proper domain name).  jgit just has a different policy and accepts it.


Is there a name for a minor scale with a raised 3rd or a major scale with a lowered 6th and 7th?

Question: I've noticed a pattern in chord progressions and melodies where I like to use the b7 and b6 chords with a major tonic and there are several modern songs that like to use this pattern as seen in a recent question leaving me to think that the following pattern is common.

 1  2  3  4  5 b6 b7

I've never hear of a scale though containing this combiniation of notes though. Is there a name for this scale?
Answer: Yes, it's the 5th mode of melodic minor, and it's usually called Mixolydian b6 or Mixolydian b13. Other names for this scale, in my opinion slightly less fortunate, are Aeolian Dominant or Hindu scale. You can find even a few more obscure names for it in the article linked above. However, in a jazz context I've only come across the name Mixolydian b6 (or b13).
Comment: All scale names are unfortunate... it's not like ancient-greece Aeolian music probably sounded much like present-day tunes in a natural-minor key.
Comment: Interestingly, when I first saw the title of this question, I immediately thought it should be named "Aeolian Dominant", even though I don't think I'd ever heard that name before. I even googled the name before clicking through to read the full question.
Comment: @CalebHines: Yeah, Aeolian Dominant makes sense as an analogy to Phrygian Dominant, but I've never heard anyone use this term.
Comment: What are you guys talking about. It is clearly a major-minor scale. T
Answer: While Mixolydian ♭6 is valid, of course, I've heard another name for it: Melodic Major.
Why? I'm guessing that it's "melodic" because it lowers major's 6th and 7th degrees (just as melodic minor alters the 6th and seventh scale degrees). Obviously, "major" because it has the major third.
I've also heard of a harmonic major, being major with the lowered 6th degree only.
For A minor: Natural-Harmonic-Melodic have F G A; F G♯ A; and F♯ G♯ A respectively.
For C major: (Natural)-Harmonic-Melodic have A-B-C; A♭-B-C; and A♭-B♭-C respectively.
Comment: What about major minor?
Answer: Bruckner 4 uses an E-flat scale of this type at the end -- one of my favorite scholars refers to it simply as "dark Eb Major!"
Comment: Who is that scholar?
Comment: Not to drop names, but Will Carragan's the author of "dark Eb Major!"
Answer: For those familiar with Indian Ragas, these are the swaras (notes) of Charukesi Raga. An example of a song in this Raga:


How do you estimate the gas usage of a NEAR smart contract method call?

Question: Is there a tool that can estimate how much gas a contract call will make before submitting to the NEAR network?
Answer: Currently the best estimation is to use runtime-standalone, which can process transactions without having to worry about consensus/networking.  This means you can create accounts, deploy contracts, and invoke them and the outcome returned includes how much gas was burnt and used. The difference being burnt gas is used to execute the function call and used gas is how much was used by contract promise calls.
However, it's currently a MVP prototype and has only been used to test our core contract, here is it being used to test the lockup contract.
If your contract method doesn't invoke any batch promises and only normal promises,the mock runtime in near-sdk-as provides a way to create accounts and "deploy" contracts.  It does this by internally using the binary of near-vm-runner-standalone, which is a rust crate. The binary provides a CLI to invoke a single transaction, which takes as input the current state of the contract being called, the contract's binary, the config file that defines the current context (who is calling the contract, how much gas is prepaid, etc), and a config for the cost of different fees. It then returns the updated state, the outcome of the transaction (e.g. how much gas was used and any receipts of transactions queued by promise calls).
The near-vm-runner-standalone is also published to npm with the package name: near-vm, which is what the mock runtime uses.
This is still an active area of development and we hope to turn runtime standalone into a useful easy to use tool for testing and gas estimation.
Answer: The easiest way to do it is to submit sample transaction with more than needed gas attached and then check in explorer how much gas was used, e.g. see
https://explorer.testnet.near.org/transactions/23dgV15pydiVhirWJ4He7TMoyRJM2DUXtcWb7VXFSy2G
300 Tgas was attached and 47 Tgas used for that given transaction.


How to set a timer for a modal dialog to appear at the press of a button

Question: Hi I have an onclick button. When I press this onclick button, a modal dialog should appear after 5seconds (5000 milliseconds). However after 5 seconds the modal closes and reopends after 5 as if its been looped. Everything looks fine with the code but I don't know where I am going wrong.
What I want:
1) When the onclick is pressed, the modal dialog opens after 5 seconds. The modal shouldn't close unless someone presses the save button.
2) When The "save" button is pressed the modal dialogue closes and is reset.
3) The modal dialogue doesn't reopen itself again. It only opens 5 seconds after the button is clicked.
I hope that is clear.
Any helped would be appreciated

var modal = document.querySelector(".modal");
var trigger = document.querySelector(".trigger");
var closeButton = document.querySelector(".close-button");

function toggleModal() {
setTimeout(toggleModal, 5000)
    modal.classList.toggle("show-modal");
}

trigger.addEventListener("click", toggleModal);
closeButton.addEventListener("click", toggleModal);
.modal {
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    opacity: 0;
    visibility: hidden;
    transform: scale(1.1);
    transition: visibility 0s linear 0.25s, opacity 0.25s 0s, transform 0.25s;
}
.modal-content {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: white;
    padding: 1rem 1.5rem;
    width: 24rem;
    border-radius: 0.5rem;
}
.close-button {
    float: right;
    width: 1.5rem;
    line-height: 1.5rem;
    text-align: center;
    cursor: pointer;
    border-radius: 0.25rem;
    background-color: lightgray;
}
.close-button:hover {
    background-color: darkgray;
}
.show-modal {
    opacity: 1;
    visibility: visible;
    transform: scale(1.0);
    transition: visibility 0s linear 0s, opacity 0.25s 0s, transform 0.25s;
}
<button class="trigger">Click here </button>

          Please state your confidence with this decision (0-100%)

         <input class="bottomaftertrialquestions" type="number" placeholder="Type here" name="conf1d3nce"min="0" max="100" required>

            <button type="button" class="close-button">SAVE</button>

. I am unsure what is wrong with my code to get it to work
Answer: You're causing the loop yourself with this function:
function toggleModal() {
    setTimeout(toggleModal, 5000);
    modal.classList.toggle("show-modal");
}

This defines a function called toggleModal, which does two things:
1) schedules toggleModal to run in 5 seconds' time
2) toggles the show-modal class.
1) is the important thing here: the function schedules itself to run again in 5 seconds, each time it runs - thereby ensuring that, when called once, it will continue to be called every 5 seconds from then onwards.
So don't schedule the same function in the setTimeout, instead schedule the effect you want - the toggling of the class. This can be done most simply with an anonymous function:
function toggleModal() {
    setTimeout(function() {
        modal.classList.toggle("show-modal");
    }, 5000)
}

Answer: you should try this
<!DOCTYPE html>

Click "Try it". Wait 3 seconds, and the page will alert "Hello".

<button onclick="setTimeout(myFunction, 3000);">Try it</button>


Why tf-idf truncates words?

Question: I have a dataframe x that is:
> str(x)
'data.frame':   117654 obs. of  2 variables:
$ text  : chr  "more about " ...
$ doc_id: chr  "Text 1" "Text 2" "Text 3" "Text 4" ...

I can't report it here, with dput, because it is too large. I'm trying to estimate the TF-IDF and I wrote the code:
library(dplyr)
library(janeaustenr)
library(tidytext)
book_words <- x %>%
  mutate(text = as.character(text)) %>%
  unnest_tokens(output = word, input = text) %>%
  count(doc_id, word, sort = TRUE)

book_words <- book_words %>%
  bind_tf_idf(term = word, document = doc_id, n)

book_words<-book_words[order(book_words$tf_idf,decreasing=FALSE),]
book_words = book_words[!duplicated(book_words$word),]

Anyway, I noticed that some words appear to be truncated in book_words. For example:
             doc_id          word n  tf      idf    tf_idf
 792727  Text 33268     disposabl 1 1.0 11.67321 11.673214

I'm sure this is a truncated term because, if I run:
x[grepl("^disposabl$",x$text),]

I obtain no rows.
This ever happen to you?
Comment: I suspect there are leading spaces (typically `data.frame` columns are not unevenly distributed like that without some leading spaces). Does `x[grepl("disposabl$",x$text),]` (no leading `^`) find anything?
Comment: @r2evans: thank you! You are right! I obtained just 1 row!
Answer: From your output, it appears that there is leading blank-space in the name. If it were just "dispoabl" with no leading/trailing blanks, I would expect
            doc_id      word n tf      idf   tf_idf
 792727 Text 33268 disposabl 1  1 11.67321 11.67321
 ###              ^         ^   one space each

but your output shows
             doc_id          word n  tf      idf    tf_idf
 792727  Text 33268     disposabl 1 1.0 11.67321 11.673214
                    ^^^^  four extra blanks

This means that your "^dispoabl$" is too restrictive. Try to filter (here) with:
x[grepl("disposabl$",x$text),]

removing the leading ^ and therefore allowing something before the d. Alternatives:

"\\bdisposabl$" adds a word-boundary, so "adisposabl" won't match but "a disposabl" will still match;
"^\\s*disposabl$" requires that anything leading be blank-space;
trim the blankspace with x[grepl("^disposabl$",trimws(x$text))], where your original pattern would have worked.

Why tf-idf truncates words?


Updating ManyToMany Checkboxes PlayFramework 2

Question: I have some troubles to update Many-To-Many Relationship with checkboxes in Play Framework 2.1.0
Account Model:
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "account_security_role", joinColumns = { @JoinColumn(name = "account_id", referencedColumnName = "id") }, inverseJoinColumns = { @JoinColumn(name = "security_role_id", referencedColumnName = "id") })
public List<SecurityRole> roles;

I want to update account roles in account edit view
Edit Account View:
@for(role <- SecurityRole.find.all()) {

       @role.description

            <input type="checkbox" name="roles[@role.id].id" value="@role.id" class="toggle"
            @if(loggedAccount.hasHole(role.id)) {
               CHECKED
            } />

}

So, when I call Update POST method I get this error:

InvalidPropertyException: Invalid property roles[3] of bean class [models.Account]: Illegal attempt to get property roles threw exception; nested exception is org.springframework.beans.NullValueInNestedPathException: Invalid property roles of bean class [models.Account]: Could not instantiate property type [be.objectify.deadbolt.core.models.Role] to auto-grow nested property path: java.lang.InstantiationException: be.objectify.deadbolt.core.models.Role

Is there some example to update a model using checkbox and Many-To-Many relationship?
Thanks a lot.
Lew
Comment: Can you give us the POST controller method?
Answer: Thanks Alban, I found the Error.
There is a convention for attribute names in models, so when a I change the name from roles to securityRoles It works fine and found the correct model class to instantiate.
Account Model:
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "account_security_role", joinColumns = { @JoinColumn(name = "account_id", referencedColumnName = "id") }, inverseJoinColumns = { @JoinColumn(name = "security_role_id", referencedColumnName = "id") })
public List<SecurityRole> securityRoles;

Edit Account View:
@for(role <- SecurityRole.find.all()) {

       @role.description

            <input type="checkbox" name="securityRoles[@role.id].id" value="@role.id" class="toggle"
            @if(loggedAccount.hasHole(role.id)) {
               CHECKED
            } />

}


angularjs and angular 4 http request

Question: I am porting an app from angularjs to angular 4
I encounter a problem with http request.
Here is a call in angularjs :
$http.post(/get_paginate_items_with_search', params).succes(function (data) {})

data is displaying
now in angular 4
import { Injectable, NgModule } from '@angular/core';
import { HttpClient } from '@angular/common/http';

declare const angular: angular.IAngularStatic;
import {downgradeInjectable} from '@angular/upgrade/static';

@Injectable()
@NgModule()
export class ItemsService {
    constructor(private http: HttpClient) {

    }

    GetItemsList(params: any) : void {
        this.http.post('/get_paginate_items_with_search', params).subscribe(
            data => console.log(data),
            err => console.log(err)
        )

    }
}

angular.module('module').factory('ng4itemsService', downgradeInjectable(ItemsService));

is not returning anything. the payload is the same

but the request is different, there is no method and anything. In the Network tab, it is display as "pending". Do I have to make a special header and stuff to make it works ?
From the DOC of angular, they don't do anything particular to make it works.
I am missing something ?
Answer: Your screenshot for Angular 4 likes an OPTIONS request. Can you check it again in the Network tab of Chrome, maybe you can see 2 requests to the same api (1 OPTIONS and 1 POST) then check the POST one. The response should be within the POST request
Comment: Can you take a screenshot?
Comment: I added

        const httpOptions = {
            headers: new HttpHeaders({
              'Content-Type':  '*/*',
              'Authorization': 'my-auth-token',
              "Access-Control-Allow-Origin": "*"
            })
          };

and it works

angularjs and angular 4 http request


Using partitions of List/Collections dynamically in Java?

Question: I have a usecase of picking up x number of elements in a batch from total n number of elements. Currently I'm using Google Guava Lists like this :
List<String> dataList;

List< List<String> > smallerLists = Lists.partition(dataList, maxRecordsInABatch);

for ( smallerList : smallerLists ) {
    doSomething(data);
}

Is there a better way to do it, in which I can avoid making smallerLists and on-the run time pick x-sized lists from n-sized list.
I was also exploring Java 8 Streams and Lambda expressions but couldn't find something to cater this.
Comment: Lists.partition() strikes me as a very good way to do it; I can't tell how to beat it without more information about what you think of as "better". None of the items in the list are duplicated, and virtually no object pointers are duplicated, either - according to the javadocs, the smaller lists are a view onto the larger list. The only two possible improvements I can guess at are that you want to modify the smaller lists without altering the larger one (soln: clone the sublists), or you want to do some sort of cloud job. Do either of these hold?
Comment: If you have a look at the source of `Lists.partition()` you'll see that you'll get a `Partition` which call `subList()` on the list you pass. In case of the built-in lists that call will create small objects that operate on the underlying list so in fact your code should not generate any new lists.
Comment: http://stackoverflow.com/a/30694866/829571
Comment: @Thomas @Paul Brinkley My only concern was data-redundancy. I was thinking `Lists.partition()` creates new smaller lists with copy of data from original list. If this is not the case, and in fact I'm working with the same underlying list, then I'm fine with my approach.
Comment: In fact even if you'd get new lists they'd still refer to the same data, i.e. the elements in a list will not be copied, just the references to them (which is about 8 bytes per reference).
Comment: Similar to [this question](http://stackoverflow.com/q/28210775/2711488). If the source is a `List` and the result ought to be a `List>`, i.e. neither source nor target ought to be a stream, `Lists.partition` is good enough (note the second answer there)…
Comment: The concern about redundancy is definitely fair. Even a concern about *pointer* redundancy is fair, IMO, if the list is very large. And in fact, I'd misread the javadoc for Lists.partition(); it's copying all of those pointers for the outer list, whereas I'd thought the sublists were views into the input list.

That said, if you're only concerned about data redundancy, all's well.
Comment: Are you looking to just split the data. Or to perform parallel tasks after splitting the data?
Answer: There is a small trick you can use for list partition in java-8.
First you group splitting by the number of partions then you create a new list with grouped values. Something like this:
List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
Map<Integer, List<Integer>> groups = intList.stream().collect(Collectors.groupingBy(s -> (s - 1) / 3));
System.out.println(groups);
List<List<Integer>> subSets = new ArrayList<List<Integer>>(groups.values());
System.out.println(subSets);

Answer: You can use partioningBy the collector.
As described in the below link:
https://www.javacodegeeks.com/2015/11/java-8-streams-api-grouping-partitioning-stream.html


Help with proposed iSCSI SAN VMware implementation

Question: We have four (with plans to grow to four more) Dell servers with 6 NICs. They are running VMware ESXi 4.1. We would like to connect all of them to an Openfiler iSCSI SAN via HP ProCurve 1810G switches. Based on the design below, is there anything I should be concerned about or anything unusual that I should look out for when making the iSCSI network configurations on the servers, switches and OpenFiler? Should I bond the connections on the servers or simply setup them up for failover? The primary goal is to maximize IOPS. Thanks in advance.
Answer: I don't think bonding will help you at all in this scenario, pretty certain in fact. You want multipathing to do its thing on the ESX 4.1 Hosts - you will be limited with multipathing policy options as I don't think there is a full Openfiler vSphere PSP or Multipathing Extension Module available but round robin should work and distribute load across all available paths to some degree, it should certainly deliver better performance than plain failover would.
VMware do not recommend NIC bonding at all for iSCSI on vSphere 4.1 - their recommendations now clearly state in the iSCSI SAN configuration Guide that you should create multiple independent iSCSI VMkernel ports, with one physical NIC and only one mapped to each iSCSI port (do not use teaming at all, not even for failover) and leave iSCSI failover to the multipathing stack.
Other than that your proposed layout looks good - make sure you have nothing else on those Switches if at all possible, VLAN the iSCSI network if you can't, enable hardware Flow control and use Jumbo Frames if you can. I'm not sure I'd be confident in Openfiler on commodity hardware for this but if you are then that's your call, hosting more than a handful of VM's off a single point of failure like that wouldn't allow me to sleep all that easily at night (or party hard when on holiday :) ).
Comment: +1 on bonding. Even your filers should go separate and let MPIO do its thing.
Comment: +1 for Jumbo Frames and TOE
Comment: +1 for dedicated switches and +1 for Jumbo Frames.
Also I share Helvick's concern about using openfiler and commodity hardware. If you are going to bother with having 8 ESX host you should invest in an entry level SAN. Or at a minimum a NAS with iSCSI and dual SCSI cards.


Determining why $\int_{\partial R} z\ dz = 0$ and $\int_{\partial R} z\ dz = 0$ independently of Cauchy's Theorem for a Rectangle

Question: Let $R$ be a rectangle on the complex plain and $\partial R$ its closed curve.  Without making use of Cauchy's Theorem for a Rectangle (or any of the other Cauchy theorems), I'm curious why we know already that in the follow special cases, Cauchy's Theorem for a Rectangle holds:
$$
\tag{1}
\int_{\partial R} 1\ dz = 0
$$
$$
\tag{2}
\int_{\partial R} z\ dz = 0
$$
Ahlfors makes a passing remark that it has something to do with the fact that $1$ and $z$ are the derivatives of $z$ and $z^2/2$ respectively.  Is his implication, then, that $1\ dz = 1\ dx + i\ dy$ and $z\ dz = z\ dx + iz\ dy$ are exact differentials and hence since $\partial R$ is a closed curve, we have that these integrals must equal zero?
Comment: I appreciate the explanations below.  I'm curious also if the explanation I offered above makes any sense as well.  Is this the case?
Comment: That is the essence of what I stated.
Answer: The definition of path integral implies that if $\gamma:[0,1]\rightarrow \mathbb{C}$ is a $C^1$ path, and $f$ is differentiable, then $\int_{\gamma} f'(z) dz = \int_0^1 f'(\gamma(t))\gamma'(t)dt= f(\gamma(1))-f(\gamma(0))$. Then it follows directly that if you have a piecewise $C^1$ closed curve, the integral of a derivative over it must be zero.
Answer: This follows from Stokes' Theorem (these conditions are met by compactness and rectifiability which one needs to verify) once one shows that $dw = 0$, since closed implies exact in this case (star-convex). This is clear in the first case. Now, in the second case $$d(z\; dx + iz\; dy) = -i dx \wedge dy + i dx \wedge dy = 0,$$ which is just multivariable calculus.


Como inserir dados em outra tabela a partir da chave estrangeira?

Question: Tenho uma tabela no meu banco de dados chamada imoveis onde nela tenho algumas colunas, destacando-se localizacao_fk e correspondencia_fk, ambas chaves estrangeiras que fazem referência à tabela enderecos. O que eu quero saber é como inserir dados na tabela imoveis de tal forma que o povoamento das colunas localizacao_fk e correspondencia_fk automaticamente seja feito na tabela enderecos.
Uma visão geral do que pretendo fazer é a seguinte:
Tenho um formulário de cadastro onde, em determinado ponto, tenho campos de dois tipos de endereços a serem preenchidos: o primário (referente à coluna localizacao_fk) e o secundário (correspondencia_fk). Mas no banco, campos desse formulário como CEP, logradouro, bairro e cidade não estão na tabela imoveis, e sim em enderecos. Logo, o preenchimento de tais campos povoariam tanto localizacao_fk quanto correspondencia_fk (caso eu deseje fornecer esse endereço secundário).
Help!
Eis os prints das tabelas:
Tabela endereços:

Tabela imóveis:
Comment: Poderia posta suas tabelas.
Comment: Já disponibilizei os links no post.
Answer: vc tem que adicionar primeiro na tabela endereco pegar a id e adicionar esse id na imoveis.
no seu formulario tem os campos de endereço localização e correspondencia.
quando vc salvar o formulario,  primeiro salve a tabela endereco.
como poderao ser 2 endereços salve o primeiro guarde o id numa variavel depois o mesmo com o segundo.
finalize colocando os ids em imoveis
Comment: Localização e correspondência são chaves estrangeiras da tabela endereços.
Comment: Disponibilizei no post os links dos prints das tabelas.


Number of ring homomorphisms from $\mathbb Z_{12}$ to $\mathbb Z_{28}$.

Question: Question:

Find the number of non trivial ring homomorphisms from $\mathbb Z_{12}$ to $\mathbb Z_{28}$. ($f$ is not necessarily unitary, i.e., $f(1)$ need not be $1$.)

Suppose $f$ is a ring homomorphism from $\mathbb Z_{12}$ to $\mathbb Z_{28}$.
Consider $f$ as a additive group homomorphism.  Let $k= |\ker f|$ and
$ t = |\operatorname{im}(f)|$. Then $k\mid 12$ and $t\mid 24$ and $kt=12$, by first isomorphism
theorem of groups.
There are two possibilities $k=3$, $t=4$   and $k=6$, $t=2$.
For the first case $f$ should map $1$ to an element of the subgroup generated by $7$ as there is a unique subgroup of $\mathbb Z_{28}$ of order $4$ generated by $7$. For the second case $1$ has to map to $14$, for the same reasoning.
So there are at most two ring homomorphisms from $\mathbb Z_{12}$ to $\mathbb Z_{28}$.
Question is how to check the possible maps which are ring homomorphisms.
Thanks.
Comment: For counting the group homomorphisms, it's true there's only one subgroup of order 4, but you can map 1 to *any* generator of that subgroup.
Comment: So why didn't you change your incorrect statement that $f$ should map $1$ to $7$ when you edited the question?
Comment: What about $k=12$?
Comment: We need non trivial homomorphisms.
Comment: @GerryMyerson you are right. Thanks
Comment: Related: http://math.stackexchange.com/questions/263063/the-number-of-ring-homomorphisms-from-mathbbz-m-to-mathbbz-n/1564242#1564242
Answer: Number of ring homomorphism from $\mathbb Z_m$ into $\mathbb Z_n$ is $2^{[w(n)-w(n/\gcd(m,n))]}$ , where $w(n)$ denotes the numbers of prime divisors of positive integer n.
From this formula we get number of ring homomorphism from $\mathbb Z_{12}$ to $\mathbb Z_{28}$ is $2$.
Comment: Will above formula work for Zn to Zn. Please reply
Comment: What is $w(1)$ defined
Answer: Even if not necessarily $f(1)=1$, we still need $f(1)\cdot f(1)=f(1\cdot 1)=f(1)$, hence $f(1)$ must be a solution of $x^2-x=0$ in $\mathbb Z_{28}$. The solutions for this are the residue classes of: $0, 1, 8, 21$.
Therefore, $f\colon \mathbb Z_{12}\to\mathbb Z_{28}$ is necessarily induced by $\mathbb Z\to\mathbb Z$, $x\mapsto cx$ with $c\in \{0,1,8,21\}$.
Also, we need $28|12c$, i.e. $c$ must be a multiple of $7$. This leaves only the cases $c=0$ and $c=21$.
Answer: A ring homomorphism $f:Z_{12}\to Z_{28}$ must map $1$ to $1$, because ring homomorphisms do that (if you are not assuming your ring homomorphisms to be unitary, you should always be explicit about it!)
Now $\underbrace{1+1+\dots+1}_{\text{$12$ summands}}=0$ in $Z_{12}$, so applying $f$ we must have $$\underbrace{1+1+\dots+1}_{\text{$12$ summands}}=\underbrace{f(1)+f(1)+\dots+f(1)}_{\text{$12$ summands}}=0$$ in $Z_{28}$. As this is not true, there is no morphism!
Comment: You should not have accepted this, as this does not do what you wanted"
Comment: We assume that f is not unitary.
Comment: Then **please** do add that information to the question.
Answer: Hint $\ $ Applying the hom $\rm\,f\,$ to $\rm\:12\cdot 1 = 0\:$ and $\:1^2\!= 1,\:$ denoting $\rm\:e = f(1),\:$ we infer that $\rm\: 12\,e = 0\:\Rightarrow\:28\:|\:12\,e\:\Rightarrow\: 7\:|\:e,\:$ hence $\rm\:mod\ 28\!:\ e \equiv 0,7,14,21;\:$ also $\rm\:e^2 \equiv e\:$ hence $\rm\:e\equiv\,\ldots$
To understand better the role played by idempotents $\rm\:e^2 = e\:$ look up the Peirce decomposition.


Is Covariance Matrix analogous to Jacobian Matrix?

Question: In probability theory covariance matrix denote how each variable relates to other in a pairwise manner. So 1 would mean they are identical and 0 would mean they are independent and are not related. Is this concept similar to Jacobian matrix where such relation between multiple variables are denoted by partial derivative?
Comment: Because covariance matrices represent *quadratic forms* (which is why they are always symmetric and positive semi-definite) and Jacobians represent arbitrary *linear transformations,* about the only thing they have in common is that they are square matrices.  Your question sounds like you are asking whether apples and squid are similar.  They are in the sense that they are derived from living things, but there's little to recommend the comparison.
Comment: @whuber: I'm sorry that I added to the confusion. Yes, it is a special circumstance that the Jacobian is square. When I'm teaching about coordinate transformations (I'm a physicist) this actually comes up frequently. In most cases the transformation isn't linear (e.g. cartesian to spherical), so it's just the first order approximation. But sometimes (e.g. simple translations or scaling -- linear), it is true. I tried to add a little practical info, but didn't intend to confuse.
Comment: In general, whuber is right. But there are actually some similarities. And in some cases, the covariance matrix *is* the jacobian matrix -- e.g. when a variable transformation is performed; to be more precise, it would need to be a linear transformation, otherwise it's only an approximation. In general it helps to think of the Jacobian simply as the derivative in spaces with dimension larger one. But I'd also be careful to associate covariance with "how a variable relates to another"; it's just the expectation value of the product.
Comment: @cherub much of what you write is confusing.  In particular, any covariance matrix can be considered a linear transformation--that's standard, but in a statistical application it is important to describe *what* it might be transforming.  A Jacobian cannot possibly be a covariance matrix unless it is square, symmetric, and positive-semidefinite, which in more than one dimension would be a rare circumstance, and even then it's unclear what it would be the covariance of.
Comment: allright makes sense! +1 for creative analogy
Comment: @cherub is there any concrete example you would like to share where covariance matrix is the jacabian matrix. My initial motivation of seeking similarities between the two were due to taking point-wise partial derivative in Jacobian matrix where each element of the matrix quantify how one varies when other being kept constant. or relative increment. Can this notion be related to an equivalent element of covariance matrix where this relative increment is quantified as expectation value of the product of the corresponding variables?
Comment: @GENIVI-LEARNER I'm sorry, I don't really understand what your question is. There are formal similarities between Covariance matrices and Jacobians, as whuber mentioned. But they are still entirely different things. I was just trying to state that under certain circumstances a particular Jacobian can be the Covariance matrix. In that particular case, this makes sense; you can express the variation of one variable exactly by a particular formula, which happens to be the derivative. But in general this is not true. Covariance matrices are generally not transformation matrices; but Jacobians are.
Comment: @cherub yes whuber made good analogy that they both are similar as they are square matrices.  I wanted to know that under what circumstances a Jacobian can be a covariance matrix as you stated. I think you answered that in this comment that in circumstances where we variation of one variable can be expressed by a formula that happens to be a derivative. I am just curious if there is a concrete example for when the variation of one variable can be expressed by a particular formula in a derivative form so covariance matrix is indeed jacobian matrix.
Answer: I'd rather say that the covariance matrix is similar to the Hessian matrix  .. Furthermore, the Hessian tends to be proportional to the precision matrix (which is the inverse of the covarinace matrix). The intuition behind is that the higher the curvature in a given direction is, the lower the auto-covariance (the variance) in that same direction will be.
Comment: Hi, could you please provide more details in the answer. In terms of how parwise relation in Jacobian matrix conveys something. Also how is covariance matrix similar to Hessian matrix where single element is partial second derivative?
Comment: Assuming a linear relationship between Y and X in the form $Y=aX+b$, the first derivative (Jacobian) will be a constant equal to the regression coefficient $a$ which is proportional to $Cov(Y,X)$ , whereas the second derivative (Hessian) will be 0. In general, pairwise, a null Hessian coefficient means there is a collinearity or a correlation between variables, the degree of intensity of this correlation is conveyed by the Jacobian coefficient. But, the Jacobian coefficient must be constant, otherwise the relationship would be of a higher order than a simple collinearity.
Comment: alright. this is the worked example I was looking for. Also why is it that "higher the curvature in a given direction is, the lower the auto-covariance (the variance) in that same direction will be"?
Answer: Consider the direction of $x$ axis in the figure below. At a fixed $y$ ($y = 15$ in the example) the sample of points $x_i$ drawn from the blue plot has a higher variance than the red sample. However, in the same direction $x$, the red plot has a higher curvature $.6$ compared to the blue one $.2$.
Comment: Could you explain how any of these plots determine how to draw samples??
Comment: @GENIVI-LEARNER Nothing about that "explanation" makes much sense, beginning with the fact that the y-axis does *not* map to the x-axis (there's no objective way to determine the sign of the result) and the red and blue smears on the x-axis clearly do not correspond, even qualitatively, with the result of such an approach.
Comment: @whuber could this be that he meant to show normal distribution, so blue would have higher variance and red with lower variance and the in the x-axis line the red/blue points are the draws? I am curious to see how this particular example can be worked out to show how plots determine the sample draws.
Comment: @metron I don't see anything resembling a Normal distribution in this plot.
Comment: We can just draw a uniform sample from the interval $[0,15]$ on the $y$  $axis$, then map each sample to its projection on the $x$  $axis$  via one of the plots. Using the same original uniform sample, we get the visualized blue samples when the projection occurs via the blue plot and the red ones when it occurs via the red plot.
Comment: @whuber, I believe the explanation using uniform sample from the y-axis and checking its projection on x-axis given the three plots makes sense, right?
Comment: @whuber I got your point. I thought I was beginning to understand the notion of curvature with respect to variance.
Comment: @whuber There was a little imprecision in the first figure, it is fixed now. I hope it makes more sense. I gave a geometric interpretation but we could find a proper analytical formulation that is not necessary to grasp the main idea.
Comment: Thanks -- the consistency helps us understand the idea.  It looks like you may be trying to establish a connection based on a "delta method" type of analysis, but specifically how isn't completely clear.


How to set number of bytes with memcpy?

Question: I read about the heartbleed exploit and that is was mistake with memcpy.
void * memcpy( void * dest, const void *src, size_t len );

A proper call to memcpy can look like this
int a[4711] [4711];
 int b[4711] [4711];
/* initialize a */
(void) memcpy( &b [0] [0], &a [0] [0], sizeof( a ) );

But why the third parameter, when would that be different from the size of the src? I've seen other examples where it's the dest size that is used, when should that be done?
Comment: I think you mean `memcpy` not `memcopy`.
Comment: Why the downvote? This is an important question with serious history, especially for folks who came up programming in Java or other memory managed languages.
Comment: also, C cannot look at the source of the calling function to guess which array and how much of it you actually wanted copied.
Comment: well, use cases of memcpy are much wider and much more complicated than create exact copies of two structures. Suppose you need to copy only a part of `a`.
Answer: If you take a look a the the memcpy Man page, the third argument is the number of bytes that is copied from src to dst. So it doesn't matter if you use the size of src or size of dst. But you must ensure that the source and destination buffer sizes are at least equal or greater than the number of bytes copied. Otherwise, buffer overflow will occur.
Answer: In this case, the src and dest arrays are the same size so it does not matter which one you do sizeof on.
In general, if you use the dest size, then you guarantee that your writing does not cause a buffer overflow, which is typically (but not always) a more serious problem than reading past the end of src.
However, reading past the end of src can also be serious, as the Heartbeat case shows. To be robust, it's best to check both src and dest sizes and confirm that they are both what you expect them to be, before proceeding.
Comment: There are many use cases for different size buffers, and truncation in one part can easily result in overflow elsewhere. Also, reading too much can result in all kinds of bad things happening, it just depends on the context.
Answer: The third parameter of memcpy(dst,src,len) gives the number of bytes to copy.
If that number of bytes is bigger than the memory pointed to by either parameter, you are hosed. That's a technical term describing things like the Heartbleed bug, as well as quite a few other bugs I've had the delightful experience :-( of fixing.
If your software development mindset is oriented toward memory objects, the code pattern in your question is valid. For example, if you develop around the idea that you use memcpy() to make exact copies of entire objects, I suppose you would never use any third parameter besides sizeof(src).
But memcpy() is useful for many other sorts of operations, such as management of partial buffers, gathering disjointed streams of data into consecutive memory locations, and similar things.
It's also subject to misuse, and ordinarily has no checks against that. For example, there are probably tens of thousands of code snippets in the wild, many of them in embedded systems, that look something like this.
char [10] out;
char [] in = "Yo ho ho and a bottle of rum!";
...
memcpy (out, in, 1+ strlen(in));  /*don't do this or you're hosed!*/

Comment: Just a C reminder: The above code should be `char out[10]; char in[];`
Comment: Another common example use: Counted strings.

How to set number of bytes with memcpy?


Import gzipped css files into html header?

Question: To increase my website response time, I'm trying to use gzipped css and js files. I've
created style.css.gz file for my wordpress website, but couldn't import it. I copied both
style.css and style.css.gz files into the required directory, but it is not importing the
files. I've changed the .htaccess files. The online tool   whatsmyip.org shows me that server is ready for sending gzipped files to
the browser, but through gzipwtf.org the style.css is shown as unzipped.
Can someone help me how to import this file into my webpage. Currently I'm importing it as:
<code>       <link rel="stylesheet" type="text/css" href="http://localhost:8888/wordpress/wp-content/themes/WP-Answers-Theme/style.css" />
</code>
Answer: you can use gzip compression via your htaccess file itself. it can be processed without gripping the files yourself. Just add the following to your htaccess:
<code><ifModule mod_gzip.c>
  mod_gzip_on Yes
  mod_gzip_dechunk Yes
  mod_gzip_item_include file \.(html?|txt|css|js|php|pl)$
  mod_gzip_item_include handler ^cgi-script$
  mod_gzip_item_include mime ^text/.*
  mod_gzip_item_include mime ^application/x-javascript.*
  mod_gzip_item_exclude mime ^image/.*
  mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>
</code>


Superkey vs Primary Key

Question: I'm having issues understanding super keys in a relation when the relation only contains one functional dependency.
When considering a relation R(A,B,C,D,E) where A is the primary key and with the functional dependency A->B, can A be considered a super key to the relation since there is only one FD?  Or would one need to expand the functional dependency to include the unmentioned parts of the relation (C,D,E) in order to find a super key?
I'm mainly confused because all the material I've seen on the web until this point has contained multiple functional dependencies all of which have contained all of the attributes within the relation, so I'm not sure how to interpret the unused attributes.  If someone could help clarify this I'd appreciate it!
Answer: If the only explicitly mentioned FD for the relation schema is A ⟶ B, then there is the implicit, trivial FD {A,B,C,D,E} ⟶ {A,B,C,D,E}.  Given that A ⟶ B, we can deduce that:

{A,C,D,E} is the primary key of R.
There is a partial key dependency for A ⟶ B so R is not in BCNF and the relation schema R should be broken down into two non-loss projections:

R1(A,B) with A ⟶ B so A is the primary key.
R2(A,C,D,E) which is all key (primary key is the combination {A,C,D,E}).
And R1 ⋈ R2 ≡ R (assuming ⋈ is the join operation).

As Catcall says in comments, there is mention of A being the primary key of R.  If A is a primary key, then each of the singleton FDs A  ⟶ B, A ⟶ C, A ⟶ D and A ⟶ E (or, collectively, A ⟶ {B,C,D,E}) applies, and there's no need to call out A ⟶ B separately.  If A is a primary key of R, there's no need to decompose R at all; there is really nothing interesting about the table because it is normalized to 5NF given the available information (assuming there are no unstated non-trivial FDs, MVDs or JDs).
If A is a primary key, then it is also a superkey, but not a proper superkey.  Any of the attribute combinations with A and one or more of the other attributes is also a superkey, and is a proper superkey.
Comment: In the OP's question, it's given that A is the primary key of R.
Comment: If A is a primary key, then A ⟶ {B, C, D, E} by definition of what a primary key means.  However, the only FD given is A ⟶ B.  So, you might be right and then there's just the trivial FD A ⟶ {A,B,C,D,E} and there's no normalization needed.  But there's no interest in that hypothesis.
Comment: "Given that A ⟶ B, we can deduce that: {A,C,D,E} is the primary key of R." No, we can't. If you want to treat {A ⟶ B} as a cover, say so. Don't give "the only explicitly mentioned FD" or the asker's "with the FD A ⟶ B" meanings they don't have. But anyway this first part of the answer has nothing to do with the question, and is just an exercise in vaguely related reasoning that is only going to distract & possibly mislead the asker,  who needs to be disabused of "there is only one FD" & given the definition of "superkey".
Answer:
When considering a relation R(A,B,C,D,E) where A is the primary key
  and with the functional dependency A->B, can A be considered a super
  key to the relation since there is only one FD?

If it's given that A is the primary key of R, then by definition you have the FD A->BCDE. It also follows that

A->B
A->C
A->D
A->E

If A is a primary key of R, then it follows by definition that A is also a candidate key and a superkey of R.
Answer: Lets make it simple:
Here is a definition for Super,candidate and primary keys
Super Keys

Super key stands for superset of a key.
A Super Key is a set of one or more attributes that are taken collectively and can identify all other attributes uniquely.

Candidate Keys

Candidate Keys are super keys for which no proper subset is a super key.
In other words candidate keys are minimal super keys.

Primary Key:

It is a candidate key that is chosen by the database designer to identify entities with in an entity set.
Primary key is the minimal super keys. In the ER diagram primary key is represented by underlining the primary key attribute.
Ideally a primary key is composed of only a single attribute. But it is possible to have a primary key composed of more than one attribute.
Comment: "Super key stands for superset of a key." Begging the question of what "key" means. And  "key" is never defined. Define superkey correctly either via uniqueness or functionally determining all attributes. This answer has other problems also.

Superkey vs Primary Key


Firebase InstanceID Token Refresh delay on ios device

Question: I have implemented Firebase Cloud Messaging in my iOS application. Everything seems to work just fine, except one thing, the fact that it takes almost 10 seconds from the app to launch to get the device token refreshed in Firebase.
I have added this code to the application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions method in the App Delegate:
[FIRApp configure];

//Add an observer for handling a token refresh callback.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tokenRefreshCallback:) name:kFIRInstanceIDTokenRefreshNotification object:nil];

And this is the tokenRefreshCallback: method:
- (void)tokenRefreshCallback:(NSNotification *)notification {

    NSString *refreshedToken = [[FIRInstanceID instanceID] token];
    NSLog(@"InstanceID token: %@", refreshedToken);

    if ([[FIRInstanceID instanceID] token] != NULL) {
        [[FIRMessaging messaging] subscribeToTopic:@"/topics/news"];
        NSLog(@"Subscribed to news topic");
    }

    //Connect to FCM since connection may have failed when attempting before having a token
    [self connectToFirebase];

}

And this is the relevant part of logger:
2016-10-13 14:36:23.844 My-App[1111] <Debug> [Firebase/Core][I-COR000001] Configuring the default app.
2016-10-13 14:36:26.492 My-App[1111:2222222] InstanceID token: (null)
2016-10-13 14:36:32.732 My-App[1111:2222222] InstanceID token: c1kmaskdmj...(the actual device token)

Why is the tokenRefreshCallback: called when the InstanceID is (null)?
Why does it take almost 10 seconds before an actual token is retrieved?
Answer: In my case.  I had the same problem when using deeplinking to navigate between screens.
Without that all was working good.
this was working for me.  In  application didFinishLaunchingWithOptions I call  [self configureFirebase];
- (void)configureFirebase {
    [FIRApp configure];
    if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_9_x_Max) {
        UIUserNotificationType allNotificationTypes =
        (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
        UIUserNotificationSettings *settings =
        [UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    } else {
        // iOS 10 or later
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
        UNAuthorizationOptions authOptions =
        UNAuthorizationOptionAlert
        | UNAuthorizationOptionSound
        | UNAuthorizationOptionBadge;
        [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) {
        }];

        // For iOS 10 display notification (sent via APNS)
        [UNUserNotificationCenter currentNotificationCenter].delegate = self;
        // For iOS 10 data message (sent via FCM)
        [FIRMessaging messaging].remoteMessageDelegate = self;
#endif
    }

    [[UIApplication sharedApplication] registerForRemoteNotifications];
}

also I implement this messages:
// [START receive_message]
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    if (!(application.applicationState == UIApplicationStateActive)) {
        [AuthenticationController showAuthenticationViews:self.window];
    }
    [self readNotification:userInfo];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    [self readNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}
// [END receive_message]

// [START ios_10_message_handling]
// Receive displayed notifications for iOS 10 devices.
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
// Handle incoming notification messages while app is in the foreground.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    NSDictionary *userInfo = notification.request.content.userInfo;
    [self readNotification:userInfo];
    completionHandler(UNNotificationPresentationOptionNone);
}

// Handle notification messages after display notification is tapped by the user.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    NSDictionary *userInfo = response.notification.request.content.userInfo;
    [self readNotification:userInfo];
    completionHandler();
}
#endif
// [END ios_10_message_handling]

// [START ios_10_data_message_handling]
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
// Receive data message on iOS 10 devices while app is in the foreground.
- (void)applicationReceivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage {
    // Print full message
    //NSLog(@"%@", remoteMessage.appData);
}
#endif
// [END ios_10_data_message_handling]

// [START refresh_token]
- (void)tokenRefreshNotification:(NSNotification *)notification {
    // Note that this callback will be fired everytime a new token is generated, including the first
    // time. So if you need to retrieve the token as soon as it is available this is where that
    // should be done.
    //NSString *refreshedToken = [[FIRInstanceID instanceID] token];
    // NSLog(@"InstanceID token: %@", refreshedToken);

    // Connect to FCM since connection may have failed when attempted before having a token.
    [self connectToFcm];

    // TODO: If necessary send token to application server.
}
// [END refresh_token]

// [START connect_to_fcm]
- (void)connectToFcm {
    // Won't connect since there is no token
    if (![[FIRInstanceID instanceID] token]) {
        return;
    }

    // Disconnect previous FCM connection if it exists.
    [[FIRMessaging messaging] disconnect];
    [[FIRMessaging messaging] connectWithCompletion:^(NSError * _Nullable error) {
        if (error != nil) {
            // NSLog(@"Unable to connect to FCM. %@", error);
        } else {
            [[FIRMessaging messaging] subscribeToTopic:notificationTopic];
            //NSLog(@"Connected to FCM.");
        }
    }];
}
// [END connect_to_fcm]

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //  NSLog(@"Unable to register for remote notifications: %@", error);
}

// This function is added here only for debugging purposes, and can be removed if swizzling is enabled.
// If swizzling is disabled then this function must be implemented so that the APNs token can be paired to
// the InstanceID token.
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    // NSLog(@"APNs token retrieved: %@", deviceToken);

    // With swizzling disabled you must set the APNs token here.
    // [[FIRInstanceID instanceID] setAPNSToken:deviceToken type:FIRInstanceIDAPNSTokenTypeSandbox];
    BOOL automatic = [[[NSUserDefaults standardUserDefaults] objectForKey:@"automaticLogin"] boolValue];
    if (!automatic) {
        [[NSUserDefaults standardUserDefaults] setObject:@(YES) forKey:@"automaticLogin"];
        [self moveToInit];
    }
}

// [START connect_on_active]
- (void)applicationDidBecomeActive:(UIApplication *)application {
    [self connectToFcm];
}
// [END connect_on_active]

// [START disconnect_from_fcm]
- (void)applicationDidEnterBackground:(UIApplication *)application {
    [[FIRMessaging messaging] disconnect];
    // NSLog(@"Disconnected from FCM");
}
// [END disconnect_from_fcm]

#pragma mark - Process notifications

- (void)readNotification:(NSDictionary *)userInfo {
   //read your notification
}

-(void)readLaunchWithOptions:(NSDictionary*)launchOptions{
    if (launchOptions[notificationKey]) {
        [self readNotification:launchOptions[notificationKey]];
    }
}


Problem getting Params in injected controller Zend Framework

Question: I have a layout 'profile'

 $this->action(action1, controller1, module1)

 $this->layout()->content

 $this->action(someotheraction, soController,soModule );
</div

And the problem starts when I want to get the $request->Params() from the  action1 , controller1 module1 , it is empty.
I looked at the code of a helper Action , it does accept as a 4th parameter Params, but then I will have to set it somewhere in the layout - which is not good.
Basically what are the recommendations of guru people that are pretty professional with zend Framework. Maybe I should do some work around or should change the concept of how I am injecting additional Controller(module) actions
Comment: Can you please rephrase your question. The way it is phrased now it makes no sense to me and doesn't convey what you are trying to do.
Comment: yea I know I was doing what you asked while you were asking , cause it seem to me also very ambiguous
Comment: you might be missing an `echo` and I still don't get what are you are trying to do. What do you mean by getting the $request->params() from the action helper?
Comment: (echo yea for sure(+action(...)) "profile/photo/actionName" . Then I have a situation where I send "user_id" param in the /profile/profile/list/user_id/123 - This one I can get from $this->getRequest->getParam('user_id') in the profile controller (of profile module), but in the Photo Controller all I get is a empty erray when I dump $this->getRequest->getParams();
Answer: If you want to get the current Request object in the View, you can either inject it to the View from the controller or get it from the Front Controller via
$request = Zend_Controller_Front::getInstance()->getRequest();

The above is how the Action helper gets it itself.
Any argument, including $params, set to the action method of Action Helper will be set to the current Request object before it is dispatched. The Request will go through the entire dispatch cycle again, which is slow and why the Action Helper is generally avoided. The Action Helper will return (but not output) the body of the Response.
Not sure if that answers your question though.
Comment: Well , YES you have answered my question, Especially by providing the link , which lead me to the thought that using the Action Helper is not really good idea for certain means =)


Real-time baseball data?

Question: I want to make a display using arduino that shows "who's on first" etc at yankee stadium. So, I'm looking for a real-time feed with that info. What are my options?
Answer: Not sure you're going to find a "free" solution that is legitimately usable in the fashion you require and official/guaranteed to persist.
That said, MLB does publish an API, and has for years - it's just not something they guarantee.  It's their GamedayAPI.  I'm not sure how frequently it's updated, but I just peeked at the folder for 9/24/2015 ARIvsLAN and found that they were at least on the current inning compared to the live site, so it's obviously pretty up to date.
The most common commercial product is from Baseball Info Solutions, which provides data to sites like FanGraphs.

Real-time baseball data?


Product Reference inside a Product Reference?

Question: In my attempt to solve a "variation can update second variation" issue, I am wondering if a Product reference can go inside another Product Reference?
So that the 'Variation' itself has a product reference inline form to another type of variation? ( I have tried and nothing shows up).
The idea is that loading 1 variation will then load the referenced product variations therein and combine the 2 to create the final price.
(This is a case where the 2nd variations price is based on what is selected in the 1st variation.)
Comment: Are you trying for bundling several product together ?
Comment: no, i dont think so. Im trying a case where there are beds, and bed covers. So the beds have a size of Twin, Queen etc. And THEN the covers price should change when a different size bed is selected.
Answer: I figured this out by using taxonomy terms (categories in commerce kickstart), and then yes, indeed, make a product for each combination. (ive heard bulk product creation can do this, and incase you are dealing with a customer input size (how many inches long do you want it), then check out custom line items and Pricing rules.
Thread on drupal commerce > http://www.drupalcommerce.org/questions/7894/adjust-variation-price-based-next-variation#comment-7566


Mongodb db.serverStatus().storageEngine are not shown

Question: I'm using MongoDB of version 4.2.8
The storage engine is wiredTiger
I entered the db.serverStatus().wiredTiger to monitor cache usage, but storageEngine and wiredTiger field are not shown.
On the other hand, consist of standalone can see these field
Can't we check in shard cluster mode?
this is my shard server & config server config file
<code>systemLog:
  verbosity: 0
  traceAllExceptions: true
  path: "~~~~~"
  logAppend: false
  logRotate: "rename"
  destination: "file"
  timeStampFormat: "iso8601-utc"

net:
  port: 20001
  bindIp: "0.0.0.0"

storage:
  dbPath: "~~~~~~"
  journal:
    enabled: true
    commitIntervalMs: 100
  directoryPerDB: true
  engine: "wiredTiger"
  wiredTiger:
    engineConfig:
      cacheSizeGB: 1.0
    collectionConfig:
      blockCompressor: "snappy"
    indexConfig:
      prefixCompression: true

security:
  keyFile: "~~~~~"

sharding:
  clusterRole: "configsvr"

replication:
  replSetName: "config-server"
</code>

<code>    systemLog:
      verbosity: 0
      traceAllExceptions: true
      path: "~~~~~~"
      logAppend: false
      logRotate: "rename"
      destination: "file"
      timeStampFormat: "iso8601-utc"

    net:
      port: 20002
      bindIp: "0.0.0.0"

    storage:
      dbPath: "~~~~"
      journal:
        enabled: true
        commitIntervalMs: 100
      directoryPerDB: true
      engine: "wiredTiger"
      wiredTiger:
        engineConfig:
          cacheSizeGB: 10.0
        collectionConfig:
          blockCompressor: "snappy"
        indexConfig:
          prefixCompression: true

    security:
      keyFile: "~~~~~"

    sharding:
      clusterRole: "shardsvr"

    replication:

  replSetName: "shard1-server"
</code>
Answer: mongos does not store any data itself, this is probably why it doesn't report a storage engine.
I don't know if you can have different storage engines in different shards, seems theoretically possible to me.
You could use https://docs.mongodb.com/manual/reference/command/listShards/ to identify the shards and query each of them for their storage engines.
Comment: I know mongos don't have the data.
If so, connect to mongod --port {port} and db.serverStatus() command show the field?
Comment: i solve this problem.

can connect through data mongo server  without listening through mongos


Non-significant Multiple Regression Coefficients to significant journey

Question: I am teaching my students Multiple linear regression.I loaded a dataset and fit multiple regression to it using SPSS.
I got non-significant regression coefficients with some negative and positive values.
Now a student asked me how can one manipulate the variable(s) corresponding to the specific non significant regression coefficient so that we have significant result?
My Intuition
Significant regression coefficient means that by changing value of that variable and keeping the rest constant it show it has significant effect on the output variable.But I do not know how that variable manipulation can change significance of the corresponding regression coefficient?
Comment: You're asking how to do significance-hunting (data dredging)?
Comment: @Glen_b  yes please tell me if you have any suggestion here....do u have some magic say as to how to manipulate those variables so to get significant regression coefficients?................
Answer: You can divide the explanatory variable by its non-significant coefficient to get a perfect fit.


Planar graph constructed from the edges of another planar graph

Question: Let $G$ be a planar graph. We construct a graph $H$ from $G$ in the following manner :

The vertices of $H$ are interior points of the edges of $G$, one on each edge.
Two vertices of $H$ are joined by an edge if and only if the two edges of $G$ corresponding to them have a common vertex in $G$ and are incident to the same face of $G$.

It's easy to see that $H$ is planar.
So for instance, if $G$ is the complete graph on 4 vertices, then $H$ will be a hexagram ("star of david") whose six vertices are joined in a cycle (I hope you get the picture).
Does this construction have a name ? I have some difficulty finding more information about this without a name.
And is $H$ independent of the plane embedding of $G$ used ? I think yes, but I'm not sure.
Context : this construction is used in a proof of Steinitz's theorem.
Comment: $H$ is not planar in all cases, e.g any graph $G$ with $\Delta >= 5$, $H$ won't be planar, are you sure you get definition correctly? would you show your reference?
Comment: @Saeed It is true that $H$ is not planar in all cases. However not every graph with $\Delta \geq 5$ is a counterexample. Let $G$ be a wheel with an arbitrary number of spokes. Then $H$ will be planar.
Comment: @Oliver, $H$ for wheel with an arbitrary number of spokes, is not planar. Assume you have star with $n\ge 5$ leaf, then $H$ is $K_n$ graph, and for $n\ge 5$, $H$ wont be a planar, Also your wheel contains such a star as subgraph, so $H$ for wheel contains $K_n$ as subgraph, so it's not planar.
Comment: @Saeed, no the graph is planar. "Two vertices of $H$ are joined by an edge if and only if the two edges of $G$ corresponding to them have a common vertex in $G$ *and are incident to the same face of $G$*. With the star, all the leaves are on the same face, but with the wheel each face is a triangle (well not the infinite face), so $H$ will have no cliques of size $\geq 3$.
Comment: @Oliver you are right I missed the part "same face of $G$".
Answer: I don't know a name for this construction. I suspect that there isn't a standard name, as the construction does in fact depend on the plane embedding.
Let $G$ be a triangle with two pendant edges attached to the same vertex. There are two distinct plane embeddings of $G$: either we put both pendant edges inside the triangle, or we put one inside and one outside. When we construct $H$ for the first embedding, we find it contains an induced $K_4$, but when we construct $H$ for the second embedding, we find that it does not.
Further $H$ won't always be planar. For example consider the previous example with more than 2 pendant edges inside the triangle.
The more general construction is that of line graphs, which require no planarity hypothesis and have lots of nice properties.
Comment: Thank you for your answer. The construction I described in my question seems to be called the "medial graph", according to the Wikipedia article you linked.


using EntityFieldQuery, how to order results based on a node reference field title and/or field collection item field, says name

Question: I have a node which references another, I want to order the results based on the title of the referenced field title.
I'm using
function listAll(){
  $query = new EntityFieldQuery();
  $entities = $query->entityCondition('entity_type', 'node')
                    ->entityCondition('bundle', 'building')
                    ->fieldOrderBy('field_reference_area', 'title', 'ASC')
                    ->execute();

  $nodes = entity_load('node', array_keys($entities['node']));

  foreach($nodes as $key => $fac){
      dsm($fac);
  }
}

Comment: so basically you need to use join to achieve this.
Answer: I'm afraid this won't be possible using EntityFieldQuery. You could build your own query using db_select() and have full control over it.
You can refer to this post and try to adapt it to fit your needs.
Comment: thxs !, it seems you are right
Answer: You can use join using something like

 $query = new EntityFieldQuery();
  $entities = $query->entityCondition('entity_type', 'node')
                    ->entityCondition('bundle', 'building')
                    ->fieldOrderBy('field_reference_area', 'title', 'ASC')
 ->addTag('JOINTABLE');
  ->execute();

And now use this tag to join another table

function MYDMOULE_query_JOINTABLE_alter(QueryAlterableInterface $query) {
  $query->join('reference_table', 'r', 'r.nid = node.field_referencefield_value');
}

This is just a sample example. Try to modified it with your need. :)


Decay of the Fourier Transform of non-integrable functions.

Question: An integrable function generally means an $L^1$ function. If we stick to functions from $\mathbb{R}\to\mathbb{C}$, then $f$ is integrable means that
$$
\|f\|_1 = \int\limits_\mathbb{R} |f(t)|dt < \infty.
$$
In this case the Fourier transform of $f$ which we denote by $F$ is well defined as an integral and we have the standard inequality (for $\xi\in\mathbb{R}$),
$$
|F(\xi)| \leq \|f\|_1.
$$
If $f$ takes on positive values, then I expect we can modify the proof of the Rieman-Lebesgue lemma to show that
$$
|F(\xi)| \leq \frac{\|f\|_1}{|\xi|}
$$
for $|\xi| \gg 0$.
My Question is whether analogous bounds exist if we assume just that
$$
\int\limits_\mathbb{R} f(t) dt < \infty
$$
and not necessarily that $f\in L^1(\mathbb{R})$.
Thank you.
Comment: "Assume just that $\int f<\infty$" is very unclear: If $f\notin L^1$ then what is $\int f$ in the first place? Doesn't matter since the preliminary result that you "expect" you can prove is false...
Answer: The result you want to extend to the case $f\not\ge0$ is already false for $f>0$:

There exists $f\in L^1(\Bbb R)$ with $f>0$ such that $\hat f(\xi)\ne O\left(\frac1{|\xi|}\right).$

I "knew" immediately that $f>0$ could not give that bound on $\hat f$, but I thought the counterexample might be tricky. No, we can do this with no work at all:
Say $f>0$, $\int f<\infty$, $\int f^2=\infty$. Since $\hat f$ is continuous, if we had $\hat f(\xi)=O\left(\frac1{|\xi|}\right)$ it would follow that $\hat f\in L^2$, hence $f\in L^2$, contradiction.
Comment: Yes, if you want simple examples that decay at any chosen rate $a\in(0,1)$, you can take $f(x) = \frac{1}{|x|^{1-a}} \,\varphi(x)$ with $\varphi\in C^\infty_c$ nonnegative. Then
$$
\widehat f = \frac{c}{|x|^{a}} * \widehat\varphi \underset{x\to \infty}{∼} \frac{c}{|x|^{a}}
$$


When a UIControl is Hidden does it lose its Functionality

Question: If we hide a control with Control.Hide(); in C# (win-forms) does the Control lose its Functionality, in that way that Control's Stop's its Execution like if we Have an MP3 Player Control and if we Hide it does it Stop Sounding, or if we Populate Data in a DataGridView than if we Play with it's Visibility does  GridView clear it's Data .
If the Control does lose ,what can i do to prevent it and if anyone knows why?
PS: Where is e Difference between Control.Visible = false; and Control.Hide();
Answer: The control will not lose its functionality. It is still an object in memory and if you call any method on it, it will execute. Hiding it simply means it does not display on a form anymore.
In your example, hiding a control will not automatically stop the sound, unless that is built into the hide function.
As for you PS - from MSDN, Control.Hide Method:

Hiding the control is equivalent to setting the Visible property to false. After the Hide method is called, the Visible property returns a value of false until the Show method is called.


NIC Active/Passive bonding with priority

Question: I will configure a bond of three NIC's. I want to define which one will be first used and which NIC will be used as the second and third NIC when failover is done. Is this possible?
Thanks
Answer: The bonding mode for the is active-backup mode and to specify a preferred interface you use the primary keyword specifying the preferred interface:
<code>BONDING_OPTS="mode=1 miimon=100 primary=eth0"
</code>
So in this example you want it to always be eth0 if it is available.

primary
      A string (eth0, eth2, etc) specifying which slave is the primary
  device. The specified device will
  always be the active slave while it is
  available. Only when the primary is
  off-line will alternate devices be
  used. This is useful when one slave is
  preferred over another, e.g., when one
  slave has higher throughput than
  another. The primary option is only
  valid for active-backup mode.

The documentation for Linux bonding is actually quite thorough. I highly recommend reading at least the more relevant parts.
Comment: Oh I missed the 3 NIC requirement.  I am not aware of a way to specify more than one preferred nic. This makes me curious as to why the 3 are being use and why the 3 way priority matters....
Comment: Two are in a 1 Gb switch, one in a 100 Mb switch which only should be used when the 1 Gb switch (or the two interfaces in the 1 Gb switch) fails.
Comment: Option "secondary=eth1" does not work (unknown parameter). I also could not find any other doc. Someone tried this?

In ESXi, I can define the order of failover for more than two interfaces. Can I do this in Red Hat also?

Thanks.
Answer: NIC Bonding set up try may help you what your looking at