Drupal confusion when including multiple instances of same webform on a page

Question: I have nearly the same problem than this : Multiple forms on single page?
But the answer  is for an inclusion on a page template and I want to do the same on a node template where I can't use any incremental ID loop. I'm using Drupal 7.
Answer: In either Display Suite or a node template just call the forms using drupal_get_form each form will given a unique build_id and there should be no problem displaying any number of forms on the page.
hook_forms in this answer https://drupal.stackexchange.com/a/6230/3279 has nothing to do with your question. You don't need to worry about incremental form IDs or anything.
Here is an example of how to use a preprocess function for a Node (type):
http://purencool.com/drupal-7-preprocess-tutorial-adding-variable-to-template this uses this Drupal API function https://api.drupal.org/api/drupal/modules!node!node.module/function/template_preprocess_node/7
Your code would look something like (this is example code not guarenteed to work):
function MYMODULE_preprocess_node(&$vars) {
  if ($vars['node']->type == 'MY_NODE_TYPE') {
    // link to webform paths.
    $vars['custom_form_links'] = implode(' ', array(l('Please Fillout Form 1', 'some/path/to/webform'), l('Please Fillout Form 2', 'some/path/to/webform2')));
    // Or just embed the forms.
    $form1 = drupal_render(drupal_get_form('myform1'));
    $form2 = drupal_render(drupal_get_form('myform2'));
    $vars['custom_forms_embed'] = $form1 . $form2; // You may want additional HTML wrappers, figure it out.
  }
}

Then in your themes template files for like node--YOURCONTENTTYPE.tpl.php you echo these new variables.
Display Suite makes all this a ton easier with Code Fields, or custom fields, and dynamic view_modes so you don't need to touch template files either ...
None of this code is guarenteed to run -- it's just a rough example.
Answer: I think you can get your form on template if you know their ids.
$form1 = drupal_get_form('form1_id');
$form2 = drupal_get_form('form2_id');

And then render by drupal_render()
drupal_render($form1);
drupal_render($form2);

Comment: @cocoggu, you should update your question with information on comment, as other people might not read full comment of each answer.
Comment: Thank you for answer but I want to add each form at the bottom of a type of node. Each form is linked with the title of the node. So I have to code it in my node template one time and it will add the SAME form at the end of each node. So for example with a view, I will have multiple same form on my page but all are linked with the first node.
Answer: Use Panels module. You can embed any number of webforms in a single page using panels module. Create a custom page and add existing nodes as content
Comment: Thank you but I think I have poorly explain my problem, see my comment on Shuaib Nawaz answer


Laravel 5.2 No connector for []

Question: I have just installed Laravel 5.2 and i'm trying to get the reset password feature to work, but i'm getting the following error:

InvalidArgumentException in QueueManager.php line 150:
No connector for []

Does anyone know how to fix this?
My .env file contains:
APP_ENV=local
APP_DEBUG=true
APP_KEY=xxx

DB_HOST=localhost
DB_DATABASE=mydb
DB_USERNAME=mydb
DB_PASSWORD=xxx

CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=iron

MAIL_DRIVER=mailgun
MAIL_HOST=smtp.mailgun.org
MAIL_PORT=587
email@example.com
MAIL_PASSWORD=xxx
MAILGUN_DOMAIN=mydomain.co.uk
MAILGUN_SECRET=key-xxx

Comment: Please post your .env file
Comment: @KaloyanDoichinov I have edited my original post and included the contents of the `.env` file.
Comment: Do you have the iron-mq client library installed? The queue is configured for IronMQ but it's complaining about that driver
Answer: Laravel 5.2 removed the IronMQ queue driver. It is no longer included by default.
If you would like to use IronMQ, you will need to use the Laravel Collective IronMQ package.
Once you install this package (installation instructions provided by package), your issue should be resolved.
Answer: Check your config/queue.php file to make sure the driver property is set to env('QUEUE_DRIVER').
Also make sure that the iron-mq dependency is met (documented in the Laravel 5.2 Queue Configuration)
Comment: and run `php artisan config:cache` just in case, this was the cause of the problem in my case, default config was cached

Laravel 5.2 No connector for []


The zeros of an analytic function are isolated

Question: I am reading a homework problem. I have to prove that the zeros of analytic functions are isolated, what does "isolated zeros" mean? Could you, please, examples or some drawings? In my understanding isolated zeros mean the zeros of the function have no multiplicity.
Comment: Isolated $0$s mean that for each $z$ such that $f(z)=0$ then there exists an open set $U$ containing $z$ with the property that $f(w) \neq 0$ for every $w \neq z$ in $U$
Answer: $f$ has an isolated zero at $z_0$ if $f(z_0)=0$ and for some $r>0, 0<|z-z_0|<r\implies f(z)\ne 0 $.  This has nothing to do with multiplicity:  $z^2$ has an isolated zero at $z=0$
Answer: One definition of the zeroes of a function $f$ being isolated is that whenever $f(z) = 0$ there is an $\varepsilon > 0$ such that $f(w) \neq 0$ for every $w$ such that $0 < |z-w| < \varepsilon$.
A side remark is that you probably mean to talk about non-zero analytic functions.
Answer: zeroes are said to be isolated if for each zero $x_i$, you can find a neighborhood $U_i$ of $x_i$ so that $U_i$ does not contain any of the other zeroes.
In other words, you can draw a little disk around each zero so that it contains only that zero.
To see that this is really important, consider the function $\sin(1/x)$ with $x>0$, which is continuous but has many concentrated zeroes.
Comment: The zeroes of $\sin(1/x)$ are isolated. A better example would be $f(x)=x\sin(1/x)$ for $x\neq0$ and $f(0)=0$.


Mutable vs. Immutable with business logic objects

Question: A lot has been said about mutable / immutable objects in the data model.
But what about the business logic? For example: a CD player. One class is responsible for playing the CD.
// Immutable version:
class Player
{
    CD cd;
    public Player(CD cd) { ... }
}

// Mutable version:
class Player
{
    CD cd;
    public void ChangeCD(CD cd) { ... }
}

I can think of several subtle advantages and disadvantages to both versions.
For example, when player is mutable, other objects can take the player and it stays valid even if the CD changes. When player is immutable, you need a wrapper object (e.g. Command Pattern) that gets updated when a new Player is created.
Which version is preferable in which cases? Are there any general guidelines?
Answer: Here's a third option.
class Player
{
     // private CD myCD <- no private field for the CD
     public Player() {}
     public void playCD (CD cd) {}
}

A player should never own a CD object. It should just be told here is a CD object, play it.
A better option would be
class CDPlayer : DataPlayer
{
    public Player() {}
    public void playData (IData cd) {}
}

class CD : IData {}

If you reduce the amount of coupling between your CD and Player then you really don't have to think too hard about this.
I believe your example is a bit flawed with respect to your actual question.
Comment: So you would pass a CD object with each method - e.g. Pause(cd), Seek(cd, time)? And the Player has no state that pertains to any CD. Looks good, but where would you store the CurrentPlaybackPosition in this design?
Comment: @LTR that depends. I was going to load the data from the CD directly into some kind of private binary buffer. Then you can just stop, walk forwards/backwards and overwrite that buffer completely.


Find a field $K$ with $\operatorname{char}K=2$ which has an algebraic extension $F$ containing a particular subset

Question: I am looking for an example of a field $K$ of characteristic 2, which, for some algebraic extension $F$ of $K$, $F$ contains a subset $S$ such that:
a) $K\subseteq S$,
b) $S$ is a vector space over $K$,
c) $s^n\in S$ for all $s\in S$ and all positive integers $n$,
d) $S$ is $\textit{not}$ a subfield of $F$.
This is from Beachy and Blair Abstract Algebra, which asks to find an example of a field $K$ which is a counter example to exercise 6.2.11 (no such $S$ exists if $\operatorname{char}K\ne2$).
Thank you for any help and I apologize if my grammar is bad, I am learning English. Thank you.
Comment: With "$s^n\in S$" you mean this is true for all integers $n\ge0$?
Comment: Yes, sorry , all positive integers.
Answer: Take a field $K$ of characteristic 2, let $L=K(x,y), F=K(u,v)$ rational functions in two variables and consider the inclusion $L\subset F$ given by $x\mapsto u^2, y\mapsto v^2$. Let $S$ be the $L$ vector space generated by $1,u,v$. Then $S$ is not a subfield, since $uv\not\in S$. But, easy to check that $s^n\in S$ for any positive integer $n$ and $s\in S$.


How do I show only those node that have images available via a view?

Question: I have a content type with image, title, and body fields. I created a view to show these things on front end.
Here images are not available for all nodes of this content type.
I need to show only those nodes in front end that have images.
Comment: @Kiamlaluno why you put this question on hold????
Answer: You can achieve it by following steps.

Add  Image field filter criteria.
Now in configuration, select operator Is not empty (NOT NULL).
Comment: I think the previous comment is obsolete now ...


How to filter based on I18n content with pagination component?

Question: I have comeup with strange problem in cakephp 3.4. I am running filter query on i18n content like this.
if($this->request->query("q")){
    $this->paginate["conditions"][$this->ContractTypes->translationField('title').' LIKE'] = '%'.$this->request->query("q").'%';
}

but following call is ending up in Database error
$records = $this->paginate($this->ContractTypes);

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'ContractTypes_title_translation.content' in 'where clause' SELECT (COUNT(*)) AS `count` FROM contract_types ContractTypes WHERE ContractTypes_title_translation.content like :c0

The paginator's count query is not joing i18n table. What is the best approach to solve this problem.
Thanks in advance,
Comment: Please always mention your _exact_ CakePHP version (last line in `vendor/cakephp/cakephp/VERSION.txt`) - thanks!
Answer: I have solved this by creating my custom paginator component by editing the paginate function. My paginator contains following code incase somebody else is facing the same problem.
namespace Console\Controller\Component;
use Cake\Controller\Component\PaginatorComponent as BasePaginator;

class PaginatorComponent extends BasePaginator
{
    public function paginate($object, array $settings = [])
    {
        $query = null;
        if ($object instanceof QueryInterface) {
            $query = $object;
            $object = $query->repository();
        }

        $alias = $object->alias();
        $options = $this->mergeOptions($alias, $settings);
        $options = $this->validateSort($object, $options);
        $options = $this->checkLimit($options);

        $options += ['page' => 1, 'scope' => null];
        $options['page'] = (int)$options['page'] < 1 ? 1 : (int)$options['page'];
        list($finder, $options) = $this->_extractFinder($options);

        if (empty($query)) {
            $query = $object->find($finder, $options);
        } else {
            $query->applyOptions($options);
        }
        $cleanQuery = clone $query;
        // My Modification Starts Here
        $table      = $cleanQuery->repository();
        $results = $query->all();
        $numResults = count($results);

        $count = $numResults ? $cleanQuery->select([
            "count"=>$cleanQuery
                        ->func()
                        ->count($table->alias().'.'.$table->primaryKey())
        ])->first()->count : 0;
        // My Modification ends Here
        $defaults = $this->getDefaults($alias, $settings);
        unset($defaults[0]);

        $page = $options['page'];
        $limit = $options['limit'];
        $pageCount = (int)ceil($count / $limit);
        $requestedPage = $page;
        $page = max(min($page, $pageCount), 1);
        $request = $this->_registry->getController()->request;

        $order = (array)$options['order'];
        $sortDefault = $directionDefault = false;
        if (!empty($defaults['order']) && count($defaults['order']) == 1) {
            $sortDefault = key($defaults['order']);
            $directionDefault = current($defaults['order']);
        }

        $paging = [
            'finder' => $finder,
            'page' => $page,
            'current' => $numResults,
            'count' => $count,
            'perPage' => $limit,
            'prevPage' => $page > 1,
            'nextPage' => $count > ($page * $limit),
            'pageCount' => $pageCount,
            'sort' => key($order),
            'direction' => current($order),
            'limit' => $defaults['limit'] != $limit ? $limit : null,
            'sortDefault' => $sortDefault,
            'directionDefault' => $directionDefault,
            'scope' => $options['scope'],
        ];

        if (!$request->getParam('paging')) {
            $request->params['paging'] = [];
        }
        $request->params['paging'] = [$alias => $paging] + (array)$request->getParam('paging');

        if ($requestedPage > $page) {
            throw new NotFoundException();
        }

        return $results;
    }
}


