Obtaining the node type being added with php

Question: Other than pulling the information from the url itself, is there a way to retrieve/obtain the node type that has been selected in the add content area. ie: www.mydomain.com/node/add/article... using PHP? I have been able to do this when updating/editing a node using menu_get_object() in a template file but not when adding a node.
Answer: If you are changing the form used to create a node, then you could use the following code.
function mymodule_form_node_form_alter(&$form, &$form_state) {
  $node = $form_state['node'];
  if (!isset($node->nid) || isset($node->is_new)) {
    // The node is being created.
    // Use $node->type to get the content type of the node.
  }
}

The reason is that node_add(), the page callback for the node creation form, contains the following code.
  $types = node_type_get_types();
  $node = (object) array(
    'uid' => $user->uid,
    'name' => (isset($user->name) ? $user->name : ''),
    'type' => $type,
    'language' => LANGUAGE_NONE,
  );
  drupal_set_title(t('Create @name', array('@name' => $types[$type]->name)), PASS_THROUGH);
  $output = drupal_get_form($type . '_node_form', $node);

This means that the form used when creating a node is the node edit form.
As alternative, if you need to change the node creating form when the content type is, for example, article, you can use the following code.
function mymodule_form_article_node_form_alter(&$form, &$form_state) {
  $node = $form_state['node'];
  if (!isset($node->nid) || isset($node->is_new)) {
    // The node is being created.
  }
}

As in this case the form is altered only when article is the content type of the node, you don't actually need to check the content type.
If you need that information in other cases, then you can only get it from the URL.
Comment: thanks kiamlaluno. I will have a look at node_add(). Where do I put the custom form function?
Comment: The code I am showing in my answer is not a custom form function, but an implementation of [hook_form_BASE_FORM_ID_alter()](http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_form_BASE_FORM_ID_alter/7), which can be placed in a theme, or a module. Its purpose is modifying the form. If you are not doing that, you should not implement that hook.
Comment: Thanks. I'll have a look at hook_form_BASE_FORM_ID_alter() link too.


auto fill of two adjacent cells in excel

Question: I want to use the auto fill but with two adjacent cells which contain different values as in the following
Image #1
I want to fill cells from E1 to H1 with the following values
Image #2
I don't want to use VBA. Just auto fill method
Answer: How much do you want to autofill? Kind of a roundabout way, but could you start auto filling just letters a, b, c.... as far as you need down col A, then numbers 1, 2, 3.... at bottom of your letter range. Then 1, 2, 3, down col B to end of letters then start at 1 again. Then sort by col B ascending, col A desending should give you the alternating sequence. Finally copy, paste special.... transpose to get across the way.
Comment: I don't understand "then start at 1 again", So Col B will contain 1,2,3, ... and what?
Comment: Col B = 1, 2, 3......, 1, 2, 3...... It is used purely for sorting col A in correct order.


Expressing polynomial equations as a set of linear equations

Question: Suppose the $4$-vector $c$ gives the coefficients of a cubic polynomial $p(x) = c_1 + c_2x+c_3c^2+c_4c^3$.
Express the conditions
$p(1) = p(2), p'(1) = p'(2)$
as a set of linear equations of the form $Ac=b$. Give the sizes of A and b, as well as their entries.
So far, what I've done was sub in the values and differentiate the polynomials and let it equal to each other after subbing their values.
I get
$c_1 + c_2 + c_3 + c_4 = c_1 + 2c_2 + 4c_3 + 8c_4$
then,
$0 = c_2 + 3c_3 + 7c_4$
as well as
$c_2+2c_3+3c_4 = c_2 + 4c_3+12c_4$
then,
$0 = 2c_3 + 9c_4$
I am a bit lost oh what to do now.
Answer: So you have
\begin{align}
0c_1 + 1c_2 + 3c_3 + 7c_4 &= 0\\
0c_1 + 0c_2 + 2c_3 + 9c_4 &= 0
\end{align}
Now write these two equations of four variables in matrix-vector form.  You already know that $c$ is $4\times 1$, that is, $4$ rows and $1$ column.  What should the sizes of $A$ and $b$ be?
Comment: ahhh, so it will be $A = [(0 &1 & 3 & 7 ) (0 & 2 & 0 & 9)]$ , A = 2x4 matrix, C is [x1,x2,x3,x4] and b = [0,0,0,0] ? so 4x1 as well ?
Comment: Close, but the second row of $A$ is wrong, use $c_j$ instead of $x_j$, and $b$ is the wrong shape.
Comment: Sorry, I mean 2nd row of a is 0,0,2,9. Is b not 4 rows of zeros ?
Comment: No, $b$ should have one row per equation.
Comment: My bad, b is 2x1


Executing function on focus in Chrome and Safari

Question: I am trying to build a fullsized background-slider that stops playing when the tab/window is inactive and continues when it's focused.
The problem is that Chrome and Safari both don't do anything on loading/refreshing the page - you have to click out- and then inside the window for them to start the animation.
Is there any way to avoid this?
This is my code so far:
<code>$(window).load( function(){
    var autopager;

    function startAutopager() {
        autopager = window.setInterval("slideSwitch()", 5000);
    }

    function stopAutopager() {
        window.clearInterval(autopager);
    }

    window.addEventListener('focus', startAutopager);
    window.addEventListener('blur', stopAutopager);

    slideSwitch();
    $("#sliderContent img").fullBg();
});
</code>
This starts the animation for both browsers but when I click outside the window again it won't stop:
<code>if(true == $.browser.safari || true == $.browser.chrome) {
    startAutopager();
}
</code>
Hope someone can help.
Cheers!
Comment: Is there a reason you're not using jQuery's methods for binding events? Also, I noticed that you're using setInterval which is strongly discouraged in the documentation: [link](http://api.jquery.com/animate/)  See "Additional Notes"
Comment: Thanks for answering! I didn't know about binding events, but I'll have a look at that.
SetInterval maybe discouraged but in my case it's no problem or is it?
Comment: It would seem to me that, knowing JS, focus/blur will not always be called properly. It's _possible_ that focus could get called twice in a row... causing your slideSwitch() function to fire twice: "queuing" more animations than you want it to. Perfect practice might be to use:

`if (autopager) window.clearInterval(autopager);`
`autopager = window.setInterval("slideSwitch()", 5000);`
Answer: Try this and let me know in a comment how it goes. :)
<code>$(function(){
  $("#sliderContent img").fullBg();

  var autopager;
  function startAutopager() {
    if (autopager) window.clearInterval(autopager);
    autopager = window.setInterval("slideSwitch()", 5000);
  }
  function stopAutopager() {
    window.clearInterval(autopager);
  }
  window.focus(startAutopager);
  window.blur(stopAutopager);
  startAutopager()
});
</code>
Comment: First of all thank you!
I replaced
   window.focus(startAutopager);
   window.blur(stopAutopager);
by
    window.addEventListener('focus', startAutopager);
    window.addEventListener('blur', stopAutopager);
and now it seems to work!


Ajax - Issue - Sending JavaScript Var to PHP script

Question: I have not been able to find a simple example of ajax with single variable, everything on here is made way too complicated for an AJAX beginner. I've watched about 4 different YouTube videos on the topic, but can't seem to get it right.
I have the src of an image in a variable like so with a JavaScript..

