502 Bad Gateway Nginx

Question: Edited: This error only occurs when I'm using Chrome. If I switch to Safari or FireFox, my server code works OK.
Here's the error log. Please help. I'm playing with the Google OAuth 2.0 API and there's something wrong after Google calls my server back.
Let me know if you need more information to diagnose. (I'm a super newbie so I've no idea what to paste here...)
Besides, 114.247.XXX.YYY is my local office IP, with which I'm browsing websites and accessing remote servers.
<code>2012/06/28 09:54:08 [error] 2170#0: *21 upstream sent too big header
while reading response header from upstream, client: **114.247.XXX.YYY**,
server: my_domain_name.com, request: "GET
/login-callback/google?state=my_randomly_generated_state&code=my_google_authorization_code
HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "my_domain_name.com"
</code>
Comment: Try to catch raw http data with tcpdump and find out which headers are too big.
Comment: You can fix it by adjusting the *proxy* values, like [this page](http://www.howtoforge.com/nginx-upstream-sent-too-big-header-while-reading-response-header-from-upstream)
Answer: Ok, i' had this problem too, but in every browser.
Validate if you are not listen a socket.
nano /etc/php5/fpm/pool.d/www.conf
The solution for me was:
<code>$ sudo nano /etc/nginx/sites-available/default

server {
[...]
location ~ \.php$ {
  root /your/site/root;
  fastcgi_index index.php;
  include fastcgi_params;
  fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

  fastcgi_pass 127.0.0.1:9000;
  #IF you are using a socket change the line above for thise one:
  #fastcgi_pass    unix:/var/run/php5-fpm.sock;

  ###to be sure validate on /etc/php5/fpm/pool.d/www.conf
  ####listen = 127.0.0.1:9000 #not a socket
  ####listen = /var/run/php5-fpm.sock #listen a socket

  # add these two lines:
  fastcgi_buffer_size 16k;
  fastcgi_buffers 4 16k;
}
[...]
}
$sudo service nginx restart
</code>
Source: click here
Answer: change the localhost with your VPS IP. Worked for me

502 Bad Gateway Nginx


How to find standard deviation when sample size changes in R

Question: How do you find the standard deviation for tails in R, when the sample size changes from n=100 to n=50 when tossing a coin?
Answer: The standard deviation of $X \sim\mathsf{Binom}(n,p)$ is $\sigma_X = \sqrt{np(1-p)}.$ So when $n$ is halved, the standard deviation is divided by$\sqrt{2}.$
For example, with $p=1/2,$ the SD decreases from $5$ to $3.535534$ when $n$ decreases from $100$ to $50.$
sqrt(100/4)
[1] 5
sqrt(50/4)
[1] 3.535534

A simulation in R, with a million iterations, accurate to two decimal places:
set.seed(2021)
sd(rbinom(10^6, 100, 1/2))
[1] 5.002196
sd(rbinom(10^6, 50, 1/2))
[1] 3.533623


Give user admin rights on a single server

Question: Is it possible to give a Windows Domain User account administrator rights on a single server? We have a vendor installing software and they are requiring domain administrator access to the machine.
Comment: @Hennes: you typically need admin rights to do the installation, unless the application is only going to run when a particular user is logged on, which is unlikely for server software.
Comment: `"and they are requiring domain administrator access to the machine"` - I assume that's a typo and the word "domain" should not be in there?
Comment: The answer has already been given and accepted. Still, shouldn't the ideal answer be 'kick the form which produced the software and tell them to come out of the stone ages?'. Most properly coded software does not need admin rights.  /petpeeve.
Comment: I agree. *During installation*.  The server administrator installs the software (after logging in with an account with admin priveleges). But the regular user account should not need it just to use the software.  And yes, I know that this often fails to work. E.g. when software opens the registry without specifying that it want to READ (the default is RW).
Comment: @Hennes: certainly, but what does that have to do with this question?  The people asking for admin access were installing the software, not using it.
Comment: If you want to give a single domain user admin rights so that that domain user can install the software then yes. You are correct.  If you have a vendor stating that they need [domain] admin rights just to use a program (which is the way I read it) then things are different.
Comment: @Hennes: the OP specifically described the situation as a "vendor installing software" not as a "vendor using software".  I interpret that as meaning that the vendor sent a technician to do the software installation, and said technician needed admin access.  YMMV.
Comment: All to often, developers write their code on a PC with the full development product suite installed (e.g.: Visual Studio with all options, and all .NET versions), and write their code signed in as a local admin.  They then try to pass their shoddy security model off as "this is how it has to be".  Sat through numerous face-to-face and teleconference sessions with external developers explaining (for example) that the IUSR_xxxxxxx user cannot be a local admin.  Like Hennes said, stone ages.  Developers should focus a little less on function, and a little more on security.
Answer: If it's a member server, you can add them to local administrator group:

(2003) http://technet.microsoft.com/en-us/library/cc739265%28v=WS.10%29.aspx
(2008) http://technet.microsoft.com/en-us/library/cc772524.aspx

This won't work if it's a domain controller though -- there are no local accounts. You'd need to run the installer as a different user or temporarily elevate their account.
Answer: Yes, add them to the local administrators group on the server. You can do this from the command-lind as follows:
net localgroup administrators /add domain\user
You can also do this from the Users and Groups MMC snap-in.


django haystack not returning results according to expectations

Question: I have configured Django haystack with Elasticsearch Search Engine using QueuedSignalProcessor with redis Queue backend. Everything working except now I have some issue. I have two objects in db whose title is code fixes and code fixess (with extra s at end). I need to perform partial search. When I search for code fix it return the object with title code fixes but it is not returning object with title code fixess:
my_model = SearchQuerySet().models(MyModel)
objects = my_model.filter(content__contains=q) # q = "code fix"

indexes file:
from haystack import indexes
from myapp.models import MyModel

class MyModelIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    title = indexes.CharField(model_attr="title")

index template:
{{ object.title }}
{{ object.description }}

P.S the index is updated. As if I search for fixess it shows the second object with title code fixess but not first in this case. If I search for just code it returns both.
What would be the reason?
Answer: The reason is because Haystack is configured to use the Snowball analyzer
This looks for known (English) word endings, such as the es in fixes and storing the stem word (fix) in the index instead of the exact word, allowing a kind of fuzzy matching.
I presume the Snowball analyzer does not recognise the ess from fixess as an ending, hence it doesn't prune the word down to a stem.
ElasticSearch actually provides many other analyzers, and also allows you define a custom analyzer from the building blocks of tokenizers + filters. Mis-spellings in the source data is maybe a tricky one to deal with though... you may need to try a phonetic ('sounds like') approach:
https://github.com/elasticsearch/elasticsearch-analysis-phonetic
Finally, try this project which makes it easier to customise the ElasticSearch config that Haystack uses:
https://github.com/bennylope/elasticstack


Validation error on back button in Multistep Form

Question: Validation errors with a back button on Multistep form.
I used form alter for this but this is also not working below are my code.
function mymodule_form_alter(&$form, &$form_state, $form_id)
{ if($form_id=='dataset_node_form')
{
 $form['actions']['previous']['#submit'][] = array();
 $form['actions']['previous']['#limit_validation_errors']=array();
}
}

Comment: Please describe what exactly is happening and show us some code.
Comment: I am using multistep form with four step i.e(step1,step2,step3--) on step2 there are some required fields so if i go to step2 and wants to come in step1 with out filling required field of step2 then it always shows validation error and do not go to step1 from step2.
Comment: I used form alter for this but this is also not working below are my code.function mymodule_form_alter(&$form, &$form_state, $form_id){
    if($form_id=='dataset_node_form'){
       $form['actions']['previous']['#submit'][] = array();
       $form['actions']['previous']['#limit_validation_errors']=array();
    }
  }
Answer: Enable devel module. Then put a dpm to make sure that your code is being called.
function mymodule_form_alter(&$form, &$form_state, $form_id){   if($form_id=='dataset_node_form')
{
 dpm($form, 'From my custom module');
 $form['actions']['previous']['#submit'][] = array();
 $form['actions']['previous']['#limit_validation_errors']=array();
}
}

If your message shows up then some other module is overriding your form_alter. You can implement hook_module_implements_alter in your custom module to make sure that the form_alter of your module is called last.
Comment: after using hook_module_implements_alter() it is not working.
Comment: Is there any options for creating multistep form?


Deriving the age process CDF from a renewal process

Question: My question is whether I correctly derived the CDF of the steady-state age process. For context on why I' am asking this question is problem 6.1(a) from Introduction to Stochastic Processes by Lawler which I' am reading on my own. Here is the problem:
$\textbf{6.1}$ Suppose the lifetime of a component $T_i$ in hours is uniformly distributed on [100,200]. Components are replaced as soon as one fails and assume that this process has been going on long enough to reach equilibrium.
$\textbf{(a)}$ What is the probability that the current component has been in operation for at least 50 hours?
Here is what I think the answer should be in order to answer the question. The distribution function of $T_i$ is,
$$F(t)=\frac{t-100}{100}$$
Then according the Lawler, the distribution function of the steady-state age distribution is
\begin{align}
\psi_A(x)&=\lim_{t\rightarrow \infty}P(A_t\leq x) \\
&=\frac{1}{\mu}\int_{0}^{x}[1-F(s)]ds \\
&=\frac{1}{150}\int_{0}^{x}\left[1-\frac{s-100}{100}\right]ds \\
&=\frac{1}{150}[2s\Big|_0^{x}-\frac{s^2}{200}\Big|_0^{x}] \\
&=\frac{1}{150}[2x-\frac{x^2}{200}]
\end{align}
The answer to the question would be $P(A\geq 50)=1-P(A\leq 50)=0.416$. But I do not think I derived the correct CDF for the age process. I say this because I would expect $\psi_A(200)=1$ because the maximum age is 200, however, using my derivation from above $\psi_A(200)=1.333$.
Answer: Since $T_i \sim \mathcal{U}[100,200]$ then the
corresponding CDF is
$$ F(t) = \begin{cases} 0 & \mbox{ if } t<100 \\ \frac{t-100}{100} & \mbox{ if } t \in [100,200] \\ 1 & \mbox{ if } t >200\end{cases}.$$
Therefore, the steady-state age distribution is
$$ \psi_A(x) = \lim_{t \to \infty} P(A_t \leq x) = \frac{1}{\mu}\int_0^x (1-F(s))\mathrm{d}s= \begin{cases}\frac{x}{\mu} & \mbox{if } 0\leq x<100 \\ \frac{1}{\mu}\left(100 + \int_{100}^x\left(1-\frac{t-100}{100}\right) \mathrm{d}t \right) & \mbox{if } 100 \leq x< 200 \\ 1 & \mbox{if }  x\geq 200\end{cases}. $$
Now you should be able to find your answer.


Removing event attributes from tags

Question: I need a clean and simple script that can find and remove all event attributes from all html tags in a string. The "on..." attributes that is - onclick, onkeyup etc.
EDIT: Here's how they do it in Kohana:
$string = preg_replace('#(<[^>]+?[\x00-\x20"\'])(?:on|xmlns)[^>]*+>#iu', '$1>', $string);

EDIT: Here's how they do it in CodeIgniter:
$string = preg_replace("#<([^><]+?)([^a-z_\-]on\w*|xmlns)(\s*=\s*[^><]*)([><]*)#i", "<\\1\\4", $string);

Comment: You're not concerned about event listeners that have been added programmatically?
Comment: Not concerned about that in the current context.
Answer:
The function takes 4 parameters.

$msg. The text you want to strip attributes from.
$tag. The tag you want to strip attributes from (p, for instance).
$attr. An array with the name of the attributes you want to strip (leaving the rest intact). If the array is empty, the function will strip all attributes.
$suffix. An optional text to append to the tag. It may be a new attribute, for instance.

Taken from Stripping Tag Attributes from HTML code where the author posts the code, I omitted it from my answer since it was lengthy and did not want to claim ownership of the code.
Hope this is what you are looking for.
Answer: You could do something on this line:
<?php

$html = '

    Lorem ipsum dolor sit amet, consectetur adipisicing elit,
    sed do eiusmod tempor incididunt ut labore
    et dolore magna aliqua.
    t enim ad minim veniam.

';

$doc = new DOMDocument;
$doc->loadHTML($html);

echo "Before:\n" . $doc->saveHTML() . "\n";

foreach($doc->getElementsByTagName('*') as $node){
    $remove = array();
    foreach($node->attributes as $attributeName => $attribute){
        if( substr($attributeName, 0, 2)=='on' ){
            $remove[] = $attributeName;
        }
    }
    foreach($remove as $i){
        $node->removeAttribute($i);
    }
}

echo "After:\n" . $doc->saveHTML() . "\n";

?>

This is a just an idea. It needs some tweaking because it adds tags to convert the HTML fragment in a full document but you can use it as a starting point.

Removing event attributes from tags


Two objects sharing one random script spawn the same order when they should spawn different orders

Question: I have two "customer" objects that share an Order Manager script in Unity. Ideally, every time a customer needs to create a new order, it should be different than the last one. What happens instead is that customer 1 orders X and Y, and then customer 2 will order X and Y instead of Z (or whichever different combination). When the script is placed on just one customer instead of 2, the random order function works correctly. There are no static variables.
To add, if I clear customer 1's order, the next order is different. Customer 2's orders will still follow customr 1. Ex:
Customer 1 has 2 orders: X X, then Y Y
Customer 2 won't start at the second order, it will order the same way: X X, then Y Y
This is the method that's causing an issue:
<code>   IEnumerator CustomerOrder(bool status, float delayTime)
{
  yield return new WaitForSeconds(delayTime);//delay between orders
 imageOffset.y = -0.75f;//space between order visuals
 numberOfOrderItems = rnd.Next(1, maxOrderNumber + 1);//between 1 and 3 items per order
 customerOrder = new GameObject[numberOfOrderItems];// order collection
 Instantiate(orderBackgrounds[numberOfOrderItems - 1], orderVisual.transform);//Spawn correct background for number of items
 for (int x = 0; x < numberOfOrderItems; x++)
 {
     int y = rnd.Next(products.Length);//choose a random number representing an index in the products array
     customerOrder[x] = Instantiate(productImages[y],
     orderVisual.transform.position + imageOffset,
     Quaternion.identity,
     orderVisual.transform);//spawn a visual representation of the order
     imageOffset.y += -0.95f;//places next order visual lower
 }

 makingOrder = false;//we've finished making the order
}
</code>
Answer: I feel really silly. I was able to fix this issue by adding one line to the beginning of the method:
rnd = new System.Random();
I'm not certain if this is really the best way, but it seems to work.


Algorithm time complexity

Question: Supposing I have an insertion-sort algorithm with a cost function $8n^2$ and a merge-sort algorithm with a cost function $64n\log_2n$, for which n values is better to execute the insertion-sort?
I've tried doing $8n^2<64n\log_2n$ and found $2<n^{\frac{8}{n}}$ but I can't seem to find a way to properly isolate n. Is this result satisfactory?
Answer: Use standard Calculus methods to sketch a graph of $f(n) = n^{8/n}$.
$$  f'(n) = -8n^{-2 + 8/n}(\ln(n) -1)  $$
We find a critical point at $n = \mathrm{e}$, so expect a maximum at $n = 2$ or $n = 3$.  Further, $f$ is monotonically increasing on $(0,\mathrm{e})$ and monotonically decreasing on $(\mathrm{e},\infty)$.  Also,
$$  \lim_{n \rightarrow \infty} f(n) = 1  \text{,}  $$
so $f$ is initially less than $2$, is greater than $2$ on an interval, then is forever after less than $2$.
We should explicitly check $n = 1, 2, 3$:
\begin{align*}
f(1) &= 1^{8/1} = 1  \text{,}  \\
f(2) &= 2^{8/2} = 16 \text{, and}  \\
f(3) &= 3^{8/3} = 18.720{\dots}  \text{.}
\end{align*}
So restricting $f$ to the positive integers, it has a maximum at $n = 3$.  It then decreases.  We perform (initially) unbounded binary search to find where $f$ decreases through $2$.
\begin{align*}
f(6) &= 10.90{\dots}  \text{,}  \\
f(12) &= 5.24{\dots}  \text{,}  \\
f(24) &= 2.88{\dots}  \text{,}  \\
f(48) &= 1.90{\dots}  \text{,}  \\
f(36) &= 2.21{\dots}  \text{,}  \\
f(42) &= 2.03{\dots}  \text{,}  \\
f(45) &= 1.96{\dots}  \text{,}  \\
f(43) &= 2.01{\dots}  \text{, and}  \\
f(44) &= 1.98{\dots}  \text{.}
\end{align*}
We find that $f(n) > 2$ for $2 \leq n \leq 43$.
Comment: Instead of exponentiating to get the final inequality, we can stop when at $$n < 8 \log_2 n,$$ which is a bit easier to work with. I decided not to make it a separate answer, though, since the technique ends up being about the same.
Comment: I will add that $n < 8 \log_2 n$ strongly suggests probing using powers of 2, rather than strict bisection. It's clear that $n=2$ works and $n=2^8=256$ does not. From there, trying $n=2^7, 2^6, 2^5$, etc., you quickly find that it's between $32$ and $64$. From there, proper bisection can take over.

Algorithm time complexity


Having an icon in an TextInput in react-native

Question: I want to have an icon inside my TextInput in react native. This is my custom input I created. How can I have an icon in the left corner inside my TextInput?
<code>import React from "react";
import { TextInput, StyleSheet } from "react-native";

const defaultInput = props => (
  <TextInput
    {...props}
    style={[
      styles.input,
      props.style,
      !props.valid && props.touched ? props.invalidInput : null
    ]}
  />
);

const styles = StyleSheet.create({
  input: {
    width: "100%",
    borderColor: "#eee",
    padding: 5,
    marginTop: 8,
    marginBottom: 8
  }
});

export default defaultInput;
</code>
Comment: Possible duplicate of [How can I put an icon inside a TextInput in React Native?](https://stackoverflow.com/questions/40935381/how-can-i-put-an-icon-inside-a-textinput-in-react-native)
Answer: If you need this only in android platform you can easily use inlineImageLeft prop of TextInput in react-native.


Knex.JS Auto Update Trigger

Question: I am using Knex.JS migration tools. However, when creating a table, I'd like to have a column named updated_at that is automatically updated when a record is updated in the database.
For example, here is a table:
knex.schema.createTable('table_name', function(table) {
    table.increments();
    table.string('name');
    table.timestamp("created_at").defaultTo(knex.fn.now());
    table.timestamp("updated_at").defaultTo(knex.fn.now());
    table.timestamp("deleted_at");
})

The created_at and updated_at column defaults to the time the record is created, which is fine. But, when that record is updated, I'd like the updated_at column to show the new time that it was updated at automatically.
I'd prefer not to write in raw postgres.
Thanks!
Answer: With Postgres, you'll need a trigger. Here's a method I've used successfully.
Add a function
If you have multiple migration files in a set order, you might need to artificially change the datestamp in the filename to get this to run first (or just add it to your first migration file). If you can't roll back, you might need to do this step manually via psql. However, for new projects:
const ON_UPDATE_TIMESTAMP_FUNCTION = `
  CREATE OR REPLACE FUNCTION on_update_timestamp()
  RETURNS trigger AS $$
  BEGIN
    NEW.updated_at = now();
    RETURN NEW;
  END;
$$ language 'plpgsql';
`

const DROP_ON_UPDATE_TIMESTAMP_FUNCTION = `DROP FUNCTION on_update_timestamp`

exports.up = knex => knex.raw(ON_UPDATE_TIMESTAMP_FUNCTION)
exports.down = knex => knex.raw(DROP_ON_UPDATE_TIMESTAMP_FUNCTION)

Now the function should be available to all subsequent migrations.
Define a knex.raw trigger helper
I find it more expressive not to repeat large chunks of SQL in migration files if I can avoid it. I've used knexfile.js here but if you don't like to complicate that, you could define it wherever.
module.exports = {
  development: {
    // ...
  },

  production: {
    // ...
  },

  onUpdateTrigger: table => `
    CREATE TRIGGER ${table}_updated_at
    BEFORE UPDATE ON ${table}
    FOR EACH ROW
    EXECUTE PROCEDURE on_update_timestamp();
  `
}

Use the helper
Finally, we can fairly conveniently define auto-updating triggers:
const { onUpdateTrigger } = require('../knexfile')

exports.up = knex =>
  knex.schema.createTable('posts', t => {
    t.increments()
    t.string('title')
    t.string('body')
    t.timestamps(true, true)
  })
    .then(() => knex.raw(onUpdateTrigger('posts')))

exports.down = knex => knex.schema.dropTable('posts')

Note that dropping the table is enough to get rid of the trigger: we don't need an explicit DROP TRIGGER.
This all might seem like a lot of work, but it's pretty "set-and-forget" once you've done it and handy if you want to avoid using an ORM.
Comment: awesome answer!
Comment: Not only does it work, great example on how to add functions to postgres. Thanks!
Comment: This is a fantastic solution and boy is it clean. Thanks, Rich!
Comment: Great solution! I added `WHEN (OLD.* IS DISTINCT FROM NEW.*)` to my `onUpdateTrigger` to prevent updates from triggering when nothing actually changed. This example is taken from [here](https://www.postgresql.org/docs/9.1/sql-createtrigger.html).
Comment: Working with knex 2.x, for multiple tables you chain `then`....
    .then(() => knex.raw(knexfile.default.onUpdateTrigger('users'))
        .then(() => knex.raw(knexfile.default.onUpdateTrigger('invoices'))
Comment: Excellent answer. Is it required to write method `onUpdateTrigger ` on knexfile?
Comment: No, it essentially just returns a string so you could put it anywhere you like. I just find it easier to store such things with (or near) `knexfile.js`.
Comment: Why do you need to to change the time stamp or put it in the first migration, is this just so you can use it in subsequent migrations? If you only want to use it in future migrations would it be fine to have it within a migration sequence, or is there something specific about it that means it goes first?
Comment: Yes, it's so the function exists when you go to use it in subsequent migrations. If you don't need it for tables that already exist in your schema, there would be no need to worry about this.
Comment: Oh good call. I wrote this years ago, when I barely knew what `NEW` was! I'll update.
Answer: You can create a knex migration using timestamps:
exports.up = (knex, Promise) => {
  return Promise.all([
    knex.schema.createTable('table_name', (table) => {
      table.increments();
      table.string('name');
      table.timestamps(false, true);
      table.timestamp('deleted_at').defaultTo(knex.fn.now());
    })
  ]);
};

exports.down = (knex, Promise) => {
  return Promise.all([
    knex.schema.dropTableIfExists('table_name')
  ]);
};

With timestamps a database schema will be created which adds a created_at and updated_at column, each containing an initial timestamp.
To keep the updated_at column current, you'll need knex.raw:
table.timestamp('updated_at').defaultTo(knex.raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));

To skip the knex.raw solution, I suggest using a high level ORM like Objection.js. With Objection.js you could implement your own BaseModel which then updates the updated_at column:
Something.js
const BaseModel = require('./BaseModel');

class Something extends BaseModel {
  constructor() {
    super();
  }

  static get tableName() {
    return 'table_name';
  }
}

module.exports = Something;

BaseModel
const knexfile = require('../../knexfile');
const knex = require('knex')(knexfile.development);
const Model = require('objection').Model;

class BaseModel extends Model {
  $beforeUpdate() {
    this.updated_at = knex.fn.now();
  }
}

module.exports = BaseModel;

Source: http://vincit.github.io/objection.js/#timestamps
Comment: Upvote for Objection.js. Really nice ORM for node.js
Comment: Probably a bit late to the party, but shouldn't the line of the first script: `table.timestamp('deleted_at').defaultTo(knex.fn.now());` read `table.timestamp('deleted_at').defaultTo(null);` instead? As it stands, you seem to be setting the `deleted_at` to current timestamp by default.
Answer: This is my way of doing that in Mysql 5.6+
The reason I didn't use table.timestamps is because I use DATETIME instead of timestamp.
table.dateTime('created_on')
        .notNullable()
        .defaultTo(knex.raw('CURRENT_TIMESTAMP'))

table.dateTime('updated_on')
        .notNullable()
        .defaultTo(knex.raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'))

Comment: This is the best and the easiest workaround. Knex has `table.timestamps(true, true)`, but it doesn't work as expected, i.e. for update.
Answer: This is not a feature of Knex. Knex only creates the columns, but does not keep them up to date for you.
If you use, the Bookshelf ORM, however, you can specify that a table has timestamps, and it will set & update the columns as expected:

Bookshelf docs
Github issue
Answer: exports.up = (knex) => {
return knex.raw(create or replace function  table_name_update() RETURNS trigger AS $$ begin new.updated_at = now(); RETURN NEW; end; $$ language 'plpgsql'; create or replace trigger tg_table_name_update on table_name  before update for each row execute table_name_update();)
};
exports.down = (knex) => {
return knex.raw(drop table if exists table_name; drop function if exists table_name_update;)
};
Comment: This is the content of the migration file. Sorry for the format. I am on mobile.
Answer: You can directly use this function
table.timestamps()

This will create the 'created_at' and 'updated_at' columns by default and update them accordingly
https://knexjs.org/#Schema-timestamps
Comment: Even if `table.timestamps(false, true);` is used, it does not update the `updated_at` column.
Comment: `table.timestamps()` needs to be turned into `table.timestamps(false, true);` to guarantee that the current timestamp is used when no data is given.

Knex.JS Auto Update Trigger


Find all parent id's in array in C

Question: I have  to find all parents, for example i search all PID and PPID with id 10.
If PID has id, for example let's take 10,  I print printf("%d %d", PID[i], PPID[i]) and it's done.
Problem is if PPID has id 10, then I also print it (printf("%d %d",PID[j],PPID[j])), but now I also have to find all PID and PPID with new id PID[J]. example PPID with id 10 is at index 3 , i print (PID[3] , PPID[3]) and also on index 7 . PID[3] is 13 and PID[7] is 31 so now i have 2 new IDS and have to repat procedure.
I don't know how to program that. Probably recursive function? But don't know how to write it (when to stop it and how to call).
I did try with loops (non recursive) but my program got stuck, should i also put that code here?
If writing with  loops i need some kind of stack
#include<stdio.h>

int recursion() {
    return 0;
}

int main() {
    int PID[10]={1,15,10,13,44,28,30,31,50,17};
    int PPID[10]={0,3,20,10,18,7,13,10,30,47};
    int findID=10;

    recursion();

    //result should be following pairs: 10|20 ; 13|10 ; 30|13 ; 31|10 ; 50|30
}

Comment: For clarity purposes, do you want to find `PID[i]` alongside `PPID[j]`? + your second paragraph is not cleared.
Comment: Your code is incomplete and your question is vague. You should clarify what you've tried, want to do and what the current results are
Comment: Why do you want to use `recursion` ?
Comment: I taught it would be better/ easier  with recursion,  Tho i tried with loops, but it didn't work, my program got stuck printing only PID of  PPID of base value until it crashed
Answer: if the PID and PPID array sizes are in same, the Answer is as below.
#include<stdio.h>

void find(int id,int arr1 [],int arr2 [],int size,int notId) {
    for(int i=0;i<size;i++){
        if((arr1[i]==id || arr2[i]==id) && arr1[i]!=notId && arr2[i]!=notId) {
            printf(" %d | %d;",arr1[i],arr2[i]);
            if(arr1[i]!=id){
              find(arr1[i],arr1,arr2,size,id);
            }
        }
    }

}

int main() {
    int PID[10]={1,15,10,13,44,28,30,31,50,17};
    int PPID[10]={0,3,20,10,18,7,13,10,30,47};
    int size = sizeof(PID)/sizeof(PID[0]);
    int findID=10;
    find(findID,PID,PPID,size,0);
    return 0;
}

Find all parent id's in array in C


How to make dialog`s activity Transparent?

Question: I am opening a dialog activity on click of notification in notification-bar, if the application is in foreground then dialog's activity is transparent on clicking of notification but if the application is in background in this case dialog-activity's background is appearing as black in-spite of transparent. I implemented this in styles.xml

In manifest.xml for my activity I used
android:theme="@style/Theme.Transparent"

Comment: Did you give `Theme.Transparent` to that particular `activity`
Answer: just set your theme in AndroidManifest.xml....
<activity
    android:name="com.example.YourDialogActivity"
    android:theme="@android:style/Theme.Translucent.NoTitleBar">
 </activity>


Longest time between ATP or WTA #1?

Question: What is the longest time from the first to the last time that a player was ranked number 1 of the ATP/WTA rankings?
Comment: Wikipedia article [List of ATP number 1 ranked singles tennis players](https://en.wikipedia.org/wiki/List_of_ATP_number_1_ranked_singles_tennis_players) now has a section [Time spans holding the ranking](https://en.wikipedia.org/wiki/List_of_ATP_number_1_ranked_singles_tennis_players#Time_spans_holding_the_ranking) ([current revision](https://en.wikipedia.org/w/index.php?title=List_of_ATP_number_1_ranked_singles_tennis_players&oldid=841234639#Time_spans_holding_the_ranking)). This section was probably added only in 2018, so after this question was posted.
Answer: Longest time span between the First and Last time at #1 (ATP)
Roger Federer was first ranked at the top of the ATP Rankings on February 2nd, 2004. The last time he was promoted to the top of the ATP Rankings was June 18th, 2018.

The length of time spent between his first and last appearance at
  number one in the ATP Rankings, is 14 years, 1 month, and 16 days. No
  other male player has a greater time span between his first appearance
  at number one to his last appearance. He also became the oldest
  player to achieve the number one
  ranking usurping the title
  from Andre Agassi.

My reference for this information is here.

Longest time span between the First and Last time at #1 (WTA)
For the WTA, it is Serena Williams who first became world number one in the WTA rankings on July 8th, 2002 and last was world number one on May 14th, 2017.

With a time span 2 months shy of 15 years, Serena Williams holds
  the record for WTA players in terms of longest length between first
  being ranked number one, and last.

My reference for this information is here.
Answer: I took data from the Tennis ATP and Tennis WTA repositories in GitHub. They do not have all the rankings, so it is not comprehensive and Logan's answer will be more accurate.
From there we see that:

(this is to be changed)
Rafa Nadal was 1st on 18 August 2008 for the first time and hist last week on that position was on 21 August 2017. This makes it 9 years and 3 days.
Andre Agassi was 1st on 10 April 1995 for the first time and his last week on that position was on 1 September 2003 (100 weeks all together). This makes it 8 years and 5 months.
Roger Federer was 1st on 2 Feb 2004 for the first time and the last time was on 29 Feb 2012 (for a total of 297 weeks all together). This makes it more than 8 years.

In women:

Serena Williams started on 8 July 2002 and her last was on 9 September 2016, for a total of 14 years and 3 months. 308 in total.
Steffi Graff started on 17 August 1987 and her last was on 24 March 1997, for a total of 9 years and 7 months. 383 weeks in total.

Longest time between ATP or WTA #1?


How to manage Lazy Loading in Mapstruct?

Question: I am dealing with a problem related with lazy loaded objects from the database.
Let's say that we have the below entity.
@Entity(name = "User")
@Table(name = "USERS")
public class User{
    @Id
    @GeneratedValue
    private int id

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="NOTES_ID")
    private List<Note> notes;
}

And the Dto would be
@Mapper
public interface UserDtoMapper{

    /** the INSTACE HERE **/

    User fromDto(UserDto dto);

    UserDto toDto(User user);

}

So which could be the best approach for fetching all the users without to have a EJBException because I'm fetching them laziness?
Edit: Solution
Let's say you have the following data model
public class User{

    private String name;

    //... other fields

    @OneToMany
    private Set<Address> addresses;
}

Querying without addresses, exception: When mapping from Model to DTO it will try to map addresses but because is lazy loaded (via hibernate, or any other framework) will end up in exception.

Additionally you can ignore the addresses from being mapped, as @Mehmet Bektaş . But is not needed to define the source, it's optional.
@Mapping(target = "addresses", ignore = true)

Fetching relationships: This is the way. Add a join to query the addresses and Mapstruct will do the rest.
Comment: Fetch all the necessary data in the same transaction. That way there will be no exceptions related to lazy loading.
Comment: Where (in which application layer) are you doing the mapping? It should happen as part of the transaction ideally, or you specify an entity graph which ensures all relationships to be mapped are eagerly loaded.
Comment: https://stackoverflow.com/questions/53465814/lazy-loading-not-working-in-jpa-with-hibernate/56568692#56568692
Answer: You can use Mapstruct to Lazy Load all of the entities you want when it does it's mapping (assuming session is still active).  The unloaded proxies that you don't want can be ignored by using ignore annotation.  More details here.
Can MapStruct do a deep deproxy of Hibernate Entity Classes
Answer: You can use ignore option.
 @Mapping(source = "user.id", target = "userId", ignore = true)

But in this way you can't map the relational fields like eager fetch type.


What if mounting point conflicts with local directory?

Question: This might help me hunt down some system configuration bug.
Suppose I make a local directory (e.g., "/foo") in one disk partition, and copy some files to it. But later on I forget about it, and configure the same directory as mounting point for another disk partition in /etc/fstab.
Now if I reboot the system, what will happen, will /foo still hold local files or point to the other disk partition?
Thanks.
Answer: Both.
When you mount some device to /foo, then the files on the new device appear, and the ones on the original device are hidden.
If you unmount /foo, then the original files will reappear.


iptables: allow everything that aims towards nginx

Question: my router has a port forwarding from port 80 to 8080 to a linux server. On port 8080 there is nginx listening and acting as a reverse proxy. Nginx can redirect to another port on the same machine. (port 8080 redirects to another web interface on the server running on port 9000)
Now I want to setup iptables on the server but would like to accept everything that wants to reach Nginx. Can iptables still detect that the original destination port was 80 and allow every port redirect that is following (80 -> 8080 -> 9000)? Or do I have to add 8080 to iptables? Or even 9000?
Thank you!
Comment: Most likely only `8080`, unless you have traffics to `lo` blocked (in that case `9000` needs to be an exception I guess). `80` is irrelevant to the server.
Answer: Iptables on the server can't see the original port as 80, as it is receiving it as port 8080 because the router modified the packet when it was being forwarded. You tell iptables on the server to accept traffic for port 8080.
You would also want iptables to accept connection on port 9000 on local host. You most likely don't need to do anything here as there is typically a rule allowing anything to/from localhost. This is because a proxy terminates the incoming connection and sets up a second connection from itself to the target.
Comment: Thank you for the answer! Localhost is never blocked, so I should be fine allowing port 8080.


Existe alguma padrão de organização de projeto para C++?

Question: Em Java e ActionScript3.0 usamos os namespaces baseados pelo caminho do diretório, eu vejo muito uso de namespace, mas não se baseiam pelo caminho da "localização" da classe na pasta.
Busquei muito se havia algum tipo de organização igual tem aquela "recomendação" para PHP, o PSR-4, mas para C++ não encontrei nenhuma recomendação, sei que deve ser algo trivial, mas creio que um mínimo de organização, independente do tamanho da equipe ou ser um projeto pessoal pode ser um bom caminho, no caso o intuito não é usar namespaces em todas classes, só em libs isoladas que irei reaproveitar para diversas aplicações.
Existe algo assim para C++, um padrão de projeto "oficial"?
Sendo que não exista, pensei em fazer algo assim:

./fornecedor/categoria/foo.h
namespace Fornecedor
{
    namespace Categoria
    {
        class Foo()
        {
            public:
                Foo();
        };
    };
};

./fornecedor/categoria/foo.cpp
#include "foo.h"

using namespace Fornecedor::Categoria;

Foo::Foo()
{
    ...
}

Neste exemplo acima:

O nome da classe é associado ao nome do arquivo
Os arquivos e pastas sempre são em lowercase (letras minúsculas)
Categoria seria apenas para dividir o uso da classes, por exemplo fornecedor/matematica/soma.cpp e fornecedor/matematica/divisao.cpp

Isto é apenas uma ideia, seria um bom caminho?
Comment: A resposta resolveu o que estava em dúvida? Precisa que algo mais seja melhorado? Acha que é possível aceitá-la agora?
Answer: O namespace do C++ funciona da mesma forma que no C#. Ou seja, eles são apenas "sobrenomes" para seus membros, nada mais que isso.
Uma das vantagens disso é que eles podem ser compostos. Você pode juntar no mesmo namespace coisas completamente isoladas, que não se conhecem. Por isso é um erro tentar usar esse mecanismo da forma apresentada na pergunta. Não que não possa ser feito, mas ele não foi criado para ser usado assim.
É conceitualmente errado, e pode impedir fazer alguma coisa no futuro por ter organizado desta forma. Eu não iria por esse caminho. Não é recomendado oficialmente não fazer assim, mas também não é recomendado fazer.
Note que o próprio std funciona justamente da forma como eu falei. Ele é composto por várias partes independentes. É para ter poucos namespaces, não é para fazer igual ao Java. Que por sinal o C# não copiou porque consideraram essa forma problemática.
O que o C++ tem de diferente do C# é que este último incentiva a hierarquia de nomes e o C++ não, deve ser o mais simples possível.
Note que os includess é que realmente determinam a organização do que é cada coisa.
E agora tem os módulos, que talvez seja o que deseja. Dependendo de como fizer agora, poderá ter dificuldade em usar o novo recurso.
Coloquei no GitHub para referência futura.
Comment: +1 excelente link, estou lendo o `Design Choices`, vai ser um grande avanço.


Commerce: programmatically create new product with my ID

Question: I have database of products and I want to export it to Drupal Commerce database with my Ids being saved:
<code>$product = commerce_product_new('product');
$product->product_id = '100500';
$product->title = 'my title';
commerce_product_save($product);
</code>
But it always returns STATUS_UPDATE because in sites/all/modules/commerce/modules/product/includes/commerce_product.controller.inc in line 80 there is:
<code>// Determine if we will be inserting a new product.
$product->is_new = empty($product->product_id);
</code>
It always clears "is_new" when "product_id" is filled.
If I change that string like:
<code>$product->is_new = !empty($product->is_new) || empty($product->product_id);
</code>
Everything works fine.
Is it a Commerce bug or I do something wrong?
Comment: I doubt you can not say it new when product has already id associated with it.
Comment: id comes from different database, it has to be the same
Answer: I don't see this as a bug, as we do want to prevent arbitrary IDs from being set in general. If you're doing it intentionally, though, I think your best bet would be to implement an override in a custom entity controller that extends the core functionality and changes the behavior of the is_new check like you've done.


rails - how to let the client choose location for download a file

Question: I create an option to export a csv file via my rails code, it's look like this :
 def to_csv
    company = current_company
    @opportunities = company.opportunities.company_visible.not_rejected
CSV.open("/Users/yarden/Downloads/file6.csv", "wb") do |csv|
  csv << @opportunities.attribute_names
  @opportunities.all.each do |opportunity|
    csv << opportunity.attributes.values
  end
end

end
and, I added a btn in the client side (using Angular and js) for this function.
However, my question is - how can I let the client choose where to locate the file in his pc, when he tried to download the csv file ?
right now for my testing I wrote a a specific root in my pc for it.
Thanks ahead !
Answer: This code will only save the file locally on the server. If you want to let a user download the file, I'd advise you to save this CSV to a tempfile, then sending it to the user by using the following method in the controller
// Controller action is called 'download_file'
def download_file
    // Generate file
    send_file my_generated_csv
end

The user then can download the file by clicking a link routing him to this action. You can find more information on the send_file method in the docs


Calculating the coefficient of $x^k$

Question:
In order to calculate the coefficient of $x^k$ in the sum $$\sum_{n\geq 1} \frac {\big(-(\frac {x}{1!}+\frac {x^2}{2!}+\cdots )\big)^n}{n}=\frac {-1}{1}\big(\frac {x}{1!}+\frac {x^2}{2!}+\cdots \big)+\frac {(-1)^2}{2}\big(\frac {x}{1!}+\frac {x^2}{2!}+\cdots \big)^2+\cdots +\frac {(-1)^n}{n}\big(\frac {x}{1!}+\frac {x^2}{2!}+\cdots \big)^n+\cdots $$
  , we just need to find the coefficient of $x^k$ in
  $$\frac {(-1)^n}{n}\big(\frac {x}{1!}+\frac {x^2}{2!}+\cdots \big)^n \quad , \text {when} \quad n\leq k$$
So, $$\sum_{1b_1+2b_2+\cdots +(k-n)(b_{k-n})=k} \binom {n}{b_1}x^{b_1\cdot 1}\binom {n-b_1}{b_2}\dfrac {(x)^{b_2\cdot 2}}{(2!)^{b_2}}\binom {n-b_1-b_2}{b_3}\dfrac {(x)^{b_3\cdot 3}}{(3!)^{b_3}}\cdots n \dfrac {x^{\big(k-n\big)\big(b_{k-n}\big)}}{\big(k-n\big)!} \tag {*}$$

These are in my lecture notes, and I didn't understand the starred part. How is that obtained?
Comment: Are you familiar with the [multinomial theorem](https://en.wikipedia.org/wiki/Multinomial_theorem)? This is a direct use of it.
Comment: It's according to the multinomial thm done this way as I see: $$(x+\frac{x^2}{2!}+\cdots )^n=\sum \binom{n}{b_1,b_2,\cdots ,b_{k-n}}\big(x \big)^{b_1}\big(\frac{x^2}{2!} \big)^{b_2}\cdots \big(\frac{x^{k-n}}{(k-n)!} \big)^{b_{k-n}}$$
The thing that I didnt understand is why it goes from $x$ to $x^{k-n}$ Does this sum cover all the term in $(x+\frac{x^2}{2!}+\cdots )^n$? @PrasunBiswas
Comment: It looks to me like $k-n$ is supposed to be the *largest possible index contribution* to $x^k$. However, I think that should be $k-n+1$ which happens when we get a contribution of $x^1/1!$ from $n-1$ of the factors and $k-n+1$ from the remaining factor.
Comment: Could you write it email@example.com
Answer: Observe we have
\begin{align}
\left(\sum^\infty_{i=1} \frac{x^i}{i!} \right)^n = \underbrace{\left(\sum^\infty_{i_1=1} \frac{x^{i_1}}{i_1!} \right)\cdots \left(\sum^\infty_{i_n=1} \frac{x^{i_n}}{i_n!} \right)}_{n-\text{times}}
\end{align}
which we would like to rewrite in the form
\begin{align}
\left(\sum^\infty_{i_1=1} \frac{x^{i_1}}{i_1!} \right)\cdots \left(\sum^\infty_{i_n=1} \frac{x^{i_n}}{i_n!} \right)=\sum^\infty_{k=n} c_k x^k.
\end{align}
Naively, it's clear that
\begin{align}
\left(\sum^\infty_{i_1=1} \frac{x^{i_1}}{i_1!} \right)\cdots \left(\sum^\infty_{i_n=1} \frac{x^{i_n}}{i_n!} \right) = \sum^\infty_{k=n}\left(\sum_{i_1+\ldots + i_n=k}\frac{1}{i_1!\ldots i_n!} \right)x^k.
\end{align}
However, we would like to use a more combinatorical argument to rewrite the coefficient.
First, fix some $k\geq n$.
Viewing each $\left(\sum^\infty_{i_j=1} \frac{x^{i_j}}{i_j!} \right)$ as a "basket" we see that the maximum term which we can consider is $x^{k-n+1}$ from this basket. For instance, as remarked by @N.Shales, if I consider $i_1 = k-n+1$, then $i_2=\cdots=i_n = 1$. This little observation allows us to truncate each summation so we can consider
\begin{align}
\left(\sum^{k-n+1}_{i_1=1} \frac{x^{i_1}}{i_1!} \right)\cdots \left(\sum^{k-n+1}_{i_n=1} \frac{x^{i_n}}{i_n!} \right). \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ (\ast)
\end{align}
Let us note that we only care about the coefficient of $x^k$ from $\ (\ast)$, but this amounts to finding the number of ways of choosing $b_1\geq 1$ numbers of $x^1$ from $n$ baskets, number of ways of choosing $b_2\geq 2$ numbers of $x^2/2!$ from $n$ baskets, etc, so that
\begin{align}
b_1+ b_2 \ldots + b_{k-n+1} = n\\
1\cdot b_1 + 2\cdot b_2 + \ldots + (k-n+1)\cdot b_{k-n+1} =k
\end{align}
This is precisely given by
\begin{align}
&\sum_{1\cdot b_1 +\ldots + (k-n+1)\cdot b_{k-n+1}=k} \binom{n}{b_1}\underbrace{x^1\cdots x^1}_{b_1-\text{times}} \binom{n-b_1}{b_2}\underbrace{\frac{x^{2}}{2!}\cdots \frac{x^{2}}{2!}}_{b_2-\text{times}}\cdots \binom{n-b_1-\ldots-b_{k-n}}{b_{k-n+1}}\underbrace{\frac{x^{k-n+1}}{(k-n+1)!}\cdots \frac{x^{k-n+1}}{(k-n+1)!}}_{b_{k-n+1}-\text{times}}\\
=&\ \sum_{1\cdot b_1 +\ldots + (k-n+1)\cdot b_{k-n+1}=k} \binom{n}{b_1}x^{1\cdot b_1}\binom{n-b_1}{b_2}\left(\frac{x^{2}}{2!}\right)^{b_2}\cdots \binom{n-b_1-\ldots-b_{k-n}}{b_{k-n+1}}\left(\frac{x^{k-n+1}}{(k-n+1)!}\right)^{b_{k-n+1}}.
\end{align}
Comment: It now makes a lot sense. Thanks for this great answer. However, I only have an issue with the idea of "$x^{k−n+1}$ being the maximum term from this basket" I can't see why it is the maximum.
Comment: Great work Jacky, very clear. @LeylaAlkan, sorry I didn't get back sooner. Anyway, it might help is you use an example, say $n=4$ and $k=8$. Then $(x^1/1!+x^2/2!\cdots)^4$ and the "biggest" contributor to $x^8$ from the factors is $x^5$ because we have $3$ contributions of $x^1$ and thus $8-3=5$ is the greatest power of $x$ that can go with these. Look back at the variables and you'll see that $5=8-(4-1)1$ or $5=k-(n-1)1=k-n+1$.
Answer: Hint: By using the Taylor expansion of the exponential function you can rewrite the first sum as:
$$\sum_{n=1}^{\infty}\dfrac{(1-\exp(x))^n}{n}.$$
Compare this to the Taylor series of
$$-\ln(1-u)=\sum_{n=1}^{\infty}\dfrac{u^n}{n},$$
which is valid if $|u|<1$.
Hence we obtain for $u=1-\exp(x)$ for $|1-\exp(x)|<1$
$$\sum_{n=1}^{\infty}\dfrac{(1-\exp(x))^n}{n}=-\ln\left(1-(1-\exp(x))\right)=x.$$
Comment: This is an alternative solution. I also do not understand your lecture notes.
Comment: Tell me that :)
Comment: Yes, I get this part but I didn't understand how the starred part is done
Comment: @LeylaAlkan: I think the sum in your proposed problem should have limits $r=1$ to $n$ and we would investigate the coefficient of $x^r$, because otherwise, the sum as explicitly stated, evaluates to $x$ which has coefficient $1$ when $k=1$ and $0$ otherwise. The alternate version which I think is the actual aim of your lecture notes can be done by just applying multinomial theorem (though the expression for the coefficient would be quite cumbersome).

Calculating the coefficient of $x^k$


Why are all of the non-value columns indexed, but the value column isn't?

Question: I'm working on improving performance for a Drupal 7 website and noticed that all of the non-value columns (entity_type, bundle, delete, etc) are indexed, but the actual value field isn't...does this make sense to anyone?
I know Drupal uses the other fields to join against other tables, but any views/custom queries that are searching for nodes with specific field values are going to suffer are they not?
Is there some reason why the value column isn't indexed by default? Will it cause problems if an index is added?

The specific field I'm looking to index is a date field if that provides any more insight into the situation
Answer: I'm not an expert in this but I think it's probably due to the fact MySQL enforces a maximum key length for indexes. For InnoDB this is 3500 bytes (further limited to 3072 bytes by MySQL itself), and for MYISAM it's 1000 bytes.
Whether or not the value columns are indexed is actually done on a per field-type basis. For example, the long text field type (for fields like the node body) has no index on the fieldname_value column, but it does have an index on the fieldname_format column.
The fieldname_format column is a varchar limited to 255 characters, and so would not produce an index key that is too long. Conversely the fieldname_value column is a longtext type, which has the potential to create a key that would be too long. (You can specify a prefix length to get around this but I don't think Drupal supports it).
As another example, if you then look at a table for an image (or file) field type you'll notice there is an index on the fieldname_fid column. Because this field is an integer type it naturally lends itself to be indexed, without having to worry about the maximum index key length.
I think it basically comes down to the type of data the field is storing. entity_type/bundle/etc. are all integer columns and so can be easily indexed by whatever storage engine you're using, while text types (or varchar types with a large enough length) will create an index key that's too large for the storage engine to handle.
Hope that helps a bit
Answer: Just to complete Clive's answer above, nothing can prevent you from adding indexes wherever you want, and it sure could improve performance, but be aware that it can be counter-productive.
Indexes can be used automatically by MySQL, even in cases you wouldn't expect, so you have to be careful and use some EXPLAIN queries to ensure your indexes get used at the moment you want and at no other time.
Long story short : it is a case by case problem, which explians why the devs didn't try to guess what performance gains one would be looking after.


jquery ui css does not appear when changes from display:none to display:inline

Question: High everyone,
In my web-based app, I have a div that is usually display:none so that it is hidden and doesn't take up any space.  When something happens, I want the div to appear with the styling for the class ui-state-highlight ui-corner-all and i will put in some dynamic content.  So i give this hidden div these classes initially.  The problem is when I show the div with some dynamic content, the styling for the classes i just mentioned is not there.
See this fiddle which illustrates the problem: http://jsfiddle.net/qR8gK/
The desired outcome is the div that appears when you click the button has the same styling as the one that is visible initially.  Does anyone know how I can do this??
Thanks!
Comment: check this out http://jsfiddle.net/qR8gK/1/
Answer: Just use .show() instead of manually setting the css display setting.
$('#a').button().click(function() {
    $('#dynamic').show().html('
some dynamic content
');
});

Answer: The actual problem in your code was because of the paragraph tag. Remove the
 and try.
$('#a').button().click(function() {
    $('#dynamic').css('display', 'inline').html('some dynamic content');
});

sample : http://jsfiddle.net/qR8gK/19/
Answer: Call the show() method to make it visible.
$('#a').button().click(function() {
    $('#dynamic').html('
some dynamic content
').show();
});

working sample : http://jsfiddle.net/qR8gK/16/


Autofill texfields based on select option in dynamic fieldset

Question: In my custom form i am dynamically generating multiple fieldsets.Each field set has select option(dropdownlist) and textfield generated dynamically. The value for textfield is dynamically generated based on user selected value from select option.

My problem is that if i select species from fieldset2 then density texfield1 in fieldset1 is overwritten and density textfield2 in fieldset2 is empty which is wrong. Each time the ajax callback return value is overwriting textfield1 in fieldset1(Field#1)
function fuel_design_tool($form, &$form_state) {
$form = array();
$form['#tree'] = TRUE;

if (empty($form_state[FIELDS_NUM])) {
    $form_state[FIELDS_NUM] = 1;
}

for ($i = 1; $i <= $form_state[FIELDS_NUM]; $i++) {

    $form['field'][$i] = array(
        '#type' => 'fieldset',
        '#title' => t('Field #@num', array('@num' => $i)),
        '#collapsible' => TRUE,
        '#collapsed' => FALSE,

    );

    $form['field'][$i][FORM_FIELD_SPECIES] = array(
        '#type' => 'select',
        '#required' => TRUE,
        '#title' => 'Choose Species',
        '#options' =>  _load_species1(),
        '#default_value' => 0,
        '#ajax' => array(
             'callback' => 'fuel_design_tool_callback',
             'wrapper' => 'fuel_design_tool-wrapper',
             'event' => 'change',
           )

       );

      $profile = isset($form_state['values']['field'][$i]['FORM_FIELD_SPECIES']) ? ($form_state['values']['field'][$i]['FORM_FIELD_SPECIES']) : NULL;
    $form['field'][$i][FORM_FIELD_DENSITY] = array(
        '#type' => 'textfield',
        '#prefix' => '
',
        '#suffix' => '
',
        '#title' => t('Density'),
        '#value' =>$profile,

    );
    $form['add_field'] = array(
    '#type' => 'submit',
    '#value' => t('Add More fieldet'),
    '#submit' => array('fuel_design_tool_add_name')
    ),

     $form['submit_button'] = array(
     '#type' => 'submit',
     '#value' => t('Submit'),
     "#submit" => array("fuel_design_tool_submit"),
    );

     return $form;
 }

 function fuel_design_tool_add_name($form, &$form_state) {

    $form_state[FIELDS_NUM]++;
    $form_state['rebuild'] = TRUE;
   }

function fuel_design_tool_callback($form, &$form_state)
 {
   for ($i = 1; $i <= $form_state[FIELDS_NUM]; $i++)
   {

  $form['values']['field'][$i]['FORM_FIELD_DENSITY'] = $form_state['values']['field'][$i]['FORM_FIELD_SPECIES'];
  return array (
    $form['field'][$i]['FORM_FIELD_DENSITY'],

   );
  }

 }
 }

My callback function returns only one value and that by default filled to fiedset#1 textfield.I guess i need to modify my callback function.
I am looking forward for your kind help.
If my question is not clear please let me know. I am finding bit difficult to explain this problem
Answer: Give the textfield wrappers unique ids, e.g. fuel_design_tool-wrapper-1 and fuel_design_tool-wrapper-2, and assign accordingly in the FAPI array.
Comment: Before your reply i made some changes to my code.i have no problem with fiedset1.In fieldset2 if i select value from dropdown2,the textfield2 is empty but filled with correct value when i click on "add more fieldset" button. please find my edited code above in my question. If you want me to provide unique ids for wrappers can you please be bit clear or more explanation please


Maximum runs scored in an inning by a batsman

Question: What are the maximum runs scored in an inning of 50 overs by 1 batsman?
Comment: Welcome to Sports SE! This question needs more details - what level of cricket: domestic, international, club? Also, assuming you're talking about international cricket, it's very easy to find the answer by a quick Google search: [highest individual ODI score](https://www.google.co.uk/search?q=highest+odi+score+individual&oq=highest+odi+score+individual&aqs=chrome..69i57.912j0j1&sourceid=chrome&es_sm=122&ie=UTF-8#q=highest+individual+odi+score) should give you your answer.
Answer: As of 27th November 2014, for One-Day internationals, it's Rohit Sharma who scored 264 v Sri Lanka in Kolkata on the 13th November 2014.
For other forms of 50-over cricket, you'd need to consult the national sites, available from that link also.


Stable Distribution Log-likelihood and AIC values

Question: I have used the stableFit function from the fBasics package to come up with parameters (alpha, beta, gamma, and delta) for a stable distribution as you can see below:
stableFit(x)

I then did the following to come up with log likelihood values and for some reason, it doesn't seem to work:
stable.fit<-function(alpha=1.387,beta=0.279,gamma=0.006948893,delta=-0.0017933)-sum(dstable(x,1.387,0.279,0.006948893,-0.0017933,pm=0,log=T))

mle.results<-mle2(stable.fit,start=list(alpha=1.387,beta=0.279,gamma=0.006948893,delta=-0.0017933),data=list(x)) #max likelihood using bbmle package

mle.results #produces the log-likelihood values

It seems that when I run the "mle.results<- mle2(.." line, R is continuously running and will not stop until I press the "STOP" button. Because of this, I am unable to then ask for the "mle.results". Why is this happening? This process seems to work fine for the normal, logistic, cauchy, student T,skewed student T, gumbell and generalized extreme value distributions.
Answer: Looks like I was able to answer my own question. The problem was that R took a lot longer to got through the mle2 calculation along with the integration of the dstable function. Log-likelihood results took less than 10 seconds for the other distributions but for some reason, it took 45-50 minutes!! for the stable distribution. I only figured this out after I decided to just let it run while I worked on other things and after 45-50 minutes, it finished. However, I can't figure out why the stable distribution is taking exceptionally long to do this calculation. Anyway, problem solved.


Double Minor Penalty Kill Counts as 1 or 2 Kills?

Question: In NHL hockey when you receive a double minor penalty (4:00 penalty given for example high sticking leading to bleeding) does this count as 2 separate penalty kills if no goals are scored during the 4 minutes or does it only count as 1 penalty kill? And for that matter if a goal is scored in the first 2 minutes but not in the 2nd 2 minute penalty, is it considered one failure and one kill?
I am just curious how this is kept statistically. But my guess would be that it counts as 2 penalty kills.
Comment: And how does it work if there is a power play goal scored during the first 2:00 does the second penalty start right away?
Comment: If a goal is scored during the first 2 min then that will negate the first powerplay. The second minor will start counting after the puck drop
Answer: A double minor counts as two separate penalties, one after the other. When keeping the game statistics, therefore, you count them separately as well.
This leads to the situation where a four-minute double minor counts as two power-plays but a five minute major penalty counts as just a single power-play.
Comment: I can't point to a specific rule, but I found an example from a recent game which shows how a double-minor is counted for statistical purposes: [New York - Washington](http://www.nhl.com/ice/boxscore.htm?id=2011030216). NYR are 0/5 for power-plays. Washington received four penalties, one of which was a double minor to Halpern at 12:05 of the second period.
Comment: Can you add a reference for this?
Comment: Does it count twice even if the match ends before the second one starts?
Comment: Powerplays are counted as they occur not when the penalty is given. For example, in team A gets a double minor and team B gets a major part-way through the first of the double minors, the second of the double minor power plays will never occur. The result would be one power play to each team. Likewise, if the game ends before a power play starts, then it won't be counted for statistical purposes.
Comment: I think if you get a double minor at say 19:00 of the last period (assuming no OT and no goals are scored during the first minor), the 2 min 2nd minor penalty still count and is added to the stats


How do I create a predictor for a time series once I've confirmed Granger-causality?

Question: I have a set of time series data that I've found granger-causality (i.e. regressed Y vs. X, X-1, Y-1), and am wondering how I can create a predictor from this linear model?  Is it simply the coefficients I get back from my model? (I'm trying to code this programmatically, and am still a stats rookie, so if this is obvious, forgive me)
Answer: Granger causality test was invented to test statistically that variable $x_t$ has a significantly sound information that helps to predict $y_t$. If however $y_t$ is potentially linked with some other variables than $x_t$ (both are a part of a vector, which could be modeled by vector autoregression) the testing scheme becomes a bit more complicated (involves some matrix manipulations). Note also that since testing for Granger causality involves $F$-test in the final stage it is sensitive to deviations from normality assumption (you may then consider some extensions from the wiki link above).

To make a predictive model you have to choose the horizon (denote it by $h$) up to which you would want to predict. Your complete predictive model is then:
$$y_t = \alpha_0 +\alpha_1 y_{t-1} + \dots + \alpha_p y_{t-p} + \beta_1 x_{t-1} + \dots + \beta_p x_{t-p} + \varepsilon_t, $$
for sequential predictions (note that in sequential case you have to make a predictive model for $x_t$), and in direct $h$ step ahead case:
$$y_t = \alpha_0 +\alpha_1 y_{t-h} + \dots + \alpha_p y_{t-h-p+1} + \beta_1 x_{t-h} + \dots + \beta_p x_{t-h-p+1} + \varepsilon_t, $$
then the $h$ step prediction after estimation and testing for Granger-(non)causality ($H_0: \beta_1 = ... = \beta_p = 0$) in direct case:
$$ y_{T+h}^{(h)} = \hat\alpha_0 +\hat\alpha_1 y_{T} + \dots + \hat\alpha_p y_{T-p+1} + \hat\beta_1 x_{T} + \dots + \hat\beta_p x_{T-p+1} $$
and in sequential:
$$ y_{T+1}^{(1)} = \hat\alpha_0 +\hat\alpha_1 y_{T} + \dots + \hat\alpha_p y_{T-p+1} + \hat\beta_1 x_{T} + \dots + \hat\beta_p x_{T-p+1}, $$
$$ y_{T+2}^{(2)} = \hat\alpha_0 +\hat\alpha_1 y^{(1)}_{T+1} + \dots + \hat\alpha_p y_{T-p} + \hat\beta_1 x^{(1)}_{T+1} + \dots + \hat\beta_p x_{T-p}, \dots $$
Thus estimation/testing step is separated from the prediction step which for linear models is straightforward. All this scheme is easily implementable in $R$.
Comment: Great explanation, you rock! (Plus, I had no idea we could use TEX in our posts -- thanks for showing me the light)


re-run jobs in laravel scheduler

Question: I want to re-run jobs in laravel Scheduler in case of failure , assume the following :
Kernal.php
protected function schedule(Schedule $schedule)
{
    $this->generateData($schedule);

}

protected function generateData($schedule){

   $schedule->command('My Command')
   ->monthly()
   ->after(function ($schedule){
     $command = DB::table('commands')
     ->where("name","My Command")
     ->orderBy('id', 'desc')
     ->first();
     if(!$command->succeeded){
       echo "task not finished";
       $this->generateData($schedule);
     }
     else{
       echo "task finished";
       return;
     }
   });
 }

this command sometimes fails, on after function I check if the command fails or not, then I try to re-execute it again, but this didn't work and I got the following error :   [ErrorException]
  Missing argument 1 for App\Console\Kernel::App\Console{closure}()
any suggestions ?
Answer: You're setting the $schedule the wrong way in the anonymous function, use the 'use' statement like this:
protected function generateData($schedule){

  $schedule->command('My Command')
  ->monthly()
  ->after(function() use ($schedule){
    $command = DB::table('commands')
    ->where("name","My Command")
    ->orderBy('id', 'desc')
    ->first();
    if(!$command->succeeded){
      echo "task not finished";
      $this->generateData($schedule);
    }
    else{
      echo "task finished";
      return;
    }
  });
}

re-run jobs in laravel scheduler


Menu bar - fixed vertically, allows horizontal scrolling - without use of scripts

Question: I am trying to build a site that has a menu bar that remains fixed at the top of the screen.
I have it more or less working as I want, the bar stays where it is. The only problem is that when the window is sized smaller than the menu bar width, it is impossible to horizontally scoll the menu bar (only the content scrolls). This means someone with a small monitor will be unable to use the menu items towards the right.
I've read other questions related to this but the answers all involve scripts, is it possible to achieve a vertically-fixed but horizontally-scrolling menu, using purely css and html? Or do I have to use scripts?
This is the code and relevant css:
html:

            Yectlahuilli hC

                Inicio

                Servicios

            <more links...>

<content...>

css:
#header {
    background-color: #ffffff;
    border-bottom: 0px solid #e6e6e6;
    padding-top: 10px;
    padding-bottom:30px;
    position:fixed;
    height:134px;
    width:100%;
}
#header > div, #footer > div {
    width: 970px;
    margin: 0 auto;
    padding: 0 20px;
}
#spacer {
position:relative;
height:174px;
z-index:-1;
}

Any suggestions welcome, thanks in advance.
Answer: The first things that comes to mind is to use css media screens to control the width and height of the menu based on the screen size.
@media screen and (max-width: 960px){
     #navigation {width: 200px; font-size:12px; and so on...}
}

Adjust the max-width to change when the new style come into effect.  Any style that you place in the media screen will take effect when the screen (or window) size is 960px or less.
Comment: if I understand correctly, this would dynamically resize the font and menu bar size if the screen is too small. Is there no way to keep the menu bar the same, and just allow me to horizontally scroll the menu bar if I need to?
Comment: I would need to see the code you are working with but I am pretty sure that the only way to do that is with javascript.
Comment: Thanks for your help. What more code should I post? I thought all the relevant information was included above.
Comment: Well you keep saying horizontally.  Do you mean vertically. Up and down?
Comment: Nope, I mean horizontally. I want a bar that stays fixed vertically, but allows me to scroll horizontally. That is, I only want to prevent movement in the up-down direction. Left-right, I want the element to behave like a normal page, that allows scrolling if it doesn't fit into the window
Comment: ok well the only way that I can think of is to use javascript


Regex to capture GPA with Python

Question: I am trying to capture GPA with regex in Python. For example, I want to capture just 3.75 for both lines. The word GPA could be at the beginning or end of 3.75.
GPA 3.75 / 4.0
3.75 / 4.0 GPA

((?:gpa[ :]+)(\d\.?\d{0,2})(?:[/\d\. ]{0,6})?)|((\d\.?\d{0,2})(?:[/\d\. ]{0,6})? ?(?:gpa))
Here is my attempt.  It works but I would like to know if there is a way not to repeat the yellow parts. They are exactly the same.

You can see more examples here. Thanks!
Comment: You can use `re.search(r'(gpa[ :]+)?(\d+(?:\.\d+)?)(?(1)| *gpa)', text, re.I).group(2)`, see [the regex demo](https://regex101.com/r/0T2ZW3/2).
Comment: Thanks, I am looking for something like this. But this incorrectly captures `4.0` instead of `3.75` for `3.75 / 4.0 GPA`.
Comment: So, `r'(\bgpa[ :]+)?(\d+(?:\.\d+)?(?:[/\d\. ]{0,6})?)(?(1)| *gpa\b)'`? Or, `r'(\bgpa[ :]+)?(\d+(?:\.\d+)?)(?:[/\d\. ]{0,6})?(?(1)| *gpa\b)'`?
Comment: Oh the second one seems to be good! Do you want to post as an answer so that I could accept yours and resolve?
Answer: You can use
m = re.search(r'(\bgpa[ :]+)?(\d+(?:\.\d+)?)[/\d. ]{0,6}(?(1)| *gpa\b)', text, re.I)
if m:
  print(m.group(2))

See the regex demo.
Details:

(\bgpa[ :]+)? - an optional capturing group with ID 1: a whole word gpa (case insensitive search is enabled via re.I) and then one or more spaces or colons
(\d+(?:\.\d+)?) - Capturing group 2: one or more digits followed with an optional sequence of a dot and one or more digits
[/\d. ]{0,6} - zero to six /, digits, dots or spaces
(?(1)| *gpa\b) - If Group 1 matches, match an empty string, else, match zero or more spaces and a whole word gpa.

See a Python demo:
import re
texts = ['GPA 3.75/4.00','GPA 3.75/4.0','GPA 3.75 /4.0','GPA 3.75 / 4.0','GPA 3.7 / 4      aaa','Major GPA: 3.6/4.0','GPA 3.1','GPA 3','some text GPA 3','3.25/4.0 GPA','some text 3.26 / 4.0 GPA','Minor in Art and Technology - 3.5/4.0 GPA aaaa','Minor in Art and Technology - 3.5 / 4.3 GPA aaaa']
rx = re.compile(r'(\bgpa[ :]+)?(\d+(?:\.\d+)?)[/\d. ]{0,6}(?(1)| *gpa\b)', re.I)
for text in texts:
  m = rx.search(text)
  if m:
    print(text, "=>", m.group(2), sep=" ")

This outputs:
GPA 3.75/4.00 => 3.75
GPA 3.75/4.0 => 3.75
GPA 3.75 /4.0 => 3.75
GPA 3.75 / 4.0 => 3.75
GPA 3.7 / 4      aaa => 3.7
Major GPA: 3.6/4.0 => 3.6
GPA 3.1 => 3.1
GPA 3 => 3
some text GPA 3 => 3
3.25/4.0 GPA => 3.25
some text 3.26 / 4.0 GPA => 3.26
Minor in Art and Technology - 3.5/4.0 GPA aaaa => 3.5
Minor in Art and Technology - 3.5 / 4.3 GPA aaaa => 3.5

Comment: Thank you, for the capturing group 2, `(\d+(?:\.\d+)?)`, why do I need `?:`?
Comment: @E.K. `(?:...)` is a [non-capturing group](https://stackoverflow.com/questions/3512471/what-is-a-non-capturing-group-in-regular-expressions) used only to group a sequence of patterns.
Comment: Yeah, for the case of `3.75`, I think `\d+` matches `3` and `(?:\.\d+)` captures `.75`, which is also a part I want to capture. So why non-capturing group for `.75`?
Comment: @E.K. Since `.75` value is not necessary in the output, there is no need allocating memory for this submatch.

Regex to capture GPA with Python


Unattended automatic security updates / upgrades

Question: What is the best way to get Drupal to automatically perform security updates? And are people commonly employing such a method?
For motivation, consider this: Drupal just released a PSA about a recent vulnerability saying:

...You should proceed under the assumption that every Drupal 7 website was compromised unless updated or patched before Oct 15th, 11pm UTC, that is 7 hours after the announcement.

Fortunately I caught this one and performed the update manually one hour after the announcement. But what if I hadn't? I'd like to have an automatic update process in place to give me some piece of mind.
And I'd like for this automatic upgrade system to only apply security updates. (It just doesn't seem worth the risk to bother with potentially breaking some functionality after an update, unless the update is critical.)
Comment: Hello welcome. This has been asked numerous times. Simply search for `security`, `7.32`, etc. In general `drush up --security-only` will apply security updates. Choose any means of scheduling you want: Puppet, cron, whatever to invoke the command.
Answer: Please also keep in mind there are '0-day' vulnerabilities out there, which can be used to compromise your website even before Drupal publishes a security advisory and corresponding patch. And that even if you use an automated update for Drupal core, there still will be a time window in which your site was vulnerable.
The best way to deal with these kind of issues is therefore to have all your Drupal code in a version control system - Subversion or Git for example. This way you can easily:
- identify when there has been an intrusion with a status command (this will show you all modified files in your source files)
- reverting these changes, and therefore repair all harm done, by resetting the source tree to your latest commit
The only downside is that you have a little more work to do with each update, as you need to commit all changes back to your repository after each code change. But this is a very small price to pay for the added benefits and piece of mind this provides.
Comment: Don't forget malicious code can hide in the database as well.
Answer: There's a huge discussion regarding this. Follow up https://www.drupal.org/node/2367319 and decide.


COUNT in a WHERE statement SQL

Question: My Table consists of 3 columns; id, state, carColour, and over 1mil rows.
I want to return all states which have more black cars than white cars.
I have tried:
SELECT state
FROM table
WHERE state IN (SELECT state
                FROM table
                WHERE COUNT(carColour = 'Black') > COUNT(carColour = 'White'))
GROUP BY state

But obviously a count() in a where statement doesnt work... How can I solve this?
Comment: You want `having` not `where`
Comment: What type of database is it? SQL server? Oracle?
Answer: No need for a subquery. You can filter in the having clause, using conditional aggreation:
select state
from mytable
group by state
having sum(case when carColour = 'Black' then 1 else 0 end)
     > sum(case when carColour = 'White' then 1 else 0 end)

This uses standard case syntax, which is supported pretty much everywhere. Some databases have shortcuts. For example, Postgres and SQLite support the filter clause:
having count(*) filter(where carColour = 'Black')
     > count(*) filter(where carColour = 'White')

Comment: first one works. Filter seems to not be working even tho Im using sqlite. Thanks!
Comment: @broccoli: you need SQLite 3.30.0 for the `filter` clause...

COUNT in a WHERE statement SQL


How i connect from android to another cellphone with (DUN or PAN)?

Question: I create a simple bluetooth terminal for android and i want to connect with other cellphone not android support uuid=1115(PAN) with personal area network....and share internet connection to android.How i do this?I know for (DUN) is AT+CGDCONT=1,"IP","APN"...and after dial with ATD*99***1# What is the procedure for PAN?I connected with my PC and BlueSoleil with cellphone share internet to pc...I test it again with DUN bluetooth service...
<code> AT+CGDCONT=1,"IP","MYAPN"
 REPLY OK

 ATD*99***1#
 REPLY CONNECT
</code>
After what can i do?I can use url from my terminal?How i keep my application to backgroung and open my browser for use internet?
Answer: For PAN, it is totally different as against the way you did for DUN which involves remote RAS-dial using the access point settings you provided (consider PPP link). PAN involves using the BNEP layer to give you the needed network connection via a virtual Bluetooth Ethernet driver/interface. There is no RAS-dial involved in PAN, and therefore you don't need the AT commands you did with DUN to initiate a connection.
For PAN to work, you need to have PAN profile supported on your phone + on your Desktop PC (let's say) as well. Imagine if you want to use the browser on your phone with no mobile data subscription or Wi-Fi not available, but you have an internet + Bluetooth enabled PC nearby, you would initiate a PAN connection from your phone to your PC. The underlying BNEP will be responsible for carrying and routing your Bluetooth packets with Ethernet frames in the ACL payload. Please refer more of the BNEP protocol to understand more.


Only options for 'trans' are 'noop', 'context "xxx"', and 'as VAR'

Question: in my template than contains {% i18n %} i receive this error :
Only options for 'trans' are 'noop', 'context "xxx"', and 'as VAR'.

for this line of my template:
title="{% trans site_title = settings.APP_SHORT_NAME %}RSS feed from {{ site_title }}{% endtrans %}"

Comment: `{% trans site_title = settings.APP_SHORT_NAME %}` should be `{% trans site_title as settings.APP_SHORT_NAME %}`and there is no tag called `endtrans` - Just remove it.
Answer: Probably it should be:
title="{% blocktrans with site_title = settings.APP_SHORT_NAME %}RSS feed from {{ site_title }}{% endblocktrans %}"


When did cross-checking become illegal in the NHL?

Question: Does anybody know when the NHL prohibited cross-checking?
Cross-checking occurs when a player checks an opponent by using the shaft of his or her stick with both hands [See Rule 59.1 of the NHL Rulebook 2015-6]. I saw that players were suspended in the 80s for that, but it might be an even older rule.
Answer: As far as I can tell it has always been a rule. This article references all major rule changes in the NHL since 1910, and cross-checking is not listed whatsoever. So I think it was probably a rule at the NHL's conception.


Height of a prime ideal and number of generators.

Question: Let $k$ be a field and $A=k[x_1,\dots,x_n]\big/(I)$ where $I$ is a prime ideal and $\operatorname{dim}(A)=1$, i.e $\operatorname{Spec}(A)$ is a curve. I want to construct a dense open set $U \subset \operatorname{Spec}(A)$ such that $U$ is a normal scheme. To do this I want to take as open set,
$$U=\{ x \in \operatorname{Spec}(A)| x \text{ is a smooth point}\}$$
since the notion of smoothness and normality coincide in dimension $1$. Furthermore the generic point $\eta \in \operatorname{Spec}(A)$ corresponding to the zero ideal is clearly smooth so density of $U$ follows. I'm having problems finishing the proof that $U$ is actually open.
Since $k[x_1,\dots,x_n]$ is catenary it follows by the dimension formula,
$$ \operatorname{dim}(k[x_1,\dots,x_n])= \dim(A)+ \operatorname{ht}(I)$$
that $I$ has dimension $n-1$. Now this implies that the minimal number of generators of $I$ must be greater of equal to $n-1$. Let us denote the cardinality of this set $\mu(I)$ and assume that $\mu(I)=n-1$. Then we can use the Jacobian criterion for smoothness to show that $x \in \operatorname{Spec}(A)$ is smooth if and only if the rank of the Jacobian at that point is maximal. Therefore a point is not smooth if and only if the rank of the Jacobian is not maximal and this corresponds to the point $x$ satisfying some polynomial equations that clearly constitute a closed set in $\operatorname{Spec}(A)$.
However if $\mu(I)=n$ for example then this argument fails. Is there any way to fix this?
Answer: Let me first mention that this is not always possible in positive characteristic as the curve $V(x^p+y^p+a)\subset \mathbb{A}^2_{k}$ for $k$ of characteristic $p$ and $a\in k$ not a $p^{th}$ power shows. I'll be working in characteristic zero for the rest of the answer.
The claim "the singular points of a variety in characteristic zero form a closed subset of that variety" is true, and it may be proven in the following manner: show that any variety is birational to a hypersurface in $\mathbb{P}^n$, and then compute there using the Jacobian criterion.
Your proof ought to be fixable by asking for the rank of the Jacobian to be at least $n-1$ on an open subset. This open subset would be determined by the nonvanishing of the determinants of all $n-1\times n-1$ minors of the Jacobian matrix.
You need not worry about imposing equations to make the Jacobian have exactly rank $n-1$: it already has rank at most $n-1$ no matter what (you can test this with the twisted cubic, $V(z-x^3,z^2-y^3,y-x^2)\subset\mathbb{A}^3$, for example- the Jacobian has determinant $6x(y^2-xz)$ which vanishes on the twisted cubic and therefore the Jacobian has rank at most 2 at all points of this curve). Here is a proof:
Let $I\subset k[x_1,\cdots,x_n]$ be the ideal defining our curve $X$ inside $Y=\operatorname{Spec} k[x_1,\cdots,x_n]$. Then the following exact sequence is standard:
$$I/I^2\to \Omega_Y|_X\to \Omega_X\to 0$$
We may tensor by $k(x)$ for $x\in X$ to get
$$I/I^2\to \Omega_Y\otimes k(x)\to \Omega_X\otimes k(x)\to 0$$
The first map sends $f$ to $df\otimes 1$, so if $f_i$ generate $I$, then $df_i$ generate the image of $I/I^2$ in $\Omega_Y\otimes k(x)\cong k(x)^n$. Let this image be called $Im$. Then the Jacobian $J_x$ associated to $f_i$ at the point $x$ has columns corresponding to the images of $df_i$ in $Im\subset \Omega_Y\otimes k(x)$. This shows us that $\dim_{k(x)}(\Omega_X\otimes k(x))=n-\operatorname{rank} J_x$, and given that the tangent space to a curve is always at least one dimensional, $\operatorname{rank} J_x$ is always at most $n-1$.
Comment: @Abellan The rank of the Jacobian at a point $x$ cannot be larger than the dimension of $X$ at $x$. I have edited my answer to include this fact and proof.
Comment: But if the rank of the Jacobian at $x$ were n wouldn't this imply that the point is not smooth? So I think I need the rank to be exactly $n-1$..
Comment: $x^p+y^p+1=(x+y+1)^p$.
Comment: @Mohan eek, good catch. I knew I was going too quickly... I fixed it.


Lower E and A string resonates with high frequency when playing the higher E string on my acoustic guitar

Question: this is a new acoustic classic guitar I have just bought. It has strange sound.
when I play the high E string (open) and then immediately touch the string to mute it the guitar keeps playing a similar but different frequency sound for 8-10 seconds. I have found that the lower E and A string resonates (if I touch the lower E and A the sound is gone).
What should I do? Should I take the instrument back to the shop?
Answer: This is not a "problem" necessarily.  Each string has a natural set of harmonics that are n*(open string frequency).  If the note you play matches one of these then that open string will vibrate.  The octave and the fifth are the strongest harmonics and the ones most likely to be heard for a long time after excitation.  If you play a fretted D on the B string (3rd fret) you should experience vibration of the open D string.  This resonance is part of what makes a good full sound on a classical (many texts encourage the student to allow these open resonances to persist while playing).  If they become a problem then the guitarist needs to dampen them with their hands as they play (this is part of the technique).  What type of guitar is this?  Brand, model, etc.
Comment: took the guitar to a experienced musician. The guitar is fine as described here. Looks like my old guitars were not so good.
Comment: well that's good news.  Sometimes resonance is annoying.  Now you'll develop very fine technique.  Have you worked through a book like Carcassi Guitar Method?  it discusses (1) the value of resonance in making good sound, and (2) damping when needed.  You'll grow to appreciate it.
Answer: The problem caused by "sympathetic resonance." On any string instrument, the strings actually cause the whole instrument to resonate. So, the vibration of the higher strings is activating those lower strings as well.
Some instruments (like the sitar) are designed specifically to enhance these sympathetic resonances, but if you don't want the lower strings to resonate, you will need to mute them with either your left-hand fingers or right-hand palm.
If the sound is unpleasant, though, you should take it to a guitar tech, so they can take a look at it.
Comment: I dunno. Sounds to me like the guitar has a very nice sensitive top. All my guitars do this.
Comment: It isn't normal. Sympathetic vibration can, and does occur, but nowhere near to the extent shown in the question. And generally, it's the other way - low notes may create s.v. in higher open strings. And if both E and A are affected, it sounds like the guitar may be faulty.
Comment: Thanks. I have 2 other guitars and neither does this at least it is not so noticeable. And the sound it produces it actually harsh on my ear. Not a nice sound.
Comment: Perhaps the guitar needs some adjustment, but the reason for the vibrating low E and A is definitely sympathetic vibrations. I'll adjust the answer.
Comment: I wouldn't judge this as a problem without a measure of the natural sustain of the instrument.  I have acoustics that sustain for ~20-30sec which is wonderful!  The sympathetic resonances will ring for a long time, this in not abnormal, it is entirely normal.  If you OP is having trouble with just 2 notes then there is some irregularity in the guitar, otherwise this is absolutely normal.
Comment: I am an advanced beginner and this guitar supposed to be my new nice guitar. However compared to my old guitar the sustained E and A ruins my play. For example while I am picking the upper strings they produce a sound which overshadows my play.
Comment: @RM. I can't imagine what this could be if not normal sympathetic resonance (which, as both answers said, is a _good_ thing). But if it really sounds so strange, why don't you post a short recording? That would allow much better diagnosis.
Comment: @RM, I agree with leftaroundabout, post a short recording.  It is possible that your guitar has an unnatural resonance and you don't always want it.  Like I said, classical guitarists learn technique for controlling with both hands.  But as you said this is your "nice" guitar.  You may have learned on a guitar with weak or no resonance and developed your technique accordingly, as well as expectations.  Did you play this guitar before buying it?  And is it just resonance or do you hear buzzing too?


Question about head voice and high notes

Question: Isn't the head voice where you feel the vibrations of singing in your head, whereas the chest voice is where you feel them in your upper chest? I am confident I have sung in chest voice several times, but I don't think I have ever sung in head voice! However, most times I do not notice any vibrating at all.
I notice that when I try to sing high notes, I have to sing louder to get them! In contrast, when I sing in lower notes, a normal to low volume is sufficient. Could me unwittingly staying in chest voice have anything to do with this when I try to sing high notes? Or do higher notes in general require more volume than low notes to be sung?
Also, I feel my singing a lot in my throat. While there is no pain or hoarseness in my voice, there is a slight tension there, especially when trying high notes or sustaining any note for too long. Some websites have said this is wrong. Is that correct? It may be my breathing is wrong. I am a novice singer, so there is a lot I don't know. Does transitioning into head voice require more volume or air?
Thank you!
Answer: The terms "head" and "chest" voice don't actually make a whole lot of sense since classical singing pretty much invariably tries to sing with an "open" throat and the feeling of singing on an air column starting on the diaphragm and reaching to the "mask" which feels like more of the source of sound than the throat should: if you ask a megaphone which part of it feels "the loudest", it will probably misidentify the actual sound of vibration as well.
I think you'll find a lot of useful information in the questions How do I know if I am using mixed voice? and What is the difference between male head voice and falsetto?.


Sails.js: how to populate array using model associations

Question: I'm using  "sails": "~0.10.0-rc5", "sails-mongo": "^0.10.0-rc3".
I have 2 models: Invoice, Item.
Invoice model
Invoice: {
    name: 'sample 1',
    items: [1,2] // 1,2 is id of Item model
}

Item model
Item {
    id: 1,
    name: "king"
}
Item {
    id: 2,
    name: 'queen'
}

I want the result to be:
Invoice: {
    name: 'sample 1',
    items: [{
        id: 1,
        name: "king"
    }, {
        id: 2,
        name: 'queen'
    }]
}

I read model associations from the sails docs but i don't know how to use it in my situation.
Comment: could you share the solution if you managed to find one?
Answer: Your item model will look like this:
attributes: {
    name: "STRING"
    // You don't need the ID field as this is automatically created for you
}

Your invoice model will look like this:
attributes: {
    name: "STRING"
    items: {
        collection: "item",
        via: "item"
    }
}

Now create a few documents of the item model.
sails> ModelNameOfItem.create({name:'MyFirstItem'}).exec(console.log)
null { name: 'MyFirstItem',
  createdAt: Tue Feb 11 2014 15:45:33 GMT-0600 (CST),
  updatedAt: Tue Feb 11 2014 15:45:33 GMT-0600 (CST),
  _id: "some_id_created_by_mongo" }

Now create a document of the invoice model.
sails> ModelNameOfInvoice.create({name:'MyFirstInvoice', items:"the_id from_item_created"}).exec(console.log)
null { name: 'MyFirstInvoice',
  createdAt: Tue Feb 11 2014 15:45:33 GMT-0600 (CST),
  updatedAt: Tue Feb 11 2014 15:45:33 GMT-0600 (CST),
  _id: "some_id_created_by_mongo" }

Thats all! To query this, use the populate method.
sails> Invoice.find({name:'MyFirstInvoice'}).populate('items').exec(console.log);

Comment: Hi display_name:
I try, but it doesn't work with array of item. It just work on item.
Comment: @user3487954 I updated my answer to include the `collection` and `via` attribute. The code is not tested, but fetched from the sailsjs documentation. Should work :)
Comment: In the Invoice.create, Shouldn't items:"the_id from_item_created" be items:["the_id from_item_created"]?
Comment: @aludvigsen the question clearly states it requires an array of items. This answer is only re-inventing the wheel!
Answer: The right answer is:
in invoice model:
...
items: {
  collection: 'item'
}

Comment: I do not know how I can get this to work. Is that really supported. @Thinh Pham can you point us at any official sails documentation


How to slow down migrate? Cloud Files can't keep up

Question: I'm using migrate to import 2800 blog posts. Each have a header image which is getting imported. I'm using Rackspace Cloud Files as my CDN so the system is copying the image files up to Rackspace Cloud Files, but after it's been running for awhile I start getting this error:

(/home/drupal/html/sites/all/libraries/rackspace/php-cloudfiles/cloudfiles.php:608)
  Invalid response: (curl error: 35) error:02001018:system
  library:fopen:Too many open files: Failed  [error] to obtain valid
  HTTP response.

My -guess- is that the migrate is working too quickly and the file transfers are happening in parallel or something and I'm hitting a limit on the number of open files for Rackspace. I'm not exactly sure.
I'd like to try adding a delay in between each node. There are only 2800 and I can let it run for a little while, so I don't mind the delay as long as it'll let me complete the migrate.
Comment: Do you have any code to share on how your doing this using Migrate ? What libaries / functions are you using ...
Answer: In your migration scripts you can use either prepare() or complete() (http://drupal.org/node/1132582) and add in sleep(). It's a hacky solution but it should give you enough time between processing each row for Rackspace to catch up.
<code>public function prepare($node, stdClass $row) {
  sleep(30); //wait for 30 seconds
}
</code>
Comment: I'm experimenting with sleep(1) for now. :) Thanks.
Answer: I discovered the true problem (although I'm still accepting the other answer because my question was specifically about slowing the migration down).
I believe there is a bug in the rackspace cloudfiles api which causes connections to not be closed properly. In normal, web-based, circumstances this isn't a problem because at the end of the processing all of the connections are closed and you never usually open enough connections to have a problem.
However, I'm running the migration via drush from the command line which means the process isn't ending for a VERY long time after A LOT of connections and eventually I hit the limit for the max number of open "files."
Please see this question for the solution I used to avoid the problem entirely:
Migrate with Cloud Files fopen:Too many open files


iOS CollectionView: Display View, then download images, then display images

Question: I have a collection view, which contains cells in each section, and each cell has an image in it.
Possibly, the collection view holds 20 or more cells.
I want to load the images off the internet into the cells. The issue is that this can take a few seconds, and I want the collectionView to be displayed even if the images have not downloaded completely.
The collection view is given an array that contains the URLs, and so far, I have been downloading off the internet within collection view cellforitematindexpath
However, the view only becomes visible after all the cells have been loaded, and since each call to collection view cellforitematindexpath downloads an image, if 20 images are pulled off of URLs, it takes way to long.
What can I do to display the view, and THEN download the images, and then display them?
Hope I made myself understandable, if not, please ask!
Thanks!
C
Comment: Have you seen `SDWebImage`? Will make your life 100x easier: https://github.com/rs/SDWebImage
Comment: Another option would be AFNetworking. AFNetworking has some categories on UIImageView that will do what you want: https://github.com/AFNetworking/AFNetworking/blob/master/UIKit%2BAFNetworking/UIImageView%2BAFNetworking.h
Answer: Yes, you could use SDWebImage (as mention at comment above).
Another interesting side you could face out, that if image haven't load yet and user scroll view, it could be problems with dequeueReusableCellWithReuseIdentifier:forIndexPath, so it's better to download images throw id <SDWebImageOperation>.
Prepare for reuse will be something like this:
- (void)prepareForReuse
{
    [super prepareForReuse];

    if (self.imageOperation)
        [self.imageOperation cancel];

    self.imageOperation = nil;
}

And load will be like this:
SDWebImageManager *manager = [SDWebImageManager sharedManager];
self.imageOperation = [manager downloadWithURL:[NSURL URLWithString:urlString]
                                      options:SDWebImageRetryFailed
                                     progress:nil
                                    completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) {
                                        if (image)
                                        {
                                            self.imageView.image = image;
                                        }
                                    }];

Comment: Do I need to make my CollectionView a UICollectionReusableView? That means I need to get rid of my loadView method?
Comment: The method's described in the answer should reside in the UICollectionViewCell subclass, not the UICollectionView and yes you should by default use reusable cells.


Why does pure-ftpwho require root permissions?

Question: Why does pure-ftpwho require root permissions to run, if you run it without it you get,

You must be root to run this. Sorry.

However, /usr/bin/who can run fine without root?
Answer: From the pure-FTPd FAQ

How do I give access to the 'pure-ftpwho' command to non-root users?
The 'pure-ftpwho' command is restricted to root by default, because users
probably shouldn't be given the ability to spy what other users are doing on
the same host. However, it's safe to put the setuid bit on that command, in
order to have it work as any user:

sudo chmod 4711 /usr/sbin/pure-ftpwho


Keeping single sheets of music on the stand

Question: I have been looking for a music stand with a retaining lip to stop single sheets of music from sliding off the shelf at the bottom of the stand, so far without success. Is there a particular term I should be searching for, or perhaps other stand designs to help hold music in place?
Comment: What's wrong with gluing/screwing a strip of wood onto the shelf?  Or doing what we do when playing in the open, use a couple of clothes pegs. Stick a strip of carpet. Adapt ! Think laterally!
Comment: I've taken the liberty of rewording your question so that it won't be closed as off topic (equipment recommendations are off topic here). Please, if I've unduly damaged your question, post a comment back to me, and I'll roll back my changes.
Comment: I believe they don't make them this way because it would interfere with turning pages of a book. It would also not allow a thicker book to sit flush on the stand. Another solution is a sheet of clear plexiglass over the music. The music will stay put and also keeps the wind from taking it if you're outdoors or under a strong A/C vent.
Comment: Use of a lip won't work anyway. The slightest breeze or vibration will send your sheet flying.  Use a stand with builtin clips as Tetsujin's answer says.
Comment: I thought the reason stands weren't available with lips might be to do with page turning - that's not normally an issue for me as I stick several sheets together.  Plexiglass sounds like the way to go - thanks all
Comment: @JohnBelzaguy - funny, that. I've just finished welding a music stand to slot into my keyboard stand - over 1 metre wide (some of my charts are 8+ pages), and I used clear plastic sheet, like you'd find on a ragtop car roof, with a 1" strip of Plexiglass glued to its bottom. Just in case I ever get another gig.
Comment: PetGriffin Home improvement stores usually carry clear plexiglass in various sizes. As long as you can angle the stand so you're not getting a direct reflection they work great. Avoid wire stands, they're very portable but unstable and have very small desks. @Tim I'm a big fan of WIDE music stands. I have one that opens up into a double but unfortunately it's pretty  heavy.
Comment: @JohnBelzaguy - trouble is, carriage from U.S. is not cheap! Those stands that get used in schools - I've never passed the exam you have to take to be able to open and close them in one go. Yes, my wide one is heavy, but fits onto the k'board stand, so isn't a big deal. i wonder whether those Ipad things might be a better option - with the footswitch, you can do repeats and everything!
Comment: @Tim IPad has made up 90% of my reading gigs the last couple of years so the big stand collects dust.. I have a Peak stand, lightweight, portable, collapses into an included gig bag. There are other similar ones.
Comment: @John Belzaguy - Which is fine when you turn up after being given the dots previously. A lot of my gigs I'm lucky (or not) to be given the key to the next number. Actually, it's better when I'm not... And what happens when the bandleader changes an arrangement at rehearsal?
Answer: Any basic folding stand has little clips that fold up to stop your pages flipping, or a sheet falling off.
tbh, it was only a search on Amazon that threw up solid face ones without clips that made me even think such without clips were even available. Obviously made by manufacturers who have never played an instrument in their lives.:\
Just search "folding music stand" for a million varieties.
Comment: I thought of these too. There are a few non-wire stands that have this feature as well, Donner and Peak to name a couple.
Answer: Magnets tend to work reasonably well for pinning down single sheets.  One reason not to use a single sheet, however, is that it tends to become a real nuisance when backlit.