Oracle SQL Select Unique Value AND Only one value from matching rows with non-unique values

Question: I have two tables, a master table and a general information table. I need to update my master table from the general table. How can I update the  master table when the general info table can have slightly different values for the descriptions?
Master
+------+---------+
| Code |  Desc   |
+------+---------+
|  156 | Milk    |
|  122 | Eggs    |
|  123 | Diapers |
+------+---------+

Info
+------+---------------+--------+
| Code |     Desc      | Price  |
+------+---------------+--------+
|  156 | Milk          | $3.00  |
|  122 | Eggs          | $2.00  |
|  123 | Diapers       | $15.00 |
|  124 | Shopright Cola| $2.00  |
|  124 | SR Cola       | $2.00  |
+------+---------------+--------+

As you can see item 124 has 2 descriptions. It does not matter which description.
My attempt is returning 124 with both codes, I understand my code is looking for both the unique Code and description in the master which is why it returns both 124 but I'm unsure how to fix it.
INSERT INTO MASTER
(
SELECT UNIQUE(Code), Desc FROM INFO A
WHERE NOT EXISTS
   (SELECT Code FROM MASTER B
   WHERE A.Code = B.Code )
);

I have also tried:
INSERT INTO MASTER
(
SELECT UNIQUE(PROC_CDE), Desc FROM FIR_CLAIM_DETAIL A
WHERE Code NOT IN
    (SELECT Code FROM FIR_CODE_PROC_CDE_MSTR B
    WHERE A.Code = B.Code )
);

Comment: You write "*I need to update my master table*" but your examples are all `SELECT` statement. What exactly do you want to do? Just display those values or actual run an `UPDATE` statement that changes the master table?
Comment: `GROUP BY Code` and `SELECT MIN/MAX(Desc)`
Comment: Sorry I forgot to add my Insert statement in. I was working the select to identify the problem / verify the results before inserting the values because there is a need for the master table to have only unique codes.
Answer: Unique filters the duplicated entries in the SELECTed result set across all columns, not just one key.
When you want to extract the other attributes of a key you filtered, you have to instruct the database to first group the unique keys. To choose one of attributes of a grouped key, we can use an AGGREGATE function. Like MAX(), MIN().
INSERT INTO MASTER
(
SELECT PROC_CDE, MAX(Desc) FROM FIR_CLAIM_DETAIL A
WHERE Code NOT IN
    (SELECT Code FROM FIR_CODE_PROC_CDE_MSTR B
    WHERE A.Code = B.Code )
GROUP BY PROC_CDE
);

There're analytical functions which can be used for even complex requirements.
Comment: This worked! Thank you so much, I'm still new to SQL.


Enumerate possible states transition of Workflow Foundation state machine

Question: For GUI purposes I need by current state of state machine to enumerate possible available states of transition. For example there is transitions: A->B, A->C, B->D, C->D. Assuming state machine is in A state, so I need get list of B and C.
Answer: I've found my own answer, right now it looks as stupid question.
So, it is enough to create lightweight object StateMachineWorkflowInstance around my instance of Workflow, here the code:
StateMachineWorkflowInstance smw =
            new StateMachineWorkflowInstance(MyWorkflowRuntime, A);
return smw.PossibleStateTransitions.ToArray();

Answer: In .NET 4.0, the WorkflowApplication.Idle event contains WorkflowApplicationIdleEventArgs, which contains a Bookmarks property.


Express in gamma/beta functions $\int_{0}^{\pi/2}\tan^n x \ dx$

Question: Express in gamma/beta functions and find n's that intergral converges.
$\int_{0}^{\pi/2}\tan^n x \ dx$
i am stuck a little bit
Comment: Also relevant, https://math.stackexchange.com/questions/1041201/int-0-frac-pi2-frac1-tanpx-mathrmdx-where-p-ge-0
Answer: Hint:
Let $t=\sin^2x$, giving $dt=2\sin x\cos x\,dx$.
Then
$$2\int \sin^n(x)\cos^{-n}(x)\,dx=\int \sin^{n-1}(x)\cos^{-n-1}(x)\,dt=\int t^{(n-1)/2}(1-t)^{-(n+1)/2}\,dt.$$


Add "more" button/link to end of the grid list

