Admin port with Dropwizard metrics not working

Question: I'm following the DropWizard "Getting Started" tutorial and while I got everything else working the 8081 admin port is blank and clicking on any of the hyperlinks to the metrics resource, threads resource, and health check resource is giving me a 101 error. Can't figure out why I followed it pretty much verbatim.
Here's my POM if that helps:
<code>    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>DropWizard</groupId>
    <artifactId>DropWizard</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>com.yammer.dropwizard</groupId>
            <artifactId>dropwizard-core</artifactId>
            <version>0.6.2</version>
        </dependency>
        <dependency>
            <groupId>com.codahale.metrics</groupId>
            <artifactId>metrics-core</artifactId>
            <version>3.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.codahale.metrics</groupId>
            <artifactId>metrics-servlets</artifactId>
            <version>3.0.0</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>1.6</version>
                <configuration>
                    <createDependencyReducedPom>true</createDependencyReducedPom>
                    <filters>
                        <filter>
                            <artifact>*:*</artifact>
                            <excludes>
                                <exclude>META-INF/*.SF</exclude>
                                <exclude>META-INF/*.DSA</exclude>
                                <exclude>META-INF/*.RSA</exclude>
                            </excludes>
                        </filter>
                    </filters>
                </configuration>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer
                                    implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
                                <transformer
                                    implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>com.example.helloworld.HelloWorldService</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <archive>
                        <manifest>
                            <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
</code>
Answer: Figured it out, there are a couple of things to note:
1) If you specify the dropwizard dependency you do not need to specify the metrics dependencies.
2) The 8081 port, for whatever reason, was not cooperating. When I changed the admin port to 9091 everything worked as expected. If you want to change the ports then specify the following in your admin file:
<code>http:
    port: 9090
    adminPort: 9091
</code>
I assume you can use whatever ports you like, these happened to work when I used them. When specifying the ports there must be a tab in between http and the information that comes afterwards. Hopefully this helps others avoid the hair-pulling frustration I encountered
Comment: I am pulling my hair out.  The above worked on 0.6.2, but now on 0.7.0 I get errors about 'unrecognized field http'.  Also the port 8081 problem, if like me, is on Windows and McAfee is using that port and not an easy task to change that, so I am still fighting this on 0.7.0.
Comment: I haven't touched DropWizard in 6 months but I remember it being very particular about that sort of thing. Make sure you don't have any trailing whitespace or anything of that sort. There is also a dropwizard google group where you can ask for help:

https://groups.google.com/forum/#!forum/dropwizard-user
Comment: Finally got is solved - using the docs from 0.7.0 - the configuration format is being changed as part of 0.7.0, so using the new format it now works! Just wanted to get the mention of the adminPort because it was very frustrating that their 'Getting Started' wouldn't start on Windows.  So those of you reading this - check the new docs for 0.7.0 (and beyond) for the correct format because the format above does NOT and will not work for 0.7.0.
Answer: The Dropwizard admin interface (as of 0.6.2) is only compatible with Metrics 2.*. Dropwizard 0.7.0 will work with Metrics 3 once it's released.
Comment: So how do I get it to work then? I looked up the Metrics release notes and changed the versions for each metrics dependency to 2.2.0 (the last before 3.0.0) and got this error:
Comment: [ERROR] Failed to execute goal on project DropWizard: Could not resolve dependencies for project DropWizard:DropWizard:jar:0.0.1-SNAPSHOT: The following artifacts could not be resolved: com.codahale.metrics:metrics-core:jar:2.2.0, com.codahale.metrics:metrics-servlets:jar:2.2.0: Failure to find com.codahale.metrics:metrics-core:jar:2.2.0 in http://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced -> [Help 1]


Mudança de Diretório Matlab

Question: Gostaria de saber como soluciono este problema; Estou usando um bloco de função dentro do Simulink, no entanto quando clico em executar meu código aparece o seguinte erro:
The current directory 'c:\program files\matlab\matlab production server\r2015a\bin' is reserved for MATLAB files.
Please change your current directory to a writeable directory outside of the MATLAB installation area.
Component: Stateflow | Category: General error
Vocês poderiam me ajudar a solucionar este problema ?
obs: Sou novo aqui e bem inexperiente em linguagens de programação, me desculpem se não fui tão claro em minha duvida.
Answer: Isso é normal conforme o que se deseja fazer no Matlab.
Caso você não tenha nenhum script ou algo assim, mude o diretório do matlab na interface mesmo, seja tal qual "unix" diretamente no prompt de comando (cd C:\Users\SEU_NOME) ou então com o mouse mesmo.
Acima seu nome é seu diretório padrão do windows, mas talvez use algum outro diretório que você criou juntamente com seu respectivo caminho (por exemplo C:\MEUS_TESTES\TESTE1).
Caso a sua simulacão dependa de scripts e arquivos que você criou, transfira estes arquivos para o diretório que você deseja rodar, mude o diretório no matlab (Matlab faz isso automaticamente dependendo de como você abre e roda os arquivos) e comece a rodar a partir de lá. Cuidado com dependência que você possa ter criado, tal qual rodar simulações e pedir pra escrever em um diretório especifico ou chamar um arquivo pelo caminho inteiro.
Um ponto importante, Matlab chama automaticamente as funcões da biblioteca dele, porém outras funcões ou scripts que tenham sido criados devem estar no mesmo diretório que está sendo rodado ou então em alguma pasta que esteja no path do matlab.
O path é uma lista de diretórios que um sistema irá procura por programas automaticamente.
O Matlab tem seu próprio path que deixa disponivel suas bibliotecas, ele pode ser alterado nas configuracões. Não recomendo ficar alterando o path por qualquer coisa, pois suas funcões podem ter preferencia sobre funcões de mesmo nome da biblioteca do matlab, e no futuro isso pode dar problemas.
Caso isso não tenha solucionado, deixe comentários que posso tentar ver qual o problema.
Comment: Consegui resolver meu problema, amigo, muito obrigado pela ajuda !
Comment: @FelipeVieira De nada, neste caso, se a resposta está de acordo com o que você quer, pense em aceitar ela, afinal este é uma das ideias do stackoverflow! Caso não seja o que você quer, esteja livre a fazer mais comentários ou editar a pergunta.  :D

Mudança de Diretório Matlab


Unable to understand this expression

Question:
I am unable to understand the above expression from the 3rd line onwards. Why is P(A|q1...qt-1)P(q1..q-1) = P(A|qt-1)P(q1..q-1)
I am not clear of the subsequent line as well
Comment: Is this from a Markov process?
Comment: I think the third line is a typo.  I think it shoulbe $P(A|q_{t-1})P(q_1, ... , q_{t-2}) = P(A|q_{t-1})P(q_{t-1}|q_{t-2})P(q_1,....,q_{t-e}) = ..... P(A|q_{t-1})P(q_{t-1}|q_{t-2})....P(q_2|q_1)P(q_1)$.
Comment: yes its about Markov process
Answer: This follows from the Markov property (or the memoryless property) that the conditional probability of a future event only depends on the current state.
See link for more information about this property.

Unable to understand this expression


how to show node title when mouseover on image in the node by drupal views?

Question: I have a content type in which there is a cck image field and now I have listed the images with the node title as a block by views.
Now I want to show the node title when user mouseovers the image. I think I can implement it by views itself but I don't know how to do it?.
Can anyone help?
Answer: I don't think you can do that using views. However you can "hack" a way to add title element to a div, for instance.
go to your view config page
add a node: title field.
edit the node: title field.
tick "Exclude from display" and "strip HTML tags"
click save
move the title node to top of the fields.
edit your image field and tick "Rewrite the output of this field"
a textarea appears. write this code in the textarea

[image]

Note: the [fields] are tokens. If you already have a title field, you don't need to exlude it, you can re-use it.
if the image displays another title its because the module automatically sets a title tag to the image. You can either change this tag with javascript:
document.getElementById("idElement").setAttribute("Title", "title");

or edit your image module and set the page title to be your title tag.
Answer: Use a  tag on your views like so:
[image]


approximation problem

Question: We know that 30/3=10,
therefore 30/3 could be written as 10×3/3=3.333.....×3=9.9999........
Which is approximately equal to 10 but not exactly 10.
Why this kind of approximation errors happen ?
Comment: So 10 is not exactly 10.
Answer: Actually, 10 and 9.99999... are exactly the same number. This is the issue of the non-uniqueness of decimal representation of numbers.

approximation problem


Definite Integral of $(\sin x)^2\cos x$ from $\pi/2$ to $-\pi/2$

Question: Can someone show me the steps to solve the following Finite Integral?
$$\int_\frac{-\pi}{2}^\frac{\pi}{2} \sin^2x\cos x \,dx$$
I know you can solve it by doing $u$-substitution with $\sin x$, but I must be doing something wrong in the last steps since I don't get the desired result, which is $\frac{2}{3}$.
Thank you in advance for your help!
Comment: Notice that $\sin^{2}(x)\cos(x)\mathrm{d}x = \sin^{2}(x)\mathrm{d}(\sin(x))$
Answer: Set $\sin x=u$
$$\int_{-1}^1u^2du=(u^3/3)|_{-1}^1=?$$
Comment: There is no more $\sin x$. Everything is in terms of $u$. That's why you transform the limits of integration as well.
Comment: I got to that, but when I plug sinx and try to solve it, I don't get 2/3, but another weird number
Comment: @Nello 1 cubed divided by 3 is 1/3. -1 cubed divided by 3 is -1/3. 1/3 minus -1/3 is 2/3.


Default value of a 'managed file' field

Question: I created an edit custom form (of a node) via a custom module. From this form, I have a "managed file" field (for one picture) and I set his default value to a fid;
However, when my form is rendered, the "managed file" field doesn't show the image ratached. I don't understand why
My code :
$form['project']['image'] = array(
  '#type' => 'managed_file',
  '#title' => t('Image'),
  '#default_value' => 10, //Set 10 for the test, the fid "10" exist, I checked
);

My form rendered:

As you see, no image is loaded whereas the default_value is set to an existing fid (10)
Answer: For a managed file form element, #default_value is an array containing the file ID, as in the following code.
$form['project']['image'] = array(
  '#type' => 'managed_file',
  '#title' => t('Image'),
  '#default_value' => array(10),
);

Answer: In My case i needed to add default files to a multiple managed file field element in drupal 8. my filed name was "field_dpe_submission_file"
  $fids = [
      10,
      11,
      12,
    ];

function setDefaultsForFileField(array &$form, $fids) {
    $widget_clone = $form['field_dpe_submission_file']['widget'][0];
    $form['field_dpe_submission_file']['widget']['#file_upload_delta'] = count($fids);
    $form['field_dpe_submission_file']['widget']['#value'] = null;
    $form['field_dpe_submission_file']['widget']['#defaults_loaded'] = TRUE;
    foreach ($fids as $key => $value) {
      $value = (int) $value;
      $form['field_dpe_submission_file']['widget'][$key] = $widget_clone;
      $file_array = [
        'fids' => [
          $value,
        ],
        'display' => '1',
        'description' => '',
        'upload' => ''
      ];
      $form['field_dpe_submission_file']['widget'][$key]['#value'] = $file_array;
      $form['field_dpe_submission_file']['widget'][$key]['#default_value'] = $file_array;
      $form['field_dpe_submission_file']['widget'][$key]['#input'] = TRUE;
      $form['field_dpe_submission_file']['widget'][$key]['#delta'] = $key;
      $name = 'field_dpe_submission_file[' . $key . ']';
      $form['field_dpe_submission_file']['widget'][$key]['#name'] = $name;
      $form['field_dpe_submission_file']['widget'][$key]['#theme'] = 'file_managed_file';
      $form['field_dpe_submission_file']['widget'][$key]['#multiple'] = FALSE;
      $form['field_dpe_submission_file']['widget'][$key]['fids'] = [
        '#type' => 'hidden',
        '#value' => [
          $value,
        ],
        '#theme' => 'input__hidden'
      ];
    }
    // Add the default widget back in.
    $count = count($fids);
    $form['field_dpe_submission_file']['widget'][$count] = $widget_clone;
  }
?>

Answer: Simple settings form with Managed file field with default value:
Config file form:
public function buildForm(array $form, FormStateInterface $form_state) {
 $config = $this->config('bk.settings');

$form['static'] = [
  '#type' => 'details',
  '#title' => t('Static Files'),
  '#open' => TRUE,
];

$form['static']['upload'] = [
  '#type' => 'managed_file',
  '#title' => t('File Upload.'),
  '#progress_indicator' => 'bar',
  '#progress_message'   => t('Please wait...'),
  '#upload_location' => 'public://static',
  '#description' => 'Allowed formats: jpg img png svg woff woff2, File location: public://static',
  '#upload_validators'  => [
    'file_validate_extensions' => ['jpg img png svg woff woff2'],
  ],
  '#default_value' => $config->get('upload'),
  '#multiple' => TRUE,
];
}

Form Submit:
public function submitForm(array &$form, FormStateInterface $form_state) {
parent::submitForm($form, $form_state);

if ($file_id = $form_state->getValue(['upload', '0'])) {
  $file = File::load($file_id);
  $file->setPermanent();
  $file->save();
}

  $config = $this->config('bk.settings');
  $config->set('upload', $form_state->getValue('upload'));
  $config->save();
}
}

Default value of a 'managed file' field


When does the Group Policy update interval start?

Question: When exactly does the 90 minute (+ 30 minute random offset) Group Policy update interval begin?
Is it when a PC boots into Windows?
Also, is the 30-minute randomization offset applied each time Group Policy updates, or just once (at the beginning)?
Answer: It is scheduled after the computer starts, and after group policy is first applied.  You can observe this from the 5315 event in the GroupPolicy-Operational event log:
Next policy processing for DOMAIN\COMPUTERNAME$ will be attempted in 112 minutes.

It will also occur in response to specific events.  An example is a network state change.  It is not uncommon to observe this during startup, and will be recorded as a 4002 event in the GroupPolicy-Operational event log:
Starting policy processing due to network state change for computer DOMAIN\COMPUTERNAME$ .
Activity id: {0a3dd15b-b6c6-4ad9-9509-e5d36caf26fa}

The random value is applied each time.
Troubleshooting Group Policy Using Event Logs
http://technet.microsoft.com/en-us/library/cc749336%28v=ws.10%29.aspx
Answer: Yes, the update is applied on the OS loading and logon, and the offset updates are applied after that.
The randomization is applied on each GP update, and is intended to prevent congestion and other complications from lots of clients updating GP at once.


Export Dataframe with Sheetname as Column

Question: I have 40 or so excel documents and I want to read the first sheet into a Dataframe and then export the combined sheets to a csv file. The below code works so far,  but I also need to add a column that has the imported sheet name. The sheet name is different for each workbook. I basically want to replace 'WorsksheetName' below with the actual sheet name.
import pandas as pd
import numpy as np
import glob
import openpyxl
glob.glob("..\*.xlsx")
all_data = pd.DataFrame()
for f in glob.glob("M:\Completed\*.xlsx"):
        df = pd.read_excel(f,sheetname=1)
        df['Sheet'] = 'WorksheetName'
        all_data = all_data.append(df,ignore_index=True)
all_data.to_csv('Workoad.csv')

Answer: If you use the setting sheetname=None, pandas imports all sheets of the workbook into a dictionary, where the key is the sheet name and the value is the dataframe of the worksheet itself. Using this, you could do the following:
import pandas as pd
import numpy as np
import glob
import openpyxl

all_data = pd.DataFrame()
for f in glob.glob("M:\Completed\*.xlsx"):
    sheets_dict = pd.read_excel(f, sheetname=None)
    for name, frame in sheets_dict.items():
        frame['Sheet'] = name
        all_data = all_data.append(frame, ignore_index=True)

all_data.to_csv('Workload.csv')

Your current setting seems to only keep the second sheet of the workbook - you could do this by using some kind of filter on name.
Comment: The first and second sheet of each workbook have different column headings, but they are consistent across all workbooks (i.e. sheet 1 has the same headings on each workbook and same is true for sheet 2). How would I modify this code so that all sheet 1s are exported to one csv and all sheet 2s are exported to a seperate csv?
Comment: @Dread is there any kind of consistent naming between the workbooks?
Comment: The first sheet always has a department abbreviation followed by "Teaching Load" (e.g. "AN GIO Teaching Load") and second sheet has the same abbreviation followed by "Workload" (e.g. "AN GIO Workload".) Each department has a workbook with these two sheets but with their department abbreviation. Since the abbreviations change for each department's worksheets, I used sheet0 and sheet1.  The structure of the two sheets is different (different columns and data starts on a different row).
Answer: You could use pd.ExcelFile to retrieve the sheet name, as below.
import pandas as pd
import glob
all_data = []
for f in glob.glob("M:\Completed\*.xlsx"):
        xl = pd.ExcelFile(f)
        sheet = xl.sheet_names[0]
        df = xl.parse(sheet)
        df['Sheet'] = sheet
        all_data.append(df)
pd.concat(all_data).to_csv('Workoad.csv')

The change to using pd.concat instead of df.append should speed things up some – this way you only need to build a new dataframe once, instead of forty times, once for each you add. I also changed the index selected. Feel free to change that to sheet = xl.sheet_names[1] if you do in fact want the second sheet; python and its packages generally count from zero, even when working with programs that count from 1, like excel.


The character table of $G/Z(G)$ and $G/N$ given knowledge of the character table of $G$

Question: Suppose for a group $G$, of which we completely understand its conjugacy class structure and character table, is there a simple algorithm to deduce the character table of $G/Z(G)$? Or more generally, $G/N$ for $N \trianglelefteq G$?
Comment: @Shaun The question is intentionally isolated and general - this could come up in many different contexts.
Comment: I also believe the question is clearly motivated to anyone who knows character theory. Let's not close questions just because they're short.
Comment: [Restricted representation](https://en.wikipedia.org/wiki/Restricted_representation), [Clifford theory](https://en.wikipedia.org/wiki/Clifford_theory)
Answer: The answer is "yes". You can identify the columns of the character table of $G$, which correspond to elements in $N$. Then you take only those characters $\chi$, which have $\chi(1)=\chi(g)$ for every $g\in N$. This gives you some rectangle matrix with some duplicate columns. Just delete duplicate columns until you end up with a square matrix. This is the character table of $G/N$.


How do you add drag-n-drop upload ability from Outlook to a Web form?

Question: I am looking for a way to allow users to upload Outlook emails to a web-based system in a simple manner.
I can get this to work in a manual fashion for the users.  They can drag and drop the email from Outlook to their desktop, which creates a .msg file.  This works very nicely, esp. if there are attachments in the email which are also stored in the .msg file.  This file can then be uploaded using a traditional "input type=file" html field.
I would like to simplify this process, if possible. I have seen some websites that have a drag-n-drop upload feature for files that exist on the hard drive.
However, I am not sure if anything exists that would allow for a straight drag-n-drop from Outlook that could create a .msg file or something similar and handle the file upload.    In other words, a solution to cut out the manual step of dragging the email message to the desktop to create the temporary .msg file for upload.
Is this possible, and if so, how?  All of the users are currently on Windows XP and have Outlook 2007, IE6 or higher, and Firefox. The backend server is running Java for the application in question (our programming staff uses ASP.NET w/ C# for our web development), though I assume any solution would be largely based upon a client-side technology like Flash or JQuery.
Answer: I don't think you'll achieve this with jQuery / JavaScript - you might have a chance with something like Flash.
As an alternative, could you create a simple client application that they can run on their desktop, which allows them to drag the message onto - that way, you can be running in full trust and perform whatever tasks you wish to get the file and upload it from this application (this was the solution used by a file-scanning application I once worked on - we had a small window that users could drag the file or email onto to initiate the upload to the scan store.
Answer: How did you eventually implement this? I was looking for a similar solution but couldnt find much so ended up using a VBA macro in Outlook which they click on when a message is selected. The message is then copied as a .msg to their temp folder, then submitted to an HTML form.
I have added the code I patched together from various web sources (including here - sorry, I didnt remember to save the links) below in case anybody ever wants to do the same.
Im sure it can be optimized etc as I am very new to VBA (yesterday!) but it does the job for now, although one think I would like to do is check if an IE window exists and add a new tab rather than opening a new browser every time it is clicked.
' Function to maximize IE window
Declare Function apiShowWindow Lib "user32" Alias "ShowWindow" (ByVal hwnd As Long, ByVal nCmdShow As Long) As Long

Global Const SW_MAXIMIZE = 3
Global Const SW_SHOWNORMAL = 1
Global Const SW_SHOWMINIMIZED = 2

Sub test()
 'the mail we want to process
Dim objItem As Outlook.MailItem
 'question for saving, use subject to save
Dim strPrompt As String, strname As String
 'variables for the replacement of illegal characters
Dim sreplace As String, mychar As Variant, strdate As String
 'put active mail in this object holder
Set objItem = Outlook.ActiveExplorer.Selection.Item(1)
 'check if it's an email ... need to take a closer look cause
 'gives an error when something else (contact, task) is selected
 'because objItem is defined as a mailitem and code errors out
 'saving does work, if you take care that a mailitem is selected
 'before executing this code
If objItem.Class = olMail Then
     'check on subject
    If objItem.Subject <> vbNullString Then
        strname = objItem.Subject
    Else
        strname = "No_Subject"
    End If
    strdate = objItem.ReceivedTime
     'define the character that will replace illegal characters
    sreplace = "_"
     'create an array to loop through illegal characters (saves lines)
    For Each mychar In Array(" ", "/", "\", ":", "?", Chr(34), "<", ">", "¦")
         'do the replacement for each character that's illegal
        strname = Replace(strname, mychar, sreplace)
        strdate = Replace(strdate, mychar, sreplace)
    Next mychar
     'Prompt the user for confirmation
    strPrompt = "Upload the email to CRM?"
    If MsgBox(strPrompt, vbYesNo + vbQuestion) = vbYes Then
        Dim location As String
        Dim tempPath As String
        tempPath = IIf(Environ$("tmp") <> "", Environ$("tmp"), Environ$("temp"))
        location = tempPath & "\" & strname & "-" & strdate & ".msg"
        objItem.SaveAs location, olMSG
        'upload to IE
        UploadFile "http://intranet/test.php", location, "msgupload"
    End If
End If
End Sub

'******************* upload - begin
'Upload file using input type=file
Sub UploadFile(DestURL As String, FileName As String, _
  Optional ByVal FieldName As String = "File")
  Dim sFormData As String, d As String
  'Boundary of fields.
  'Be sure this string is Not In the source file
  Const Boundary As String = "---------------------------0123456789012"
  'Get source file As a string.
  sFormData = GetFile(FileName)
  'Build source form with file contents
  d = "--" + Boundary + vbCrLf
  d = d + "Content-Disposition: form-data; name=""" + FieldName + """;"
  d = d + " filename=""" + FileName + """" + vbCrLf
  d = d + "Content-Type: application/upload" + vbCrLf + vbCrLf
  d = d + sFormData
  d = d + vbCrLf + "--" + Boundary + "--" + vbCrLf
  'Post the data To the destination URL
  IEPostStringRequest DestURL, d, Boundary
End Sub

'sends URL encoded form data To the URL using IE
Sub IEPostStringRequest(URL As String, FormData As String, Boundary As String)
  'Create InternetExplorer
  Dim WebBrowser: Set WebBrowser = CreateObject("InternetExplorer.Application")
  'You can uncoment Next line To see form results
  WebBrowser.Visible = True
  'Send the form data To URL As POST request
  Dim bFormData() As Byte
  ReDim bFormData(Len(FormData) - 1)
  bFormData = StrConv(FormData, vbFromUnicode)
  ' Submit message to intranet
  WebBrowser.Navigate2 URL, , , bFormData, "Content-Type: multipart/form-data; boundary=" + Boundary + vbCrLf
  ' Maximize window
  apiShowWindow WebBrowser.hwnd, SW_MAXIMIZE
End Sub

'read binary file As a string value
Function GetFile(FileName As String) As String
  Dim FileContents() As Byte, FileNumber As Integer
  ReDim FileContents(FileLen(FileName) - 1)
  FileNumber = FreeFile
  Open FileName For Binary As FileNumber
    Get FileNumber, , FileContents
  Close FileNumber
  GetFile = StrConv(FileContents, vbUnicode)
End Function
'******************* upload - end

A simple PHP script to capture the file would be:
<?php
if($_FILES['msgupload']){
move_uploaded_file($_FILES['msgupload']['tmp_name'], "./crm_uploads/".substr($_FILES['msgupload']['name'], 0 ,-24).".msg");
print("You are adding the email '".substr($_FILES['msgupload']['name'], 0, -24)."'");
print("
dated ".substr($_FILES['msgupload']['name'], -23, -4));
}
?>

Answer: You can try
http://xupload.aspupload.com/
It's an ActiveX control so IE only but drag/drop from outlook is not a problem.


Can't find analytic solution to geometry problem with unique solution

Question: I have been struggling finding an analytic solution to the following geometry problem:
Consider an acute triangle $ABC$ (with all sides and angles known), with some unknown point $X$ in its interior. Denoting the (unknown) distances from the vertices to this interior point by $AX$, $BX$, and $CX$ (for simplicity assume $AX < BX < CX$), we are given the values of $s = BX-AX$, and $t = CX-BX$. We want to find $AX$. (I believe this should entirely pin down everything, see discussion later).
A way to illustrate this is to draw three circles with center $X$ and radii $AX$, $BX (= AX + s)$ and $CX (= AX + s + t)$ respectively.
Alternatively we can draw these circles with their centerpoints at $A$, $B$ and $C$ instead, which gives us $X$ as their intersection point:

Now if we imagine varying the radius of the smallest circle $(AX)$, and always keeping the radii of the other two circles $AX + s$ and $AX + s + t$ respectively, then there should be(?) a unique value for $AX$ where all three circles intersect, and thus the point $X$ is uniquely determined. So although I'm pretty convinced there should be a unique solution, I'm struggling to actually derive an analytic formula for the answer.
I did try using pythagoras' theorem a bunch on a picture like this:

However I didn't seem to get very far, I just got kinda lost in the formulas. Is it possible to find a formula for the distance $AX$?
As a sidenote, during digging through the formulas I discovered that in this setup (interior point in acute triangle with normals splitting all three sides), we get that $a^2 + b^2 + c^2 = (a')^2 + (b')^2 + (c')^2$ is satisfied. Does this result have a name? Can it be generalized? (What happens with non-interior points, obtuse triangles, is this condition satisfied if and only if the sides are split by a point in such a way?)
Comment: Your sideway result is valid for all points in the plane and all triangles. I doubt it has a name, but I remember seen it as an exercise somewhere.
Comment: For the side note ... Way-back-when, I playfully dubbed it "Ortha's Theorem" in [this answer](https://math.stackexchange.com/a/652127/409). As I later noted in a comment, the result is known as [Carnot's Theorem](http://www.cut-the-knot.org/pythagoras/Carnot.shtml) (not to be confused with [Carnot's Theorem](http://www.cut-the-knot.org/proofs/carnot.shtml)).
Answer: The formula to be derived are so messy that I can only write down the general ideas and illustrate the work with a special example.

Refer to the figure, let $p=s+t$.
From  $\Delta ABX$,
$$ XB^2=AX^2+AB^2-2(AX)(AB)\cos \alpha$$
$$(r+s)^2=r^2+c^2-2rc\cdot \cos \alpha$$
$$r^2+2rs+s^2=r^2+c^2-2rc\cdot \cos \alpha$$
$$2r(s+c \cdot \cos \alpha)=c^2-s^2  \tag{1}$$
Similarly from $\Delta ACX$,
$$2r(p+ b \cdot \cos(A-\alpha))=b^2-p^2  \tag{2}$$
From $(1), (2)$, we have
$$(c^2-s^2)(p+b \cdot \cos(A-\alpha))=(b^2-p^2)(s+c\cdot \cos \alpha)$$
$$(c^2-s^2)(p+b \cdot (\cos A \cos \alpha+ \sin A \sin \alpha))=(b^2-p^2)(s+c\cdot \cos \alpha)$$
The equation above can be reduced to the form:
$$m \cdot \cos \alpha + n \cdot \sin \alpha = k   \tag{3} $$
From $(3)$, we can find $\alpha$ by standard method  Solving $a \cos x + b \sin x = c$ and hence $r$ from either $(1)$ or $(2)$.
Example: Suppose we want to solve for $r$ with the information given in the figure.

From  $\Delta ABX$,
$$(r+\sqrt 3-1)^2=r^2+2^2-4r\cos \alpha$$
$$2r((\sqrt 3 -1)+2 \cdot \cos \alpha) = 4-(\sqrt 3 - 1)^2   $$
$$r((\sqrt 3 -1)+2\cos \alpha) = \sqrt 3    \tag{1}$$
Similarly from $\Delta ACX$,
$$(r+\sqrt {13}-1)^2=r^2+16-8r\cos(120^{\text o}-\alpha)$$
$$2r((\sqrt {13}-1)+4 \cdot \cos (120^{\text o}-\alpha))= 16-(\sqrt {13}-1)^2$$
$$r((\sqrt {13}-1)+4\cos (120^{\text o}-\alpha))= 1+ \sqrt {13}  \tag{2}$$
$(1), (2) \implies$
$$\sqrt 3\left( \sqrt {13}-1 +4 \cos(120^{\text o}-\alpha) \right)=(\sqrt {13}+1)\left(\sqrt 3 -1 + 2 \cos \alpha \right)$$
$$\sqrt {13}-2\sqrt 3+1=(2\sqrt{13}+2)\cos \alpha -4\sqrt 3(\cos 120^{\text o} \cos \alpha + \sin 120^{\text o}\sin \alpha  )$$
$$(2\sqrt {13}+2\sqrt 3+2)\cos \alpha - 6 \sin \alpha = \sqrt {13}-2\sqrt 3 +1   \tag{3}$$
$(3)$ is of the form
$$m \cdot \cos \alpha + n \cdot \sin \alpha = k  $$
which can be solved by standard method.
Indeed the solution of $(3)$ is
$$\alpha = 60^{\text o}$$
Once we have $\alpha = 60^{\text o}$, we can find  the value of $r$ from $(1)$
$$r((\sqrt 3 -1)+2\cos \alpha) = \sqrt 3$$
which gives $$r=1.$$
Answer: It is possible to give an analytic solution, using the $p,q$ method. It turns out to be a rather complicated function of your variables $s,t$ and the side lengths--too long to post here but I can describe the rather simple method.
We denote the side lengths by $a,b,c$ as usual. Then there is a unique pair $p,q$ so that your triangle is directly congruent to one with vertices $(0,0)$, $(c,0)$ and $(p,q)$.  You can determine $p,q$ as functions of the side lengths by solving (by hand or using, say, Mathematica) $$p^2+q^2=b^2, (p-c)^2+q^2=a^2.$$  Now suppose that $X$ is $(x ,y)$ . You can solve your equations for $x$ and $y$ in terms of $p,q,c$ (I used Mathematica for this task--it coped  with ease).  You can now  use the first solution to express this one  in terms of the side lengths to get the required result.  As explained it is too long for me to post here but is the work of a few minutes with the aid of Mathematica.


Visually represent two-dimensional decomposition

Question: Lets say i have the decompositions of a financial result into 21 portfolios and 11 asset classes below. I can decompose the result into either portfolios or asset classes easily by using a waterfall chart (which my bosses really love), but I am looking for something, hopefully similar, which can decompose both dimensions simultanously.

P1
P2
P3
P4
P5
P6
P7
P8
P9
P10
P11
P12
P13
P14
P15
P16
P17
P18
P19
P20
P21
Total A

A1
-120
-100
-75
-395
-76
24
-2
-2
-10
0
-216
-46
-1
-18
-2
-26
-10
-4
0
-9
-6
-1094

A2
99
36
18
19
1
92
7
6
16
0
2
18
0
0
0
1
0
4
0
2
0
321

A3
75
23
12
8
0
62
5
4
10
0
0
6
0
0
0
0
0
2
0
1
0
208

A4
82
55
34
160
24
103
10
8
6
0
26
25
1
-8
-1
7
1
6
0
8
4
551

A5
7
5
1
2
0
6
1
1
1
0
1
-8
0
1
0
0
0
0
0
0
0
17

A6
2
1
1
0
0
2
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
7

A7
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0

A8
28
3
-1
-8
0
56
0
0
0
0
0
3
1
12
1
0
0
0
0
1
1
96

A9
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0

A10
1
1
1
4
1
-1
0
0
-1
0
2
0
0
0
0
0
0
0
0
0
0
7

A11
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0

Total P
173
24
-10
-210
-52
343
21
17
22
0
-184
-3
1
-13
-2
-18
-9
9
0
3
0
113
Comment: @user2974951: the table contains a "Total" row and column, so the OP presumably would like to visualize how the separate entries contribute to these two-dimensional totals.
Comment: Are you looking for a *spineplot*?
Comment: What do you mean by `decomposition`? What are you decomposing and why?
Answer: I would create a heatmap with the data except for the totals, and add a separate row and column next to the heatmap showing the totals. This does not really capture the "decomposition" aspect, but it should at least draw attention to particularly high or low values. (Just be careful to actually use black body radiation colors rather than, say, rainbow colors - see also here.)

R code (which I am not overly proud of; see also https://stackoverflow.com/q/46091522/452096):
<code>dataset <- structure(c(-120, 99, 75, 82, 7, 2, 0, 28, 0, 1, 0, 173, -100,
36, 23, 55, 5, 1, 0, 3, 0, 1, 0, 24, -75, 18, 12, 34, 1, 1, 0,
-1, 0, 1, 0, -10, -395, 19, 8, 160, 2, 0, 0, -8, 0, 4, 0, -210,
-76, 1, 0, 24, 0, 0, 0, 0, 0, 1, 0, -52, 24, 92, 62, 103, 6,
2, 0, 56, 0, -1, 0, 343, -2, 7, 5, 10, 1, 0, 0, 0, 0, 0, 0, 21,
-2, 6, 4, 8, 1, 0, 0, 0, 0, 0, 0, 17, -10, 16, 10, 6, 1, 0, 0,
0, 0, -1, 0, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -216, 2,
0, 26, 1, 0, 0, 0, 0, 2, 0, -184, -46, 18, 6, 25, -8, 0, 0, 3,
0, 0, 0, -3, -1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, -18, 0, 0,
-8, 1, 0, 0, 12, 0, 0, 0, -13, -2, 0, 0, -1, 0, 0, 0, 1, 0, 0,
0, -2, -26, 1, 0, 7, 0, 0, 0, 0, 0, 0, 0, -18, -10, 0, 0, 1,
0, 0, 0, 0, 0, 0, 0, -9, -4, 4, 2, 6, 0, 0, 0, 0, 0, 0, 0, 9,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -9, 2, 1, 8, 0, 0, 0, 1,
0, 0, 0, 3, -6, 0, 0, 4, 0, 0, 0, 1, 0, 0, 0, 0, -1094, 321,
208, 551, 17, 7, 0, 96, 0, 7, 0, 113), dim = c(12L, 22L), dimnames = list(
    c("A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "A10",
    "A11", "Total P"), c("P1", "P2", "P3", "P4", "P5", "P6",
    "P7", "P8", "P9", "P10", "P11", "P12", "P13", "P14", "P15",
    "P16", "P17", "P18", "P19", "P20", "P21", "Total A")))

blackBodyRadiationColors <- function(x, max_value=1) {
    # x should be between 0 (black) and 1 (white)
    # if large x come out too bright, constrain the bright end of the palette
    #     by setting max_value lower than 1
    foo <- colorRamp(c(rgb(0,0,0),rgb(1,0,0),rgb(1,1,0),rgb(1,1,1)))(x*max_value)/255
    apply(foo,1,function(bar)rgb(bar[1],bar[2],bar[3]))
}

plot(c(0,ncol(dataset)+2),c(0,nrow(dataset)+2),xaxt="n",yaxt="n",xlab="",ylab="",type="n",
    xlim=c(0,ncol(dataset)+2),ylim=c(1,nrow(dataset)+2))
axis(1,at=1:(ncol(dataset)+1),labels=c(head(colnames(dataset),-1),"",tail(colnames(dataset),1)))
axis(2,at=rev(1:(nrow(dataset)+1)),labels=c(head(rownames(dataset),-1),"",tail(rownames(dataset),1)),las=1)

for ( ii in 1:(nrow(dataset)-1) ) {
    for ( jj in 1:(ncol(dataset)-1) ) {
        rescaled_value <- 0.2+0.6*(dataset[ii,jj]-min(dataset))/diff(range(dataset))
        rect(jj-0.5,nrow(dataset)-ii+1.5,jj+0.5,nrow(dataset)-ii+2.5, col=blackBodyRadiationColors(rescaled_value),border=NA)
        text(jj,nrow(dataset)-ii+2,dataset[ii,jj],col=ifelse(rescaled_value>0.5,"black","white"))
    }
    rescaled_value <- 0.2+0.6*(dataset[ii,ncol(dataset)]-min(dataset))/diff(range(dataset))
    rect(ncol(dataset)+0.5,nrow(dataset)-ii+1.5,ncol(dataset)+1.5,nrow(dataset)-ii+2.5, col=blackBodyRadiationColors(rescaled_value),border=NA)
    text(ncol(dataset)+1,nrow(dataset)-ii+2,dataset[ii,ncol(dataset)],col=ifelse(rescaled_value>0.5,"black","white"))
}
for ( jj in 1:(ncol(dataset)-1) ) {
    rescaled_value <- 0.2+0.6*(dataset[nrow(dataset),jj]-min(dataset))/diff(range(dataset))
    rect(jj-0.5,0.5,jj+0.5,1.5, col=blackBodyRadiationColors(rescaled_value),border=NA)
    text(jj,1,dataset[nrow(dataset),jj],col=ifelse(rescaled_value>0.5,"black","white"))
}
</code>


Maximum likelihood estimator (Gaussian errors, known SD)

Question: Suppose that the random variables $Y_1, ..., Y_n$, satisfy $Y_i = \beta \cdot x_i + \epsilon_i$ for $i = 1,...,n$
where $\beta$ is a constant, $x_1,...,x_n$, are constants, and $\epsilon_1,...,\epsilon_n$, are independent and identically distributed random variables with $\epsilon_i \sim N(0,\sigma^2)$, where $\sigma^2$ is a known constant.
(a) Determine the exact distribution of $Y_i$.
(b) Find the maximum likelihood estimator $\hat{\beta}$ of $\beta$ and show that it is an unbiased estimator of $\beta$.
(c) Determine the exact distribution of $\hat{\beta}$.
Comment: Please consider formatting your question in a more neat manner. Your title is atrocious! See the [advanced markdown help](http://stats.stackexchange.com/editing-help), including how to use latex to format mathematical notation in your question.
Comment: Joytee, Please indicate what attempts you have made at this problem and where you might need some assistance.
Answer: Since $Y$ is the sum of a constant and a normal random variable it has an normal distribution figure out its mean and variance.  Write down the likelihood function set the partial derviative of it with respect to $\beta$ to $0$ and solve for $\beta$.  Once you have the formula for the estimate of $\beta$ you should be able to figure out its distribution and determine its mean.  If the mean turns out to be $\beta$ it is unbiased.  I am suggesting to do 3 first and then 2 but it probably can be done either way.


Prove that the equation $\phi(x)=\int_{0}^{x}\frac{(x-t)^{n-1}}{(n-1)! }\phi(t) dt $ have trivial solution for each $n\in \mathbb{N}$

Question: Prove that the equation  $$\phi(x)=\int_{0}^{x}\frac{(x-t)^{n-1}}{(n-1)! }\phi(t) dt $$ have trivial solution for each $n\in \mathbb{N}$ in $C[0,\alpha]$
Proof
I want prove that exists a transformation $T:C[0,\alpha]\to C[0,\alpha]$ such that $T^{n}$ is contractil for conclude that $T$ have a unique fixed point say $x_0$ and conclude that $\phi(x_0)=x_0=0$.
For it I assume that $T_{n}(\phi(t))=\int_{0}^{x}\phi_{n-1}(t)dt$ and hence $T_{n}^{n}=\phi(x)$.
From here I need find $\gamma\in(0,1)$ such that $d(T(x)-T(y))\leq \gamma d(x,y)$.
Let $\phi_1(t),\phi_2(t)$arbitrary functions in $C[0,\alpha]$.
$$Sup_{x\in [0,\alpha]}=\left|\int_{0}^{x}\frac{(x-t)^{n-1}}{(n-1)! }\phi_1(t) dt -\int_{0}^{x}\frac{(x-t)^{n-1}}{(n-1)! }\phi_2(t) dt \right|=Sup_{x\in[0,\alpha]}\frac{1}{(n-1)!}\left| \int_{0}^{x} (x-t)^{n-1}(\phi_1(t)-\phi_2(t))dt\right|$$
From here I need bound it by $Sup_{x\in[0,\alpha]} |\phi_1(t)-\phi_2(t)|$.
Since $0\leq x\leq \alpha$ then $0 \leq x^n \leq \alpha^n$ and hence
from here I can´t continue but I think that $\gamma$ should be  $\gamma=\frac{1}{(n-1)!}$.
Any advice for this proof?
Comment: can $\alpha$ be any positive real number?
Comment: Yes $\alpha\in \mathbb{R}^{+}$
Comment: I'm actually not sure it's necessarily true for $n=1$
Answer: I think you are misinterpreting the problem, we want to show that the solution is trivial for each $n\in \mathbb{N}$.
Fix $n\in\mathbb{N}$ and consider $\varphi_1,\varphi_2\in C[0,\alpha]$ and define
$$T_n\varphi=\int_0^x\frac{(x-t)^{n-1}}{(n-1)!}\varphi(t)dt$$
Note I will use $\|\cdot \|_\infty$ to denote the sup-norm on $[0,\alpha]$
and consider
$$\|T_n\varphi_1-T_n\varphi_2\|_\infty=\Big\|\int_0^x\frac{(x-t)^{n-1}}{(n-1)!}(\varphi_1(t)-\varphi_2(t))dt \Big\|_\infty$$
since $\varphi_1,\varphi_2\in C[0,\alpha]$ we know they each obtain their supremums and you can move the absolute value inside the integral to get
$$\|T_n\varphi_1-T_n\varphi_2\|_\infty\leq\Big\|\int_0^x\frac{(x-t)^{n-1}}{(n-1)!}|\varphi_1(t)-\varphi_2(t)|dt \Big\|_\infty$$
$$\leq \|\varphi_1(t)-\varphi_2(t)\|_\infty \Big\|\int_0^x\frac{(x-t)^{n-1}}{(n-1)!}dt\Big\|_\infty$$
Now we compute $\Big\|\int_0^x\frac{(x-t)^{n-1}}{(n-1)!}dt\Big\|_\infty$ directly
$$\Big\|\int_0^x\frac{(x-t)^{n-1}}{(n-1)!}dt\Big\|_\infty=\Big\| \frac{x^n}{n!}\Big\|_\infty=\frac{\alpha^n}{n!}$$
Now, for every $n>1$ this says that $T_n$ is a contractive map and since the zero function satisfies the equation it must be the only solution.
Consider the case $n=1$ on your own.
Comment: In the last identity there should be an $\alpha^n$.
Comment: It seems this argument depends on $\alpha$
Comment: Thanks a lot, I misinterpret the problem
Comment: anytime @Juan T, maybe ask your professor to clarify the problem.  The $\alpha$ dependence is definitely an issue
Comment: Yes I think that is a typo and there should be $1$
Comment: @JuanT why would that be a typo? The problem doesn't ask to prove that $T_n$ is a contraction, it ask to prove that it has only a fixed point. There are other ways to do it, for instance, it's enough to prove that $T_n^k$ is a contraction for some $k > 0 $


Can the long line be embedded in the ordered plane?

Question: It is a well known result that the long line (namely, the topological space $S_\omega \times [0, 1)$ in the order topology, where $S_\omega$ is the minimal uncountable well-ordered set) cannot be embedded in Euclidean space of any dimension. Is it possible, however, to embed the long line in $\Bbb{R}^2$ in the lexicographic order topology? What about the ordered square?
My intuition about this space is that it is composed of an "uncountable number of real lines" which makes me conjecture it could be possible to embed it in such a space; as it stands, I'm not yet able to give a rigorous proof of the matter - or the opposite.
Comment: I believe $\mathbb{R}^2$ with the dictionary topology is first-countable while the long line is not, so certainly the long line cannot be embedded in the ordered plane. That doesn't rule out the converse.
Comment: https://en.m.wikipedia.org/wiki/Long_line_%28topology%29?wprov=sfla1 This article on Wikipedia lists the (non-extended) long line or ray (actually, my example is on the non extended closed long ray) as first countable. As much as I trust SE more than most other sites, I would like to clarify this mismatch as well.
Comment: Ah, my bad. I was looking at the extended version. That said, the extended version is obtained by adding a single point, so maybe you can still extract something useful from the observation. (For instance given an embedding of the non-extended long line into R2, maybe we can we extend the embedding to an embedding of the extended long line into R2 and thus find a contradiction.)
Answer: For $\mathbb{R}^2$ with the lexicographic order, this is very simple,  Note that for each $x\in\mathbb{R}$, $\{x\}\times\mathbb{R}$ is clopen in $\mathbb{R}^2$ and homeomorphic to $\mathbb{R}$ with the usual topology.  Since the long line is connected, any continuous map from the long line to $\mathbb{R}^2$ must have its image contained in $\{x\}\times\mathbb{R}$ for some $x$, and thus cannot be an embedding since the long line does not embed in $\mathbb{R}$.
For the unit square the argument is a bit more complicated.  Let $L$ denote the long line and let $S$ denote $[0,1]^2$ with the lexicographic order.  Let $p:S\to [0,1]$ be given by $p(x,y)=x$; note that $p$ is continuous (for the usual topology on $[0,1]$).  So, if $f:L\to S$ is any continuous map, we have a continuous composition $p\circ f:L\to [0,1]$.  Any continuous map $L\to[0,1]$ is eventually constant, so $p\circ f$ is eventually constant.  However, this means that there exists $a\in L$ and $x\in [0,1]$ such that $f(b)\in \{x\}\times[0,1]$ for all $b>a$.  Since $\{x\}\times[0,1]$ just has the usual topology of $[0,1]$, this again implies that $f$ is eventually constant, and so cannot be an embedding.
(This second argument applies equally well to the space $\omega_1$ instead of $L$, to show that it does not embed in either $\mathbb{R}^2$ or $[0,1]^2$ with the lexicographic order topology.)

Just for completeness, here is a proof that any continuous map $f:L\to\mathbb{R}$ is eventually constant (the same argument also applies with $\omega_1$ in place of $L$).  First, fix $\epsilon>0$.  Suppose that for all $a\in L$ there exist $b,c>a$ such that $|f(b)-f(c)|>\epsilon$.  We can then choose an increasing sequence $b_1<c_1<b_2<c_2<\dots$ such that $|f(b_n)-f(c_n)|>\epsilon$ for each $n$.  Every sequence in $L$ is bounded above, so this sequence has a supremum $x$ which it converges to.  But this contradicts the continuity of $f$, since the sequence $(f(b_1),f(c_1),f(b_2),f(c_2),\dots)$ is not Cauchy and so cannot converge to $f(x)$.
So for every $\epsilon>0$, there exists $a\in L$ such that $|f(b)-f(c)|<\epsilon$ for all $b,c>a$.  For each $n$, choose $a_n$ that works as such an $a$ for $\epsilon=1/n$.  Letting $a$ be an upper bound for all these $a_n$, we have $|f(b)-f(c)|<1/n$ for all $n$ if $b,c>a$.  That is, $f(b)=f(c)$ for all $b,c>a$, so $f$ is constant above $a$.
Comment: Yes! Originally I thought of the argument from continuity of the long line, but couldn't tell if the lines of the ordered plane were connected or not. Thank you for both proofs.
Comment: I was trying far too hard. +1!
Answer: Great question! Here is partial work towards a negative answer.
(Incidentally, note that it's easy to show that the answer is no if we consider the long line and the ordered plane as linear orders, and look at order-preserving embeddings. That doesn't answer your question, but lends some plausibility to a negative answer.)

Below, I'm going to write "$\omega_1$" for what you call "$S_\omega$" - this is in fact the standard notation.
Suppose $f$ is an embedding (in the sense of topology) of the long line into the ordered plane. Then we get an embedding $g$ from $\omega_1$ into the ordered plane, by composing $f$ with the obvious embedding $e$ of $\omega_1$ into the long line (sending $\alpha$ to the "$0$" of the "$\alpha$th copy of $[0,1)$").
Let $h:\omega_1\rightarrow\mathbb{R}$ be the map sending $\alpha$ to the index for the "copy" of $\mathbb{R}$ which $g(\alpha)$ lives in. Then $h$ is a continuous map from $\omega_1$ into $\mathbb{R}$. It is not guaranteed to be an embedding, since there is no reason it should be injective, so this isn't immediately a contradiction; we're going to have to do some work.
The key claim - which I can't prove yet - is:

Claim: For each $r\in\mathbb{R}$, $h^{-1}(\{r\})$ is countable.

That is, $h$ only "comes back" to a given real countably many times.
Taking the claim above on faith for the moment, I'm going to define a set $A\subseteq\omega_1$ with the following two properties:

$h$ restricted to $A$ is injective.
$A$ with the subspace topology is homeomorphic to $\omega_1$. Note that for this, it is not enough to have $A$ be uncountable: the set of successor elements of $\omega_1$ with the subspace topology is discrete, after all.

This will give a contradiction, since - composing the restriction of $h$ to $A$ with a homeomorphism between $A$ and $\omega_1$ - it gives us an embedding of $\omega_1$ into $\mathbb{R}$.
(Well, we'll still have to prove the claim! But we'll be close to done.)
So here's how we build $A$. By transfinite recursion, we can define a sequence $(\theta_\eta)_{\eta\in\omega_1}$ of elements of $\omega_1$ satisfying $$\theta_\eta=\min(\{\alpha\in\omega_1: \forall\beta<\eta(\mbox{$h(\alpha)\not=h(\theta_\beta)$})\}).$$ The fact that $\theta_\eta$ is well-defined for each $\eta\in\omega_1$ follows from the claim above. Now let $$A=\{\theta_\eta:\eta\in\omega_1\}.$$ Clearly $h$ restricted to $A$ is injective, and the fact that $A$  (with the subspace topology) is homeomorphic to $\omega_1$ follows from the easily-checked fact that for every limit ordinal $\lambda\in\omega_1$, we have $$\theta_\lambda=\sup\{\theta_\beta:\beta<\lambda\}.$$

So all that's left to do is prove the claim above. I don't immediately see how to do this, although there are a couple tempting approaches (in particular, Fodor's lemma seems potentially quite useful).
Comment: Thank you for your beautifully attempted proof!


Sheafs appearing in philosophy?

Question: I apologize in advance if I make mistakes in the following construction. I have very recently been introduced to the concept of a sheaf.
I am currently a mathematics major and philosophy minor and have found certain concepts in mathematics to be particularly useful in discussing certain philosophy (the most useful of which being different sizes of infinity, orders on sets, etc). Recently I've been thinking about causality (in philosophy) and sheafs (in mathematics).
If we let $E$ be the set of events the occur in the universe, we can give $\mathcal{P}(E)$, the power set of $E$ a partial ordering $\leq$ that is reflexive. Namely, if $U,V \in \mathcal{P}(E)$, we say $U \leq V$ if $U$ causally implies $V$ or in other words, if all events in $U$ occur, then all of the events in $V$ must occur. So we can construct the category of events with respect to this partial order (that is, Hom$(U,V)=\{(U,V)\}$ if $U\leq V$ and is empty otherwise).
Furthermore, time, or $T$, is traditionally viewed as a subset of $\mathbb{R}$ and thus inherits a subset topology.
Let $F: T \to \mathcal{P}(E)$ be defined so that for every open subset of time $W \subset T$, $F(W)=\{x \in E \mid x$ occurs at time $t_x$ such that $t_x \in W\}$, that is, we associate to a subset of time $W$, the collection of events that happen at any time in $W$.
I claim $F$ is a presheaf. We get natural restriction morphisms since for example, knowing all of the events that occur today is enough for me to know the events that occur between 1 o'clock and 2 o'clock today.
My question is: "Have I made any mistakes?", "Is this also a sheaf?", "Are there any properties of sheafs that can be translated back into language about causality that could be useful? or is this a completely trivial construction?", "Does this tell us anything about the philosophical idea of determinism?".
Comment: First problem with this is your definition of time. GR says that the time that two events occur relative to each other depends on your position in space. So either you must fix some position and take time to be the time relative to that position is space, or otherwise $T$ cannot be a subset of $R$.

The second problem I think is larger. I mean how the hell do you define 'an event'?
Comment: Thank you for the comment. These thoughts are definitely in the primitive stages for me so I hadn't thought about rigorously defining an event and instead have been just going with my intuitive notion of it. I indeed might need to scrap the whole idea if I can't come up with a clear definition of 'an event'.
Answer: When you say "We get natural restriction morphisms since for example, knowing all of the events that occur today is enough for me to know the events that occur between 1 o'clock and 2 o'clock today" you seem to suggest that ${\cal P}(E)$ is partially ordered as the opposite of the usual subset ordering. But then your notion of "causal implication" is rather vacuous: all it says is that if some things have occured, then any subset of those things have also ocurred $-$ this is purely logical rather than "causal" in nature. Indeed, there is nothing to connect what events occur at time $t_1$ with what events occur at time $t_2$, for any times $t_1$ and $t_2$, which is a big hole if this is supposed to be a kind of physical model. At any rate it is in fact a presheaf.
I think in differential geometry and special relativity there are notions like timelike, spacelike, null, causal, etc. in regards to directions in spacetime (modelled as a Lorentzian manifold) which are relevant to what you're trying to think about. You may try searching these keywords (and learning some geometry appropriate for the occasion).
Comment: Good point. I am definitely thinking via causality in one sense and logical in another. But it seems like causality is in particular "logical" in the sense that "U causes V" would gives us "Not V implies not U".

Sheafs appearing in philosophy?


How to check if the data is intermittent or too many zeros are due to seasonality?

Question: I have a dataset for weekly number of calls to  a call center for three years.The data is seasonal (I know this from practitioners knowledge) which means that calls normally come on summer and winter. However, without having practitioners knowledge, how can I check if my data is intermittent or this is seasonality which is impacting zeros for specific time intervals. Is there anyway in R that I can do that? The reason is that I need to do further analysis on those parts of the data which are not zero and I need to classify my data to in-season and off-season. Any help is appreciated.
Comment: why don't you post your data . Daily data is best as what happens in week i of year 1 may not happen in week i of year 2 etc. while the analysis of daily data can pick up the kind of structure that you are after.
Comment: I dont have daily data. It is weekly and it barely take values. So daily data is going to bring much more zeros to my data set. I also dont need accurate forecasts for daily data I just need to know my dataset and the inherited trend in that.
Comment: OK .... please post your data and some of our experts in time series analysis will give you some answers.
Answer: You can decompose (STL decomposition) you time series into trend, seasonal and remainder using "forecast" package. See example and explanation in the amaizing online book by  Rob J Hyndman and George Athanasopoulos, who are also the authors of the package.  Once decomposed, you can analyze trend or remainder or both.


Why the first moment is standardized before computing higher moments, but higher moments are not?

Question: Wikipedia says:

For the second and higher moments, the central moments (moments about the mean, with c being the mean) are usually used rather than the moments about zero, because they provide clearer information about the distribution's shape.

Could someone explain/convince me why this is true? Why is there a discrepancy?
This has always bugged me and I have never seen a good explanation for it -- I just don't quite understand why/how standardization provides "clear" information in one case but not in another.
For example:

To compute the skewness, why not standardize both the mean and the variance?
To compute the kurtosis, why not standardize the mean, the variance, and the skewness?
...
To compute the nth moment, why not first standardize all the mth moments for m < n?
If standardization is useful then why only do this for m = 1?
Comment: How do you understand "shape"? I take it to be *the collection of all properties of a distribution that are not altered by any change of location or scale*--in other words, properties that persist in a graph of the distribution when all axis labels are erased.  If you share this understanding then (a) the answer to your question should become obvious and (b) it will be evident that central moments are not the only way to solve the problem of describing shapes; they are merely one way to establish a location and scale for (most) distributions.
Comment: The word "normalize" is one of many in statistical science that changes meaning from field to field, to the extent that it is dangerous. Using it to imply "mean-subtracted" isn't standard for many of us. I would be exceeding my knowledge to say that it is non-standard for all, but I challenge you to cite literature where "normalize" is identical to "subtract the mean".
Comment: I didn't say that I felt confused; unfortunately I remain of the view that the precise import of your question is likely to be unclear to others. A paper with tutorial flavour at http://www.stata-journal.com/sjpdf.html?articlenum=st0204 may have interest for people curious about moments.
Comment: ["The second type of **normalization** originates from statistics, and eliminates the unit of measurement by **transforming the data into new scores *with a mean of 0* and a standard deviation of 1**."](https://www.utdallas.edu/~herve/abdi-Normalizing2010-pretty.pdf) @NickCox I think my usage of the word wasn't too outlandish and made enough sense to get the point across, so let's not go on a tangent here.
Comment: Sorry; that's not what I asked. Your question was why use moments about the mean rather than moments about zero. For example, the second moment about the mean is the variance; it's not scaled by the standard deviation. Naturally I agree that skewness and kurtosis are often defined as moment ratios, which is equivalent to scaling by the standard deviation too, but neither is mentioned in your question at all. In short, my comment is about the wording in your question. You've provided evidence for my assertion, as subtracting mean and dividing by SD is commonly called standardization.
Comment: If your question is unclear or confusing in any sense, that's not a tangent; it's crucial to the wider usefulness of this thread. The purpose of any question is not just to satisfy the OP, but to contribute to an archive of well-written, useful questions that benefit many readers.
Comment: @NickCox: Is it clearer now?
Comment: In part, but you mention "standardize" but never define it.  Further, the talk in statistics is of standardizing variables, not standardizing the mean, or the variance, or the skewness. Rather, standardization yields mean 0 and variance (SD) of 1, and moment ratios are the same for standardized variables as for unstandardized. Unfortunately I can't rewrite the question for you as (a) it's your question (b) I don't understand what you are confused about.
Comment: @NickCox: Fixed.
Comment: You've fixed one problem by cutting the word "normalize". I have to leave the discussion there for now.
Comment: @Nick because I'm not sure what you're confused about, so I'm not sure what to tell you. If you don't understand the question then I guess there's not much else you can do other than leave it and see if other people get it? Paulius understood it just fine after my clarification.
Answer: Since the question was updated, I update my answer:
The first part (To compute the skewness, why not standardize both the mean and the variance?) is easy: That is precisely how it's done! See the definitions of skewness and kurtosis in wiki.
The second part is both easy and hard. On one hand we could say that it is impossible to normalize random variable to satisfy three moment conditions, as linear transformation $X \to aX + b$ allows only for two. But on the other hand, why should we limit ourselves to linear transformations? Sure, shift and scale are by far the most prominent (maybe because they are sufficient most of the time, say for limit theorems), but what about higher order polynomials or taking logs, or convolving with itself? In fact, isn't it what Box-Cox transform is all about -- removing skew?
But in the case of more complicated transformations, I think, the context and the transformation itself becomes important, so maybe that is why there are no more "moments with names". That does not mean that r.v.s are not transformed and that the moments are not calculated, on the contrary. You just chose your transformation, calculate what you need and move on.

The old answer about why centralized moments represent shape better than raw:
The keyword is shape. As whuber suggested, by shape we want consider the properties of the distribution that are invariant to translation and scaling. That is, when you consider variable $X + c$ instead of $X$, you get the same distribution function (just shifted to the right or left), so we would like to say that its shape stayed the same.
The raw moments do change when you translate the variable, so they reflect not only the shape, but also a location. In fact, you can take any random variable, and shift it $X \to X + c$ appropriately to get any value for its, say, raw third moment.
The same observation holds for all odd moments and to lesser extent for even moments (they are bounded from below and lower bound does depend on shape).
The centralized moment, on the other hand, does not change when you translate the variable, so that's why they are more descriptive of the shape. For example, if your even centralized moment is large, you known that random variable has some mass not too close to mean. Or if your odd moment is zero, you known that your random variable has some symmetry around mean.
The same argument extends to scale, which is transformation $X\to cX$. The usual normalization in this case is division by standard deviation, and the corresponding moments are called normalized moments, at least by wikipedia.
Comment: Aaahh! Now I get it. The question is: why don't we normalize by requiring, say, that third moment was equal to zero, and that the tenth one was equal to one? OK, that's a completely different question, let me think about it :)
Comment: Could you explain your assertion about "move it around to get any value of third moment"? What exactly do you mean by "move it around," what bearing does this operation have on distributional *shape*, and why does it change the *third* moment?
Comment: Sure: by moving around I meant translations $X \to X + c$. It does obviously change the value of the third moment and you can get it be equal to whatever value. It does not change the shape of the distribution by your nice definition of shape above.
Comment: Ah... you mean the *raw* third moment rather than the central third moment. In this context, where we are discussing several kinds of moments, I lost track of which one you actually meant.  That misreading was surely my fault, but when you modify this post to clarify what "move it around means" you might consider making some additional minor edits to help prevent others from falling into the same trap.
Comment: (+1) Many thanks for turning this into a really clear, authoritative post.
Comment: You seem to be explaining why normalization is useful for understanding the shape, whereas my question is why it would be *not* useful for higher-order moments if it's useful for the first moment. Did I misread your answer or did you not address this?
Comment: It seems that I have misread yours and answered something you did not ask: I focused on the wiki citation, which claims that centralized moments describe shape better than raw moments.

Now I am puzzled about this comment of yours and I don't really understand the question. :(
Comment: @PauliusŠarka: My question was about the discrepancy between first- and higher-order moments: i.e., why should they be treated differently? I understand the motivation for centralization but I don't understand why it only applies to the first moment. Why not do something equivalent for *all* moments rather than just the first one? Why is the first moment special?
Comment: @PauliusŠarka: Yeah. I edited the question too, I hope that's clearer.
Comment: @Mehrdad You are asking for something that is mathematically impossible: true, one can use *any* measure of spread to establish a scale, but this can happen only once: after recentering and rescaling, there is nothing else that can be done to change any of the other moments further. What you could do, if you so chose, would be to use (say) the tenth root of the tenth moment to establish the scale. That would make the tenth moment equal to unity. But you cannot force all the moments to equal prespecified values (such as zeros and ones) without completely changing the shape of the distribution.
Comment: @whuber: No, that's not what I'm saying. I'm **not** forcing *all* the moments to a prespecified value; I'm only forcing some of them. Read my question to understand which ones I'm talking about.
Comment: If "some" is more than two, what you are asking for is impossible in general.


Infinity $\times\ 0=$ ? indeterminate or zero?

Question: I got the following equation for a differential solution
$$Q= e^{-Rt/2L} (A \cos wt + B \sin wt)$$
where $R,L,w,A,B$ are constants.
If $t$ tends to infinity, find $Q$?
$e^{-Rt/2L} = 0$, if $t$ tends to infinity
$(A \cos wt + B \sin wt) = \infty$, if $t$ tends to infinity is it?
So $Q = \infty \times 0$, that is indeterminate.
then what is the value for $Q$, if $t$ tends to infinity?
The answer was $Q =0$. How? Explain me?
Comment: Is not $-1\le \cos \le 1?$ And $-1\le \sin \le 1?$
Comment: Indeterminate means "knowing it has this form is not enough to tell you the answer". $0*\infty $ is indeterminate, but that doesn't stop the answer to a particular limit from being 0.
Comment: Shouldn't you already know basic limits theory **before** differential equations?
Answer: By triangle inequality, you have
$$\forall t\in \mathbb R\;\; |Q(t)|\leq (|A|+|B|)e^{-\frac{Rt}{2L}}$$
since $|\cos(wt)|\leq 1, |\sin(wt)|\leq 1$.
and
$$\lim_{t\to+\infty}e^{-\frac{Rt}{2L}}=0$$
if $R.L>0$.
thus
$$\lim_{t\to +\infty}Q(t)=0.$$
Comment: if t tends to infinity sin t is?
Comment: @Nisha Bounded.
Comment: Got it. thank u


How does the bottom number of the time signature affect counting?

Question: I have learnt all the complicated mathematics subjects in my school, but that bottom number, I can't understand.
Ok, the notation will be different, and it will say what kind of note gets the beat, but why do I need to know that if it won't change what I'll play? Can someone show me the difference if I play something in 5/4 or 5/8, or 7/4 and 7/8?
There was a time when I thought I understood, I thought that since it was a quaver note in the bottom I would count 1 and 2 and 3 and 4...; if it was 16th note in the bottom I would count 1 e and a 2 e and a 3 e and a 4; but I asked on reddit and they said I'm completely wrong.
After all, if it's only going to make a small difference in how I read and no difference in how I play the song or count, then what's the point of the bottom number? It's just there to complicate things?
Comment: Not sure if it will help but in case it does, knowing math is no benefit to understanding time signatures. They are musical symbols not based on mathematics.
Comment: @ToddWilcox - there is still an element of maths in time signatures. Which bears a relationship with fractions which to a degree they actually are. Numerator tells how many, denominator tells what each is.
Comment: Does this answer your question? [I don't understand the bottom number in a time signature](https://music.stackexchange.com/questions/108517/i-dont-understand-the-bottom-number-in-a-time-signature)
Comment: @Neal I've updated the title in an attempt to clarify the distinction between this question and the proposed duplicate.
Comment: @ToddWilcox time signatures are musical symbols that are very much based on mathematics.
Comment: @ToddWilcox math doesn't always have "numbers" in strict ways. The logic of multiples and fractions always applies in music (for time, and for pitch, as they're always related), the fact that some music symbols are not "mathematical" is pointless.
Answer: I believe there are fundamentally 2 main reasons I can think of:

historically, the tempo was not strict as it has been considered in the last 2-3 centuries, and it was usually decided based on the time signature; so, for instance, 3/8 was considerably faster than 3/4, and that's usually true even for today's music: if the fraction has a larger denominator, it's usually played fastly;
readability;

Tempo indications based on signature
Before tempo markings (and, obviously, the introduction of metronome), the signature was used to indicate how fast a piece should have been played.
See the following diagram, taken from this answer:

As you can see, the suggestions (created to relate the signatures to modern metronome marks) are very different.
Readability
Readability is a very important aspect in music writing: the musician must focus only on playing, not decyphring what's written (just like an actor must focus on delivering the feeling of the lines, not how they're written). Using simpler tempo markings could cause serious issues, especially for slower music that has phrasings based on small subdivisions. This aspect is obviously also considered for writing: many notation aspects are "tricks" composers used to write "less" and faster - and, I believe, to use less ink and reduce risk of errors).
Consider the following excerpt from the 8th Prelude of the Well-Tempered Clavier, first book, which is written in 3/2:

Now, let's see how it would look if it were written in 3/4:

While it is "mathematically" correct, it's simply awful to read.

Let's take the third Prelude instead:

You could say that, if written in 3/4, it could have been more easy to read. But then we have to recall the first rule (remember, it was written in the first half of the 1700).
Finally, the only problem could rise for equivalent fractions, but that's easily answered: in music, equal mathematical values don't always mean the same musical result: 6/8 is not 3/4; 8/16 is not 4/8 (nor 2/4), and it usually is considered a "tempo misto" (sorry, I don't know the English term), often as 3+3+2.
Comment: @J... no, maybe I finally found out, I believe they're called [Additive rhythms](https://en.wikipedia.org/wiki/Additive_rhythm_and_divisive_rhythm), which include not only odd meters, but also even meters that use odd subdivisions (8 as 3+3+2, etc).
Comment: Unusual key sig. at the end - but at least all the # are within the stave.
Comment: @Tim yeah, I didn't realize that. But I don't think it's about making them fit the stave, as the lower part has that B above it, so I assume it was just to put them "in linear order".
Comment: Somehow, though, it's a tidier version than the existing one. I've always questioned why the G# needed to be out of the stave although maybe that puts a question mark over the bass clef?
Answer: The other important information that the "denominator" of a time signature conveys is the beat in relation to other sections of the music. The meter of a piece does not have to remain constant, and as an example, it is possible to go from 4/4 to 3/8. In that case, the new time signature uses the eighth note as its beat for a triple meter, and the old time signature was using the quarter note as its beat in quadruple time. Thus, one of the reasons the beat value is significant is that the beat value can change.
Theoretically, it makes no difference whether the above example was 4/4 to 3/8 or whether it was written as 4/2 to 3/4. However, musicians have expectations about what types of musical ideas should be expressed in what place in the meter. In a lot of rock music, the snare will hit on the 2nd and 4th beats of a measure, and it is most common that these represent the 2nd and 4th quarter notes in 4/4. In most pop songs, the quickest syncopations fall on the 16th-note subdivisions. In most music that swings, the swing will be expressed as uneven 8th notes in the notation. These are not hard-and-fast rules, but following the note-values that musicians expect is part of the practice of writing easily understandable sheet music.
Comment: "In a lot of rock music, the snare will hit on the 3rd beat of a measure" Do you mean in general or as an common occurrence? Because, in the first case, rock (and 4-beat-pop in general, but it actually is valid even from roots of jazz music), the snare hits on 2 and 4. In the second, that's referred to as "half-time" or "half-tempo".
Comment: @musicamante Good catch, and good point.
Answer:
After all, if it's only going to make a small difference in how I read
and no difference in how I play the song or count, then what's the
point of the bottom number?

The point is, you have to write SOMETHING there, or otherwise the top number doesn't mean ANYTHING.
It's about culture, conventions, tradition and language. Not natural science, laboratory measurements and math. If you ask yourself "should I write this in 7/4 or 7/8" and cannot tell the difference, then you lack cultural, not theoretical knowledge. To me, 7/4 means something slower than 7/8 and so that I don't think about dividing the bigger ticks. But it's not a very commonly used time signature, so I might look at and listen to more pieces written in 7/4 to study how people traditionally understand it.
What does 4/4 mean? It won't tell you the intended pulse of the song. The time signature doesn't specify if you should be thinking One-e-and-a Two-e-and-a Three-e-and-a Four-e-and-a, or One-and Two-and Three-and Four-and. In other words, is it an 1/8 beat or 1/16th beat feel. Or if it should be played with swing. The time signature gives you a class or category of rhythmic feelings that have traditionally been written with that time signature. To know the intended pulse and feel of the song, you'll have to look at other hints, such as what is the smallest time value in the melody, is there 1/16 syncopation, what is the tempo marking, does it say "swing", or is there perhaps a name of a rhythm style such as tango.
Why aren't 8th beat songs written in 8/8, and 16th beat songs in 16/16? Why do people say "How do you do?" How do you do what? What's the point, if the answer is going to be "How do you do"? You can't calculate it, you need to get involved in the culture to understand it.
Answer: When counting with the system you're using, the beat is always the whole number.

X/2 time: minim = 1 2 3 ...; crotchet = 1 & 2 & ...; quaver = 1 e & a 2 e & a ....
X/4 time: crotchet = 1 2 3 ...; quavers = 1 & 2 & ...; semiquavers = 1 e & a 2 e & a ....
X/8 time: quaver = 1 2 3 ...; semiquaver = 1 & 2 & ...; demisemiquaver = 1 e & a 2 e & a ....
X/16 time: semiquaver = 1 2 3 ...; etc.

For the answer to the rest of the question, see
Is there any real-world difference between time signatures such as 4/4 and 8/8?
Comment: I don't understand the '1 2 3...' in each example. Help!
Comment: The whole numbers correspond to the basic pulse of the music — the beats. The top number in a time signature (X in these examples) indicates the number of beats. The "&" and "e/a" represent divisions of beats: "&" marks the 1/2-beat; "e" and "a" mark 1/4 and 3/4 parts of a beat.
Comment: I've been aware of that for many decades!!! Some things I don't understand. Why 1 2 3...??? I'm not a complete idiot, but working on it. Just help them out when they need some support.
Comment: The idea behind 1 2 3 is to keep track of which beat within the measure you're on. Some (piano) method books, however, have begun moving away from that, especially in the earliest levels. Instead, they count the length of the notes. So, crotchet, crotchet, minim would be 1 1 1-2.
Comment: @Tim why not? Being able to count out loud while playing (assuming the instrument allows it) should be a basic skill. Or am I not understanding your question?
Comment: Ah, you mean 'e.g.1 2 3 etc'. It just didn't make sense to me with only 1 2 3 each time.And wouldn't the top version count 1 e & a (etc) for quavers?
Comment: Ahh, yes quavers. Good catch. ("..." = "etc")
Answer: Well, if an English text is preceded with "[to be read in a heavy Yorkshire accent]" this does not really have an effect on the sequence of words following as such (assuming they don't employ special terms or phonetic spelling) but are still an important performance indicator.  Syllable stress will be totally different than when preceded with "[to be read in a heavy French accent]".
The meter specifies how the material is structured, where the accents in the music lie and how they are connected.  In some respects, it tells you what kind of dances will work with the music.
Now the most important number certainly is the top number.  However the choice of bottom number is still somewhat relevant by convention rather than logic: 3/1 tends to be faster than 3/4 (since 3/1 is a baroque triplet rhythm), 3/8 has a somewhat more rigid substructure than 3/4 (which may have a somewhat elongated 4 in execution) because of different dances they are associated with, 4/4 is a standard structure while 4/8 again tends to be a bit faster and with less of an accent on the 3rd beat and so on and so on.
Basically you are best off not trying too much to understand the underlying logic but just taking in examples as you go and eventually developing some sort of feeling for it.
Answer: I don't think the confusion is your basic understanding of meters and time signatures, but probably how you are counting aloud with syllables.
In simple time signatures - those that subdivide the beat by 2 - it's the note value that gets the beat. Ex...

4 (four beats per measure)
4 (quarter note gets the beat)

In compound time - those that subdivide the beat by 3 - it's the value of the subdivisions. Ex...

6 (divide this by three, 6/3 = 2, there are two beats per measure)
8 (each of the 2 beat is subdivided by three eighth notes)

Time signatures are not fractions.
Time signatures are not really math.
Time signatures are short hand signs for meters. You could replace them with any other sign. Case in point: the C for common time or 4/4.
After learning how to read a time signature, it's probably more practical to just recognize the commonest by memory: 2/4/, 3/4, 4/4, 3/8, 6/8, 9/8, 12/8`.
Additive time signatures like 7/8, 5/4, etc. are sort of "advanced" but shouldn't be too hard to deal with provided you understand simple and compound time signature.

...it will say what kind of note gets the beat, but why do I need to know that if it won't change what I'll play? Can someone show me the difference if I play something in 5/4 or 5/8...I thought that since it was a quaver note in the bottom I would count 1 and 2 and 3 and 4...; if it was 16th note in the bottom I would count 1 e and a 2 e and a 3 e and a 4...

Technically, the person at Reddit was right to say your counting aloud is wrong. If the 16th note was on the bottom, like 4/16, then the beat count should still be "1,2,3,4" on  each sixteenth note.
I think the think to keep in mind is: beats, subdivisions, beats per measure.
When using the rhythm syllables, like "1 e & a", be careful of what is a beat and what is a subdivision. There are different systems of syllables, but I think it doesn't matter much what you say as long as you keep to numbers on the beats, which is what the person a Reddit must have taken issue with in your example. Here is how I think you would count aloud for some examples...

Notice that with 5/4 the beats are subdivided by 2 so it a kind of simple meter, but in 5/8 you get beamed groups of 3 eighth notes subdividing a beat, which is like compound meters, mixed with groups of 2 eighth note subdivisions. In odd or additive meters like these the bottom number can signal the difference between simple to compound feel.
4/16 looks strange... because it is, but if you wrote it, that is how it would be counted. It's essentially common time, but you change which note values are assigned to a full beat. There probably isn't a practical reason to do this.


Best approach to create a troubleshouting section?

Question: I am looking to create some kind of troubleshooting section on a website. Sort of like the Windows help with some sections, questions and answers.
I was thinking of doing this with a regular Book, and write a small form module which allows me to track the page with a "Was this information helpful or not?" question.
But are there possible alternatives, either existing modules or an approach which works best?
Answer: If you go down the book route then you can always use the flag module for the "Was this information helpful".
There is also the FAQ module which doesn't quite fit your use case but might be worth checking out just in case.


I think that there's something wrong with my search method otherwise it should work

Question: I am trying to search a list and then extract some objects of it put them into another list and write the list to a file.
I think that my code is right but when I execute it I get a NullReference exception. If someone could check my code would I would be really grateful.
Here's my code for the Search method that I use
public void Search( string day)
{
    foreach (Classes c in studentClasses)
    {
        if (c.Day == day)
        {
            studentClassesByDay.Add(c);
        }
    }
}

And that's the code which adds the new list to a file
private void btnDay_Click(object sender, EventArgs e)
    {
        SelectDayForm selectDay = new SelectDayForm();
        if (selectDay.ShowDialog() == DialogResult.OK)
        {
            l.Search(selectDay.theDay);
            trg.GenerateSortedListReport(l.studentClassesByDay, AppData.byDay);
            MessageBox.Show("A list of sorted student classes written to file " + AppData.byDay+ ".");
           // txtDay.Text =selectDay.theDay;

        }
    }

Comment: I don't think it is possible to answer this with the supplied information. Do you have anything else? Error details?
Comment: Are you sure your: `studentClasses`,`studentClassesByDay`,`l`,`trg` variables have all been instantiated? Have you run it with the debugger attached to see which line the NRE is happening on?
Comment: Well theDay is a string which is working when I pass it. I have already checked that by displaying theDay on a listbox. That's why I thought that my Search method is wrong. Maybe it doesn't add the objects into the new List because when I tried to display it there was nothing in it
Answer: You haven't shown on which line the exception occurs (which would be handy) but you also haven't shown where studentClassesByDay has been instantiated.
That would be the first thing I would check.
The only possibilities in the code you've shown are:

l is null;
trg is null;
l.studentClassesByDay is null; or
AppData is null (though that's probably not so - it looks like a class).

Simply put some debug statements (or breakpoints in your debugger) before each attempted dereference and check the values.
Based on your comment that the errant line is:
studentClassesByDay.Add(c);

it's almost guaranteed (as suspected) that you havent actually instantiated this variable. I'd look into that.
Comment: The line is studentClassesByDay.Add(c);


What, exactly, does the "coordinate gradient descent algorithm" do?

Question: I knew about "Coordinate descent" and "Gradient descent" algorithms before; they are well-known and Wikipedia has articles for those. However I recently came across an algorithm called "Coordinate gradient descent".
How does this algorithm exactly work, and how does it relate to "Coordinate descent" and "Gradient descent"?
An example for usage of this term can be found on slide 7 at the link http://courses.cs.washington.edu/courses/cse546/12wi/slides/cse546wi12ClusteringEM.pdf. I think what K-means or EM does is "Coordinate gradient descent" (or "Coordinate gradient ascent", based on how you view the optimization), but I could not figure out the intuition behind the name.
Comment: There are a few papers about that mention it, for example, [this one](http://cbio.ensmp.fr/~jvert/svn/bibli/local/Tseng2009Coordinate.pdf)
Answer: The difference is that for Coordinate Descent, when you update a weight $w_i$, you update by setting the gradient of the function wrt $w_i$ to 0, then simply solving for $w_i^{new}$. If you have a convex differentiable function $F(\pmb{w})$, then updating $w_i$ attains a global minimum over the coordinate $w_i$ in a direction where all other points $w_j$ are held fixed. Once you've reached a point where $F(\pmb{w})$ is minimized along every coordinate and no further changes can be made, then you have reached a global minimum.
By contrast, with coordinate gradient descent (CGD), you basically follow gradient descent, but with respect to one weight. So an updated weight $w_i^{new}$ is defined at as $w_i^{new} = w_i^{old} - \eta u_i$, where $\eta$ is step size and $u_i$ is $\nabla F$ wrt $w_i$. The big difference is that you are not attaining a global minimum over the coordinate $w_i$ in a direction where all other points are held fixed (like in CD), but rather slowly descending in the direction of a global minimum of $F$, one point at a time. It's a step-wise version of gradient descent but doesn't converge at any faster rate.


MySQL Get Results of Joins or Zeroes

Question: Quite a bit rusty on my queryfu... and I've been trying to get the needed results for a while now. Have tried searching first, but perhaps I'm not searching the right terms.
I have a people table and a hours table. I'm trying to get results like this:
name    mon     tue     wed     thu     fri     total
Bob     15      8.5     9.25    8.75    15      56.5
Joe     10.5    0       0       0       0       10.5

This is the query I currently have:
SELECT e.name,m.mon,t.tue,w.wed,th.thu,f.fri,sum(m.mon+t.tue+w.wed+th.thu+f.fri) as total
FROM people e
JOIN (SELECT uid, round(((TIME_TO_SEC(tout) - TIME_TO_SEC(tin))/60)/60,2) AS mon FROM vhours WHERE DAYNAME(wdate)='Monday' AND YEARWEEK(wdate)=YEARWEEK(NOW())) as m ON m.uid=e.id
JOIN (SELECT uid, round(((TIME_TO_SEC(tout) - TIME_TO_SEC(tin))/60)/60,2) AS tue FROM vhours WHERE DAYNAME(wdate)='Tuesday' AND YEARWEEK(wdate)=YEARWEEK(NOW())) as t ON t.uid=e.id
JOIN (SELECT uid, round(((TIME_TO_SEC(tout) - TIME_TO_SEC(tin))/60)/60,2) AS wed FROM vhours WHERE DAYNAME(wdate)='Wednesday' AND YEARWEEK(wdate)=YEARWEEK(NOW())) as w ON w.uid=e.id
JOIN (SELECT uid, round(((TIME_TO_SEC(tout) - TIME_TO_SEC(tin))/60)/60,2) AS thu FROM vhours WHERE DAYNAME(wdate)='Thursday' AND YEARWEEK(wdate)=YEARWEEK(NOW())) as th ON th.uid=e.id
JOIN (SELECT uid, round(((TIME_TO_SEC(tout) - TIME_TO_SEC(tin))/60)/60,2) AS fri FROM vhours WHERE DAYNAME(wdate)='Friday' AND YEARWEEK(wdate)=YEARWEEK(NOW())) as f ON f.uid=e.id

However, the query will only produce a result if person has hours for every day. If they don't have hours on every day, their hours don't show up at all.
Here is an SQL Fiddle: http://sqlfiddle.com/#!9/4ac3cd/1
Comment: Consider handling issues of data display in application code
Comment: Use `LEFT JOIN` instead of `JOIN`.
Comment: Don't use `sum()`. That's combining everything into one row, because you have no `GROUP BY`.
Comment: @Barmar - I have. No difference. http://sqlfiddle.com/#!9/4ac3cd/2
Comment: You don't actually say what result you want, how output is a function of input. You just leave it to us to guess from an example. Also: Try to make an example that is as representative as possible--that is sufficiently complex. Also: When you get a result you don't expect, find, present & justify the smallest wrong code--code that doesn't do what you expect--that is an extension of correct code--code that does what you expect. Don't just leave it to us to debug some big lump of code. [mre] PS Please put everything needed to ask your question in your post, not just at the fiddle.
Answer: You need only 1 join of the tables and conditional aggregation:
SELECT p.name,
  COALESCE(SUM(CASE WHEN DAYNAME(v.wdate)='Monday' THEN round(((TIME_TO_SEC(v.tout) - TIME_TO_SEC(v.tin))/60)/60,2) END), 0) mon,
  COALESCE(SUM(CASE WHEN DAYNAME(v.wdate)='Tuesday' THEN round(((TIME_TO_SEC(v.tout) - TIME_TO_SEC(v.tin))/60)/60,2) END), 0) tue,
  COALESCE(SUM(CASE WHEN DAYNAME(v.wdate)='Wednesday' THEN round(((TIME_TO_SEC(v.tout) - TIME_TO_SEC(v.tin))/60)/60,2) END), 0) wed,
  COALESCE(SUM(CASE WHEN DAYNAME(v.wdate)='Thursday' THEN round(((TIME_TO_SEC(v.tout) - TIME_TO_SEC(v.tin))/60)/60,2) END), 0) thu,
  COALESCE(SUM(CASE WHEN DAYNAME(v.wdate)='Friday' THEN round(((TIME_TO_SEC(v.tout) - TIME_TO_SEC(v.tin))/60)/60,2) END), 0) frid,
  COALESCE(SUM(round(((TIME_TO_SEC(v.tout) - TIME_TO_SEC(v.tin))/60)/60,2)), 0) Total
FROM people p LEFT JOIN vhours v
ON v.uid = p.id AND YEARWEEK(v.wdate)=YEARWEEK(NOW()) AND DAYOFWEEK(v.wdate) BETWEEN 2 AND 6
GROUP BY p.id, p.name

See the demo.
Or even better:
SELECT p.name,
  COALESCE(SUM(CASE WHEN v.day = 'Monday' THEN v.hours END), 0) mon,
  COALESCE(SUM(CASE WHEN v.day = 'Tuesday' THEN v.hours END), 0) tue,
  COALESCE(SUM(CASE WHEN v.day = 'Wednesday' THEN v.hours END), 0) wed,
  COALESCE(SUM(CASE WHEN v.day = 'Thursday' THEN v.hours END), 0) thu,
  COALESCE(SUM(CASE WHEN v.day = 'Friday' THEN v.hours END), 0) fri,
  COALESCE(SUM(v.hours), 0) Total
FROM people p LEFT JOIN (
  SELECT uid, DAYNAME(wdate) day,
    ROUND(TIMESTAMPDIFF(SECOND, tin, tout) / 3600, 2) hours
  FROM vhours
  WHERE YEARWEEK(wdate) = YEARWEEK(NOW()) AND DAYOFWEEK(wdate) BETWEEN 2 AND 6
) v
ON v.uid = p.id
GROUP BY p.id, p.name

See the demo.
Results:
| name | mon | tue | wed  | thu  | fri  | Total |
| ---- | --- | --- | ---- | ---- | ---- | ----- |
| Bob  | 15  | 8.5 | 9.25 | 8.75 | 15   | 56.5  |
| Joe  | 0   | 11  | 0    | 0    | 0    | 11    |
| Dan  | 0   | 0   | 0    | 10.5 | 0    | 10.5  |
| Carl | 0   | 0   | 0    | 0    | 0    | 0     |

Comment: Nice. This is a case of choice... better code or slightly better performance. First one is just a hair faster more consistently. Thanks again!
Comment: Fine if it works. Just check another option in my edited answer which simplifies the code.
Comment: Found that if person has 2 entries for same day, it does not reflect total on the day column, but does on the total column.
Comment: If there is a case of a person with 2 entries in a day replace MAX() with SUM(). See my edited answer.
Answer: Use LEFT JOIN instead of JOIN. This will return null values for all the non-matching rows, you can use IFNULL() to convert them to 0.
Don't use SUM(). That's for summing across rows, you don't need it when you're adding columns together. That's done just by using + with all the column names.
SELECT e.name,IFNULL(m.mon, 0) mon,IFNULL(t.tue, 0) tue, IFNULL(w.wed, 0) wed, IFNULL(th.thu, 0) thu, IFNULL(f.fri, 0) fri,
      IFNULL(m.mon, 0)+IFNULL(t.tue, 0)+IFNULL(w.wed, 0)+IFNULL(th.thu, 0)+IFNULL(f.fri, 0) as total
FROM people e
LEFT JOIN (SELECT uid, round(((TIME_TO_SEC(tout) - TIME_TO_SEC(tin))/60)/60,2) AS mon FROM vhours WHERE DAYNAME(wdate)='Monday' AND YEARWEEK(wdate)=YEARWEEK(NOW())) as m ON m.uid=e.id
LEFT JOIN (SELECT uid, round(((TIME_TO_SEC(tout) - TIME_TO_SEC(tin))/60)/60,2) AS tue FROM vhours WHERE DAYNAME(wdate)='Tuesday' AND YEARWEEK(wdate)=YEARWEEK(NOW())) as t ON t.uid=e.id
LEFT JOIN (SELECT uid, round(((TIME_TO_SEC(tout) - TIME_TO_SEC(tin))/60)/60,2) AS wed FROM vhours WHERE DAYNAME(wdate)='Wednesday' AND YEARWEEK(wdate)=YEARWEEK(NOW())) as w ON w.uid=e.id
LEFT JOIN (SELECT uid, round(((TIME_TO_SEC(tout) - TIME_TO_SEC(tin))/60)/60,2) AS thu FROM vhours WHERE DAYNAME(wdate)='Thursday' AND YEARWEEK(wdate)=YEARWEEK(NOW())) as th ON th.uid=e.id
LEFT JOIN (SELECT uid, round(((TIME_TO_SEC(tout) - TIME_TO_SEC(tin))/60)/60,2) AS fri FROM vhours WHERE DAYNAME(wdate)='Friday' AND YEARWEEK(wdate)=YEARWEEK(NOW())) as f ON f.uid=e.id

DEMO
Comment: Thank you for your working example. It just happened to be slower performing than the accepted answer.
Comment: Indeed, I was going to suggest that as an alternative, but he beat me to it.

MySQL Get Results of Joins or Zeroes


How do I implement two-way node references?

Question: The node-reference module (a component of CCK) provides a great way to create a reference one node from another. What is the best way to expose a two-way relationship between the two? Example below:
For instance, in a ticket tracking system with two tickets (nodes) A & B, you could create a node reference from ticket A --> B and mark B as a child. When viewing ticket A it would be trivial to display this information. However, I would also like to display this relationship when viewing ticket B and show ticket A as its parent.
This same requirement would also apply in non-hierarchical situations (tickets C & D) with a reference from C --> D, the relationship should be exposed on ticket D as well as on C.
Comment: You can also try the [Reverse Node Reference](http://drupal.org/project/reverse_node_reference) module.
Comment: Simply use Rules and this rule http://drupal.org/node/1836240
Comment: You can use the [Content Dependency](http://drupal.org/project/content_dependency) module. It provides you reverse references via tab, and it supports the following modules: *Node Reference* and *Entity Reference*.
Comment: Not really sure how the  Content Dependency module can be used to create mutual references?
Answer: There are many modules available, your milage may vary:
BackReference (Drupal 6 only)
NodeReferrer (Drupal 7 beta release)
Node Relationships (Drupal 6 only)
Corresponding node references (Drupal 7 stable release)
Corresponding entity references (Drupal 7 dev release)
Content Dependency (Drupal 7 stable release)
Comment: Corresponding node references works perfectly for me, and once CER is stable I will switch to that.
Answer: Entity Reference Module now works with Corresponding Entity References.  This is ideal for all nodes and non node entities.
Answer: For Drupal 6, the best option is probably the NodeReferrer module. For Drupal 7, Relation fits the bill but is not yet ready.
Comment: The Relation module is now ready, since July '12
Comment: I always use NodeReferrer module, for what it's worth
Comment: Yes, Relation seems to be quite a powerful option. Otherwise, CER is also a good lightweight option.
Answer: If you're using Drupal 7 / Views, you can build a 'reverse' relationship to get a listing of nodes that refer to a given node (or, perhaps, users that refer to a given node). Check out the patch in this issue: http://drupal.org/node/1043260
In my opinion, unless you need the explicit, pre-built reverse relationship stored in the database (this can be sometimes be helpful for performance reasons), using one of the other solutions is overkill. You can always look up a relationship in your own SQL query if you need to...
[Edit: Since originally writing this post, the patch in the issue above has been committed to References for D7, and should be the preferred way of backreferencing (works great when simply needing lists of nodes or users referencing a certain other node or user).]
[Edit 2: If you're using Entity Reference, it looks like the preferred solution is to use Corresponding Entity References, and there's also the less-widely-used Entity Reference Field Synchronization.]
Comment: References will still be sticking around until D7 is a distant memory... but if you're using ER, you can use [Corresponding Entity References](https://drupal.org/project/cer) to do the same thing as References provides out of the box.
Comment: It looks like References is going to become deprecated in favor of Entity Reference. Not sure where that leaves this answer.
Answer: In Drupal 7 (which you indicated) it seems the solution is to use the Entity Reference Module in combination with the (Entity)Reference Field Synchronization module which adds the necessary functionality to keep the relationships synched.
The same can be achieved with References Module with cnr module - this solution works (I'm using it on one Drupal 7 site currently), but is becoming obsolete/deprecated in favor of the first solution I gave.
All the other solution mentioned in the above answers are relevant only for Drupal 6 (except for Relation which has the potential to become a great module, but right now, doesn't really do much and has lots of issues).
Comment: Relation haven't had lots of issues even back in March. And Moshe Eshel http://drupal.org/user/168876 != Moshe Weitzman http://drupal.org/user/23 (look at that uid...) btw.
Comment: Voting up this answer because it's recent and Moshe is a senior member of the Drupal community. In the accepted answer, the only stable D7 module is CNR, and that's being depreciated in favour of CER (which has no stable release as of yet).
Comment: @chx I was surprised myself to see me featured as a senior member... I am trying to be a better contributor but I don't think I'll ever rise to the level of the Original Moshe.

Concerning the Relation module, I based that on feedback from someone in the know (I won't name names) - I haven't had the opportunity to really test it at the time, and relied on that opinion.

I'm currently working on a D7 project - I think I have the need for it so I'll give my updated opinion here when I'm done.
Answer: Alternatively, if you're working on a custom implementation and want a straight forward way of referencing back, you can hook into nodeapi, listen for the save operation and than programmatically update the referenced node.