PHP script (hello.php):
<?php>
include_once "code.php";  //connecting to database
$s = $_POST['final'];
$temp = explode('/', $s);
$temp2 = explode('.', $temp[count($temp) - 1]); //this is getting the variable I want from the variable sent(which is actually a number)
$float = (int)$temp2; //changing the number (which is a string) to an int
mysql_query("UPDATE Variable SET `upVote` = `upVote`+1 WHERE id= (variable here)) "  //Making a row in my database w/ the id of the variable add 1 to the count
?>

Comment: How would the php page look? - Something like `$s = _POST` ?
Comment: Worked perfect, Thanks for your help!


Como enviar um arquivo de áudio do celular Android para o computador?

Question: Estou trabalhando num aplicativo em Android que faz  gravação da chamada telefônica num aparelho de celular.
Só que preciso enviar uma cópia do arquivo de áudio para o computador via TCP/IP.
Já tenho uma função que envia texto para o computador. Mas como enviar um arquivo de áudio ?
No computador já tenho um servidor feito em Delphi que se comunica com o celular e vice versa. Também sei como fazer, em Delphi, para receber o arquivo no computador. Só não sei fazer o código para enviar a partir do celular.
Alguém tem uma ideia?
Comment: Espero que ajude em algo este link [sending-file-over-tcp-between-android-and-pc](http://stackoverflow.com/questions/16508811/sending-file-over-tcp-between-android-and-pc)
Comment: Olá. Sim, é exatamente isto que procurava. Me pareceu bem simples, basta enviar bit-a-bit. Vou testar agora. Obrigado.
Answer:
De forma assíncrona ....

<code>    Socket socket  = null;
    BufferedInputStream bufferedInputStream = null;

    try {
        socket = new Socket("192.168.198.1", 8901);
        bufferedInputStream = new BufferedInputStream(socket.getInputStream());
        int counter = 0;
        String path = "/mnt/sdcard/ad.wav";
        FileOutputStream fileOutputStream = new FileOutputStream(new File(path));
        byte jj[] = new byte[1024];
        while ((counter = bufferedInputStream.read(jj, 0, 1024)) != -1) {
            fileOutputStream.write(jj, 0, counter);
        }
        fileOutputStream.close();
        socket.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
</code>
fonte
Apenas organizei o código sugerido nos comentários pelo checkmate.


How do 'meter' and 'rhythm' affect the choice of 'Polymeter' and 'Polyrhythm'?

Question: I use chevrons (⟨⟩) to denote the concept behind the word.

[ Source :] Meter is the rhythmic structure of the music. For example, a piece of music could be in 4/4 meter, which is a strong-weak-medium-weak pattern of beats. It could be in a compound meter, where the notes are subdivided into three instead of two. It's a general structure that the music fits in. Not all music has this!
Rhythm is the actual timing of the music (relative to the tempo, I guess). For example, a rhythm for one measure of 4/4 might be a half note followed by two eighth notes and a quarter note. You can have many different rhythms within the same meter! This measure may just have a whole note as its rhythm, while that other one might have eight eighth notes.

Why was 'meter' chosen as the root in ⟨polymeter⟩ and 'rhythm' in ⟨polyrhythm⟩? In other words, why wasn't ⟨polymeter⟩ called polyrhythm instead, and ⟨polyrhythm⟩ polymeter? I understand the choice of 'poly-'.
Comment: Two different words were chosen. Does it really matter which is which?
Answer: I worry that your quoted source isn't the best; "meter is the rhythmic structure of the music" is not a very good definition. Here, for instance, is a better and more concise definition:

Meter refers to the grouping of accented and unaccented beats into recurring patterns. (Steven Laitz's The Complete Musician)

(Other books/authors, like Lerdahl/Jackendoff in A Generative Theory of Tonal Music, Krebs in Fantasy Pieces, and Rothstein in Phrase Rhythm in Tonal Music, have similar (but more long-winded) definitions.)
Thus, when we talk about polymeter, we're talking about multiple grouping structures. The SE answer you link displays this nicely in its example of polymeter, because there is a 5-grouped structure playing alongside a 4-grouped one, and the downbeats of the grouping structures (that is, the accents) are not aligned.
Meanwhile, the accents in the polyrhythmic example are aligned; it's just the rhythm that takes place within these accents that differs.
When viewed in this way, we see that the word roots were chosen correctly.


Error: The method 'NavigationBody' isn't defined for the class '_HomePageState'

Question: I am creating desktop app using fluent_ui. I added package to pubspec.yaml and it was doing great before i created NavigationBody class to navigate through pages. Maybe i was using some decrepit version of the package, but it returns error like:

Error: The method 'NavigationBody' isn't defined for the class
'_HomePageState'.

'_HomePageState' is from 'package:specialityapp/presentation/ui/mainpage.dart'
('lib/presentation/ui/mainpage.dart'). Try correcting the name to the
name of an existing method, or defining a method named
'NavigationBody'.
content: NavigationBody(

Seems like this class doesn't exist anymore, since when i hover it it suggests me to create class myself
class _HomePageState extends State<HomePage> {
  int _currentpage = 0;

  @override
  Widget build(BuildContext context) {
    return NavigationView(
      appBar: NavigationAppBar(
          title: Container(
            color: bluecol,
            margin: const EdgeInsets.only(left: 20),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  'Choose your speciality',
                  style: TextStyle(fontSize: 32, color: whitecol),
                ),
                const SizedBox(width: 600),
                Flexible(
                    child: TextField(
                      decoration: InputDecoration(
                          border: OutlineInputBorder(
                              borderSide: BorderSide(color: whitecol)),
                          suffixIcon: Icon(
                            Icons.search_outlined,
                            size: 30,
                            color: whitecol,
                          )),
                    )),
                const SizedBox(width: 600),
                Icon(
                  Icons.account_circle,
                  color: whitecol,
                )
              ],
            ),
          ),
          backgroundColor: bluecol,
          automaticallyImplyLeading: true),
      pane: NavigationPane(
          size: const NavigationPaneSize(openMinWidth: 250, openMaxWidth: 320),
          onChanged: (index) => setState(() {
            _currentpage = index;
          }),
          selected: _currentpage,
          items: <NavigationPaneItem>[
            PaneItem(
                icon: const Icon(
                  FluentIcons.home,
                  size: 20,
                ),
                title: const Text('Catalog'),
                body: const Text('')),
            PaneItem(
                icon: const Icon(
                  FluentIcons.home,
                  size: 20,
                ),
                title: const Text('Rated'),
                body: const Text('')),
          ]),
      content: NavigationBody(         // error intensifies here
        index: _currentpage,
        children: [

        ]
      ),
    );
  }
}

Answer: NavigationBody no longer exists, use paneBodyBuilder.
class _HomePageState extends State<HomePage> {
  int _currentpage = 0;

  @override
  Widget build(BuildContext context) {
    return NavigationView(
      appBar: NavigationAppBar(
          title: Container(
            color: bluecol,
            margin: const EdgeInsets.only(left: 20),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  'Choose your speciality',
                  style: TextStyle(fontSize: 32, color: whitecol),
                ),
                const SizedBox(width: 600),
                Flexible(
                    child: TextField(
                      decoration: InputDecoration(
                          border: OutlineInputBorder(
                              borderSide: BorderSide(color: whitecol)),
                          suffixIcon: Icon(
                            Icons.search_outlined,
                            size: 30,
                            color: whitecol,
                          )),
                    )),
                const SizedBox(width: 600),
                Icon(
                  Icons.account_circle,
                  color: whitecol,
                )
              ],
            ),
          ),
          backgroundColor: bluecol,
          automaticallyImplyLeading: true),
      pane: NavigationPane(
          size: const NavigationPaneSize(openMinWidth: 250, openMaxWidth: 320),
          onChanged: (index) => setState(() {
            _currentpage = index;
          }),
          selected: _currentpage,
          items: <NavigationPaneItem>[
            PaneItem(
                icon: const Icon(
                  FluentIcons.home,
                  size: 20,
                ),
                title: const Text('Catalog'),
                body: const Text('')),
            PaneItem(
                icon: const Icon(
                  FluentIcons.home,
                  size: 20,
                ),
                title: const Text('Rated'),
                body: const Text('')),
          ]),
      paneBodyBuilder: (item, body) => ListView(
          padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 20),
          children: const [
            Center(child: Text('op 1')),
            Center(child: Text('op 2')),
          ]
       ),
    );
  }
}

The listview is an example


Revert DbContext.Savechanges in case a second DbContext.Savechanges fail

Question: I have the following code, which stores information in two different tables in the same method
public static async Task<Response> AddStockTransaction(StockTransactionsHeader header, List<StockTransactionsDetails> details)
{
    using (DataContext dbContext = new DataContext())
    {
        try
        {
            dbContext.StockTransactionsHeader.Add(header);
            await  dbContext.SaveChangesAsync();

            int hearderID = header.TransactionHeaderID;

            foreach (var item in details)
            {
                item.TransactionHeaderID = hearderID;
            }

            dbContext.StockTransactionsDetails.AddRange(details);
            await dbContext.SaveChangesAsync();

            return new Response
            {
                IsSuccess = true
            };
        }
        catch (Exception ex)
        {
            return new Response
            {
                IsSuccess = false,
                Message = ex.Message
            };
        }
    }
}

How can I do, in case there is an exception in the second SaveChanges () to revert the first one?
Answer: Once SaveChanges has been called, your datat is stored on your database. You should not call SaveChanges more than once in a call, unless you are willingly to persist the intermediate steps.
You can use a transaction scope to create managed transactions :
using (TransactionScope scope = CreateTransactionScope())
{
    DoSomthing(context);
    scope.Complete();
}

however, if the failure of the second part involves rolling back the first one, this means that both parts belong to the same transaction, therefore simply omitting the first SaveChanges would turn your code into a single transaction.
Answer: From my another awnser: You could use DbTransaction class.
private void TestTransaction()
{
    var context = new MyContext(connectionString);

    using (var transaction = context.Database.BeginTransaction())
    {
        try
        {
            // do your stuff

            // commit changes
            transaction.Commit();
        }
        catch
        {
            // 'undo' all changes
            transaction.Rollback();
        }
    }
}


how to control the index displayed on the tableview

Question: I am able to show a index on the right side similar to songs view on the ipod. During searching the index bar gets minimized automatically. And when i go back to my actual table view the index size is small and it displays only few alphabets. How to stop the resizing of this ?
Answer: you have to place proper delegate methods of UITableView in your viewController.m file.
for example I have placed following code.
Please read comments carefully.
#pragma mark -
#pragma mark Table view data source
// an array count which has values for index - like A,B,C etc.
// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    //return [NSArray arrayWithArray:keys];
    return [keys count];
}
// an array which has values for index - like A,B,C etc.
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    return keys;
}
// return how many number of rows are required for each section.
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [[dMain valueForKey:[keys objectAtIndex:section]] count];
}

// return title of section
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    return [keys objectAtIndex:section];
}

// create each row for different sections
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    NSString *CellIdentifier = [NSString stringWithFormat:@"%i %i",indexPath.row,indexPath.section];

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        cell.textLabel.font=[UIFont fontWithName:@"Helvetica" size:12];
        //cell.textLabel.text=[[[objects objectAtIndex:indexPath.row] valueForKey:@"marketname"] stringByReplacingOccurrencesOfString:@"_and_" withString:@"&"];

        cell.textLabel.text=[[[[dMain valueForKey:[keys objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row] valueForKey:@"marketname"] stringByReplacingOccurrencesOfString:@"_and_" withString:@"&"];
    }

    return cell;
}


If $y=x^{(e^x)}$, then what is an expression for dy/dx?

Question: If $y=x^{(e^x)}$, then which of the following is an expression for $\frac{dy}{dx}$?
Possible answers could be:
A: $e^x \ln(x)+ e^x/x$
B: $e^x x^{e^x}(\ln(x)+1/x)$
C: $x^{e^x}(e^x \ln(x) - 1/x)$
For my answer I got C but I'm not sure if that's right. Is there anyone who knows the correct answer?
Comment: https://www.wolframalpha.com/input/?i=differentiate+x%5E(e%5Ex)
Comment: It is correct, but next time show your working also, because if it were wrong, then we can point out the mistake as well.
Comment: It is not correct. The answer is B. See my previous comment.
Answer: $$y = x^{e^x}$$
$$ y = e^{\log(x)e^x}$$
The chain rule
$$\dfrac{dy}{dx} = \dfrac{dy}{du} \dfrac{du}{dx} $$
Let $u = \log(x)e^x$
$$ y = e^u$$
$$ \dfrac{dy}{dx} = e^u \dfrac{du}{dx}$$
$$\dfrac{dy}{dx} = e^u \dfrac{d \,\log(x)e^x}{dx} $$
$$\dfrac{dy}{dx} = x^{e^x} \left( \frac{e^x}{x} + e^x\log(x) \right)$$
$$\dfrac{dy}{dx} = x^{e^x} e^x \left( \frac1{x} + \log(x) \right)$$
Answer is B.
Answer: With implicit differentiation ($x > 0$):
$$
y(x) = x^{e^x} \quad \Longrightarrow \quad \log y(x) = e^x \log x.
$$
Then,
$$
\frac{d}{dx} \Big(\log y(x)\Big) = \frac{y'(x)}{y(x)} = \frac{d}{d x}\Big( e^x \log x\Big) = e^x\left(\log x + \frac{1}{x}\right).
$$
Hence
$$
y'(x) = y(x)e^x\left(\log x + \frac{1}{x}\right) = x^{e^x}e^x\left(\log x + \frac{1}{x}\right).
$$


How to alter default redirect after Entityform delete

Question: By default, entityform delete form action is hardcoded in file entityform.admin.inc to the following value:
$form_state['redirect'] = "admin/structure/entityform_types/manage/{$entityform->type}/submissions";

As this function is a submit callback, it is executed AFTER invoking hook form alter, so this approach won't work.
Answer: The solution is to add another submit callback. This one will run after the one Entityform uses for the redirect. This way, we will be able to overwrite that hardcoded value:
/**
 * Implementation of hook_form_FORM_ID_alter()
 * Makes sure it redirects to results on Delete.
 */
function MYMODULE_form_entityform_delete_form_alter(&$form, &$form_state, $form_id) {
  $form['#submit'][] = '_MYMODULE_form_delete_redirect';
}

function _MYMODULE_form_delete_redirect($form, &$form_state) {
  $form_state['redirect'] = 'MY_REDIRECT';
}


403 Forbidden Error on Azure Linux virtual machine

Question: I am trying to access the freshly created virtual machine on azure via winscp and putty, through putty I am able to access the VM but via winscp I get following error,
Proxy Error: 403 Forbidden.
I have deployed Ubuntu 14.04 VM on Azure Cloud and whenever I try to access it behind a proxy server I got above mentioned error.
Comment: So, you're behind a proxy trying to access it? Ask the proxy administrators as they probably block outgoing SSH on your network.
Comment: If they were blocking it I wouldn't be able to access the VM on putty on same ip and port. But the thing is I am only getting this on WinScp
Answer: I finally figured the answer, the Squid proxy server was corrupted and that's why it was giving me error like I was able to send traffic on to 22 and 21 port at one moment and couldn't do it on other, I updated the file and edited the conf file to add the rule. Worked for me.


Babel plugins - Member access with index

Question: I am writing a babel plugin. I came across a place where I need to use index operator. This is code I want to get a[Symbol.something](b), however, I can't seem to find a way to do it. I have tried doing something like this:
types.callExpression(
    types.memberExpression(types.Identifier('a'),
        types.memberExpression(types.Identifier('Symbol'), types.Identifier('something'))
    ),
    [types.Identifier('b')]
)

However, it throws error TypeError: Property property of MemberExpression expected node to be of a type ["Identifier","PrivateName"] but instead g
ot "MemberExpression". I googled my problem, but I can't seem to find a way to do it.
Answer: You should use computed parameter of MemberExpression.
For example,
types.MemberExpression( types.Identifier('foo'), types.Identifier('bar') );

will generate foo.bar, whereas
types.MemberExpression( types.Identifier('foo'), types.Identifier('bar'), true );

will generate foo[bar].
Thus, your code should be:
types.CallExpression(
  types.MemberExpression(
    types.Identifier('a'),
    types.MemberExpression(types.Identifier('Symbol'), types.Identifier('something')),
    true
  ),
  [types.Identifier('b')]
);

This will generate a[Symbol.something](b).


What is Best Practice for persisting configuration settings in EAR files?

Question: My application is deployed as an EAR file.
The application has traditionally required that some post installation configuration changes be made.
This was easy with the Oracle 10G OAS as the EAR was exploded into a directory thus allowing easy access to configuration files.
With 11G, the EAR is not exploded resulting in additional documentation on exploding, modifying, and recombining the EAR.
It seems to me that this must be a relatively common problem with a solution, perhaps a standard one through J2EE, that I have simply not come across or recognized it as the solution I was looking for.
Some alternatives include:
1) Providing a utility that will modify the EAR file prior to deployment.
2) Store all configuration settings in a separate location.
3) Store all configuration settings in a database; access the database via a container provide connection exposed through JNDI.
But is there an established best practice?
Lacking that, what approach has worked for you?
Thanks
Curtis
Answer: I have done some significant work around this subject with one of my clients. In a nutshell (which I believe should help you):
If you were to use configuration files, placing configuration files inside the EAR (through exploding / re-packaging) has the drawback of having your EAR files non-portable between different environments (for example, QA environments vs. Production environments). Over time, this increases overhead and there's always the odd chance of confusion between environments. Such approach is only viable for configuration items that are environment agnostic - that is, remain the same across all SDLC environments (QA, test etc).
Alternatively, you could place these files in a separate directory and add that directory to your server's classpath. This is done differently in each application server; in WebSphere, this is done using the "shared libraries" facility.
An approach that worked for us better, over the long run, is to use what J2EE technology actually designated to use for such tasks - using resource environment entries, accessible via standard JNDI mechanism under the java:comp/env namespace.
I would prefer the resource-environment entries' approach over anything else... after trying out pretty much any possible solution.
Comment: Isaac, thanks for the responce. I'll look into using the environment entries.  (Sorry, not enough rep to give it a thumbs up, I hope someone else will on my behalf)
Answer: As far as I know, this is still one of the pain point, and your analysis is mostly correct.
Here is a more elaborated answer I wrote long time ago on java.net forum to a similar question, but we were using Glassfish.
I haven't heard of any fundamental changes in the spec when it comes to this issue, but there might be some Oracle AS specific thingy that helps.
Comment: Thanks for confirming my fears. :)
Comment: (sorry, not enough reputation points yet to give your answer a nod)