Question: I have grouped GridView.
For each letter I`m displaying 10 signs (Sign). After displaing 10 I want to add "more" link/button. For example button the has diffrent color and has special onclick event.
How can I do this for each group ?
Answer: You should

Add another item of a different type at the end of each group of items you bind to the GridView with ItemsSource
Write a DataTemplateSelector implementation that will use a different DataTemplate for regular items and the last item
Set GridView.ItemTemplateSelector to your custom DataTemplateSelector.
Comment: but if I`m binding `List items` I should change it to `List items` ? But what object should I add ?
Comment: Right, you would use List and put in something like SignViewMore in the list and implement SignViewMore so that when its corresponding DataTemplate gets clicked or tapped - you get more items. Also - if you are planning on adding more items in the GridView when that item gets tapped (which is not recommended) - you would need to use an ObservableCollection instead of the List so the view updates when you do add more items to the list.
Answer: The design guidelines says: Users can tap on the section label to drill in to the corresponding page for that section. Provide a visual cue, like View all (x), to indicate to users that there are more items in this section that what is shown in the hub. Using this pattern avoids the need to use a tile space or place a link within the content.
However, I want to be honest that some developers and designers do not feel that this is a sufficient enough affordance to help users intuitively navigate their applications. In the end, the guidelines are not the rules. They are the guidelines. Adding a "view all" tile to your applications is your decision. If it helps your app, do whatever helps.
And if you do then DataTemplateSelector is the way you change the template displayed. In order for this to work, you would need to include the index of the items in your list so that you know where to put this final tile. This keeps you from having to mix data tyles as Filip suggested (a valid but heavy-lifting solution). Anyway, it's up to you and it's easy.
Comment: thank you for your response. I`m aware that guidlines are just guidlines not rules :) Bot I want to take from them a lesson and combine my solution (more button) with navigation in title of group by putting more button in the title. It is much easier to achive and I get - what in my opinion - is the best for user
Answer: This is not the way you want to develop a Windows 8 App. There is not need for a "more"-button.
Take a look at the Grip-App-Template. It is using the grid group header to navigate to the group. This is the recommended way.
Use the content as navigation and not a button.
I really recommend you to take a look at the design guidelines: http://msdn.microsoft.com/en-us/library/windows/apps/hh770552
Comment: As Jerry Nixon said below, guidelines are guidelines, and real life is real life. Endless scrolling is also good, but not for all scenarios. So, if you really need "add more" button, check Jerry's answer http://stackoverflow.com/a/12643002/883738
Comment: I've got this design from company recomended by Microsoft for us and there is link at the end of the list. I'm just implementing this so I'm not thinking is this correct way or not. But thanks for the tip. You way is much easier and I will get it for discussion :)
Comment: thanks this is much better. First of all it doesn`t need so much work. Secondly it`s more intuitive
Comment: Yes and it is what Microsoft wants. I tried to submit some apps to the store and they failed the certification cause of such little things. :)


Bootstrap navbar not working on Chrome

Question: I'm making a website using this theme:
https://bootstrapthemes.co/item/jwood-photography-portfolio-html-landing-page-template/
But there's a problem: the navbar doesn't work on Chrome. It looks good but doens't take you anywhere when clicked. It works perfectly on IE. Can you help me, where's the problem with this? I think it worked when i downloaded the theme a couple weeks ago. I haven't made any changes to the code that would effect the navbar.
The live preview page has the same problem:
https://bootstrapthemes.co/demo/html/one-page-portfolio-landing-page/
Comment: give us some code, please.
Comment: @Goran he did give the website which contains the full code ^^ That's his problem, he doesn't know where is the problem coming from
Comment: @IslamElshobokshy oops, my bad.
Comment: Since when do we consider external code ontopic on Stack Overflow? @IslamElshobokshy
Comment: Confirmed: Does not work on Chrome/Mac and on Opera/Mac either. Does work on Safari/Mac and on Firefox/Mac.
Comment: @ChristianGollhardt we do not, but I found it easier to give directly the source of the problem. Why does it bother you 4 months later? :)
Comment: Pick your answer.
Answer: In main.js change this:
$('#navbar-collapse')
to this
$('.navbar-collapse')
and it will help,
Still there is a problem with menu background on mobile devices.
Comment: to keep background menu on mobile devices it should be changed:  var windowWidth = $(window).width();
    if (windowWidth > 200)
Comment: This solves the problem. I have no idea why it works in other browsers - `$('#navbar-collapse').find('a[href*=#]:not([href=#])').length` is zero.
Answer: In the live demo HTML header:
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

It's still valid to use IE=edge, chrome=1 but the chrome frame project has been wound down (Jan 2014) so it is redundant for browsers that don't already have plugin installed. To pass the W3C validator the chrome=1 should be removed. This could be a cause.
Comment: Did you try your answer before posting it? This doesn't work.
Comment: Tried removing the **chrome=1** from the code but it didn't help. Cleared my browser cache also and still not working
Answer: This seems to be related to the jQuery Plugin localScroll being a very  old version (1.3.5 from 2014, as opposed to 2.0.0 being the current version):
https://github.com/flesler/jquery.localScroll/issues/38
Remove the plugin from plugins.js and replace it with the current version. That should fix the issue.

Bootstrap navbar not working on Chrome


My script run only through 1 "if" on 2

Question: Here is a description of what I want to do :
I've 2 csv files.
I want to search the same thing (lets call it "hugo") in my 2 files at the same time.
The thing is that it only print one and not the other.
Here is my code :
try:
    while True:
        if pm10pl[j][2] == '"Victor Hugo"':
            victor1 = pm10pl[j]
            print victor1

        if pm25pl[t][2] == '"Victor Hugo"':
            victor2= pm25pl[t]
            print victor2

        j=j+1
        t=t+1
except IndexError:
    pass

I've tried different things such as elif instead of if, replace t by j, passing by 2 functions. Each if works perfectly when the other is not here, and when I invert the 2 of them, that's the same that print aka pm25pl.
Can't do anything.
(here is only the part of my code that has interest, opening of file etc works fine, the '""' is normal hugo appeared in my file as "hugo" (with the double quote))
Plus, I can't call victor1 and victor2 outside of the if.
Do you have any idea what's going on ?
Comment: are your files the same length?
Comment: If you loop like this (an infinite loop in a `try`?!), your loop will stop when the shortest file runs out of lines. That's probably not what you want.
Comment: for each csv: look for X, print X
Comment: @bouletta : Nope, the 2 files does not have the same length :/
Comment: @WanderNauta : You're right, but if it could at least show me something that'd be great ;)
Answer: You can iterate through 2 lists simultaneously using itertool's zip function.
import itertools

l = []
for victor1, victor2 in itertools.izip_longest(pm10pl, pm25pl):
    if victor1 and victor1[2] == '"Victor Hugo"':
        #print victor1
        if victor2 and victor2[2] == '"Victor Hugo"':
            #print victor2
            l.append((victor1, victor2)) # add the pair to list.

for i in l: # prints all pairs.
    print i

Comment: I'll try it after, I've to go now, I came back to you if any problem or if it's good,
Thanks for answering anyway :)
Comment: It looks like it's working but... It never stop.
Had to add a break to stop it :)

But, if now I want to record them in a variable like :
smth = [victor1][victor2]
How can I do that ?
I'm self-learning in python so... sorry if I  have simple question :/
Comment: Never stops? What is the size and type of pm10pl and pm25pl? Is it a list?
Comment: You can use tuple to store it together. `smth = (victor1, victor2)`.
Comment: Yep, the type is list ''
Size of one is 291 and the other 194.

when I do 'smth = (victor1, victor2)' it only print me the last line. I don't have access to the other line (and each of them are important).
Answer: Do one list comprehension for each csv file:
[pm10pl[i] for i in range(0,len(pm10pl)) if 'Victor Hugo' in pm10pl[i][2]]
[pm25pl[i] for i in range(0,len(pm25pl)) if 'Victor Hugo' in pm25pl[i][2]]

Comment: Here is the error it throw :
AttributeError: 'str' object has no attribute 'str'
Comment: @Hawkydoky Try it this way. Edited
Comment: @Hawkydoky Sorry. I'm having brain farts. Shouldn't say "is in", only "in"

My script run only through 1 "if" on 2


Guitar for super-small hands?

Question: I've been playing piano for past 5-6 years and I can't reach further than an octave (Even some chords within the octave are not reachable, or it's hard/borderline impossible to play them with reasonable speed) Fingers are proportionally short.
While I still enjoying playing the piano. I'm looking for an instrument that is not significantly less versatile, but is suitable for hands of my size.
I've already taken a brief look at classical guitar, and that clearly is not an instrument I find comfortable at all. I can't play/reach most chords, or some of them only in a way that doesn't produce a clean sound.
Compared to the piano, where getting piano with 7/8 sized keys costs a fortune (well, buying decent regular piano costs a fortune too), guitars of all sizes are ridiculously cheap(comparatively speaking of course!), and getting 3/4 sized electric is easily affordable.
Now there a few questions regarding this topic:

What are the best electric guitars with small nut/neck?
Do I need to get 3/4 size guitar or is regular sized electric with small/neck nut gonna be small enough to play comfortably (remember, very small hand, can barely reach an octave!)?
What are the best 3/4 sized electric guitars?

Although I'm a complete beginner with guitars, I would like the guitar to sound really good, that is extremely important for a beginner. So I can spend significant money on the guitar if need be. (say up to 1000 eur) (If I'm gonna play on headphones mostly do I need to get an expensive AMP too? Or any will suffice?)
Comment: Have you considered learning the ukulele? They are *not* toys; if you want to spend $1000 on a uke, you can (and it will be lovely). YouTube has examples of virtuosos playing serious music. Even with your tiny hands, a soprano uke will feel small. A tenor uke is bigger, but still smaller than a 3/4 guitar, and because it's the "right" size for what it is, doesn't have the tonal compromises of a 3/4 guitar.
Comment: Shopping recommendations are off-topic (see the [FAQ]).  If you want to change this to be about distinguishing guitar types and how to select one appropriately for fit, that would be acceptable, but as-is it will be closed.
Comment: I thought I'd let you know that if you're not set on guitar and are looking for an instrument for which hand size matters not at all, woodwinds and brass are it. Like *not at all*, reach has *nothing* to do with playing them.
Comment: Always good to get some advice here, but more practical is to try out some guitars in a music store. In my humble opionion, nobody buys a guitar, I mean a real instrument from 50 euro / dollar upwards, without trying it out in the store. Classical guitars come in several sizes, I own a regular size, and one that is two frets smaller, but you also can get three frets smaller. You are looking for an electric guitar, but just try out some of these to test the reach of your fingers. Then, for a beginner, reach is not that important. An expert can use other strings if reach is a problem.
Answer: Classical guitars are distinct in that their standard method of play is notes all over, so there's a wide neck to allow you to fret one string without accidently sounding on another. Steel-string acoustic designs are designed more for strumming, so the neck is narrower, which is closer to what you want. However, the more popular body designs for acoustic were created for projecting loudly, which means big and wide. Presuming that your small hands are relatively proportional to your body, I'd say look for a 00 or smaller guitar, or maybe a Taylor Big Baby.
Electric guitars are easier in oh so many ways. One of the iconic figures in rock is Angus Young of AC/DC, jumping around in his schoolboy uniform with a Gibson SG. Angus Young is a short man with small fingers, and he's playing on a standard SG.
1) Depends on what kind of playing you want to do, whether looks matter to you, and how much money you want to spend. A lot of the "shredder" brands like Ibanez, Charvel and Jackson use neck profiles that are "fast", by which they mean skinny, which should work well with your hands. The SG also has a skinny neck that at least Angus thinks works well with his small hands.
2) The tuning of guitars is such that heroic string stretches are rarely necessary.
3) 3/4-size instruments are generally designed for young people who are not finished with their growth spurts, who will want to step up to the next guitar fairly soon. They are not of the same grade as full-size guitars.
ETA: Another thing to add is scale length. Fenders generally have a longer scale length of 25.5", which makes the reach harder on the lower frets, while Gibsons have about 24.75". Normally I see that discussed about string tension, but it works toward hand size.
Comment: "so there's a wide neck to allow you to fret one string without accidently sounding on another" - yeah, but if the finger is small, that might not be an ussue, no?
Comment: Angus Young small hands? Smallish? Yeah. Small? No. Significantly bigger than mine. I'm really afraid I'm not gonna be able to play unless its 3/4. I hate doing all sorts of acrobatic tricks - having to move hands all over the place like a madman with inhumane agility, speed and precision just to play simple things, whereas player with decently sized hands doesn't have to move hands at all (I've had plenty of that on piano). FML
Comment: Giving the best advice I can. I'm 6'3" with reasonably big hands (can't palm a basketball, but I can easily shuffle sixths in G). Really, the only way to really tell is to go to a well-stocked guitar store and start trying things on.
Comment: +1 Great answer. When it comes to acoustics, whereas 1/2 or 3/4 size classical guitars aren't that brilliant, Martin do a half size model (a la Ed Sheeran) that is not too bad at all. http://www.musiciansfriend.com/guitars/martin-lx1-little-martin-acoustic-guitar
Comment: I think there's misconceptions about what I mean with super-small-hands. Smalls hands doesn't mean the hands are just not that big, or that they are wee-bit on smallish-side. For the record, in piano players world small hands usually mean you can reach from C to E. I mean there's really no point in playing if your hands are any smaller than that unless you're willing to seriously limit yourself and your repertoire. Even with C to E reach you'll have extremely hard time playing significant amount of pieces.
Comment: Here a good picture of hand sizes: http://www.steinbuhler.com/assets/images/HandSizePage_12.gif ( I have ~7 inch reach. Yeah. ) That basically is a super-small, 12 year old boy(girl?) hand.
Comment: I started playing a full-size Yamaha classical when I was 10.  It was the first guitar I ever touched.  I am a girl and only grew to 5'2".  Sure, it was difficult, but with daily practice, I was playing things like Led Zeppelin's Over the Hills and Far Away pretty quickly.
Comment: I just looked at your reach chart and measured my own.  7 inches.
Answer: Unless you're dead set on an electric you might take a look at parlor models like this one or these?
You also have Taylor GS Mini or the Sierra ST10 Compass among others.
Comment: I'm by no means dead set on electric. It's just that electric guitars are usually have thinner necks and hence are easier/more comfortable to play.
Comment: The A&L Ami is a very nice guitar, but its sibling, the Seagull Grand, is an amazingly responsive steel-string fingerstyle guitar - and it sounds *great*. I wouldn't use it for rhythmic playing, though.
Answer: The majority of chords are going to be a 4-fret reach or less, and the frets get closer together as you move up the fret board towards the body, so worst case is at the nut (fret 1). All guitars vary by manufacturer, but a fender 22-fret is probably about 5 inches for the first 4 frets, and the distances get smaller as you go up the board. (see for instance: http://www.stewmac.com/fretscales )
There are some chords I play which are 5 frets wide with a barre, but they are easily avoided. Note that I have a finger span of about 7 inches (WITHOUT the thumb, close to 10 with it).
Daisy Rock purportedly makes smaller and slimmer fretboard guitars catering to females.
Bring a chord sheet to a store and try the first position major chords and see if you can reach. B and F are probably worst-case.
Answer: The best way (for anyone, really) to find a guitar you are comfortable with, is to go to a guitar shop and try out different models for yourself. Then you will also get professional help from the people working in the shop (if the shop is serious about guitars). Dedicated guitar shops often have highly qualified staff, and you should not be afraid of asking questions.
As for your reference to piano and cannot fully reach an octave - this is not allways comparable. I have actually trouble reaching an octave on a piano, but that is not because my fingers are short. It is more related to that I can't stretch out my fingers enough. On guitar I don't have so much problem with that, unless the chord is streched over 4 bands or more. Most basic chords does not stretch over more than 3 bands.

Guitar for super-small hands?


Hitting a line in a $d$ dimensional cube

Question: Let $F$ be a finite field of order $n$, and let $d$ be an integer. A line in $F^d$ is a function $\ell: F \to F^d$ given by $\ell(t) = x + t*h$, where $x,h \in F^d$, $h \neq 0$, and $t*h = (tx_1, \ldots, tx_d)$.
For $3 \le k \le n$, how many uniformly chosen points in $F^d$ are needed to be drawn such that with high probability (say $2/3$), the set of drawn points contains $k$ different points from (any) line?
Clarification: the last line refers to a set that contain at least one line (not all lines).
Edit: a rough estimation regarding the number of draws needed (e.g., $O(n^d)$, $O(n^{d/2})$, $poly(d \log n)$, $O(d \log n)$, etc.) would also be very helpful.
Comment: I think you want $h\ne0$.
Comment: @joriki right, thanks.
Comment: The geometry you are referring to is often called the affine space $\mathrm{AG}(d,q)$.  You would usually associate a line with a pointset $\ell = \{\vec{x} + t\cdot\vec{h}\ : \ t \in F\}$, where $\vec{t}, \vec{h} \in F^{d}$ (with $\vec{h} \neq \vec{0}$).  And you would almost always say your finite field has order $q$ (this is just a notational thing, where $p$ is always assumed to be a prime and $q$ to be a prime power).
Comment: Just clarifying -- you want to draw enough points so that, with high probability, there *exists* a line containing at least $k$ of the points you drew.  Is that right?
Comment: The special case $n=81$ (i.e. a $4$-dimensional field over $\mathbb{F}_3$) with $k=3$ corresponds to the game of Set.  There's a card for each element of the field; each line (called a Set) contains $3$ points, and the question is: what's the probability that a given collection of $r$ cards contains at least one Set.  See http://math.stackexchange.com/questions/202862/in-the-card-game-set-whats-the-probability-of-a-set-existing-in-n-cards for a detailed discussion.  (If you're sampling points with replacement, the question is slightly different, but I don't think it's easier.)
Comment: Yes Tad, exactly. Thanks for the reference. Is the asymptotical behavior of the probability of getting a set after drawing $n$ cards known?
Answer: I think you need to consider arcs (when $d=2$) or caps (when $d>3$).  The normal definition of an cap is a collection of points, no three on a common line (an arc actually only coincides with this definition in a plane).  What you are interested in are the number of $(s,k-1)$-caps (common literature will refer to $(k,d)$-arcs in planes, this is a generalization); this will be a set of $s$ points such that no more than $k-1$ are on a common line. Any set of size $s$ will either be a $(s,k-1)$-cap, or else have the property you are interested in.
Unfortunately the best reference I can find is mangled in the postscript conversion (weak).
[Old answer refers to the problem of ensuring every line contains at least $k$ points]
This is not an easy problem at all. The first question would be, how many points do you need in a set $\mathcal{S}$ for it to even be possible that every line contains at least $k$ points of $\mathcal{S}$? Such a set is called a $k$-fold blocking set (with respect to lines).  You can see some details here.  I think this type of problem is more difficult in affine spaces than in projective spaces.  To do an analysis of the probability, you would need to know how many $k$-fold blocking sets of size $s$ there were, and you could compare that to ${q^d \choose s}$.
Unfortunately I can't give you an answer, just point out that these are well-studied objects (with lots of related open problems). Probably the most interesting (and well studied) area of research is on small blocking sets in projective planes (a search on google scholar for the term "blocking sets" will turn up lots of results).
Comment: I'm afraid my question was ambiguous. I meant how many points are needed such that w.h.p. they will contain at least one line. I'll edit it accordingly (sorry for the confusion).
Comment: Thanks Morgan, I'll try to see whether I can find something helpful in the literature. Do you perhaps have a rough estimation regarding the number of draws needed? $O(n^d)$? $O(n^{d/2})$? $poly(d \log n)$? $O(d \log n)$?
Comment: Thanks Morgan! It seemed to me like the type of problems for which one can get an asymptotic bound via elementary combinatorics/probability tools (e.g., compute the expected number of draws to hit a line and then use tail bounds -- a bit like the coupon collector problem) -- but all my attempts thus far failed.
Comment: By the way, regarding the *every* line contains at least $k$ points variant -- it seems closely related to Kakeya sets: https://www.cs.princeton.edu/~zdvir/papers/Dvir09.pdf


Captcha is not working as expected.Visible on webform when logged out and invisible when logged in

Question:

I have not selected any of the options:

Default challenge on non-listed forms.
Add CAPTCHA administration links to forms
Allow CAPTCHAs and CAPTCHA administration links on administrative pages

I have selected persistence:
Omit challenges in a multi-step/preview workflow once the user successfully responds to a challenge.
Answer: That is expected behaviour. Under permissions there is an option:

Skip CAPTCHA
Users with this permission will not be offered a CAPTCHA.

Admin by default has this set meaning they won't see the Captcha. Captcha isn't necessary for an Admin since they are assumed to be trustworthy.
You can also set other roles here so that they don't see the Captcha. If you have strong Bot deterrents in user registration, you probably don't want authenticated users to have to go through the Captcha process after every node/comment/etc creation as this will just cause annoyance, especially for regular contributors. If you allow anonymous content creation, obviously you don't want to provide this option for that role, or the Bots will come knocking...


How do I not fall into other people's singing pitch?

Question: When I am at the karaoke with my friends, I often sing with them and realize, when I sing alone, I can sing the song perfectly but when I sing with someone that is of higher pitch/lower pitch, I tend to automatically switch to a higher/lower pitch, depending on the person I am singing with, which affects me. Are there any methods I can use in order for me to not fall into their pitch? Thank you in advance.
Comment: @user45266 probably an E or F?
Comment: @piiperi If OP is talking about singing harmony or with singers who are in a different octave, then there's no issue. Of course, if that's the question, it's almost certainly a dupe.
Comment: Jose, are the other singers doing a harmony part, or are they simply unable to sing the melody in tune?
Comment: @user45266 , they are singing just fine, just that their singing pitch might be higher, making me automatically sing in a higher pitch subconsciously
Comment: How much higher are we talking? If you're singing a C, what note are they singing?
Answer: This is a very common problem, particularly when singing harmonies.  It's easy to slip onto the other person's part!
If you want to study methodically, get a hymn book and practice singing the alto or bass part while a friend sings the tune.
Answer: Instruments -- piano,  tanpura etc -- are more kind and tolerant than fellow humans. They will put up with any amount of fumbling patiently!
And nowadays there exists a "universal instrument"  -- computer (or cellphone).
Just make sure it has a half decent speaker.
And spend your time -- alone with this patient harmonizing friend!

PS Can share some musescore exercises if you like


Can you solve a quadratic equation using matrices?

Question: I was wondering whether there are any alternatives or more efficient methods to finding a solution to a quadratic equation other than simply trial and error or by using the quadratic formula.
I was once told that it could be very easily done using matrices. How would this work?
Additionally, are there any other "better" alternatives?
I would really appreciate if you were to give me examples and explain how to solve them with the alternate method.
Thank you :)
Comment: what's inefficient about using the formula?
Comment: I would complete the square rather than use the formula. Just as quick but so much more informative.
Comment: elimination and matrix methods are simply flavours of the same thing really, as are using the equation or completing the square for a quadratic.
Comment: @danimal  I am not saying that it is inefficient I was just wondering whether there was anything more efficient.
Comment: @Paul Yes, I guess that would work but it still isn't very different form what usually do. I was hoping that there were a complete alternative. For example, we can solve simultaneous equations using elimination, substitution or even by using matrices.
Answer: You can solve the quadratic equation $x^2 + ax+b=0$ by computing the eigenvalues of the companion matrix
$$
\pmatrix{ 0 & - b \\ 1  & -a}.
$$
Simple and efficient.

 Of course not! It requires to solve exact the same equation most of the time. The characteristic polynimial of the matrix is $x^2 + ax+b$.
Comment: I love the spoiler!!! I am waiting for the next episode :)!
Comment: Generates the same quadratic??
Comment: .........................lol
Answer: You could use Newton's method.  If you draw a triangle, you see that for
$$\frac{f(x)}{x - x'} = f'(x)$$
that $f(x')$ is close to zero.  Since you want that $x'$, you can solve for $x'$:
$$x' = x - \frac{f(x)}{f'(x)}$$
Applying $f(x) = ax^2 + bx + c$, you get that
$$x' = \frac{ax^2 - c}{2ax + b} \approx 0$$
So use any given starting $x$ to find a closer $x'$, and use that to find a closer $x''$ by applying the same formula again, etc.
If you want a rational approximation, you can use $x' = \frac{p'}{q'}$, and $x = \frac{p}{q}$:
$$\frac{p'}{q'} = \frac{a\left(\frac{p}{q}\right)^2 - c}{2a\left(\frac{p}{q}\right) + b} = \frac{ap^2 + cq^2}{2apq + bq^2}$$
So repeatedly applying:

$$\begin{cases} p' = ap^2 - cq^2 \\ q' = 2apq + bq^2 \end{cases}$$

to almost any starting value will let you quickly approximate a root of a quadratic, as long as $p/q$ never becomes exactly the min or max of the quadratic.  I guess you might use something like this in hardware if you have to quickly compute a root and don't care much about accuracy.  I'd still probably use the quadratic formula though.

If you encounter a quadratic formula of the form $x^2 + 2bx + c$, which is a bit of a standard form for some uses (like conics), then the quadratic formula actually becomes very simple:  $$\pm \sqrt{b^2 - c} - b$$


Prove S' is a closed subset of X

Question: Given the metric space $(X, d)$, with $S$ as a subset of $X$, I'm trying to prove that $S'$ is a closed subset of $X$.
My thinking is to prove that the complement $X - S'$ is open by choosing some point $x$ in the complement and showing that it is an interior point. Is it sufficient for me to say that $x$ then must be either an adherent point or an isolated point, and therefore an interior point?
Additionally, I am to find an example of a subset $S$ in the real numbers such that $(S')'$ is not equal to $S$. I'm a little lost as to what this would mean, but I'm thinking it might be true for the set $S = \{ \frac 1n : n \in \mathbb{N}\}$. I know that the set of accumulation points for this set is ${0}$, and I'm thinking its set of accumulation points would be the null set, but I'm not sure if this is correct.
Comment: what set is $S'$?
Comment: Perhaps the prime means the complement?
Comment: @Masacroso It means the derived set: https://en.wikipedia.org/wiki/Derived_set_(mathematics)
Comment: Sorry, yes it means the derived set! I apologize for being unclear.
Answer: Let $x_n \in S'$ such that $x_n \to x$
We will prove that $x \in S'$
Now each $n \in \mathbb{N}$ we  have that $x_n$ is a limit point of $S$
So for  $\epsilon=1$ exists $y_1 \in S$ such that $d(x_1,y_1) < 1$
For $\epsilon=2$ exists $y_2 \in S$ such that $d(x_2,y_2)<\frac{1}{2}$
Continuing this way we find $y_n \in S$ such that $d(x_n,y_n) < \frac{1}{n}$
Thus $y_n \to x $ because $$d(y_n,x) \leq d(y_n,x_n)+d(x_n,x) \to 0$$ and $y_n \in  S$  so $x$ is a limit point of $S$ thus $x \in S'$ proving that $S'$ is closed.
For a counterexample take the open interval $(0,1)$  in the usual topology of the real line.

Prove S' is a closed subset of X


How to get the accurate total visitors count in ASP.NET

Question: I want to know the number of visitors online on my site. I did my research and found two solutions.
Source: Code Project
Online active users counter in ASP.NET
It is easy to setup and easy to use but it increases the user count for every Ajax request/response too. My home page alone has 12 Ajax requests(8 requests to one page and 4 requests to another page). This dramatically increases the user count.
Source: Stack Overflow Q/A
Count the no of Visitors
This one works exactly the same as the previous one.
Source: ASP.Net Forum
How to see "who is online" using C#
This one looks better than the previous two. Here is the detail code of this solution.
void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup
        HttpContext.Current.Application["visitors_online"] = 0;
    }

void Session_Start(object sender, EventArgs e)
    {
        Session.Timeout = 20; //'20 minute timeout
        HttpContext.Current.Application.Lock();
        Application["visitors_online"] = Convert.ToInt64(HttpContext.Current.Application["visitors_online"]) + 1;
        HttpContext.Current.Application.UnLock();
    }

void Session_End(object sender, EventArgs e)
    {
        HttpContext.Current.Application.Lock();
        Application["visitors_online"] = Convert.ToInt64(HttpContext.Current.Application["visitors_online"]) - 1;
        HttpContext.Current.Application.UnLock();
    }

It seems to be able to ignore the increasing the count for every Ajax response but it still adds up for each page refresh or page request.
Is there any approach to count the accurate number of online visitors in ASP.Net?
Comment: Easiest way I can think of would be to hook into the Session_Start() in the global.asax file. Increment your count there
Answer: You can never get an entirely accurate number: there is no way to (reliably) detect that a user "has navigated to another site" (and left yours) or that that user "closed the browser".
The Session_Start/Session_End way has the problem that Session_End is only called for "InProc" sessions, not if the sessions are stored in StateServer or SqlServer.
What you might be able to do:

Hold a Dictionary<string, DateTime> in Application scope. This stored session-id's (the string key) against the time of latest access (the DateTime value)
For each request with a valid session, find the session entry in the dictionary and update it's latest-access time (add a new entry if not found)
When you want to get the number of online users, first loop through all entries in the dictionary and remove items where the session timeout has passed. The remaining count is the number of online users.

One problem (at least): if one user uses two browsers simultaneously, he has two sessions open and is counted double. If users always log in, maybe you could count on login-id instead of session-id.
Comment: Thanks a lot Hans. It is all working now but the site is now working really slow for some reasons. I will update my code below if someone needs this code or has any comment.
Comment: Any ***solution*** for `Session_End` sessions are stored in _SqlServer_?
Answer: I want to propose something completely another: try to use Google Analytic for this. These guys add beta functionality that allows tracking online statistics now.
EDIT: You don't get me. I mentioned not standard Google Analytic functionality. I mentioned new feature - Real-Time. Check next article for details - What's happening on your site right now? or watch this video - Google Analytics real-time beta
Comment: We are already using it. The problem is we know how many visitors visited for each day but we don't know how many users are currently on our site. That's why I need to implement this on my own way.
Comment: full sample using GA in asp.net ?
Comment: @PreguntonCojoneroCabrón you don't need server side code to start using GA. Just put JavaScript code that Google provides on your account page into Master page of your asp.net app.
Answer: This is the source code I implemented according to Hans Kesting's suggestion.
Global.asax
void Session_Start(object sender, EventArgs e)
    {
        System.Collections.Generic.Dictionary<string, DateTime> Visitors =
                            new System.Collections.Generic.Dictionary<string, DateTime>();
        Visitors.Add(Session.SessionID, DateTime.Now);
        HttpContext.Current.Application.Lock();
        Application["Visitors"] = Visitors;
        HttpContext.Current.Application.UnLock();
    }

HttpHandleder.cs
private static void UpdateVisitors()
    {
        System.Collections.Generic.Dictionary<string, DateTime> Visitors = (System.Collections.Generic.Dictionary<string, DateTime>)HttpContext.Current.Application["Visitors"];
        Visitors[HttpContext.Current.Session.SessionID] = DateTime.Now;
    }

AnyPage.aspx.cs(where you want to get the number of total online users)
 protected int GetCurrentOnlineUsers()
        {
            int total = 0;
            Dictionary<string, DateTime> Visitors = (Dictionary<string, DateTime>)Application["Visitors"];
            foreach (KeyValuePair<string, DateTime> pair in Visitors)
            {
                TimeSpan Remaining = DateTime.Now - pair.Value;
                int remainingMinutes = Convert.ToInt32(Remaining.TotalMinutes);
                if (remainingMinutes < 21) //Only count the visitors who have been active less than 20 minutes ago.
                    total++;
            }

            return total;
        }

Comment: performance `Session_Start` and more 4000 users in appweb ? **HttpHandler** ?
Answer: Just as Hans mentioned, you will probably have to switch your session state to StateServer or SQLServer, but this is not something a snippet of code can do. There is a very good reliable and detailed article on codeproject that treats this problem properly.
Comment: You don't HAVE to switch to StateServer or SqlServer, it's when you USE them that Session_End doesn't work.
Comment: I actually thought you were ill-advising him against InProc, if he's developing a website or webapp to accommodate a lot of traffic or use multiple servers, InProc will definitely be a bad idea, the article above clearly explains the pros and cons of using InProc.
Answer: Hans's solution is really great and working exactly what I want but I just found this article on MSDN recently which seems to be the best practice for this purpose.
REF: http://msdn.microsoft.com/en-AU/library/system.web.httprequest.anonymousid.aspx
Global.asax
void Application_Start(Object sender, EventArgs e)
    {
        // Initialize user count property
        Application["UserCount"] = 0;
    }

public void AnonymousIdentification_Creating(Object sender, AnonymousIdentificationEventArgs e)
    {
    // Change the anonymous id
    e.AnonymousID = "mysite.com_Anonymous_User_" + DateTime.Now.Ticks;

    // Increment count of unique anonymous users
    Application["UserCount"] = Int32.Parse(Application["UserCount"].ToString()) + 1;
}

.ASPX file
<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>AnonymousID Example</title>

    <form id="form1" runat="server">

        Number of users:
        <asp:Label ID="lblUserCount" Runat="server"></asp:Label>

    Current user:
        <asp:Label ID="lblCurrentUser" Runat="server"></asp:Label>

    </form>

Answer: Why not check the user IP to get unique visits. Add them to a hashset so you can do nice things like make a heatmap using a location API:
 // count users online on all desktopsites
        void Session_Start(object sender, EventArgs e)
        {
            try
            {
                // lock application object
                Application.Lock();

                // get hashset containing all online ip adresses
                var ips = (HashSet<string>)Application["visitors_online_list_ip"];

                // get user ip
                var ip = HttpContext.Current.Request.UserHostAddress;

                // add ip to hashset
                ips.Add(ip);

                // store ip in session to delete when session ends
                Session["ip"] = ip;

                // save hashset
                Application["visitors_online_list_ip"] = ips;

                // unlock application object
                Application.UnLock();
            }
            catch {}
        }

        void Session_End(object sender, EventArgs e)
        {
            try
            {
                // lock application object
                Application.Lock();

                // get hashset containing all online ip adresses
                var ips = (HashSet<string>)Application["visitors_online_list_ip"];

                // get user ip from Session because httpcontext doesn't exist
                var ip = Session["ip"].ToString(); ;

                // remove ip from hashset
                ips.Remove(ip);

                // save hashset
                Application["visitors_online_list_ip"] = ips;

                // unlock application object
                Application.UnLock();
            }
            catch {}
        }


What are the mean and variance of the log of a random variable?

Question: Here's the problem.
We have a random variable X that follows a Poisson law. If we take the log of this variable, what are the first two moments (mean and variance) of the law it follows?
This looks like a simple question, but I can't find anything about it. Any idea?
EDIT: In order to prevent the X=0 case, we bias the Poisson law. Our random variable becomes log(X+epsilon) with X~Poisson(λ).
Comment: You can't take the log of a Poisson-distributed random variable. The values it assumes are not all in the domain of the log function.
Answer: Recall that the mean $\mathbb{E}(X)$ of a random variable $X$ is a weighted average of the possible values of $X$, weighted by the probability $P(X = x)$ of each outcome $x$ of $X$. Hence, the mean of a function $f(X)$ is a weighted average of the possible values of $f(X)$, weighted by the probability $P(f(X) = f(x))$. But the probability that $f(X)$ takes the value $f(x)$ is the same as the probability that $X$ takes the value $x$ (this is not exactly true, since $f$ might take the same value for multiple $x$, but for the purpose of taking a weighted average it doesn't matter since the effective weight on $f(x)$ will be the sum of the probabilities of each such $x$ either way). This allows us to use the following formula to find the mean of $f(X)$, with sums or integrals depending on whether $X$ is continuous or discrete:
$$\mathbb{E}(f(X)) = \int f(x) \cdot P(X = x) dx$$
$$\mathbb{E}(f(X)) = \sum f(x) \cdot P(X = x).$$
Similarly, the variance is a weighted average of the squared difference between each value $x$ and the average value $\mathbb{E}(X)$, weighted by the probability $P(X=x)$. So we can similarly calculate the variance of $f(X)$ "by hand" once we have the mean, using:
$$\text{Var}(f(X)) = \int \left(f(x) - \mathbb{E}(f(X)) \right)^2 \cdot P(X = x) dx$$
$$\text{Var}(f(X)) = \sum \left(f(x) - \mathbb{E}(f(X)) \right)^2 \cdot P(X = x).$$
In both cases, the sum or integral is taken over all possible values $x$ of your variable $X$.
Note that as per Henry's answer, naively plugging $f(x) = \log(x)$ into these formulas will get you in trouble if $X \sim \text{Poisson}(\lambda)$, as you'll have a diverging integral. For a Poisson distribution, which allows $X = 0$, taking the mean and variance of $log(X)$ is only sensible if you first exclude $X = 0$ from your domain somehow. So this answer is conditional on $X$ remaining in the domain of $f$.
Comment: In the case of a Poisson _distribution_, as Henry pointed out, mean and variance of $log(X)$ will be meaningless. I've added a note to the end of the answer explaining when these formulas will be useful and when they won't.
Comment: What of X=0? (see other answer)
Answer: This is also called delta method. If $g(X)$ is a function of random variable $X$, and $g(X)$ is differentiable, in practice we can use first-order Tylor expansion at $\bar{X}$, the mean of $X$: $$g(X) \approx g(\bar{X}) + \frac{d}{dX}g(\bar{X})(X-\bar{X})$$
Therefore, $$E[g(X)] \approx g(\bar{X}) + \frac{d}{dX}g(\bar{X})E(X-\bar{X}) = g(\bar{X}),$$ because the second term is 0.
Similarly, the variant is:
$$Var[g(X)] \approx Var(\frac{d}{dX}g(\bar{X})X) = [\frac{d}{dX}g(\bar{X})]^2Var(X)$$
In your case $X\sim Poisson(\lambda)$, $g(X) = logX$; plug in and you got:
$$E(logX) \approx log\lambda$$
$$Var(logX) \approx \frac{1}{\lambda}$$
You have to be careful with X=0 case, as other folks have already stated.
Answer: With a Poisson distributed random variable $X$ with parameter $\lambda$, you have $P(X =0) = e^{-\lambda} \gt 0$.
$\log(0)$ is undefined, or at best negative infinity, so it is meaningless to talk about the mean and variance of $\log(X)$.
Comment: @BCLC Perhaps I misread "Poisson law", but $0$ is in the support of every Poisson-distributed random variable and has positive probability, as I showed.  Perhaps not for a "Poisson process", but I would assume that followed an "exponential law".
Comment: Who says 0 is in the range of X?


Check if current page == a link

Question: I'm working with a content type skills, where i made a view with the titles(as links). This generates a kind of menu. Which is what i'm aiming for. Now i need it to check if you are on one of the pages in this so called menu. Because ofcourse. if the link is active it needs different markup.
note: I can't solve this with an onclick because there are multiple ways of getting on the skill pages.
I wrote the following code. but it doesn't seem to work:
function (themename)_preprocess_views_view_fields__our_skills(&$variables) {
    $variables['active_class'] = '';
    $current_uri = \Drupal::request()->getRequestUri();

    foreach ($variables['fields'] as $fieldname => $fieldvalue) {
        if ($fieldname == "path" $$ $fieldvalue == $current_uri){
            $variables['active_class'] = ' active';
        }
    }
}

The code above returns The website encountered an unexpected error. Please try again later.
thanks in advance.
Answer: CSS is enough assuming that you just want the color of link to change when active,
CSS for links within said view
.view-name > .view-content > .view-grouping > .view-grouping-header > a { color: blue; }

CSS for active links
.view-name > .view-content > .view-grouping > .view-grouping-header > a.active { background-color: white; text-decoration: none; border-left: #95e5d4 10px solid; color: black; }

Check if current page == a link


Conditional mean of Weibull to the power of N

Question: How can I (is it possible to) derive the conditional expectation of a variable $w$ that follows a 2 parameter Weibull Distribution $W(\lambda,k)$ with $\lambda$ scale parameter and $k$ shape parameter?
We know that:
$E[w^n]=\lambda^n \Gamma(1+\frac{n}{k})$
What is (is there) an expression for?
$E[w^n  |  \underline{w}<w<\bar{w}]$
Answer: As always, the effect of the scale parameter $\lambda\gt 0$ is merely to change the units of measurement of the variable.  Consequently the answer must be a multiple of $\lambda^n$ and that multiple is found by assuming $\lambda=1.$
By definition, the survival function of a Weibull variable $w$ with unit scale and shape parameter $k \gt 0$ is given by
$$\Pr(w \gt x) = \exp\left(-x^k\right).$$
Therefore, assuming $n\gt 0,$
$$\Pr(w^n \gt x) = \Pr(w \gt x^{1/n}) = \exp\left(-\left(x^{1/n}\right)^k\right) = \exp\left(-x^{k/n}\right)$$
shows $w^n$ follows a Weibull distribution with shape parameter $k/n$ (and scale parameter $1$).
These considerations have reduced the question to finding the expectation of a Weibull variable $X,$ of unit scale and shape parameter $k/n,$ that has been truncated at the values $l=\underline{w}\,\lambda^{-n}$ and $u=\bar{w}\,\lambda^{-n}.$  This expectation will equal
$$E[X] = C^{-1}\int_l^u x\,\mathrm{d}\left(1-\exp\left(-x^{k/n}\right)\right) = \frac{k}{nC}\int_l^u x^{k/n}\exp\left(-x^{k/n}\right)\,\mathrm{d}x\tag{*}$$
where the normalizing constant is
$$C = \Pr(l \le X \le u) = \exp\left(-l^{k/n}\right) - \exp\left(-u^{k/n}\right).$$
Multiply this expression for $E[X]$ by $\lambda ^n$ to account for the scale factor in $w.$
To evaluate $(*),$ change the variable to $y=x^{k/n},$ giving
$$\eqalign{
E[w^n\mid \underline{w}\le w \le \bar{w}] &= \lambda ^n\frac{k}{nC}\int_{l^{k/n}}^{u^{k/n}} y\,e^{-y}\,\mathrm{d}\left(y^{n/k}\right)\\
&= \lambda ^n\frac{1}{C}\int_{l^{k/n}}^{u^{k/n}} y^{n/k}e^{-y}\,\mathrm{d}y \\
&= \lambda ^n\frac{\gamma\left(n/k+1, u^{k/n}\right) - \gamma\left(n/k+1, l^{k/n}\right)}{\exp\left(-l^{k/n}\right) - \exp\left(-u^{k/n}\right)}\\
&= \lambda ^n\frac{\gamma\left(n/k+1, \bar{w}^{k/n}\lambda^{-k}\right) - \gamma\left(n/k+1, \underline{w}^{k/n}\lambda^{-k}\right)}{\exp\left(-\underline{w}^{k/n}\lambda^{-k}\right) - \exp\left(-\bar{w}^{k/n}\lambda^{-k}\right)}
}$$
where $\gamma(s,t) = \int_0^t x^{s-1}e^{-x}\,\mathrm{d}x$ is the incomplete Gamma function.
Comment: you are absolutely right. i was simulating the response to changes in t and i found an error in the code. a bit embarrassing. thanks for your help!
Comment: Dear whuber. For the example I'm working on, I get an expected value that is negative, which doesn't really make sense. This appears to be because the incomplete Gamma function is decreasing in the second term when this is smaller than 1. Am I missing something?
Comment: @Raimundo If by "second term" you mean the second argument of $\gamma,$ then I do not understand your remark, because the rate of change of $\gamma(s,t)$ with respect to $t$ is $t^{s-1}e^{-t}$ which is positive for all $t\gt 0.$
Comment: I have posted a question because I'm getting a strang result when trying to simulate this in R. Any help would be much appreciated. https://stats.stackexchange.com/questions/490456/incomplete-gamma-function-in-r-conditional-mean-of-weibull-to-the-power-of-n


Running rake task from a daemon

Question: I have a daemon that i made using the daemons gem
I run it and it just closes without error, but the script doesn't seem to be actually running.
 I'm running a rake task from it, will daemons run the commands inside from the directory it was called from?
This is the script
<code>require 'rubygems'
require 'daemons'

Daemons.run('rake mytask')
</code>
the rake task has a loop which should stop it from exiting.
Answer: I'm not sure the way you're doing this will work with daemons.  Can you move the rake task into an .rb file?  Daemons is going to pass what ever you have in the run command to ruby, so in essence it is trying to run "ruby rake mytask"

Running rake task from a daemon


How would you calculate the name of this C/A# 7th chord?

Question: I'm playing the following voicing of a C7 chord on the guitar:

Strictly speaking this would be denoted as a C7/A♯ slash chord.
But I'm trying to figure out what voicing name this would have.
Is this just a 3rd inversion or some other voicing name?

Let me explain why I'm confused...
A C7 in close position would be:

1 (C), 3 (E), 5 (G), ♭7 (B♭)

For me to construct the voicing shown in the image above, I would (in a practical sense) see that I needed to drop the ♭7 by an octave so it was played on the D string of the guitar. Which would then require me to move the root (C) up an octave (as I couldn't play both the ♭7 and the root on the same string).
In doing that, from a degree perspective, what we have now is:

♭7 (B♭), 3 (E), 5 (G), 1 (C)

Because the ♭7 is now in bass position, this suggests the voicing is a 3rd inversion of the chord. But the remaining degrees are not in order. Does that matter?
e.g. I would've thought a strict 3rd inversion to be [♭7, 1, 3, 5]

On a side note: I've been led to believe there are scenarios where a voicing could be called something like "drop n of n inversion", is that correct? I don't think that would apply to my primary question above. But I believe what I would've called a "drop 2 of Cmaj7" (just for example) could also have been called a "drop 2 of Cmaj7 2nd inversion" because the particular voicing I would likely use on the four high strings - d,g,b,e - would have the 5th degree in the bass position, which by definition is kind of like a 2nd inversion of the chord...
Comment: You seem well aware that the 7th is b7. So how could it be A#.?A is the 6th, making B the 7th. So now that note needs to be called Bb. I suspect it's a guitarist thing, whereby the 'black notes' always get called sharps...
Comment: Is that picture supposed to be a guitar fretboard?
Comment: I took out all the code blocks since they aren't necessary - it's fine to just type out letter names, or I like to use braces for when grouping is necessary. Code formatting can screw with screen-readers and other accessibility tools and stuff, so we try to avoid it when not necessary. Plus the blocks were preventing some of the examples from rendering properly.
Answer: The lowest note played in a chord denotes its inversion, regardless of the order of the higher notes, Thus, in C7, root position has C at the bottom, 1st inv. has E, 2nd inv. has G and 3rd inv. has Bb. The other notes need to be there (with the exception on occasions of 5), to constitute the named chord, of course.
It would be called C7/Bb (not C7/A#,as A# is an aug 6, we need b7).
On guitar there is sometimes a problem in that certain voicings cannot comfortably be fingered, thus a 5th may need to be left out, and sometimes it makes sense to double other notes, usually an octave apart.
There is a naming system called 'drop x' which you are aware of, and this is how the voicing you mention gets named.
Incidentally, you mention Cmaj7, which on guitar at least, doesn't sound good with a C note on the top string. The other inversions work well, but that one just doesn't seem to sound convincing.
Answer: Forgive the slightly pedantic answer, but this could be an A♯ in the bass and not a B♭. Spelled with an A♯, this becomes the "root-position" German augmented-sixth chord A♯–C–E–G.
While a C7 chord (with this pitch spelled as a B♭) will often resolve to an F chord, the augmented-sixth spelling will often resolve first to a B chord (or an E/B) and then to E. This is because this augmented-sixth is a predominant in E, and thus it moves to its dominant and then to tonic.
This is a relatively rare chord in the classical style (let alone in a popular style), but I think it's worthwhile to include it as a possibility.
Comment: @Aaron Yes, this is why I put "root position" in scare quotes. There are different views to it: some view C as the root, some view A♯ as the root (from a stacking-thirds standpoint), and others (myself included) consider it a chord without any real root at all.
Comment: ... or resolving ti Em/B
Comment: not root position: A# to G is a diminished seventh. C to A# is an augmented sixth. This would be third inversion.
Comment: Interesting, but extremely doubtful! Most guitarists aren't aware of German 6ths, but most guitarists *are* aware of dominant 7ths - even though they don't spell it correctly!
Answer: German augmented-sixth chords notwithstanding, this is a common guitar voicing for a C7, and it is a member of the drop-2 family of voicings. I would call it a "drop-2 in third inversion", but you could also call it a "drop-2 of third inversion"; either is correct. I wrote at some length about drop voicings on guitar in this answer.
Here are the drop-2 voicings of F7 on the top four strings; I chose F7 instead of C7 for this illustration since this makes it easy to start from root position and move up the fretboard to the subsequent inversions:
%X/X.X/X.3/1.5/3.4/2.5/4[F7]    %X/X.X/X.7/2.8/3.6/1.8/4[F7/A]

%X/X.X/X.10/1.10/1.10/1.11/2[F7/C]    %X/X.X/X.13/1.14/2.13/1.13/1[F7/Eb]

The shapes for C7 are the same as those above for F7, and you can see that the shape of the final F7/Eb matches the shape of OP C7 moved from the 8th fret to the 13th fret. On a chart I would probably only write F7; if the inversion really matters I would write, e.g., F7/Eb. But I wouldn't write out "F7 drop-2 in third inversion"; if the particular voicing is that important, I would just write it out on the staff.
Comment: Do you know the history or origin of the "drop" voicing terminology?  I've played guitar since about 1975 and never encountered it.  (Most of my theory education has been more pianistically inclined, so that may be why it is unfamiliar.)  It seems odd, especially the way it's numbered from the top.  Of course for someone who started on piano, learning theory on guitar seems to make as much sense as doing accounting work with Roman numerals.
Comment: @Theodore -- that's a good question, and I don't know. Piano players talk about drop voicings, too, but maybe its mostly a jazz thing. It's really just a systematic way to think about some useful 7th chord voicings; since they are useful, a lot of people know some of them without knowing the drop-n business.
Comment: @user45266 -- the drop-n nomenclature definitely comes from the mechanical procedure for forming these voicings (which I described in some detail in my linked answer), but I don't know when this terminology came into common use, or really anything else about its historical origins; I do think that it is an interesting question, and I'd be interested if someone had some insight into that.
Comment: Ah, you got me, somehow I missed that answer link. And on my own question, too - how embarrassing! :) Very interesting for sure. If you want to ask it as a question I'd be delighted to see where it ends up.
Comment: @Theodore You might already know this, but I believe it comes from the voicings that involve taking a close position (stack-of-thirds) seventh chord, then *dropping the second note from the top* down an octave. Why they chose to start counting from the top note, though, I have no idea. They also have drop-3 and drop 2&3, although those get weird on guitar I believe.
Comment: Funny! -- I hadn't noticed that the earlier question was yours; that was a while ago ;) Good suggestion; I might put together a question later this weekend.
Comment: @exnihilo We've been had! https://music.stackexchange.com/q/117220/37992
Answer:
Strictly speaking this would be denoted as a C7/A♯ slash chord.

Strictly speaking it's C7/Bb, there is no A# in a C7 chord.
Yes, it's third inversion.
It's an open voicing. In terms of "drop" voicing it's "drop 2" voicing. To get "drop" voicings, number voices from 1 starting with the top voice going down, then "drop" voices by lowering them by an octave, like this...

Because the ♭7 is now in bass position, this suggests the voicing is a 3rd inversion of the chord. But the remaining degrees are not in order. Does that matter?

Not in regard to the inversion. For that you only need to know which chord tone is in the bass.
After the bass, the arrangement of the remaining chord tones in various octaves will determine first whether the voicing is "close" or "open", and if it is "open", the "drop" terminology is the only standard for distinguishing specific spacings.
In terms of basic harmonic function only the root progression matters. All the rest of how individual chords are voiced is a matter of taste of how you like the intervals stacked vertically or a matter of voice leading regarding how chords connect in a progression. For example, any voicing of C7 to F is just functionally dominant to tonic, but C7/Bb to F/A brings in voice leading - specifically telling how the bass moves - then the specific voicings of the upper voices is mostly a matter of taste, unless they're specifically notated in some way. Lead sheets don't normally give voicings.
Answer: It would be interesting to have this chord in a context, e.g. G or Em.
It will be ii7 of G resp. iv7 of Em (with augmented root) resolving to BDG or BEG or B,D#,F#.
now you can say for easier reading this is C over A# but indeed this was A,C,E,G -> A#,C,E,G (chromatically transformed), so we have a dim3, dim5 and dim7, A# dim,dim,dim or A# diminished double dimineshed. I'm afraid nobody would understand this labeling.
It's simpler to describe it like Richard says as a Gerd chord , developed historically from Am7 (1st inversion=C,E,G,A)-C,E,G,A#, in "root position", an altered chord in G major or e- minor, functioning as a secondary dominant.
Answer: Inversion naming depends only on what the lowest note is.  It tells us nothing about the voicing.   So yes, it's C7, 3rd inversion.
If you wanted to describe the voicing, 'raise 2' might seem more appropriate than 'drop 2'  :-)


Views Page not showing pager

Question: I've got a Views Page showing Article teasers. There are lots of Articles in the db and I'm only showing 5 per page in the View, but the Pager is not showing up at all. Here is my Views configuration, am I doing something wrong? Is there a bug?

The preview in the Views screen does not show a Pager at the bottom of the content teaser and it also doesn't show on the real page.
Any ideas?
Comment: If I switch over to use Fields instead of Teasers, the pager DOES show up (wth?) but, of course, I've lost all of the styling that came with my theme on the teasers. I'd really prefer not to have to restyle EVERYTHING just because of what appears to be a bug. Any help?
Comment: Can you add, on the header of the view, the results summary for the view? And what happens if you change the content from teaser to fields?
Comment: Under "Advanced -> Theme" are any of the templates overridden? Or does /most-recent have a template applied?
Comment: Just to be clear - are you sure that you have more than 5 articles that are published?
Comment: When I add a Results Summary in the Header it shows "Display 1 -5 of 14" so I definitely have more content.
Comment: Advanced -> Theme doesn't show any overridden templates and that's what I expected to see.
Answer: This can have a whole bunch of reasons. I'm just providing the imho most probable non-obvious one:
Go to "pager settings" (on your screenshot click "Paged, 5 items") and change the "pager id". Docs say this is only needed when there is more than one view on a page, but i saw live examples where this fixed a non-showing pager on a single-view page.
Comment: This was the right answer for me!  I had recently included another view on the page, and apparently there was a pager id conflict.
Comment: I have long since fixed whatever page I was working on for them, but I believe this comment strikes at the heart of the problem I had (even though I solved it differently), so I'll accept it.
Comment: @KennyWyland could you please provide ur soln. too. Thanks.
Answer: I came across this issue recently since upgrading to views 3.8. for me the issue was caused by views_php module as discussed here: https://www.drupal.org/node/2276165 there is also a patch available to fix it.
Comment: Thanks Lee. I applied the patch from the link and it worked. This is a second correct solution when using views 3.8 and a views_php field within your view.
Comment: Worked for me with views_php 7.x-1.0-alpha1 as well.
Comment: https://www.drupal.org/files/issues/views_php-pager_missing-2276165-1.patch - Patch worked for me as well. Thanks.
Answer: The solution described in the answer from aexl worked for me.
For those who don't understand that answer, maybe this refined version of it helps:

Go to "pager settings" (on your screenshot click "Paged, 5 items") and
  change the "pager id" to something like 5 or any number instead of
  leaving empty.

Views Page not showing pager


SELinux - first attempt to restrict file by type - fails to fail

Question: I have a Centos 6 Linux box. I read tutorials on SELinux and wanted to try it out. Here are steps I followed,

set SELINUX=enforcing in /etc/selinux/config
turned on SELINUX with setenforce 1
service httpd restart
changed type on a php script file.
from httpd_sys_content_t
   to something else eg: init_t (maybe this is not suitable type to test with?)
chcon -t init_t /var/www/html/index.php

I hoped to get an error when I browsed to this file with web browser, but alas I was still able to see contents.
Comment: Relabel the whole system (`restorecon -r -v /`), reboot, and try again.
Comment: What was the SELinux configuration before you changed it to `enforcing`?
Answer: There is no need to relabel the whole system (this would be done with touch /.autorelabel; reboot instead of restorecon). Relabeling of /var/www/html using restorecon -Fr /var/www/html should be enough, then run your test again, assuming that yo did not change the file context of this directory using semanage.


Adding a formula to an existing code in VBA

Question: I have written this code
Private Sub CommandButton1_Click()

Dim sht As Worksheet
Dim NextRow As Long

Set sht = Sheets("Sheet1")
NextRow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row + 1

MsgBox NextRow

With sht
    With .Range("B" & NextRow & ":B" & NextRow + 4)
      .merge
      .VerticalAlignment = xlCenter
    End With
    With .Range("J" & NextRow & ":J" & NextRow + 4)
      .merge
      .VerticalAlignment = xlCenter
    End With
    With .Range("K" & NextRow & ":K" & NextRow + 4)
      .merge
      .VerticalAlignment = xlCenter
    End With
    With .Range("L" & NextRow & ":L" & NextRow + 4)
      .merge
      .VerticalAlignment = xlCenter
    End With
    With .Range("C" & NextRow & ":C" & NextRow + 4)
      .merge
      .VerticalAlignment = xlCenter
    End With
    With .Range("F" & NextRow & ":F" & NextRow + 4)
      .merge
      .VerticalAlignment = xlCenter
   End With

   .Range("A" & NextRow & ":A" & NextRow + 4).FormulaR1C1 = "=COUNTIF(R5C2:RC[1],RC[1])"

   .Range("B" & NextRow) = TextBox1
   .Range("J" & NextRow) = ComboBox1
   .Range("K" & NextRow) = ComboBox3
   .Range("L" & NextRow) = ComboBox2

   If CheckBox1 = True Then .Range("E" & NextRow) = "URS"
   If CheckBox2 = True Then .Range("E" & NextRow + 1) = "RA"
   If CheckBox3 = True Then .Range("E" & NextRow + 2) = "TM"
   If CheckBox4 = True Then .Range("E" & NextRow + 3) = "IOQ"
   If CheckBox5 = True Then .Range("E" & NextRow + 4) = "FR"

End With

MsgBox "All done"

End Sub

It is used to add a new line to my spreadsheet with  the information that is entered into a user form. I have all of this working, but I have two formulas in column C and F that I need to be carried into the new line. I can't simply drag the formulas down the column because there are merged cells in each row that are merged after my code is run. I have tried several different formula functions in my code and all are returning errors. Any ideas as to how I should add these formulas into my code?
Answer: Your formula that you're adding ("=COUNTIF(R5C2:RC[1],RC[1])") throws a circular reference error when you paste it into a workbook cell. The .Range().FormulaR1C1 = "" will fail because of the formula error. Adjust the formula and try again.


Django REST framework not picking up API endpoint

Question: I'm trying to refactor an API to use the Django REST framework. I've changed my urls.py to the following (still in Django 1.11):
from django.conf.urls import url
from . import views
from rest_framework import routers, serializers, viewsets
from .serializers import SessionSerializer
from .viewsets import SessionViewSet

router = routers.DefaultRouter()
router.register(r'^api/v1\.0/feedback/$', SessionViewSet)

urlpatterns = [
    url(r'^$', views.index),
    url(r'^api/v1\.0/profile/$', views.get_profile),
    url(r'^api/v1\.0/update_profile/$', views.update_profile),
    url(r'^api/v1\.0/update_password/$', views.update_password),
    url(r'^api/v1\.0/sessions/$', views.get_session),
    url(r'^api/v1\.0/user/$', views.get_user),
    url(r'^api/v1\.0/sessions/send_schedule_request/$', views.send_schedule_request),
    url(r'^api/v1\.0/sessions/confirm_session_time/$', views.confirm_session_time),
    url(r'^api/v1\.0/password_reset/$', views.password_reset),
    url(r'^api/v1\.0/me/apn/$', views.save_apn),
    url(r'^api/v1\.0/confirm_activation_code$', views.confirm_activation_code),
    url(r'^api/v1\.0/update_user_via_activation_code$', views.update_user_via_activation_code),
    url(r'^api/v1\.0/questions/$', views.get_questions),
    url(r'^api/v1\.0/answers/$', views.save_answers),
    # url(r'^api/v1\.0/feedback/$', views.record_feedback),
    url(r'^session_types/$', views.session_types),
    url(r'^send_custom_notification/(?P<id>\d+)/$', views.send_custom_notification, name='send_custom_notification'),
    url(r'^admin/lucy_web/send_session_time_notifications/(?P<user_id>\d+)/(?P<session_id>\d+)/$', views.send_session_time_notifications, name='send_session_time_notifications'),

    url(r'^admin/lucy_web/app_activate/(?P<id>\d+)/$', views.app_activate, name='app_activate'),
    url(r'^admin/lucy_web/create_activation_code/(?P<id>\d+)/$', views.create_activation_code, name='create_activation_code'),
]

However, if I python manage.py runserver and go to localhost:8000/api/v1.0/feedback/, I get a 404 error response:

It seems like the r'^api/v1\.0/feedback/ endpoint is not being picked up, even though it is passed as an argument to router.register(). Any ideas why this is not working?
Answer: You haven't added the default router urls back to the urlpatterns variable like this,
urlpatterns = [...]
urlpatterns += router.urls

Take a look at the usage section here
Comment: Indeed it seems I had forgotten to add `url(r'^api/v1\.0/feedback/$', include('rest_framework.urls')),` to `urlpatterns`. (I'm still getting other errors though, but the point is to `include` `rest_framework.urls`).


Reverse proxy causes issue with CSS links and HTTPS

Question: I have multiple Drupal instances behind a F5 load balancer. If I use it as http, that is OK. If I want to use http and https and ofload https on the LB, all CSS and JavaScript links in the https site comes as http and cannot be loaded because of the https security.
Comment: Install advagg, it has an option to convert css/js URLs to protocol-relative, which should fix the problem
Answer:
Do you have any css/js aggregation module installed. If so delete the caches under sites directory. You can even try uninstalling the module to debug if that is causing the issue.
Clear Drupal caches
Ensure you do not have global $base_url hard coded to http.
Answer: We have used a configuration similar to the one shown on Running Drupal Secure Pages behind a proxy. Have the F5 set a X_FORWARDED_PROTO = https header, then configure Apache to set HTTPS=on if the header is set.


How to get the perfect square for the following equation

Question: The problem is defined as follows:
$$
\min_X tr(X^T A X)-\alpha tr(X^T B)
$$
I want to get the equal perfect square equation as that above, that is
$$
\min_X \| X-C\|_F^2
$$
where $C$ is related to $A$ and $B$.
Is it possible? How to derive the perfect square equation?
UPDATED:
This problem is from this paper.
In Eqn. (15), the authors have derived a Lagrange function, but I'm not sure whether the following term in Eqn. (15) is right when optimizing the $J_n$.
From the Eqn. (15), we have
$$
\min_{J_n} \sum_{n=1}^{N}\|J_n\|_* + \lambda \|J_n^T(W_b-\alpha B_n)J_n\|_F^2 -tr(V_2^TJ_n) +\frac{\mu}{2}\|U_n-J_n\|_F^2
$$
The authors have wrote an equal optimization problem in the first equation of Eqn. (16) of the paper. But I was confused with it for a long time. And I also made a post in this link to ask for a favor, but @user1551 also thought the term $\lambda \|J_n^T(W_b-\alpha B_n)J_n\|_F^2$ in the equation above couldn't be changed into the perfect square form in Eqn. (16).
Thus, I've tried to change the term $\lambda \|J_n^T(W_b-\alpha B_n)J_n\|_F^2$ into $\lambda tr(J_n^T(W_b-\alpha B_n)J_n)$, and make a derivation as follows:

But I still couldn't get the perfect square form. Thus I made this post for your kind help. If convenient, could you help derive it, please?
Comment: Unless $A=I$ (or at least $\operatorname{tr} (X^T AX) = \operatorname{tr} (X^T X)$) I don't see how you could do this.
Comment: @copper.hat, thank you.
Comment: The addition changes things entirely. In that second term, $J_n$ appears twice within the squared Frobenius norm. Thus $J_n$ is involved in a *quartic* fashion. Your attempt to change it to a trace fails to preserve equivalence; your trace is just quadratic in $J_n$.
Comment: I am sure the authors would agree this is a non-convex problem. Indeed, the convex-analysis tag isn't even appropriate here. Nonlinear-programming, perhaps, but certainly not convex-optimization.
Comment: @MichaelGrant, yes, the $J_n$ is involved in quartic fashion, but in Eqn. (16), the $J_n$ is quadratic, thus I don't know how the quartic $J_n$ is changed to quadratic $J_n$.
Comment: (16) are the optimality conditions, and they are not independent. (For instance, $U_n$ depends on $J_n$, and vice versa.) That's going to be no easier to solve. I'm officially off the case. You should contact the authors.
Comment: @MichaelGrant, thanks. I could derive other optimization equations in Eqn. (16) except the optimization equation for $J_n$, thus I thought there were some tricks in the derivation of the perfect square for $J_n$.
Answer: As noted by copper.hat, this is not always possible.
In particular, in your second problem, there is no coupling between the different entries in the array $X$. In particular, each entry $X_{ij}$ solves the one-dimensional problem
$$\min_{X_{ij}} (X_{ij} - C_{ij})^2.$$
In the general case, this decoupling is not possible for the first problem.
Comment: thank you for replying! In fact, I meet this problem in a paper and I'm not sure how the authors get the perfect square.
Comment: Maybe you want to give a reference for that paper? Is there some structure in $A$?
Comment: thank you! I've updated the post above and give the reference link. If convenient, could you help derive the problem, please?
Answer: The other commenters are correct, in that you can't get it precisely into the form you've shown. But you can get a perfect square, if that's all you're after, as long as $A$ is positive definite. Let $A^{1/2}$ be the symmetric square root of $A$. Then
$$\begin{aligned}
&\mathop{\textrm{Tr}}(X^TAX)-\alpha\mathop{\textrm{Tr}}(X^TB)
= \langle A^{1/2}X,A^{1/2}X\rangle - \alpha\langle A^{1/2}X,A^{-1/2}B\rangle\\
&\qquad = \langle A^{1/2}X-\tfrac{\alpha}{2}A^{-1/2}B,A^{1/2}X-\tfrac{\alpha}{2}A^{-1/2}B\rangle
-\tfrac{\alpha^2}{4}\langle A^{-1/2}B,A^{-1/2}B\rangle \\
&\qquad \|A^{1/2}X-\tfrac{\alpha}{2}A^{-1/2}B\|_F^2-\tfrac{\alpha^2}{4}\|A^{-1/2}B\|_F^2
\end{aligned}
$$
You can drop the constant term in the optimization, and you have
$$\min_X \|A^{1/2} X-\tfrac{\alpha}{2}A^{-1/2}B\|_F^2$$
If you're wiling to change variables to $Y=A^{1/2}X$, you now have
$$\min_Y \|Y-\tfrac{\alpha}{2}A^{-1/2}B\|_F^2$$
Comment: Hi, Prof. Grant, Thank you very much for replying my question again! I've updated the post above and give the reference link. If convenient, could you help check it, please?


Quotient ring of a polynomial ideal

Question:
Given the ideal $I= \langle 3x^2 + y^2, xy \rangle \subset \mathbb{C}[x,y]$ show that $\mathbb{C}[x,y]/ \langle  3x^2 + y^2, xy \rangle= \mathrm{span}_\mathbb{C}\{1,x,y,x^2 \}$.

I understand how to do a simpler problem, say if the ideal was $I= \langle x,y \rangle$ then it makes sense to me why $ \mathbb{C}[x,y]/ \langle x,y \rangle =\mathrm{span}_\mathbb{C} \{1 \}$ but when I try work through the problem with a more complicated ideal I cannot seem to make sense of it, particularly the $x^2$ confuses me. I've seen questions with similar examples on here but none explain the answer explicitly.
Comment: Just to be clear, what you want to show is that $1,x,y,x^2$ is a basis for $\mathbb{C}[x,y]/ \langle  3x^2 + y^2, xy \rangle$ as a $\mathbb C$-vector space. Do not confuse this with the ideal $\langle 1, x, y, x^2 \rangle$. I normally write this as $\mathbb{C}\{1,x,y,x^2\}$ or $\operatorname{span}_{\mathbb{C}} \{1,x,y,x^2\}$.
Comment: [No-clue questions](https://math.meta.stackexchange.com/questions/27923/how-to-prevent-no-clue-questions) will not be received well here. Please consider improving your post.
Comment: @KReiser thanks for letting me know, appreciate the feedback!
Comment: @TrevorGunn I think that's correct, this example is from the examples section of this Wikipedia article: (https://en.wikipedia.org/wiki/Milnor_number). Which I didn't link because I didn't think the example was specific to this article.
Answer: $$\Bbb{C}[x,y]/(3x^2+y^2) = \Bbb{C}[x]+y\Bbb{C}[x]$$
$$\Bbb{C}[x,y]/(3x^2+y^2,xy^2)=\Bbb{C}[x,y]/(3x^2+y^2,x^3)=\Bbb{C}[x]/(x^3)+y\Bbb{C}[x]/(x^3)$$
$$\Bbb{C}[x,y]/(3x^2+y^2,xy^2)/(xy)=(\Bbb{C}[x]/(x^3)+y\Bbb{C}[x]/(x^3)) / (xy)= \Bbb{C}+x\Bbb{C}+x^2\Bbb{C}+y\Bbb{C}$$

Quotient ring of a polynomial ideal


Can I take any capping surface to apply Stokes' theorem to?

Question: I've been asked the following.

Verify Stokes' theorem for the vector field $\vec{a}=\vec{r}\times\hat{k}$, where $\vec{r}=x\hat{i}+y\hat{j}+z\hat{k}$, and $\lbrace\hat{i},\hat{j},\hat{k}\rbrace$ is the standard basis for $\mathbb{R}^3$, given the hemisphere $C$ of radius $c$ centered at $(0,0,0)$ in the upper half region of $\mathbb{R}^3$ (that is, $z\geq0$).

My attmept is as follows. Note firstly that $\vec{a}=y\hat{i}-x\hat{j}+0\hat{k}$. Note also that, due to the statement of stokes theorem, we may be immediately interested in obtaining an expression for the curl of $\vec{a}$, which is given by $\vec{\nabla}\times\vec{a}=0\hat{i}+0\hat{j}-2\hat{k}$. From here, note that the formulation of the question suggests that $C$ is the capping surface we are to use. For this reason, note that we may take the circular contour of radius $c$ centered at $(0,0,0)$ in the plane $z=0$, oriented counter-clockwise as the boundary of $C$, which we'll of course denote $\partial C$. Notice from here that $\gamma(t)=c\cos(t)\hat{i}+c\sin(t)\hat{j}+0\hat{k}$, for $0\leq t\leq 2\pi$, parameterizes $\partial C$. For this reason, consider
$$
\oint_{\partial C}\vec{a}\cdot d\vec{r}=\int_0^{2\pi}\vec{a}(\gamma(t))\cdot\gamma'(t)~dt
$$
$$
=\int_0^{2\pi}(c\sin(t)\hat{i}-c\cos(t)\hat{j}+0\hat{k})\cdot(-c\sin(t)\hat{i}+c\cos(t)\hat{j}+0\hat{k})~dt
$$
$$
=-c^2\int_0^{2\pi}~dt=-2c^2\pi
$$
And hence, by Stokes' theorem, this quantity should equate to
$$
I=\iint_C\mathrm{curl}(\vec{a})\cdot\hat{n}_C~dS
$$
Where $\hat{n}_C$ denotes the unit normal to the surface of $C$ (possibly as a function of $x$, $y$, and $z$, given $(x,y,z)\in C$). To ensure the preservation of orientation, we employ the trusty right hand rule to arrive at the conclusion that the normal to $C$ is given by $\hat{n}_C=\vec{r}/|\vec{r}|$. Note, however, that on the surface of $C$, $|\vec{r}|=c$, and so $\hat{n}_C=\vec{r}/c$. For this reason, we have that
$$
\mathrm{curl}(\vec{a})\cdot\hat{n}_C=(\vec{\nabla}\times\vec{a})\cdot\hat{n}_C=-\frac{2z}{c}
$$
Since, on $C$, $z=\sqrt{c^2-x^2-y^2}$ (we omit consideration of the negative square root of $z^2$, since we are told that $z\geq0$), we have that
$$
\mathrm{curl}(\vec{a})\cdot\hat{n}_C=-\frac{2}{c}\sqrt{c^2-x^2-y^2}
$$
And, for this reason, $I$ becomes
$$
I=-\frac{2}{c}\iint_C\sqrt{c^2-x^2-y^2}~dS
$$
We may, from here, convert to polar coordinates to arrive at the conclusion that
$$
I=-\frac{2}{c}\int_0^{2\pi}\int_0^cr\sqrt{c^2-r^2}~dr~d\theta
$$
$$
=-\frac{2}{c}\int_0^{2\pi}-\frac{1}{3}\left[(c^2-r^2)^{3/2}\right]_0^c~d\theta
$$
$$
=-\frac{2}{c}\int_0^{2\pi}\frac{c^3}{3}~d\theta=-\frac{4}{3}c^2\pi
$$
This result, however, is obviously not equal to $-2c^2\pi$, meaning that
$$
\oint_{\partial C}\vec{a}\cdot d\vec{r}\neq\iint_C\mathrm{curl}(\vec{a})\cdot\hat{n}_C~dS
$$
which, as far as my understanding of Stokes' theorem is concerned, cannot be the case. Can someone perhaps help me identify the mistake that I've made?
Answer: I think your mistake is that you treated $dS$ as if it were $dx \, dy$ when you changed to polar coordinates. But $dS$ is the area element of the surface: if the surface $S$ is the graph of $z=f(x,y)$, then
$$ dS = \sqrt{1+f_x^2 + f_y^2} \, dx \, dy $$
So in your case, since the hemisphere is $z= \sqrt{c^2-x^2-y^2}$, this is
$$ dS = \frac{c}{\sqrt{c^2-x^2-y^2}} \, dx \, dy $$
This cancels with the $\sqrt{c^2-x^2-y^2}$ that's already in your integral, so you get
$$ I = -2 \iint\limits_D dx \, dy $$
where $D$ is the disc of radius $c$ in the $x,y$-plane. This is $-2$ times the area of the disc, which is $-2\pi c^2$, which agrees with the line integral.