How to create a new tab with default values?

Question: In new tab create method I see that all Parameters for createProperties(object) are marked "optional". But when I try
//if there is no storage create a new tab

var firstRun = (localStorage['firstRun'] == 'true') ;

if (!firstRun)
{
    chrome.tabs.create()
    {
        console.log("new tab is created")
    }
}

I get Uncaught Error: Parameter 1 is required.. This answer to a similar question also appears to say that parameters are optional.
What am I missing? Thanks.
Answer: Just pass an empty object:
chrome.tabs.create({});

The object is not optional, the values in it are.


How to find the Laplace inversion of $\frac{p}{p^4+4}$?

Question: How to calculate $$\mathscr{L}^{-1}\left\{\frac{p}{p^4+4}\right\}$$ where $\mathscr{L}$ is the Laplace transform operator? I thing need to apply some partial fraction first but am unable to work it out. Any idea or further help will be very good to me.
Comment: $$\frac{p}{p^4+4}=\frac14\left(\frac1{p^2-2p+2}-\frac1{p^2+2p+2}\right)$$
Comment: Hi ! The $p$ in your numerator is different that your $P$ in the denominator. Is this a misspell ?
Comment: @Rebellos I think yes, so I've edited it.
Answer: $p^4+4$ has 4 roots: $p=\pm 1 \pm i$, so it can be written as: $(p-1-i)(p-1+i)(p+1-i)(p+1+i)=(p^2-2p+2)(p+2p+2)$, so:
$$\frac{p}{p^4+4}=\frac{p}{(p^2-2p+2)(p+2p+2)}=\frac{Ap+B}{p^2-2p+2}+\frac{Cp+D}{p^2+2p+2}$$
The solution is $A=0, B=\frac{1}{4}, C=0, D=-\frac{1}{4}$ (I can show more detail of the computation if you need it), so:
$$\frac{p}{p^4+4}=\frac{\frac{1}{4}}{p^2-2p+2}-\frac{\frac{1}{4}}{p^2+2p+2}=\frac{\frac{1}{4}}{(p-1)^2+1}-\frac{\frac{1}{4}}{(p+1)^2+1}$$
We know that $\mathscr{L}\{e^{ax}f(x)\}=F(p-a), \mathscr{L}\{\sin{(ax)}\}=\frac{a}{p^2+a^2}, \mathscr{L}\{\cos{(ax)}\}=\frac{p}{p^2+a^2}$, so:
$$\mathscr{L}^{-1}\left\{\frac{\frac{1}{4}}{(p-1)^2+1} \right\}=\frac{1}{4}e^{x}\sin{x}$$
$$\mathscr{L}^{-1}\left\{\frac{\frac{1}{4}}{(p+1)^2+1} \right\}=\frac{1}{4}e^{-x}\sin{x}$$
Finaly:
$$\mathscr{L}^{-1}\left\{\frac{p}{p^4+4}\right\}=\frac{1}{4}e^{x}\sin{x}-\frac{1}{4}e^{-x}\sin{x}$$
$$\mathscr{L}^{-1}\left\{\frac{p}{p^4+4}\right\}=\frac{1}{4}\sin{x}(e^{x}-e^{-x})$$
$$\mathscr{L}^{-1}\left\{\frac{p}{p^4+4}\right\}=\frac{1}{4}\sin{x}(2\sinh{x})$$
$$\mathscr{L}^{-1}\left\{\frac{p}{p^4+4}\right\}=\frac{1}{2}\sin{x}\sinh{x}$$
Comment: Thanks @Botond. The in between calculations are verified by me.


Como recuperar lista de amigos do Facebook

Question: Pessoal estou precisando retornar a lista de amigos do facebook usando a API do facebook 4 for PHP. Consigo logar, pegar as informações da conta mas a lista so vem o seguinte resultado para mim:
Array
(
[data] => Array
    (
    )

[summary] => stdClass Object
    (
        [total_count] => 124
    )

)

Estou usando o seguinte comando:
$friends = (new FacebookRequest($session, 'GET', '/me/friends'))
->execute()
->getGraphObject()
->asArray();
echo '
' . print_r( $friends, 1 ) . '
';

E estou com as seguintes permissões:
$permissions = array(
'email',
'public_profile',
'user_friends'
 );
 echo 'getLoginUrl($permissions) . '">Login';

Como devo fazer para retornar os amigos?
Comment: Seu APP já passou pelo Review do Facebook? Pois, segundo a [documentação](https://developers.facebook.com/docs/facebook-login/permissions/v2.2?locale=pt_BR#review), quando você requisita mais de uma dessas permissões (public_profile, email, user_friends), o APP precisa ser revisado pelo Facebook.
Answer: Primeiro vá nas suas configurações e veja se Taggable-Friends está habilitado para você (https://www.webniraj.com/wp-content/uploads/2014/06/Taggable-Friends.png).
Isto recuperará a lista de Taggable-Friends:
<?php

// requer Facebook PHP SDK 4.0.x ou +

//

// pegar taggable friends
$taggable = (new FacebookRequest( $session, 'GET', '/me/taggable_friends' ))->execute()->getGraphObject()->asArray();

// output response
echo '
' . print_r( $taggable, 1 ) . '
';

// output total friends
echo count( $taggable['data'] );

Fonte: https://www.webniraj.com/2014/06/12/facebook-api-getting-friends-using-graph-api-2-0-and-php-sdk-4-0-x/
Comment: É isto mesmo. Fiz assim e deu certinho.
Obrigado
Comment: Precisando pode perguntar!


Solving for $\cos a$

Question: Given that
$\sin(\frac{a}{2})=\frac{1}{4}$ and $405^{\circ} < \frac{a}{2} < 450^{\circ}$ find  $\cos a$
I tried the following
$\sin \frac{a}{2} = \sqrt{\frac{1-\cos a}{2}} \Longrightarrow \frac{1}{4}=\sqrt{\frac{1-\cos a}{2}} \Longrightarrow \frac{1}{16} = \frac{1 - \cos a}{2} \Longrightarrow \cos a = \frac {7}{8}$
however, the answer key says the answer is supposed to be $-\frac{\sqrt{8+2\sqrt{15}}}{4}$
How is that answer achieved?
Answer: We have: $0 < \cos(\frac{a}{2}) = \sqrt{1-\sin^2(\frac{a}{2})}=...$, and $\cos a = 2\cos^2(\frac{a}{2}) - 1 = .....$
note that you need not have $405^{\circ} < \dfrac{a}{2} < 450^{\circ}$ to find $\cos a$, and you might just apply immediately the formula $\cos a =  1- 2\sin^2 (\frac{a}{2}) = 1-2\left(\frac{1}{4}\right)^2 = 1 - \frac{1}{8} = \dfrac{7}{8}$
Comment: Are you saying that I have the correct answer?
Comment: Certainly. Your answer is right....

Solving for $\cos a$


Setting environmental variables with !Ref in AWS SAM?

Question: I'm using SAM CLI v0.8.1. I'm trying to set environmental variable MY_TABLE_VAR as name of the table in my resources (MyTableResource). However, while running my app locally, the MY_TABLE_VAR is undefined. Can you tell me what's wrong in my template and how can I set it properly? Following is my SAM template:
Globals:
    Function:
        Timeout: 30
        Runtime: nodejs8.10
        Environment:
            Variables:
                MY_TABLE_VAR: !Ref MyTableResource
Resources:
    MyTableResource:
        Type: AWS::Serverless::SimpleTable
        Properties:
          TableName: table1
          PrimaryKey:
            Name: id
            Type: String
          ProvisionedThroughput:
            ReadCapacityUnits: 5
            WriteCapacityUnits: 5

Answer: From my understanding, the Globals section cannot reference resources in the Resources section (the dependency is in the other direction, since whatever is added to the Globals section is added to all Serverless Functions and APIs in the Resourcessection). To work around this, I suggest that you use either Mappings or Parameters, e.g.
Parameters:
    TableName:
        Type: String
        Default: table1

Globals:
    Function:
        Timeout: 30
        Runtime: nodejs8.10
        Environment:
            Variables:
                MY_TABLE_VAR: !Ref TableName

Resources:
    MyTableResource:
        Type: AWS::Serverless::SimpleTable
        Properties:
          TableName: !Ref TableName
          # more table config....

Comment: This is incorrect, the `Globals` CAN reference resources in the `Resources` section, but (probably) not all types. I managed to declare a `AWS::Serverless::LayerVersion` resource object and set the `Layers` property in the `Globals: Function` scope, despite the layer being created inside the `Resources` section.
Answer: It's been a while since this was asked, but I just found this question with a Google search. I wanted to use the name of a function as a parameter to all other functions in my template. If you override the environment variable on the source function, the circular dependency goes away:
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31

Globals:
  Function:
    Environment:
      Variables:
        LOG_LEVEL: WARNING
        SPECIAL_FUNCTION: !GetAtt SpecialFunction.Arn

Resources:
  SpecialFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: functions/special_function
      Environment:
        Variables:
          SPECIAL_FUNCTION: Overriding global value to avoid circular dependency
      Handler: special_function.lambda_handler
      Runtime: python3.9
  OtherFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: functions/other_function
      Handler: other_function.lambda_handler
      Runtime: python3.9

OtherFunction will have the ARN of SpecialFunction in the SPECIAL_FUNCTION environment variable.


Vagrant: Sync folder with boot2docker box on Windows

Question: I try to synchronize a folder with the boot2docker Vagrant box (on Windows 8.1):
Vagrantfile
# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant.configure(2) do |config|
  config.vm.hostname = "docker-host"
  config.vm.box = "hashicorp/boot2docker"
  config.vm.synced_folder "./src", "/sync/src"
end

I tried several ways to synchronize the folder:
If I do not define a type (how to sync), Vagrant uses SMB. So it's like I have written:
config.vm.synced_folder "./src", "/sync/src", type: "smb"

With this configuration mounting fails (I enter the credentials of my Windows account I'm logged in):
$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Checking if box 'hashicorp/boot2docker' is up to date...
==> default: Clearing any previously set forwarded ports...
==> default: Preparing SMB shared folders...
    default: You will be asked for the username and password to use for the SMB
    default: folders shortly. Please use the proper username/password of your
    default: Windows account.
    default:
    default: Username: My Username
    default: Password (will be hidden):
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
==> default: Forwarding ports...
    default: 2375 (guest) => 2375 (host) (adapter 1)
    default: 22 (guest) => 2222 (host) (adapter 1)
==> default: Running 'pre-boot' VM customizations...
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2222
    default: SSH username: docker
    default: SSH auth method: password
    default: Warning: Remote connection disconnect. Retrying...
    default: Warning: Remote connection disconnect. Retrying...
==> default: Machine booted and ready!
GuestAdditions versions on your host (5.0.20) and guest (4.3.28 r100309) do not match.
The guest's platform ("tinycore") is currently not supported, will try generic Linux method...
Copy iso file C:\Program Files/Oracle/VirtualBox/VBoxGuestAdditions.iso into the box /tmp/VBoxGuestAdditions.iso
Installing Virtualbox Guest Additions 5.0.20 - guest version is 4.3.28 r100309
mkdir: can't create directory '/tmp/selfgz99220132': No such file or directory
Cannot create target directory /tmp/selfgz99220132
You should try option --target OtherDirectory
An error occurred during installation of VirtualBox Guest Additions 5.0.20. Some functionality may not work as intended.
In most cases it is OK that the "Window System drivers" installation failed.
==> default: Setting hostname...
==> default: Mounting SMB shared folders...
    default: C:/my-project/src => /sync/src
Failed to mount folders in Linux guest. This is usually because
the "vboxsf" file system is not available. Please verify that
the guest additions are properly installed in the guest and
can work properly. The command attempted was:

mount -t cifs -o uid=`id -u docker`,gid=`getent group docker | cut -d: -f3`,sec=ntlm,credentials=/etc/smb_creds_d1d75b0a1810a196107486250f8d20f4 //169.254.152.12/d1d75b0a1810a196107486250f8d20f4 /sync/src
mount -t cifs -o uid=`id -u docker`,gid=`id -g docker`,sec=ntlm,credentials=/etc/smb_creds_d1d75b0a1810a196107486250f8d20f4 //169.254.152.12/d1d75b0a1810a196107486250f8d20f4 /sync/src

The error output from the last command was:

mount: mounting //169.254.152.12/d1d75b0a1810a196107486250f8d20f4 on /sync/src failed: Invalid argument

==> default: The previous process exited with exit code 1.

If I use
config.vm.synced_folder "./src", "/sync/src", type: "nfs"

instead, Vagrant still uses SMB (same output as before). If I use
config.vm.synced_folder "./src", "/sync/src", type: "virtualbox"

I get
$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Checking if box 'hashicorp/boot2docker' is up to date...
==> default: Clearing any previously set forwarded ports...
The synced folder type 'virtualbox' is reporting as unusable for
your current setup. Please verify you have all the proper
prerequisites for using this shared folder type and try again.

If I use
config.vm.synced_folder "./src", "/sync/src", type: "rsync"

with vagrant-gatling-rsync plugin installed
vagrant plugin install vagrant-gatling-rsync

and run in Cygwin (Cmd has no rsync), I get this:
$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Checking if box 'hashicorp/boot2docker' is up to date...
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
==> default: Forwarding ports...
    default: 2375 (guest) => 2375 (host) (adapter 1)
    default: 22 (guest) => 2222 (host) (adapter 1)
==> default: Running 'pre-boot' VM customizations...
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2222
    default: SSH username: docker
    default: SSH auth method: password
    default: Warning: Remote connection disconnect. Retrying...
    default: Warning: Remote connection disconnect. Retrying...
==> default: Machine booted and ready!
GuestAdditions versions on your host (5.0.20) and guest (4.3.28 r100309) do not match.
The guest's platform ("tinycore") is currently not supported, will try generic Linux method...
Copy iso file C:\Program Files/Oracle/VirtualBox/VBoxGuestAdditions.iso into the box /tmp/VBoxGuestAdditions.iso
Installing Virtualbox Guest Additions 5.0.20 - guest version is 4.3.28 r100309
mkdir: can't create directory '/tmp/selfgz95812741': No such file or directory
Cannot create target directory /tmp/selfgz95812741
You should try option --target OtherDirectory
An error occurred during installation of VirtualBox Guest Additions 5.0.20. Some functionality may not work as intended.
In most cases it is OK that the "Window System drivers" installation failed.
==> default: Setting hostname...
==> default: Installing rsync to the VM...
==> default: The machine you're rsyncing folders to is configured to use
==> default: password-based authentication. Vagrant can't script rsync to automatically
==> default: enter this password, so you'll likely be prompted for a password
==> default: shortly.
==> default:
==> default: If you don't want to have to do this, please enable automatic
==> default: key insertion using `config.ssh.insert_key`.
==> default: Rsyncing folder: /cygdrive/c/my-project/src/ => /sync/src
There was an error when attempting to rsync a synced folder.
Please inspect the error message below for more info.

Host path: /cygdrive/c/my-project/src/
Guest path: /sync/src
Command: rsync --verbose --archive --delete -z --copy-links --chmod=ugo=rwX --no-perms --no-owner --no-group --rsync-path sudo rsync -e ssh -p 2222 -o ControlMaster=auto -o ControlPath=C:/cygwin64/tmp/ssh.640 -o ControlPersist=10m -o StrictHostKeyChecking=no -o IdentitiesOnly=true -o UserKnownHostsFile=/dev/null --exclude .vagrant/ /cygdrive/c/my-project/src/ email@example.com:/sync/src
Error: Warning: Permanently added '[127.0.0.1]:2222' (ECDSA) to the list of known hosts.
Permission denied, please try again.
Permission denied, please try again.
Permission denied (publickey,password,keyboard-interactive).
rsync: connection unexpectedly closed (0 bytes received so far) [sender]
rsync error: error in rsync protocol data stream (code 12) at io.c(226) [sender=3.1.1]

==> default: The previous process exited with exit code 1.

Besides that, I tried another boot2docker box
# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant.configure(2) do |config|
  config.vm.hostname = "docker-host"
  config.vm.box = "dduportal/boot2docker"
  config.vm.synced_folder "./src", "/sync/src"
end

which results in
$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Checking if box 'dduportal/boot2docker' is up to date...
==> default: Clearing any previously set forwarded ports...
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
    default: Adapter 2: hostonly
==> default: Forwarding ports...
    default: 2375 (guest) => 2375 (host) (adapter 1)
    default: 2376 (guest) => 2376 (host) (adapter 1)
    default: 22 (guest) => 2222 (host) (adapter 1)
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2222
    default: SSH username: docker
    default: SSH auth method: private key
    default: Warning: Remote connection disconnect. Retrying...
    default: Warning: Remote connection disconnect. Retrying...
    default: Warning: Authentication failure. Retrying...
    default: Warning: Authentication failure. Retrying...
    default: Warning: Authentication failure. Retrying...
    default: Warning: Authentication failure. Retrying...
    default: Warning: Authentication failure. Retrying...

==> default: Waiting for cleanup before exiting...
Vagrant exited after cleanup due to external interrupt.

How do I get folder synchonization to run with Vagrant and boot2docker?
Comment: rsync is the only method to work on the default b2d box (on windows), but since it's auth is password based, rsync fails to authenticate. it's possible to manually sync folders, have been looking for a workaround for some time though.
Comment: Hasn't the Docker Toolbox replaced the need for boot2docker? Or at least hidden it's usage behind docker machine. I'm not sure I see why you need Vagrant
Answer: My working setup with dduportal/boot2docker on windows looks like the following:
# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant.configure(2) do |config|
  config.vm.hostname = "docker-host"
  config.vm.box = "dduportal/boot2docker"
  config.vm.provision "docker"
  config.vm.synced_folder ".", "/vagrant", type: "virtualbox"
end

Comment: Declaring the type of the synced folder as `virtualbox` does not help. I still get `Authentication failure`.


Using SFML for Codeblocks C++ appears ERROR library SFML

Question: I have a problem when I tried to install SFML on Codeblocks. Well, first I install codeblocks: codeblocks-20.03mingw-setup.exe . That's compile correctly after that I download SFML 2.5.1: GCC 5.1.0 TDM (SJLJ) - Code::Blocks - 32-bit.
Following, I extract the SFML file.The problem comes I COPY THE CONTENT OF "BIN" INSIDE OF MY CODEBLOCKS PROJECT. A video helps me to do all of before, I WROTE ALL THE LIBRARIES: GRAPHICS, WINDOW, NETWORK, AUDIO, SYSTEM BUT NOTHING. I show you the error:
cannot find -lsfml-audio-d-2

And continue with network, window,system, graphics
At the ends:
error: ld returned 1 exit status

what's wrong? help me please. I have to make a video game using CODEBLOCKS as soon as I fixed this problem. I'll so thankful for your answers.
Comment: Did you configure your project?
Answer: On the SFML download website (https://www.sfml-dev.org/download/sfml/2.5.1/), it says:
The compiler versions have to match 100%!
The CodeBlocks 20.03 MinGW installation includes version 8.1.0 of the GCC compiler (as is stated on the download page: http://www.codeblocks.org/downloads/26).
Your downloaded version of SFML thus is only intended to work with version 5.1.0 of GCC, but you have version 8.1.0. This can result in a number of errors.
There are a few possibilities to fix your issue:

You could theoretically compile SFML yourself with your specific compiler, but this option may be quite complicated.
You could use a compiler with the matching version. On the SFML download website, there are some links to the needed compilers. After having installed a compiler, you will have to configure CodeBlocks to detect the new compiler on your system (reference: Adding compiler to code::blocks). Now, in order to add SFML to your project, I would suggest to use this official guide:
https://www.sfml-dev.org/tutorials/2.5/start-cb.php
You could use an environment like MSYS2 (which I use personally) to have a package manager to manage your compiler and libraries installations. This way, your compiler installation and your libraries should work with each other. But in order to use this compiler in CodeBlocks, CodeBlocks would have to be configured.

I would suggest that you refer to option 2 because it probably is the quickest solution.
Feel free to ask if you have any more questions. I know from personal experience that setting up SFML (or any other C++ library) to work with your IDE may be quite tricky.


Best strategy for tuning a 4 piece kit?

Question: I recently got an acoustic kit after playing an electric kit for a while. There's a lot to learn, but one thing that I keep getting hung up on is how to tune my kit.
I've read a bunch of guides, and definitely watched enough youtube videos – but I can't figure out how to organize this. I don't know much about music theory, but is there something I'm missing here? Or am I just over thinking it?
I picked up a Tunebot to try and help narrow things down, but I think my issue is more fundamental. Here is how I have everything tuned now, but I think both the rack/floor tom are too low (and the kick never seems quite right):

Update for more context
Todd Wilcox asked for some more context on how I ended up with this tuning. After reading all these answers it's pretty clear that the snare/kick don't matter as much – but for the toms I followed the Tunebot guide:

I started with 2A & 2D for the toms, and it sounded only OK. Then I realized my rack tom is 13" and not 12", so I thought the lower tuning (2F & 2C#) would be a better fit for this kit.
I had a feeling this would end up being very subjective, but I have definitely learned a lot reading all the responses
Comment: What will you do, whenever a song changes key? Retune each time? // As Edward pointed out, harmony is not a vital concept for drums, while sound is. Better make each sound characteristic, so we hear "oh, that's a different drum". Consider (non-)resonant tuning, e.g. metallic sound for snare, and dampening, e.g. with some tissue. // Tuning may be relevant to give room to the bass playerin the low frequencies: don't overplay them. // For inspiration see this fun video from Benny Greb: https://vid.puffyan.us/watch?v=J0pKWox-j5Q
Comment: Can you edit to explain how you arrived at the pitches you are currently tuning to? Are they semi-random/just what sounds good or did you go through a process to determine the most resonant pitches of your shells?
Answer: Warning: This is probably subjective.
The actual note pitch of your snare doesn't matter that much, it's more just a measure of how high or low it is.  I tune my snare to G, roughly, I think that's a good middle ground for rock music.
The actual note pitch of the kick only matters if you let it ring out to make a clear pitch.  For the typical rock kick sound, it doesn't matter.  I don't know what note my kick is.  I like kicks tuned to thud, or perhaps thump.
For the toms, the actual pitch doesn't matter that much either, only that they sound the right distance apart (usually about a 4th) and that they sound good together (usually means tuning them a 4th or 5th apart).  So on that note, raise your rack tom to F# or G#.  If you are tuning your kick to a note (as above) then your toms should sound good with the kick too- probably a fifth apart.
Beyond that, you could open a new question for how to tune each drum individually to achieve your target pitch, and you will get basically every possible way as an answer.  That part is extremely subjective, so I think the most sensible approach is:
Watch a youtube video on how to tune x drum (snare, kick, or both toms)
If you like the sound in the video, tune your drum like that.  Else, find another video.
Play your drums like that for a day or 2, to learn how the tuning sounds and feels in person.
Repeat.
Decide which tuning scheme you liked best.
Remember, if you're using hearing protection, like you should, then that affects how your drums sound.  Your drums will also sound different to you sitting behind the kit vs someone elsewhere in the room.  Recording your drums gives you more ways to hear them.
Answer: Having both batter and resonant heads the same is probably more important.
BUT - having said that, my kick is filled with a duvet (down and feather, of course!), so there is no ring about it. Having a ringing bass drum doesn't work for most pieces of music - particularly pop/rock/blues, as it resonates for too long, and often whatever note will clash with what the bassist is playing. Even tuned to a 'good' note, it would still clash a lot of the time. Hence, dull thud, no discernible pitch.
Snare likewise. No, not a duvet, but care to keep it away from a pitch at which it will ring sympathetically. Nothing more annoying at a recording session than that happening whenever a particular pitch gets played by someone else! That apart, the actual tuning pitch becomes somewhat obscured when the snare is on, although it can be detected with it off.
Toms - often there are three - two kick drum mounted, and a floor tom (or even two). It is possible to tune them so they work with a song, and that's been done plenty of times. Trouble is, it'll only work for one key. So generally speaking, they're tuned a 4th, or 5th apart - here, both heads in tune works well. Whatever note may be down to the size of each drum, and obviously the higher each pitch, the tighter the skin. More important a factor for the batter head, and what tension the drummer prefers.
So, no hard and fast rules. I often hear drummers tweaking the tuning before a gig, but never hear them ask for an A, for a B♭! More important, it seems, to just get  them  resonating, and relative to each other, given the time.
Answer: In 40 years [on & off] of being a drummer, I've always considered this task to be…
… an entire day of tuning, changing your mind until you're just about happy. You then follow this with a gig or session during which you invariably hate what you've done & determine to do it again tomorrow.
You follow this with several weeks of 'mañana'/procrastination/inertia… then rinse & repeat until unhappy.
You later listen back to some of those sessions & think.. "Dammit, I like that. How did I do it?"
Gigs, of course, don't count - because you never ever heard what the audience heard.
You could try "The Drum Tuning Bible" which is a much-quoted & oft-linked resource, easily googleble & linked from a myriad mirrors, including https://www.stevesuchdrums.com/stevesuchblog/drumtuningbible
which is a reference I often read during periods of ennui between tuning binges. I can't say I've ever really followed it, but I always have it in mind every time  I re-tune the kit.
It comes down to patience, your ears, patience, willingness to try many similar structures, and did I mention patience…
You can go through tricks to increase then reduce resonance; whether you like the bottom skin higher or lower pitch [makes the note rise or fall after strike]; dropping one corner once you find the 'ring point'; extreme use of damping vs one weeny bit of tape in a corner…  Kick full of duvet or let it ring then tune-damp it.
Every day is a new tuning experience, dampened [pardon the pun] only by enthusiasm, or lack thereof.
There is no definitive answer to this question, only experimentation & experience.
Comment: Would upvote this twice if possible.  I played drums for 30 years (10 or so seriously, the rest "off and on") and it never once occurred to me to tune the resonant lower or higher than the batter to affect the pitch of the decay.
Comment: I've upvoted this and also suggest it might be best to quote some of the most important bits of the The Drum Tuning Bible to make it a complete answer.
Comment: @ToddWilcox - I'd love to… but it's 20 pages of very dry, concise text. There isn't really anything you could lift out & hold up as an example. It's not a resource that's going to suffer link rot [or if this specific link rots, Google can find many others.] It's been kicking round the interwebz for over 20 years & is mirrored in many places.
Comment: Yeah I've read it and used it before - going back to when it was new.
Answer: I searched for a definitive answer on this some time ago and found information that includes much of what is being said here.
Here are two links to the same website that have videos and documentation on how to tune for different types of drumkits.
The rock and fusion kits show tuning for 5-piece kits.  You should be able to get good sounds from a 4-piece by omitting the larger rack tom from your tuning.
All this information is good no doubt.  I personally tune by ear.  I tend to like deeper notes than what is shown here.
Hopefully this helps.  Enjoy.
Sticks and Staves tuning website
Sticks and Staves PDF document on note tuning for different styles of acoustic
drums sets
Comment: Pure references will eventually suffer from rot, so this won't be much use then.
Answer: You are over thinking it. The physics of drums is fundamentally different from  "musical" instruments which have a Fundamental frequency and harmonics that are integer multiples the Fundamental. The relationship between the fundamental and the harmonics is what allows objective tuning of "musical" instruments.
Circles (like a drum head) don't have this property, and can't be tuned to a note, the shape simply does not allow it, and if you hit the drum in a different place on the drum head you will get a different sound.
Comment: Try telling that to Drums Workshop, who will stamp the resonant frequency of their shells inside in case a drummer wants to tune the heads to approximately that note. Even if the overtones of a drum head are inharmonic, that doesn't mean there is no fundamental (or perhaps a better word is "lowest") frequency for a tuned drum. If the heads are tuned to the strongest resonant frequency of the shell, then the drum will be the loudest and most responsive it can be, and have the longest sustain.

Best strategy for tuning a 4 piece kit?


Updating priors based on outcome of Bernoulli trials

Question: I am observing Bernoulli trials: independent events which either occur (with a fixed probability $p$) or do not occur (probability $1-p$). My subjective prior belief is that $p=p_0$ (for non-triviality assume $0<p_0<1$.) If I then observe $s$ successes and $f$ failures, how should I update my estimate of $p$? Is there any way to make this problem well-defined?
Comment: If your belief is that $p=p_0$, meaning a Dirac mass at this value, then no amount of observation will change it.
Answer: In Bayesian statistics you model the parameters as random variables, with a prior probability distribution, and you update that distribution based on data. Your $p$ (which I will call $\theta$ from now on) isn't really a random variable: you said you're 100% sure that it's equal to a deterministic constant. Or, to be more precise, you're saying that your prior belief is that $\theta$ is equal to $\theta_0$ with probability 1. Now, if you put all the probability mass on a single point, the posterior will be equal to the prior, no matter what the likelihood is, because from Bayes' theorem, the posterior is zero where the prior is zero, and it must have a total mass of 1. Use the Bayes' theorem when $\theta$ is a discrete random variable, which can assume the values $\theta_0,\dots,\theta_N$ with probabilities $p_0,\dots,p_N$:
$$p(\theta_0|y)=\frac{p(y|\theta_0)p_0}{\sum_{i=0}^Np(y|\theta_i)p_i}$$
if $0=N$ and thus $p_0=1$, you have
$$p(\theta_0|y)=\frac{p(y|\theta_0)p_0}{p(y|\theta_0)p_0}=1=p_0$$
To get out of this, you need to change your prior. Two simple proposals:

You could say that you're 90% sure that $\theta=\theta_0$, but there
could also be a 10% chance that $\theta=\theta_1$, which is another
parameter value which you consider less likely, but not completely
implausible. Given your likelihood, updating is immediate:
$$p(\theta_0|y)=\frac{0.9p(y|\theta_0)}{0.9p(y|\theta_0)+0.1p(y|\theta_1)}=
\frac{0.9\theta_0^s(1-\theta_0)^f}{0.9\theta_0^s(1-\theta_0)^f+0.1\theta_1^s(1-\theta_1)^f}$$
Of course, you're not limited to just one extra plausible value. You
could add as many as you want, as long as the sum of the probability
masses is 1. And if you had infinitely many plausible values? This
leads naturally to the next prior proposal.
You could consider $\theta$ as a continuous random variable, instead than a discrete one, but since you're extremely confident that $\theta=\theta_0$, you could use a prior which puts most of the mass near $\theta=\theta_0$, but also some mass on all the other values from 0 to 1. For example, a Beta prior with $\beta$ very high, and $\alpha=\frac{\beta \theta_0}{1-\theta_0}$, will give you a prior mean $\frac{\alpha}{\alpha+\beta}=\theta_0$, and a prior sample size of $\alpha+\beta=\frac{\beta \theta_0}{1-\theta_0}+\beta=\frac{1}{1-\theta_0}\beta$. If $\theta_0=0.2$, and $\beta=200$, you get

which is quite concentrated around $\theta_0$, but it gives a non-zero probability also to different values. The advantage of the Beta prior is that the Beta-Binomial family is conjugate, and since you have a Binomial likelihood, the posterior is also a Beta with updated shape parameters $\alpha^*=\alpha+s$ and $\beta^*=\beta+f$. Thus updating is again immediate.


Dot product cancellation

Question: Given vectors $a,b,c$, I know that
$$
c\cdot a=c\cdot b
$$
does not imply $a=b$ (take three orthogonal vectors, for example).
However, if I say that $c\cdot a=c\cdot b$ holds for any vector $c$, is it then true that $a=b$? How should I argue?
Comment: Since $c\cdot(a-b)=0$ for all $c$, take $c=a-b$.
Answer: Hint:
$$c\cdot a=c\cdot b\implies c\cdot a-c\cdot b=0$$
$$\implies c\cdot(a-b)=0$$
What do we infer  if this equation holds for every $c$?
Comment: Perfect, thanks!
Comment: @samwolfe You're welcome!!!!
Answer: Hint:
If the equation holds for every $c$, you can put $c=a-b$.
Answer: We have that
$$c\cdot a=c\cdot b \iff c\cdot (a-b)=0 \iff c=0 \quad \lor \quad a-b=0 \quad \lor \quad c\perp (a-b)$$
and since $c$ can assume any value only  the case $a-b=0$ remains therefore
$$\forall c\,,\quad c\cdot a=c\cdot b \iff a=b $$
Comment: @ThomasShelby The dot product of two vectors is equal to zero only if one is equal to zero or if they are perpendicular. Since c can be any vector only $a=b$ remains. Isn't it clear?
Comment: I guess one could go to the extreme of saying that, since we're assuming $c$ is any vector, imposing conditions such as $c=0$ or $c\perp (a-b)$ would go against such assumption. Thus $a-b=0$ remains as the only possibility, as you said. Very clear answer, thank you!
Comment: @samwolfe Yes exactly! Maybe not the most brilliant but it works fine I think! Thanks, Bye

Dot product cancellation


TYPO3 - Extbase - Detect missing files for a given FileReference

Question: I've tried three different ways to detect if a FileReference's original file is still existing (i.e. file has been deleted outside TYPO3 using SFTP or similar):
if($fileReference instanceof \TYPO3\CMS\Extbase\Domain\Model\FileReference) {
    $isMissing = $fileReference->getOriginalResource()->getStorage()->getFile($fileReference->getOriginalResource()->getIdentifier())->isMissing();
    $isMissing = $fileReference->getOriginalResource()->getOriginalFile()->isMissing();
    $isMissing = $fileReference->getOriginalResource()->isMissing();
}

Only the first one give me the right isMissing() value.
Answer: The property isMissing is an database value, which is set if the storage detect an missing file. On getFile the storage check if the file is missing and set "isMissing" for the file. If you dont persist this to the database, the setting is get loose with the next call.
You can also call $isMissing = $fileReference->getOriginalResource()->getStorage()->hasFile($fileReference->getOriginalResource()->getIdentifier());
You can run the file indexer scheduler (TYPO3\CMS\Scheduler\Task\FileStorageIndexingTask) if you want to check frequently for deleted files. This should be required if you let change files externaly (like ftp).
Comment: Great, good to know! Do you know how to replace a missing file for a FileReference? Tried different approaches, didn't get it... Will create a separate question for this.


Is smartd really reporting this drive is too hot?

Question: "SMART Usage Attribute: 194 Temperature_Celsius changed from 146 to 150". This is on CentOS 6.6.
What does this really mean? Is the drive really hot or is this perhaps a software bug? The drive is an eSATA 2TB drive and it feels cool to the touch and the server located in a basement is 70F.
# smartctl -A /dev/sdb
smartctl 5.43 2012-06-30 r3573 [x86_64-linux-2.6.32-504.16.2.el6.x86_64] (local build)
Copyright (C) 2002-12 by Bruce Allen, http://smartmontools.sourceforge.net

=== START OF READ SMART DATA SECTION ===
SMART Attributes Data Structure revision number: 16
Vendor Specific SMART Attributes with Thresholds:
ID# ATTRIBUTE_NAME          FLAG     VALUE WORST THRESH TYPE      UPDATED  WHEN_FAILED RAW_VALUE
  1 Raw_Read_Error_Rate     0x000b   100   100   016    Pre-fail  Always       -       0
  2 Throughput_Performance  0x0005   134   134   054    Pre-fail  Offline      -       89
  3 Spin_Up_Time            0x0007   123   123   024    Pre-fail  Always       -       507 (Average 505)
  4 Start_Stop_Count        0x0012   100   100   000    Old_age   Always       -       89
  5 Reallocated_Sector_Ct   0x0033   100   100   005    Pre-fail  Always       -       0
  7 Seek_Error_Rate         0x000b   100   100   067    Pre-fail  Always       -       0
  8 Seek_Time_Performance   0x0005   135   135   020    Pre-fail  Offline      -       26
  9 Power_On_Hours          0x0012   096   096   000    Old_age   Always       -       29541
 10 Spin_Retry_Count        0x0013   100   100   060    Pre-fail  Always       -       0
 12 Power_Cycle_Count       0x0032   100   100   000    Old_age   Always       -       71
192 Power-Off_Retract_Count 0x0032   100   100   000    Old_age   Always       -       205
193 Load_Cycle_Count        0x0012   100   100   000    Old_age   Always       -       205
**194 Temperature_Celsius     0x0002   150   150   000    Old_age   Always       -       40 (Min/Max 20/49)**
196 Reallocated_Event_Count 0x0032   100   100   000    Old_age   Always       -       0
197 Current_Pending_Sector  0x0022   100   100   000    Old_age   Always       -       0
198 Offline_Uncorrectable   0x0008   100   100   000    Old_age   Offline      -       0
199 UDMA_CRC_Error_Count    0x000a   200   200   000    Old_age   Always       -       9

Answer: That is just SMART attribute value. It is not the temperature in any regular unit.
(it is more like a number between 255 (really really cold) and 0 (really really hot), depending on drive what is hot and what not)
If you want to see the temp of your drive use smartctl -A /dev/sdx
You'll get table like this:
ID# ATTRIBUTE_NAME          FLAG     VALUE WORST THRESH TYPE      UPDATED  WHEN_FAILED RAW_VALUE
194 Temperature_Celsius     0x0022   107   097   000    Old_age   Always       -       45

RAW_VALUE is what you're looking for ... (my drive is quite warm at 45°C)
VALUE is the attribute value and when it gets below THRESH, the drive is getting ready to ask for replacement. (Not all attributes have threshold, just like my temperature)
With regards to what is hot and what is not, it really depends on drive. There is a somewhat dated paper from Google on drive failure rates, which states that drives around 40°C have the lowest failure rates (at least for google and in 2007). I remember reading another paper (can't find it now) which stated, that high temperature is not a problem for hard drive. Sharp and frequent temperature changes can cause the disk to fail sooner. So as long as the drive temp is pretty stable (you can monitor that using something like munin), you should be fine.
smartd is reporting any changes in attributes. It does not mean that there is something wrong.
Comment: Thanks. Please see above, I updated this with the smartctl output. RAW_VALUE is 40. That is 40 degrees Celsius, which is 104F. Is that considered hot? Or getting hot and it's logging it because it might be a dangerous trend? But the Min/Max is 20/49, so it doesn't sound like it's too hot at least yet,
Comment: @Edward_178118 updated the answer, hope it helps.
Comment: So the threshold values of 150, had nothing to do with being 150C?
Comment: Exactly. 150 would be way too hot. Even too hot for a CPU, which gets heatsink, to stay below 80 or so.
Comment: mine has a value of 181 which is RAW_VALUE of 33°C (so quite cold)


Contextual filter has no results when using entity translation of non default language

Question: I have a view that shows content with an entity reference field referencing the currently displayed node.
This is a scenario often used, just a block (pane in my case) that shows content (child nodes) that belongs to the current node (parent node).
This uses the contextual filter (Content entity referenced from field_section_reference) Content: Nid
with 'provide default argument': content ID from URL'
The view is filtered with 'Field Language:Current user's language'
This works fine for the default site language, showing all content of the language (url language selection)
But when I use the language switcher, the view does not show anything any more. Translated content of current language is not shown.
I removed the contextual filter and added a normal filter, selecting manually a language other than the default site language. This worked, translated content shows fine.
If you are reading this and have entity translation enabled in a similar setup, please do me a favor and test if I'm right. I have spend quite some hours trying to find alternatives and workarounds, but can't display a view of translated content that is referencing the currently displayed node, when using a not-default language.
Answer: not sure if I had the exact problem, but I solved my views / ET woes by adding 'entity translation' relationship. then you can filter by 'entity translation: language' and then select to user the user's current language. hopefully this helps!


Standard Deviation: Why divide by $(N-1)$ rather than $N$?

Question: The forumlae for standard deviation seems to be the square root of the sum of the squared deviation from mean divided by $N-1$.
Why isn't it simply the square root of the mean of the squared deviation from mean?  i.e, divided by $N$.
Why is it divided by $N-1$ rather than $N$?
Comment: To prevent bias, as explained [here](http://en.wikipedia.org/wiki/Variance#Estimating_the_variance) and [here](http://en.wikipedia.org/wiki/Variance#Population_variance_and_sample_variance).
Comment: This might help: http://stats.stackexchange.com/questions/3931/intuitive-explanation-for-dividing-in-n-1-when-calculating-sd
Comment: The reason is because it gives you an unbiased estimator.  But, do not confuse this with giving the best estimator.  In my time series class, my professor tells me that in time series you usually divide by n instead, because it's actually a better approximation.  I couldn't explain to you why or anything.
Comment: Well, one thing is that the samples are not independent in time series... I'm sure that has something to do with it.
Answer: If you have n samples, the variance is defined as:
$$s^2=\frac{\sum_{i=1}^n (X_i-m)^2}{n}$$
where $m$ is the average of the distribution.
In order to have an estimator non $biased$ you have to have:
$$E(s^2)=\sigma^2$$
where $\sigma$ is the real unknown value of the variance. It's possible to show that $$E(s^2)=E\left(\frac{\sum_{i=1}^n (X_i-m)^2}{n} \right)=\frac{n}{n-1}\sigma^2$$
So if you want to estimate the 'real' value of $\sigma^2$ you must divide by $n-1$
Comment: The sample variance uses the sample average, not $m$.
Comment: If m is the mean of the X's (cosidered iid) the estimator you wrote is unbiased. The fact of dividing by n-1 comes up when you dont know the mean and you need to estimate it (with sample average) in order to define the estimator of the variance. This requires you to pull down the numbers of degree of freedom.


Add number of items as a class to menus

Question: I would like to add a class to menu that shows how many items are in that particular level.  I.E.

1

2

3

4

5

What's the best way to do this?
I've looked at theme_menu_tree but the tree is already rendered html by that point so there is no easy way to count the number of items.
Answer: It really feels like there should be a better way to do this (but I can't find one at the moment, theme_menu_link() isn't context-aware of its parent menu); however this will work:
function MYMODULE_menu_tree(&$variables) {
  // Load the current HTML into a DOMDocument to count the links
  $doc = new DOMDocument;
  $doc->loadHTML('
' . $variables['tree'] . '
');

  // XPath query to find only top-level
s
  $xpath = new DOMXPath($doc);
  $lis = $xpath->query('//ul[@class="identifiable-string"]/li');

  // Get the count based on the number of elements returned
  $count = 0;
  if ($lis) {
    foreach ($lis as $li) {
      $count++;
    }
  }

  return '
' . $variables['tree'] . '
';
}

It seems like a huge amount of effort (not to mention processor power) for not much reward, but if you're struggling then this method will definitely work.
Comment: This definitely looks like the most reliable PHP solution, but considering the roadblocks thrown up by Drupal in this situation, I'd highly recommend that OP reconsider his aversion to using jQuery for the solution.
Answer: If you are willing to do that with jQuery.
var num_links = jQuery('.menu > li').length;
jQuery('.menu').addClass('count-'+num_links);

Comment: Unfortunately, no.  Thanks for the thought though
Answer: The API function you want is theme_menu_link(). The information about each menu link's child menu items is available in this function. You will need to count the child menu items and use that count as part of your class. However, the array that holds the child menu items also holds other information.
The following implementation of theme_menu_link() worked for me with a quick, superficial test:
function THEMENAME_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
    $count = 0;
    foreach($element['#below'] as $key=>$item) {
      //the child menu items' keys are their mlid, which is numeric
      //most other items in this array will not have numeric keys
      if(is_numeric($key)) {
        $count ++;
      }
    }
    $element['#attributes']['class'][] = 'count-'.$count;
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '
' . $output . $sub_menu . "
\n";
}

Comment: I just realized I misunderstood the question, so my answer is irrelevant. But still maybe helpful for someone? :)
Answer: You can still use theme_menu_tree(), just explode the tree into an array.
Something like this should work:
function THEMENAME_menu_tree($variables) {
$menu_items = explode('
', trim($variables['tree']));
$count = count($menu_items);

  return '
' . $variables['tree'] . '
';
}

Comment: I don't think this will work for menus that have multiple levels. The split on `` would produce some very unpredictable results
Comment: You're right. I meant to add that disclaimer to my answer.  You could explode on '' and then explode the resulting strings on '', but yeah, it gets very messy.
Answer: As pointed out here:
https://stackoverflow.com/questions/7176013/how-can-count-the-children-of-drupals-main-menu
it is possible to use menu_tree_page_data.
You could thus use this in combination with theme_menu_tree, for instance:
function MYMODULE_menu_tree(&$variables) {
  $count = count(menu_tree_page_data('main-menu'));
  return '
' . $variables['tree'] . '
';
}

Please note that this will trigger for every single menu that displays in your page and it will always return the number of items of the menu 'main-menu'.
If you want to tailor it to a specific menu, you'd have to implement THEMENAME_menu_tree__MENU_NAME() in order to override the function for a specific menu.

Add number of items as a class to menus


Determining automorphism group

Question: Let $K=\mathbb{Q}[\sqrt{2},\sqrt{3}]$. In the book Abstract Algebra by Dummit and Foote, page 563, the author gave an example of finding the Galois group of $K/\mathbb{Q}$.
Here are some arguments that relate to my question :

The extension $\mathbb{Q}[\sqrt{2},\sqrt{3}]$ is Galois over $Q$ since it is the splitting field of $(x^2-2)(x^2-3)$. Any automorphism $\sigma$ is completely determined by its action on the generators $\sqrt{2},\sqrt{3}$, which must be mapped to $\pm\sqrt{2}, \pm\sqrt{3}$, respectively.
Hence the only possibilities for automorphisms are the maps:
  \begin{cases}
     \sqrt{2}\mapsto \sqrt{2} \\
     \sqrt{3}\mapsto \sqrt{3}
\end{cases}
  \begin{cases}
     \sqrt{2}\mapsto -\sqrt{2} \\
     \sqrt{3}\mapsto \sqrt{3}
\end{cases}
  \begin{cases}
     \sqrt{2}\mapsto \sqrt{2} \\
     \sqrt{3}\mapsto -\sqrt{3}
\end{cases}
  \begin{cases}
     \sqrt{2}\mapsto -\sqrt{2} \\
     \sqrt{3}\mapsto -\sqrt{3}
\end{cases}

My question is :

Why does the automorphism have to map $\sqrt{2}$ to $\pm\sqrt{2}$, and $\sqrt{3}$ to $\pm\sqrt{3}$ ? Why can't we choose an automorphism like \begin{array}{l l}
     \sqrt{2}\mapsto \sqrt{3} \\
     -\sqrt{2}\mapsto -\sqrt{3}
\end{array}
I tried to prove that the above map is not an automorphism but my attempt failed. Where am I wrong ?
Let $\sigma$ be the 2nd automorphism, $\tau$ be the 3rd automorphism, then what is: $\sigma(-\sqrt{2})$ and $\tau(-\sqrt{3})$ ?

P/S : I do not know the latex code of the bracket, mod please help me. Thanks
Answer: If $\alpha^2=2$ then $\sigma(\alpha)^2=\sigma(\alpha^2)=\sigma(2)=2$.
In general, if $f(\alpha)=0$ with $f\in\mathbb Q[X]$, then also $f(\sigma\alpha)=0$ (because $\sigma f=f$).
For your second question note that with $u,v\in \mathbb Q$ you have $\sigma(u\alpha+v\beta)=u\sigma(\alpha)+v\sigma(\beta)$.
Comment: Thank @Hagen von Eitzen for your very nice answer and edit. I have one more question : How can we determine the Galois group of the splitting field ofsome seperable polynomial ? For example, determining the Galois group of the splitting field of $x^3-2=0$, there are 9 possibilites for the automorphism but the Galois group is only of order 6 ?

Determining automorphism group


How many unique combinations to wear seven different socks?

Question: My friend has seven unique but similar socks.
How many ways does he have to wear them, not double counting same combos?
$\mathbf {Attempt}$
I think $7! - 5!$ , but then you forget you can put the first foot sock on the other foot as well so $7!-5!+6$ is the correct answer?
Comment: Huh.  There are seven socks he can put on his left foot and six remaining socks he can put on his right foot.  So 42.  Unless the question says otherwise I refuse to contemplate wearing multiple socks on a foot or going or putting two feet in a sock or putting a sock on your tongue or....
Comment: @bof How can there be $7!$ ways to wear a single sock on the left foot? There are $7$ ways to wear a sock on the left foot.
Comment: Does your friend ever wear more than one sock on the same foot at once? (It's cold these days.) Does he sometimes wear them inside out, and does that matter when counting? I guess socks are not so big that he can fit both feet in the same sock?!
Comment: To conclude he must wear all 7 from "how many ways are there to wear then" is a stretch.  At best, this question is vague.  I say the answer is 3. He can wear them i) at home, ii) at work and iii) for formal occassions.  Three ways.
Comment: What is the $-5!$ for? The answer must be more than $7!$ because there are $7!$ ways to wear all $7$ socks on his left foot, and then another $7!$ ways to wear them all on his left foot, and lots more ways to split them between his two feet. (I assume we don't consider wearing them on his hands or his head. What about turning a sock inside out, does that count as a different way?)
Comment: @StellaBiderman The question asks "How many ways does he have to were them", the pronout *them* evidently referring to the seven socks. Given that the man has to wear seven socks, he is probably going to put more than one sock on one foot.
Comment: @fleablood It's clearer from the title: "How many unique combinations ***to wear seven different socks?***. If you have just one sock on each foot, you are (probably) not wearing seven different socks.
Comment: Well, does it count if a wear them inside out?  What body part I put them on? Is putting them on at 7 am while eating breakfast count differently than if I put them on a 3 am in a sexual escapade? And in what ontological sense is "I chose to not wear it" not count as a way to wear something?  I think it is far too vague.
Comment: Given the obvious disagreement in the comments about what counts and what doesn't count as an answer, I'm nominating that we close this question as unclear until the OP specifies what is intended.
Answer: You are choosing $2$ socks from $7$ socks. That is ${7\choose 2}=\frac{7!}{2!5!}=21$, where you can first choose from $7$ socks, then you can choose from the $6$ remaining socks (so $7\cdot 6=\frac{7!}{5!}$) and due to counting each pair double, you divide by $2!=2$.
I think it's pretty well explained here, also for the general case $\frac{n!}{k!(n-k)!}$:
https://betterexplained.com/articles/easy-permutations-and-combinations/
Answer: Hint: If he puts $n $ on the left foot, $m $ on the right foot and leaks $k $ off, there are $$\sum_{n=0}^7 7Pn (\sum_{m=0}^{7-n}7-n Pm)= \sum_{n=0}^7 \frac {7!}{(7-n)!} (\sum_{m=0}^{7-n}\frac {(7-n)!}{(7-n-m)!})= 7!\sum_{n=0}^7  (\sum_{m=0}^{7-n}\frac 1 {(7-n-m)!} )$$ ways to do this.
Answer: 7! ways to wear different sock
Answer: You have $7$ choices for your left root. Then you have $6$ choices for the right. This gives $42$ choices. However, this counts $AB$ and $BA$ as different, while the problem says to not double count the same pair. So we have half that many choices, so $21$ is the answer.
Comment: But then you forget again the scenario that you can place all 7 socks starting on *either* foot. Must be more?
Comment: And e.g. red sock left green right IS separate from green left red right
Comment: Where is Toni getting that you can place all seven socks on either foot?  The criteria of what a "combo" or what a same combo is makes this question too vague to answer.  With no other condition I think stella's answer of 42 (not 21; there is no good reason to consider AB as the same as BA) is clearly the most reasonable one.
Comment: @fleablood What do you take "not double counting same combos" to mean, if it doesn't mean that $AB$ and $BA$ are the same?
Comment: @Toni The same question to you.
Comment: I'I'm taking the question as too vague and poorly worded to be answerable.  "Same combo" is given *absolutely* no context to any meaning and I don't take to be possibly interpreted correctly.
Comment: If the socks are all different, imo, "same combos" simply are not possible.  Unless there is some stipulation as to what a same combo is.  Left and right irrelevant is one way.  Putting a green sock over a red sock being the same as the other order.  But what I think the op actually means is:  there are $7!*3^7$ ways to place seven socks on either the left, right or neither foot.  But this double counts pointing the blue sock 1st on the left and red 2nd on right as same as red on right 1st blue on left 2nd.  If so this is the ring problem.


Proving/Disproving a fact about open set of $\mathbb{R}$

Question:
Let $S\subset\mathbb{R}$ be an open set and $x\in S$. Let $T \subset S$ be the
  largest open interval containing $x$, then $S\setminus T$ is an open
  set.

My attempt:
Let $y\in S\setminus T$. Then $y \in S$ and $y \not\in T$. Since $y \in S$ and $S$ is an open set, there exists a neighborhood $I \subset S$ of $y$. We will now show that every element $z \in I$ is not in the set $T$. Otherwise if there were some element $z$ in $I$ such that $z$ is in $T$, then $T\cup I$ is a neighborhood of $z$ and so for $x$. But $T$ was the largest open interval containing $x$ (a contradiction!); thus we have that every element $z \in I$ is not in the set $T$. Thus, $I \subset S\setminus T$ and we conclude that $S\setminus T$ is an open set.

Is this proof okay or are there any counterexamples to this proposition?
Comment: Looks OK to me.
Comment: @PierreCarre OP is taking about largest open interval containing $x$ not the largest open interval symmetric about $x$ contained in $S$. In your example $T=S$.
Comment: @PierreCarre I meant the largest interval which would be $(0,3)$ in fact.
Comment: The result is true. An open set in $\mathbb{R}$ is a (possibly) countable union of disjoint open intervals, so  $S = S_1, S_2, \cdots, S_n, \cdots$, with all $S_n$ open and $T = S_j$. That way $S\setminus T= \bigcup_{n \ne j} S_n$, which is still open. The proof you presented also seems fine to me.
Comment: "The largest open interval containing $x$"? Are you sure? In that case $T=\mathbb{R}$ and $S\setminus T = \emptyset$, which is in fact an open set.
Comment: @PierreCarre I've added $T \subset S$ is this okay now?
Comment: You are correct, off course, i'll delete the comment.
Comment: @PierreCarre I was actually trying to prove the theorem that you mentioned by using the proposition that I've posted. I wonder if doing induction several times using this proposition would lead to correct proof or not.
Comment: I don't see how exactly induction would work, but you have already a few ingredients for the proof: For every $x \in S$ you can construct an open set $T_x = ]a_x,b_x[$; you have that $\cup_{x \in S} T_x = S$; you must check that: i. the open sets in that family are mutually disjoint ii. If that family is not finite it must be countable.
Answer: Since the open intervals form a basis for the topology, an open set $S$ in $\Bbb R$ is a union of disjoint open intervals (finite intersections of open intervals are also open intervals).  So which ever one $x$ is contained in,  will be $T$.  Then $S\setminus T$ will be the union of the remaining intervals,  hence open.
So this exercise is really about what the open sets in $\Bbb R$ "look like".
Your way looks ok.
Comment: This wasn't an exercise in my textbook. I stumbled upon this while actually trying to prove that every nonempty subset of R is a countable union of disjoint open intervals (I am yet to prove it!). I was thinking on using this proposition and induction to prove that an open set in R is a countable union of disjoint open intervals.
Comment: I was using exercise loosely. Good luck with this.  Note that the rationals are dense in the reals, so every interval will contain a rational.
Answer: One should first ensure that such a largest interval exists. Let $A=\{s\in S:[x,s)\subseteq S\}$. The set is not empty, because there is at least an interval containing $x$ and contained in $S$. Let $q=\sup A$ (might be $\infty$). Suppose $[x,q)\not\subseteq S$. Then there is $y\in[x,q)$, $x\notin S$; since $y<q$, there is $z\in S$ with $z\in A$. Contradiction.
By definition of supremum, no interval of the form $[x,z)$, with $z>q$, can be contained in $S$.
Similarly, if $B=\{s\in S:(s,x]\subseteq S\}$, then $(p,x]\subseteq S$, where $p=\inf B$ (might be $-\infty$).
Now, let $z\in T=S\setminus(p,q)$. Take an interval $(a,b)$ such that $z\in(a,b)\subseteq S$.
If $(a,b)\cap(p,q)\ne\emptyset$, we have that $(a,b)\cup(p,q)$ is an interval containing $x$ and contained in $S$; therefore $(a,b)\subseteq(p,q)$: a contradiction to $z\notin(p,q)$.


Continuosly Read/Monitor Serial Port(if port not opened continuously run script) using python

Question: Im newbie for python and serial port. I want to monitor serial port continuously. If port not opened or access denied, need to run the python script without stop.
I had done something, But that script has stopped when the PORT not opened or access denied. kindly, help someone to close this issue.
import serial
z1baudrate = 9600
z1port = 'COM4'
z1serial = serial.Serial(port=z1port, baudrate=z1baudrate,timeout=1)
try:
   if z1serial.is_open:
      while True:
        size = z1serial.inWaiting()
        if size:
            data = z1serial.read(size)
            res= data.decode("utf-8")
            print(res)
        else:
            print("Data not reading")
       time.sleep(1)
  else:
    z1serial.close()
    print('z1serial not open or Already in use')
except serial.SerialException as e:
  z1serial.close()
  print('COM4 not open')

Answer: You need to include the z1serial assignment inside the try block as
import serial
import time
z1baudrate = 9600
z1port = 'COM4'
while True:
    try:
        z1serial = serial.Serial(port=z1port, baudrate=z1baudrate,timeout=1)
        if z1serial.is_open:
            while True:
                size = z1serial.inWaiting()
                if size:
                    data = z1serial.read(size)
                    res= data.decode("utf-8")
                    print(res)
                else:
                    print("Data not reading")
                time.sleep(1)
        else:
            z1serial.close()
            print('z1serial not open or Already in use')
    except serial.SerialException:
        print('COM4 not open')
        time.sleep(1)

This worked for me, running on Python 3.7
Comment: if i  include the z1serial assignment inside the try block,port not open means script has stopped.But, i want to keep on watching the port until open.What to do.
Comment: I modified a little bit the code. I included an infinite loop so you keep watching at the port until it is open. I also included a `time.sleep(1)` if the port is not open to let some delay between checking the port, but you can change the delay. Does this answer your issue?


JWT Token and Multer for File Uploads (Node)

Question: I need a little help figuring out how to get this working -- I've tested and have working JWT authentication and SSL on my '/user' routes.  I'm trying to safely allow the user to upload an audio file, also using the JWT and SSL route.
The authentication middleware works, and multer works to let me upload files when I comment out the authentication middleware.  However, when I leave the middleware in, the uploaded file is created on my system, but the file fails to upload properly and I get a 404 error.
Thanks for any help!
server.js (main file)
var express     = require('express')
, app           = express()
, passport      = require('passport')
, uploads       = require('./config/uploads').uploads
, user_routes   = require('./routes/user')
, basic_routes  = require('./routes/basic')
, jwt           = require('jwt-simple');

// get our request parameters
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// Use the passport package in our application
app.use(passport.initialize());
require('./config/passport')(passport);

//double check we have an ssl connection
function ensureSec(req, res, next) {
    if (req.headers['x-forwarded-proto'] == 'https') {
        return next();
    } else {
         console.log('NOT SSL PROTECTED! rejected connection.');
         res.redirect('https://' + req.headers.host + req.path);
    }
}

app.use(ensureSec);

//authenticate all user routes with passport middleware, decode JWT to see
//which user it is and pass it to following routes as req.user
app.use('/user', passport.authenticate('jwt', {session:false}), user_routes.middleware);

//store info on site usage- log with ID if userRoute
app.use('/', basic_routes.engagementMiddleware);

// bundle our user routes
var userRoutes = express.Router();
app.use('/user', userRoutes);

userRoutes.post('/upload', uploads:q, function(req,res){
    res.status(204).end("File uploaded.");
});

// Start the server
app.listen(port);

routes/basic_routes.js (tracks engagement middleware)
var db   = require('../config/database')
, jwt    = require('jwt-simple')
, getIP  = require('ipware')().get_ip
, secret = require('../config/secret').secret;

exports.engagementMiddleware = function(req, res, next){

    if (typeof(req.user) == 'undefined') req.user = {};

    var postData = {};
    var ip = getIP(req).clientIp;
    var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;

    if (req.method=="POST") postData = req.body;

    var newEngagement = new db.engagementModel({
    user_id: req.user._id,
    ipAddress: ip,
    url: fullUrl,
    action: req.method,
    postData: postData
    });
    //log the engagement
    newEngagement.save(function(err) {
    if (err) {
        console.log('ERROR: engagement middleware db write failed');
        next();
    }
    console.log('LOG: user ' + req.user._id +' from ipAddress: ' + ip + ': ' + req.method + ' ' + fullUrl);
    next();
    });

    next();
}

config/passport.js (passport authentication middleware)
var JwtStrategy = require('passport-jwt').Strategy;

// load up the user model
var db = require('../config/database'); // get db config file
var secret = require('../config/secret').secret;

module.exports = function(passport) {
var opts = {};
opts.secretOrKey = secret;
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
    db.userModel.findOne({id: jwt_payload.id}, function(err, user) {
        if (err) {
            return done(err, false);
        }
        if (user) {
            done(null, user);
        } else {
            done(null, false);
        }
    });
}));
};

routes/user_routes.js (user route middleware, user add to header)
var jwt = require('jwt-simple');
var db    = require('../config/database');
var secret = require('../config/secret').secret;

//expose decoded userModel entry to further routes at req.user
exports.middleware = function(req, res, next){

var token = getToken(req.headers);
if (token) req.user = jwt.decode(token, secret);
else res.json({success: false, msg: 'unable to decode token'});

//should be unnecessary, double checking- after token verification against db
db.userModel.findOne({email: req.user.email}, function (err, user) {
    if( err || !user ) {
        console.log('something has gone horribly wrong. Token good, no user in db or access to db.');
        return res.status(403).send({success: false, msg: 'unable to find user in db'});
    }
});
//end unnecessary bit

next();
}

//helper function
getToken = function (headers) {
if (headers && headers.authorization) {

    var parted = headers.authorization.split(' ');
    if (parted.length === 2) return parted[1];
    else return null;

} else { return null; }
};

config/uploads.js (finally where we try to upload)
var moment = require('moment');
var multer = require('multer');
var jwt = require('jwt-simple');

var uploadFile = multer({dest: "audioUploads/"}).any();

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'audioUploads/')
    },
    filename: function (req, file, cb) {
        cb(null, req.user._id + '_' + moment().format('MMDDYY[_]HHmm') + '.wav')
    }
});

exports.uploads = multer({storage:storage}).any();

Comment: Did you get the answer? I'm pretty similar to you. I'm upload file/s with multer but when I use it the Back end returns that there's no token provided, and it is for sure! It's on my $localstorage!
Answer: in your server.js do this:
const authWare = passport.authenticate('jwt', {session:false});

userRoutes.post('/upload', authWare, uploads:q, function(req,res){
    res.status(204).end("File uploaded.");
});

works for me!


How should we configure Config link on custom module?

Question:
I need to create Config link while enabling module. In routing file, I have mention the path name of config form, but its not directly show in the Configuration page. Below is my routing code.
dm_user_timezone.user_timezone_settings:
path: '/admin/config/usertimezone/usertimezoneconfig'
defaults:
 _form: '\Drupal\dm_user_timezone\Form\UserTimezoneSettingForm'
 _title: 'User timezone page configuration'
requirements:
 _permission: 'access administration pages'
options:
 _admin_route: TRUE

My folder sructure looks like this. Need help what I missed here.
Answer: Add configure: dm_user_timezone.user_timezone_settings to the dm_user_timezone.info.yml file. The configure option is documented on drupal.org.
Comment: @latikas That is a different question that should be asked as new question. Comments should be used when there is anything not clear in the given answer, not to ask unrelated questions.
Comment: Thank you for your help. It works. :) One more question here, How should I display my module link on Configuration (/admin/config) page like People->Account Settings?
Comment: @latikas - Find a contrib module that does the same and then follow its sample.