Loading environment modules within a python script

Question: Is there a way for a python script to load and use environment modules? os.system('module load xxx') doesn't work since it executes them in a subshell (at least, I think that's what's happening).
Answer: I know this question's kind of old but it's still relevant enough that I was looking for the answer, so I'm posting what I found that works as well:
At least in the 3.2.9+ sources, you can include the python "init" file to get a python function version of module:
>>> exec(open('/usr/local/Modules/default/init/python.py').read())
>>> module('list')
No Modulefiles Currently Loaded.
>>> module('load','foo')
>>> module('list')
Currently Loaded Modulefiles:
  1) foo/1.0

I've been told earlier versions can do the same without the .py extension, but that's second hand, so ymmv.
Alternative "init" file location (from comment by @lib): /usr/share/Modules/init/python.py
To use with Python 3, version 4.0 or later of Environment Modules is required, as that is the first version to have a bug-free Python3-compliant version of the Python init file.
Comment: In the server I am using it is in /usr/share/Modules/init/python.py . I found the path be running module --version (the correct entry seems MODULES_INIT_DIR)
Comment: Cool,  I found this answer looking for a solution for perl, and my particular setup (VERSION 3.2.7 on RHEL 6.2) has initialization code for several shells in /usr/share/Modules/init/: bash, csh, ksh, perl, python, sh, tcsh, and zsh.  Thanks for the pointer.
Comment: execfile() is deprecated in python 3.6.0. How to use exec statement with python 3.6 to use environment modules?
Comment: Thanks @Jarvis. The answer has been updated for Python 3
Comment: This is much closer to what we actually use (since the `popen` calls to `modulecmd` are in the `python.py` file that you cited), so I'll set this to the answer. Thanks!
Comment: I had nearly a heart attack figuring this out! Thank you very much.
Answer: One of our admins was able to solve the problem for me using os.popen() calls to modulecmd:
cmd = os.popen('/path/to/modulecmd python load my-module')
exec(cmd)

Answer: While the accepted solution works, I found it to be easier to write:
import sys
sys.path.insert(0, '/path/to/environment/modules')
# Environment modules become available by loading python.py (the name choice could be better here)
from python import module

# ...
module('use', '/some/dir')
module('load', 'program/1.2.3')

This looks more pythonic to me and also it allows IDEs to offer auto-completion etc.
Answer: Not directly, but here's one possible workaround, depending on your environment.  Assuming you can preface your system command with ENVVAR=value, you can do something along these lines:
import os
os.environ['EDITOR'] = 'vi'
cmd = "EDITOR=%(EDITOR)s $EDITOR" % os.environ
os.system(cmd)

The code assigns vi to your EDITOR environment variable, then passes it on the command line and runs the command, which (in this case) is EDITOR.
Answer: I found the answers from jnewman, andreee and ian quite helpful. However, in my case the $MODULESHOME/init/python.py is written in Python 2 and is incompatible with Python 3 (it uses exec output instead of exec(output)). Here is my modified version that supports Python 3:
import os
import subprocess

def load_module(module_name, *, capture_output=True, check=True, **kw):
    module_home = os.environ["MODULESHOME"]
    modulecmd = os.path.join(module_home, "bin/modulecmd")
    process = subprocess.run(
        [modulecmd, "python", "load", module_name],
        capture_output=capture_output,
        check=check,
        **kw,
    )
    return process

Example use case:
CONDA_MODULE = "Anaconda3/2022.05"
load_module(CONDA_MODULE)
print(subprocess.check_output(["conda", "--help"], stderr=subprocess.STDOUT).decode("utf8"))


Reformat a timestamp

Question: I have a timestamp that looks like this 2018-09-18T21:49:16Z from an API. I need to reformat the timestamp to appear in 09-18-2018 @ 21:49:16. How can I do this in php?
Comment: Possible duplicate of [Convert one date format into another in PHP](https://stackoverflow.com/questions/2167916/convert-one-date-format-into-another-in-php)
Answer: You can do this using DateTime::format():
$dateTime = "2018-09-18T21:49:16Z";
$DateTimeFormat = DateTime::createFromFormat("Y-m-d\TH:i:s\Z", $dateTime);
echo $DateTimeFormat->format("m-d-Y @ H:i:s");
// 09-18-2018 @ 21:49:16

You'll have to convert your date and time string (2018-09-18T21:49:16Z) to a DateTime object using DateTime::createFromFormate().
Answer: The PHP datetime suite is your friend.
$mytime = new DateTime('2018-09-18T21:49:16Z');
echo $mytime->format('m-d-Y @ H:i:s');

Which results in:

09-18-2018 @ 21:49:16

Reformat a timestamp


How do I write a query that compares each row of one table to all the rows of a different table in MySQL?

Question: So I am trying to match an employee's latitude and longitude to the lat-long of a covid containment zone. In my database, I have a table called 'employee' with the columns 'Row_index', 'Address', 'Employee_ID', 'Latitude' and 'Longitude',
and a second table called 'red_zones' with the columns 'Location_index', 'Address', 'Latitude' and 'Longitude'.
Now I have to match the Lat-Long of each employee in the table 'employee' to the Lat-Long of all containment zones in the table 'red-zones'.
I decided to use a stored procedure by iterating through the 'red_zones' table:
    BEGIN
        DECLARE i, locationCount INT DEFAULT 0;
        DECLARE lat, lon VARCHAR(45) DEFAULT ' ';
        SELECT COUNT(*) INTO locationCount FROM red_zones;
        WHILE i <= locationCount DO
            SET i = i+1;
            SELECT Latitude INTO lat FROM red_zones WHERE Location_index = i;
            SELECT Longitude INTO lon FROM red_zones WHERE Location_index = i;
            SELECT Employee_ID FROM employee WHERE Latitude = lat AND Longitude = lon;
        END WHILE;
    END

After calling the procedure, I got the error 'maximum result count reached, no more results could be displayed'. I figured this was probably because the number of rows in the 'red_zones' table was over 700.
So I decided to Iterate through the 'employee' table instead (26 rows):
BEGIN
    DECLARE i, employeeCount INT DEFAULT 0;
    DECLARE lat, lon VARCHAR(45) DEFAULT ' ';
    DECLARE flag INT DEFAULT NULL;
    SELECT COUNT(*) INTO employeeCount FROM employee;
    WHILE i <= employeeCount DO
        SET i = i+1;
        SELECT Latitude INTO lat FROM employee WHERE Row_index = i;
        SELECT Longitude INTO lon FROM employee WHERE Row_index = i;
        SELECT Location_index INTO flag FROM red_zones WHERE Latitude = lat AND Longitude = lon;
        IF flag != NULL THEN
            SELECT Employee_ID FROM employee WHERE Row_index = i;
        END IF;
    END WHILE;
END

This procedure did not give me any output at all.
I have also made sure that there is a lat-long that matches between the two tables.
Should I be looking to modify my procedures, and if so, in what way?
Or should I be looking at a completely different method of achieving my goal?
Thanks.
Comment: @AarnavShah . . . You need to find someone in your organization who understands databases.  They are quite different from languages such as Java, and much of your intuition will not transfer easily (particularly anything about modularization and procedures).  You should probably also find some tutorials on SQL to learn the basics of the language -- and `JOIN` is a basic part of the language.
Comment: Why not a `join`? Please provide some sample data with expected output.
Comment: I am new to mysql, was not aware of the functionalities a join offers!
Comment: Just out of curiosity, why am I not able to achieve the same result through procedures? Since I have only worked with java, the first solution that came to my mind was iterating through all the rows.
Answer: A simple inner join will give you all the employees who are in redzone.
SELECT emp.*
FROM employee emp
JOIN red_zones rz ON emp.Latitude = rz.Latitude
                  AND emp.Longitude = rz.Longitude


Does PCA followed by LDA make sense, when there is more data available for PCA than for LDA?

Question: This is a question about classification.  I am a neuroscience student with little experience of classification methods and I'd be grateful for any advice about the best way to implement a linear classifier (LDA) on this data.
I have a magnetoencephalography dataset, recorded from people as they perform a cognitive task.  This has the following properties:

306 channels of data, but a preprocessing step has reduced the dimensionality to 64, and then reprojecting the data onto the sensors.
The data is fine-grained in the time domain (1000Hz)
The data is chopped up into short segments termed 'trials'.  These correspond to the cognitive task the subjects were performing.  The trials can differ, for example, in trial type A (of which I will have ~50) the subject may have been asked to pay attention to stimuli on the left hand side of space, and in trial type B (of which I have also 50) to pay attention to stimuli on the right hand side of space).

I want to classify my data at particular timepoints within trials (e.g. 0.5 seconds after subjects are told to attend left/right), training the classifier to discriminate between trials of type A and type B.  The feature vector for each observation (i.e. trial) is the vector of instantaneous activity at each sensor at that timepoint.  I have more features than trials (306 sensors) so I either need to do feature selection or use regularized LDA (or use something like Hastie's sparse discriminant analysis which seems to me to do both).
This I could do, BUT it seems like it throws away the information about the statistical structure of the data contained in the datapoints NOT from the exact time I am trying to classify.  Also, I know the data has a lower dimensionality than 306 - less than 50 components will likely capture the vast majority of the variance in the data.
I was thinking therefore about using a dimensionality reduction step, probably PCA, before passing the reduced-dimensionality data to an unregularized LDA or naive bayes classifier.  The idea is that the dimensionality reduction step exploits the fact that I have a large amount of data sampled over time.
And that's where I got confused.  PCA projects the data onto orthogonal dimensions, so does it makes sense to then do LDA (which estimates a covariance matrix in order to use information about the correlation between the features)?  Or should I do naive bayes following the dimensionalty reduction?  In which case, I could probably have just done naive bayes to start with, given that it's not sensitive to the number of features in the way that LDA is.
If anyone can advise on a good approach here, given the particular structure of this data, I'd be very grateful.  The key question is: does PCA followed by LDA make sense?
Comment: Without reading the whole question but in reply to the last ask `The key question is: does PCA followed by LDA make sense?` I'd reply "Often, not". In a sense, the two techniques are alternative and may impede each other. For [example](http://stats.stackexchange.com/q/12861/3277), if you retain just the 1st principal component shown on pic1 you won't be able then to separate the classes along it as well as the discriminant shown on pic2 could do it.
Comment: @ttnphns: In your linked example the number of points is much higher than the number of dimensions. If the situation is opposite (like in this question), LDA will hopelessly overfit. Reducing the dimensionality with PCA before doing LDA will often act as a sort of regularization, preventing overfitting and dramatically increasing the LDA performance.
Comment: this is an interesting question.  In the field chemometrics where one usually has few samples and many highly correlated parameters (spectral wavelengths from e.g. 400 - 2500nanometer in 1nm steps) I occasionally saw a "segmented PCA", where the cut the whole spectrum in spectral regions (segments, often 4) and took the first 3 PCs of each segment as parameters in the LDA. Here is one example:    http://gcl.csrsr.ncu.edu.tw/publication/hyperIntlRSdist.pdf
Comment: @amoeba, I agree with the logic you imply. However, in the situation where np but approaches p, better techniques, such as partial squares discriminant analysis, are somewhat better than pre-processing with PCA.
Answer: PCA calculates the eigenvalues that explain most of the variation across the data, in this case it would operate per feature vector and does not take account of class labels.
LDA maximizes Fishers discriminant ratio (or Mahalaobis distance), i.e. it maximizes the distance between classes.
If you define the feature vector for each observation (case) as the data at an instantaneous time point, then the temporal components of the data are not relevant. In this case you can apply PCA as pre-processing stage to each feature vector to reduce dimensionality prior to classification.
If however, you define each trial as a 10s epoch or segment around the point of interest, you could then calculate a summary statistic for each sensor across all time samples in the epoch. Each feature in your feature vector would then be a summary of the behaviour of each sensor over the 10s (e.g. mean amplitude across each 10s epoch). You could then apply PCA as pre-processing step to reduce the dimensionality of the feature vector from 306 to a more manageable number.
This second approach assumes that summary statistics calculated over each 10s epoch contains more information relevant to your problem than the instantaneous feature detailed above.
Comment: If anyone know of techniques which could exploit this property, that'd be great.  for example, provided the covariance matrix wasn't too non-stationary, perhaps I could estimate the covariance matrix for the LDA from many time points, and feed this to the classifier for a single time point?  the idea with using PCA was partly that since the PCA decomposition could be made over the entire dataset (all time points) that would 'implicitely' calculate the covariance matrix better than it can be estimated across trials at a single time only.  But perhaps that doesn't make sense!
Comment: Thanks @BGreene!  I am indeed classifying at instants in time.  With 306 features, I can get two-class classification accuracy of about 78% for one comparison of interest, using either Naive Bayes or regularized LDA.  However, I'm interested in making the most sensitive possible classifier (without overfitting!) as many effects of interest in the data are likely to be rather subtle.  Therefore, I was hoping to use the fact that I have a great deal more data than that from the precise time window of interest to my advantage - e.g. by permitting better estimation of the covariance matrix.
Answer: Your problem is most likely overfitting - it is typical when you use small datasets with large number of dimensions. In case of LDA what usually happens that the covariance matrix is biased because of the small sample. In order to avoid it you may try to use regularization. One useful technique is to sphere covariance matrix by adding small terms to the diagonal (also called shrinkage). In this case there is no need to use PCA. You can read about the technique in this paper on single trial EEG analysis.
Comment: Welcome to the site, @btel. There is no need to sign your posts, in fact, we'd prefer you don't. Your avatar is automatically added to every post, along with your user name hyperlinked to your userpage, & other info. Since you're new here, you may want to read our [about page](http://stats.stackexchange.com/about) & our [FAQ](http://stats.stackexchange.com/faq), which cover info like this.
Answer: I am doing the similar thing with neuronal spikes. Some papers I am following did PCA and selected components that explain 90% variance then did LDA, with the main purpose being "avoiding singular matrix", which to some extent makes sense, but can be avoided by "eigen solver" and "shrinkage".
There are 3 reasons why I chose not to do so:

very practically, your dataset is temporal, if you perform PCA at each epoch you lose the potential to compare the change across time (or at least harder). It's also harder to track back to individual neurons, but I think in your case it's not that important.
as is suggested by another answer, PCA may impair your decoding performance - it is unsupervised.
More importantly, I think scientifically it is interesting to see how different regions collectively give rise to a function. I don't think PCA before a classifier will help it.

while I'm typing this answer, I just thought of that people also pool the dimensions of trials and epochs together as sample dimension for PCA. If you perform PCA this way, then at each time point your components are not orthogonal, and you somehow still can compare different epochs.
Answer: BGreene's answer is a good one, but I would just add that it might make even more sense to go from PCA to the more closely related LDA classifier, which is Latent Dirichlet Allocation. As the name implies, it's a latent variable technique, like PCA. It's trending highly in the classification literature (I'm using it myself right now) particularly in text mining and unstructured data.
Using PCA then Fischer's LDA is statistically valid ceteris paribus, but it's not necessarily a good idea. Though I and plenty of other people do use linear discriminate in some contexts because it's so quick and easy, in most applications it's not a very statistically efficient or practically effective choice. As a classifier it often performs particularlly poorly; I usually run and rank many classifiers for any algorithm I'm building and linear discriminate is usually at the bottom of the list. It's poor performance may be the reason for needing PCA to reduce dimensional, but I would just choose a single, more appropriate classifier.
Comment: It's not obvious to me how latent Dirichlet allocation (topic modeling) could be applied here. The OPs data are continuous signals not categorical variables, so it's not clear what the "words" or the "documents" would be.


Apache Aliases On Windows 7

Question: Well, hi everybody. I'm trying to make aliases working on Apache & Windows 7.
So, this is what I have:
<IfModule alias_module>
Alias /TamasMobile/ "C:/Users/IssamTP/Documents/NetBeansProjects/TamasMobile/"
</IfModule>
<Directory "C:/Users/IssamTP/Documents/NetBeansProjects/TamasMobile/">
Options Indexes FollowSymLinks
DirectoryIndex index.html index.php
AllowOverride None
Order deny,allow
Deny from all
</Directory>

Loading website, leads to this error:
403 Forbidden
You don't have permission to access /TamasMobile/ on this server.

While the Apache Error log says:
[Tue Sep 07 00:49:29 2010] [error] [client 127.0.0.1] client denied by server configuration: C:/Users/IssamTP/Documents/NetBeansProjects/TamasMobile/

Yep, I can change the working directory to: ./htdocs/TamasMobile/ or do something similar, but I'd like to know how to fix this just for personal interest.
Thank you very much folks.
Answer: Surely the line:
Deny from all

is causing your problems. Drop that line and see if it works. What were you trying to do with the Deny from all? Typically the root directory has the strict Deny from all, and all the Alias have a more relaxed access. So for example:
<Directory />
    Options FollowSymLinks
    AllowOverride None
    Order deny,allow
    Deny from all
</Directory>

<Directory "C:/Users/IssamTP/Documents/NetBeansProjects/TamasMobile/">
    Order allow,deny
    Allow from all
</Directory>

Comment: Thank you! I guess that I should learn to read the documentation in a better way, even if the Apache one is not very clear...

Apache Aliases On Windows 7


Ionic 2 Alert issue

Question: I have a small issue with the basic alert. so here is my scenario.
-> I click the submit button on a page and if no record returned then it will give me a alert message. I click ok to dismiss that. -- Works fine.
-> I repeat the same scenario 2nd time by providing invalid input so that i don't get record back and application gives me same alert again. I click ok to dismiss the alert -- Doesn't work.
Can any on help on this??
Here is my code to fetch the records:
fetchGroupMembers(form) {
    //referring this to obj because scope of this is confusing in callback functions
    var obj = this;
    //creating loader
    let loading = Loading.create({
      content: "Please wait...",
    });
    //Showing loader on current screen
    obj.nav.present(loading);
    //Send message to server to fetch the group members
    obj.myGlobals.socket.emit('fetchGroupMembers', { groupCode: form.controls['groupCode'].value });
    obj.myGlobals.socket.on('groupMembers', function (result) {
      while (obj.students.pop()); //removing all elements from array of students
      //fetching each record and creating student
      result.forEach(function (record) {
        obj.students.push(new Student(record));
      });
      //on successfull fetch dismiss the loader
      loading.dismiss();
      if (obj.students.length > 0) {
        //set students to global
        obj.myGlobals.students = obj.students
        //navigating to next page with parameters
        obj.nav.push(HostPage, {
          Students: obj.students
        });
        console.log(obj.nav);
      } else {
        //creating alert
        obj.doAlert();
      }
    });

  }
  doAlert() {
    let alert = Alert.create({
      title: 'No Student Found!!',
      subTitle: "Please check group code. can't find students!!",
      buttons: ['OK']
    });
    this.nav.present(alert);
  }
}

If I call the doAlert() on a button click. it works like charm. I can't figure out the problem why it isn't working in my scenario.
Any help would be appreciated.
Thanks,
Comment: Could you please create a demo plunker so we can see what's going on?
Comment: I don't really know how to create the plunker for distributed code(client-server and server again further connected to mLab DB).
Comment: Seems I stumbled across a similar problem: first popup works fine, second cannot be dismissed. Submitted an issue: https://github.com/driftyco/ionic/issues/7554 Plunker here: http://plnkr.co/edit/kC2EtfmONmJ9UxPVXkJE?p=preview @BajinderBudhwar : Ionic bug report template has a handy link to an Ionic Plunker template you can use even if you don't want to submit an Ionic bug.
Answer: As discussed in the Alert class docs the proper way is to wait for the promise returned by the Alert.dismiss() call to resolve:
public TEST = () => {
    let alert1 : Alert = Alert.create({
    title: 'Prompt 1',
    message: "First",
    buttons: [{
      text : 'OK',
      handler : () => {
        console.log("First OK");
        alert1.dismiss().then(() => { // wait for the previous transition to finish or the following alert will malfunction
          let alert2 : Alert = Alert.create({
            title   : 'Prompt 2',
            message : "Second",
            buttons : [{
              text    : 'OK',
              handler : () => {
                console.log("Second OK");
                alert2.dismiss(); // DISMISSING MANUALLY
              }
            }]
          });
          this.nav.present(alert2);
        });
      }
    }]
  });
  this.nav.present(alert1);
};

Comment: Perfect example..!! really appreciate the help.. thanks
Comment: @BajinderBudhwar I'm glad it helped. An upvote and accepting the answer would be appreciated :)
Comment: doesn't work in ionic 2.. Any idea? It gives me `Uncaught (in promise): removeView was not found`
Comment: Sorry @Bla... I'm not on this project any more

Ionic 2 Alert issue


How to Set Hidden Form Field Values Permanently via Form Alter

Question: I have a webform that gets some hidden form fields set based on the referring URL.  Within hook_form_alter, I can successfully set the hidden values with $form[elements][NAME]['#value'].
function MODULE_form_alter(&$form,\Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

 //Get referring Program path/URL
 $previousUrl = \Drupal::request()->server->get('HTTP_REFERER');

 if ($form_id == FORM_ID) {

    $prog = getLeadProgramContact($previousUrl);
    $form['elements']['referrer']['#value'] = $prog->field_email->value;
    $form['elements']['program_name']['#value'] = $prog->getName();
     }
}

However, when the form gets submitted, it appears hook_form_alter is called again, breaking everything, since the referring URL is now itself.
How can I permanently set hidden field values on initial form render?  Anything I try with hook_form_alter seems to fail.  I have also tried "#default_value"
Comment: could you simply use a $_GET var ?  is this a webform submission
(as looks like it) ... if not have you thought of using "hook_entity_insert" ?
Answer: Ok webforms are a bit tricky ... but this will work i don't really care to set hidden fields just set the data direct to the entity.
if this is not a multy step form you could probably ad another submit handler in your form alter aka ...
function MODULE_form_alter(&$form,\Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
   if ($form_id === FORM_ID) {
     $submit[] = 'MODULE_form_alter_submit';
  }
}
// then
function MODULE_form_alter_submit(&$form,\Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
     // get the data you need.. via this ..
    $previousUrl = \Drupal::request()->server->get('HTTP_REFERER');
    $prog = getLeadProgramContact($previousUrl);
    // or ($_GET) or session or cookie whatever you chose.. Then set    it

    // GET the form Object.
    $webform_submission_object = $form_state->getFormObject();
    // GET the submission object.
    $webform_submission = $webform_submission_object->getEntity();
    // Optioanl default values if need to play with them ..
    $orig_data = $webform_submission->getOriginalData();
    // set form state
    $form_state->setValue('referrer', $prog->...);
    // set submission field value.
    $webform_submission->setElementData('referrer', $value);

    $form_state->setValue('program_name', $prog->...);
    $webform_submission->setElementData('program_name', $value);
    // Save it so it cant go away.
    $webform_submission->save();

  }
 }
}

Comment: T:  Tried this; still same deal, although it is updating the entity successfully.

All the docs I have read say that hook_form_alter gets called "before a form is rendered."  With Webform, it appears hook_form_alter gets called when submit is clicked, too.
Comment: I refactored and is working now.  Thanks, Taggart, for the insight!


Series $\sum\limits_{n=1}^\infty \frac{1}{\cosh(\pi n)}= \frac{1}{2} \left(\frac{\sqrt{\pi}}{\Gamma^2 \left( \frac{3}{4}\right)}-1\right)$

Question: I was playing around with Mathematica and found that
$$\sum_{n=1}^\infty\frac1{\cosh(\pi n)} = \frac12\left(\frac{\sqrt{\pi}}{\Gamma \left(\tfrac34\right)^2}-1\right)$$
Does anybody know how to prove this manually?
Answer: Here's a short sketch which I might further expand on later.
Consider the equivalent Lambert series
$$2\sum_{k=1}^\infty \frac{q^k}{1+q^{2k}}$$
with $q=\exp(-\pi)$.
This sum, through the use an appropriate geometric series, can also be expressed as
$$2\sum_{j=0}^\infty (-1)^j\frac{q^{2j+1}}{1-q^{2j+1}}$$
This sum can be expressed in terms of the Jacobi theta function $\vartheta_3(0,q)$. Using formula 57 in the previously given link, we have the expression
$$\frac{\vartheta_3(0,q)^2-1}{2}\tag{1}$$
Formula 45 in that same link gives the relation
$$\vartheta_3(0,\exp(-\pi))=\frac{\sqrt[4]\pi}{\Gamma(3/4)}\tag{2}$$
Substituting $(2)$ into $(1)$ gives the identity in the OP.
If you're interested in hyperbolic sums like these, you will want to see these three
papers.
Answer: This is by no means obvious. First, see the MathWorld page on Hyperbolic Secant.
There you will see that this identity is due to Ramanujan.
Namely, it follows from the Ramanujan cos/cosh identity.
To prove this manually, then, you may wish to read up on how this latter identity is established.
Comment: Thanks B.D! I had heard about  Ramanujan cos/cosh identity but did not know it could be used to prove this series.
Answer: it possible to gives
$$\sum _{k=1}^{\infty } \frac{1}{2 \cosh \left(\pi ^2 k\right)}=\frac{i \psi _e^{(0)}\left(1+\frac{i \pi }{2}\right)}{2 \pi }-\frac{i \psi _e^{(0)}\left(1-\frac{i \pi }{2}\right)}{2 \pi }+\frac{1}{4}+\frac{1}{4 \pi }$$


Using Stirling's Approximation to Find Maximum

Question: How can we use Stirling's approximation,
$$n!\approx\sqrt{2\pi n}(n/e)^n$$
to find the size/location of the max term in,
$$\sum_{n=0}^\infty\frac{x^n}{n! }$$
for any $x>0$.
I started off by writing the series in terms of Stirling's approximation,
$$y=\frac{x^n}{n!}\approx \frac{x^n}{\sqrt{2\pi n}\left(n/e\right)^n}$$
I'm guessing that when $n=1$, will be the max because $n!$ increases exponentially. Am I correct, or am I misinterpreting the question?
Comment: I think there must be an error in your question. The series the you have written down has no maximum since it is just the exponential function $e^x$ which has no max. https://en.wikipedia.org/wiki/Taylor_series#List_of_Maclaurin_series_of_some_common_functions
Answer: There is no need to use any approximation for this purpose.
For a given positive value $x$ the maximum term in the series will be when :
$$\frac{x^n}{n!}>\frac{x^{n+1}}{(n+1)!}$$
and
$$\frac{x^n}{n!}>\frac{x^{n-1}}{(n-1)!}$$
It is trivial to see that this occurs when $x>n$ and $x<n+1$
So the results is that  $\,x-1<n<x$
Clearly if $x$ is between 0 and 1, each term becomes smaller and smaller, so the first term ( which is $1$ ) will be the maximum.
For negative values the sign on each term alternates and this requires some other way to define the maximum term.  If you use the absolute value of each term then the result is the similar to the positive values results $|x|-1<n<|x|$.


Make classes work with jquery after updated by jquery

Question: I am currently working on a project, where I want to make a click on an object change a class and then afterwards making the next click depend on the same jquery.
I can only get it to work the first time - afterwards it won't work. My source is as follows:
<code>$(document).ready(function(){
    $("a.activate").click(function(){

        var elmid = $(this).attr('id');

        $.ajax({
            type: "POST",
            dataType: "json",
            url: "/advertisement/activate", // URL of the Perl script
            data: {adID: $(this).prev("input.ad_ID").val()},

            success: function(data){
                if (data.error) {
                    $('div#create_createresult').text(data.msg);
                    $('div#create_createresult').addClass("text-danger");

                    $("form#createForm input#createForm_submit").removeAttr('disabled');
                }
                else
                {
                    var src = $("a#" + elmid + " img").attr("src").replace("activate-16x16.png", "deactivate-16x16.png");
                    $("a#" + elmid + " img").attr("src", src);

                    $("a#" + elmid).removeClass('activate').addClass('deactivate');

                    $('div#create_createresult').text(data.msg);
                    $('div#create_createresult').addClass("success");
                }
            }
        });
    });

    $("a.deactivate").click(function(){

        var elmid = $(this).attr('id');

        $.ajax({
            type: "POST",
            dataType: "json",
            url: "/advertisement/deactivate", // URL of the Perl script
            data: {adID: $(this).prev("input.ad_ID").val()},

            success: function(data){
                if (data.error) {
                    $('div#create_createresult').text(data.msg);
                    $('div#create_createresult').addClass("text-danger");

                    $("form#createForm input#createForm_submit").removeAttr('disabled');
                }
                else
                {
                    var src = $("a#" + elmid + " img").attr("src").replace("deactivate-16x16.png", "activate-16x16.png");
                    $("a#" + elmid + " img").attr("src", src);

                    $("a#" + elmid).removeClass('deactivate').addClass('activate');

                    $('div#create_createresult').text(data.msg);
                    $('div#create_createresult').addClass("success");
                }
            }
        });
    });
});
</code>
My new source (as of Barbara's comment) is:
<code>$(document).ready(function(){

    $("a.activate").on( 'click', function(){

        var elmid = $(this).attr('id');

        $.ajax({
            type: "POST",
            dataType: "json",
            url: "/advertisement/activate", // URL of the Perl script
            data: {adID: $(this).prev("input.ad_ID").val()},

            success: function(data){
                if (data.error) { // script returned error
                alert("fejl");
                    $('div#create_createresult').text(data.msg);
                    $('div#create_createresult').addClass("text-danger");

                    $("form#createForm input#createForm_submit").removeAttr('disabled');
                }
                else
                {
                    var src = $("a#" + elmid + " img").attr("src").replace("activate-16x16.png", "deactivate-16x16.png");
                    $("a#" + elmid + " img").attr("src", src);

                    $("a#" + elmid).addClass('deactivate').removeClass('activate');

                    $('div#create_createresult').text(data.msg);
                    $('div#create_createresult').addClass("success");
                }
            }
        });
    });

    $("a.deactivate").on ( 'click', function(){

        var elmid = $(this).attr('id');

        $.ajax({
            type: "POST",
            dataType: "json",
            url: "/advertisement/deactivate", // URL of the Perl script
            data: {adID: $(this).prev("input.ad_ID").val()},

            success: function(data){
                if (data.error) {
                    alert("fejl");
                    $('div#create_createresult').text(data.msg);
                    $('div#create_createresult').addClass("text-danger");

                    $("form#createForm input#createForm_submit").removeAttr('disabled');
                }
                else
                {
                    var src = $("a#" + elmid + " img").attr("src").replace("deactivate-16x16.png", "activate-16x16.png");
                    $("a#" + elmid + " img").attr("src", src);

                    $("a#" + elmid).addClass('activate').removeClass('deactivate');

                    $('div#create_createresult').text(data.msg);
                    $('div#create_createresult').addClass("success");
                }
            }
        });
    });
});
</code>
Comment: Your revised code isn't using event delegation, it's doing the same think that `.click()` will do. Try the proper syntax for delegation: `$(document).on( 'click', 'a.activate', function(){`
Comment: You need event delegation.  Look at http://api.jquery.com/on/#direct-and-delegated-events
Comment: Yep, what @j08691 said.
Comment: possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements)
Comment: @BarbaraLaird: Thanks, but after changing the "click" to "on( 'click', " it still doesn't work. It is still performing the ajax regarding to the default class. Anything I could have forgotten?
Comment: @j08691: Of course - tried it before I edited. Thanks though - if I didn't realize it your comment was nice.
Have a nice day.
Answer: Thanks to Jason, Barbara and j08691 I came up with this solution, which should fit, if you're having the same trouble.
Beware that the $(document).ready() part is removed!
The answer to my question:
<code>$(document).on( 'click', "a.activate", function(){

    var elmid = $(this).attr('id');

    $.ajax({
        type: "POST",
        dataType: "json",
        url: "/advertisement/activate", // URL of the Perl script
        data: {adID: $(this).prev("input.ad_ID").val()},

        success: function(data){
            if (data.error) { // script returned error
            alert("fejl");
                $('div#create_createresult').text(data.msg);
                $('div#create_createresult').addClass("text-danger");

                $("form#createForm input#createForm_submit").removeAttr('disabled');
            }
            else
            {
                var src = $("a#" + elmid + " img").attr("src").replace("activate-16x16.png", "deactivate-16x16.png");
                $("a#" + elmid + " img").attr("src", src);

                $("a#" + elmid).addClass('deactivate').removeClass('activate');

                $('div#create_createresult').text(data.msg);
                $('div#create_createresult').addClass("success");
            }
        }
    });
});

$(document).on ( 'click', "a.deactivate", function(){

    var elmid = $(this).attr('id');

    $.ajax({
        type: "POST",
        dataType: "json",
        url: "/advertisement/deactivate", // URL of the Perl script
        data: {adID: $(this).prev("input.ad_ID").val()},

        success: function(data){
            if (data.error) {
                alert("fejl");
                $('div#create_createresult').text(data.msg);
                $('div#create_createresult').addClass("text-danger");

                $("form#createForm input#createForm_submit").removeAttr('disabled');
            }
            else
            {
                var src = $("a#" + elmid + " img").attr("src").replace("deactivate-16x16.png", "activate-16x16.png");
                $("a#" + elmid + " img").attr("src", src);

                $("a#" + elmid).addClass('activate').removeClass('deactivate');

                $('div#create_createresult').text(data.msg);
                $('div#create_createresult').addClass("success");
            }
        }
    });
});
</code>


Devise 404 errors on production server, No route matches {:controller=>"devise/home"}

Question: I'm getting devise 404 errors on a production server, both for get requests to /users/sign_in and its "link_to" equivalent.  If I copy development.rb to production.rb, I get the error:
No route matches {:controller=>"devise/home"}
This:

Works on my development box.
Doesn't work on the production box using either webbrick or passenger.

All other routes are working OK, but the devise routes are not.  I think I've read every stackoverflow and other google-fu link I can find twice, but no luck so far.
"Rake routes" output is below.  If I try the route that /users/sign_in GET resolves to, (i.e., devise/sessions#new), I get the error:  No route matches [GET] "/devise/sessions"
None of the following work:
link_to('Login / Register', new_user_session_path)
link_to('Login / Regsiter', :controller => "devise/sessions", :action => "new")
link_to('Login / Regsiter', :controller => "/devise/sessions", :action => "new")
link_to('Login / Register', '/users/sign_up')
I've seen some references to scoping issues, but I'll be darned if that makes any sense to me given the symptoms.  I'm completely stumped on this one.  Any ideas?
Contents of routes.rb and "rake routes" output follow:
<code>Aprojectx::Application.routes.draw do

  devise_for :users

  match "/people/test" => "people#test"

  resources :people    Aprojectx::Application.routes.draw do

  devise_for :users

  match "/people/test" => "people#test"

  resources :people

  resources :document_versions

  resources :documents

  resources :escrow_roles

  resources :escrows

  resources :tasks

  root :to => 'home#index'
  match "/specification" =>  'home#specification'
  match "/sales" =>  'home#sales'
end

  resources :document_versions
    Aprojectx::Application.routes.draw do

  devise_for :users

  match "/people/test" => "people#test"

  resources :people

  resources :document_versions    Aprojectx::Application.routes.draw do

  devise_for :users

  match "/people/test" => "people#test"

  resources :people

  resources :document_versions

  resources :documents

  resources :escrow_roles

  resources :escrows

  resources :tasks

  root :to => 'home#index'
  match "/specification" =>  'home#specification'
  match "/sales" =>  'home#sales'
end

  resources :documents

  resources :escrow_roles

  resources :escrows

  resources :tasks

  root :to => 'home#index'
  match "/specification" =>  'home#specification'
  match "/sales" =>  'home#sales'
end
  resources :documents

  resources :escrow_roles

  resources :escrows

  resources :tasks

  root :to => 'home#index'
  match "/specification" =>  'home#specification'
  match "/sales" =>  'home#sales'
end

root@escrowmaker:/var/www/apps/aprojectx# rake routes
             people_test        /people/test(.:format)                people#test
                  people GET    /people(.:format)                     people#index
                         POST   /people(.:format)                     people#create
              new_person GET    /people/new(.:format)                 people#new
             edit_person GET    /people/:id/edit(.:format)            people#edit
                  person GET    /people/:id(.:format)                 people#show
                         PUT    /people/:id(.:format)                 people#update
                         DELETE /people/:id(.:format)                 people#destroy
       document_versions GET    /document_versions(.:format)          document_versions#index
                         POST   /document_versions(.:format)          document_versions#create
    new_document_version GET    /document_versions/new(.:format)      document_versions#new
   edit_document_version GET    /document_versions/:id/edit(.:format) document_versions#edit
        document_version GET    /document_versions/:id(.:format)      document_versions#show
                         PUT    /document_versions/:id(.:format)      document_versions#update
                         DELETE /document_versions/:id(.:format)      document_versions#destroy
               documents GET    /documents(.:format)                  documents#index
                         POST   /documents(.:format)                  documents#create
            new_document GET    /documents/new(.:format)              documents#new
           edit_document GET    /documents/:id/edit(.:format)         documents#edit
                document GET    /documents/:id(.:format)              documents#show
                         PUT    /documents/:id(.:format)              documents#update
                         DELETE /documents/:id(.:format)              documents#destroy
            escrow_roles GET    /escrow_roles(.:format)               escrow_roles#index
                         POST   /escrow_roles(.:format)               escrow_roles#create
         new_escrow_role GET    /escrow_roles/new(.:format)           escrow_roles#new
        edit_escrow_role GET    /escrow_roles/:id/edit(.:format)      escrow_roles#edit
             escrow_role GET    /escrow_roles/:id(.:format)           escrow_roles#show
                         PUT    /escrow_roles/:id(.:format)           escrow_roles#update
                         DELETE /escrow_roles/:id(.:format)           escrow_roles#destroy
                 escrows GET    /escrows(.:format)                    escrows#index
                         POST   /escrows(.:format)                    escrows#create
              new_escrow GET    /escrows/new(.:format)                escrows#new
             edit_escrow GET    /escrows/:id/edit(.:format)           escrows#edit
                  escrow GET    /escrows/:id(.:format)                escrows#show
                         PUT    /escrows/:id(.:format)                escrows#update
                         DELETE /escrows/:id(.:format)                escrows#destroy
                   tasks GET    /tasks(.:format)                      tasks#index
                         POST   /tasks(.:format)                      tasks#create
                new_task GET    /tasks/new(.:format)                  tasks#new
               edit_task GET    /tasks/:id/edit(.:format)             tasks#edit
                    task GET    /tasks/:id(.:format)                  tasks#show
                         PUT    /tasks/:id(.:format)                  tasks#update
                         DELETE /tasks/:id(.:format)                  tasks#destroy
                    root        /                                     home#index
           specification        /specification(.:format)              home#specification
                   sales        /sales(.:format)                      home#sales
        new_user_session GET    /users/sign_in(.:format)              devise/sessions#new
            user_session POST   /users/sign_in(.:format)              devise/sessions#create
    destroy_user_session DELETE /users/sign_out(.:format)             devise/sessions#destroy
           user_password POST   /users/password(.:format)             devise/passwords#create
       new_user_password GET    /users/password/new(.:format)         devise/passwords#new
      edit_user_password GET    /users/password/edit(.:format)        devise/passwords#edit
                         PUT    /users/password(.:format)             devise/passwords#update
cancel_user_registration GET    /users/cancel(.:format)               devise/registrations#cancel
       user_registration POST   /users(.:format)                      devise/registrations#create
   new_user_registration GET    /users/sign_up(.:format)              devise/registrations#new
  edit_user_registration GET    /users/edit(.:format)                 devise/registrations#edit
                         PUT    /users(.:format)                      devise/registrations#update
                         DELETE /users(.:format)                      devise/registrations#destroy
</code>
Comment: Any answer on this?  I have the exact same issue when going to production.  Seems like my routes for Devise aren't being followed in production but work fine in dev
Answer: The answer -- turn on config.log_level = :debug in productiono.rb, then work from there.  Indeed, I had to add a leading forward slash to controller names starting with "home" in some of my layout partials.


How can I use Med7 and Negspacy simultaneously?

Question: I'm trying to use med7 and negspacy from Spacy but they both need separate version of spacy. How can i use both in the same script?
I'm using en_core_med7_lg from spacy to get disease, drug and other entities out of text
import spacy
import scispacy
from spacy import displacy
from spacy.matcher import PhraseMatcher
from spacy.tokens import Span
from negspacy.negation import Negex

med7 = spacy.load("en_core_med7_lg")

# create distinct colours for labels
col_dict = {}
seven_colours = ['#e6194B', '#3cb44b', '#ffe119', '#ffd8b1', '#f58231', '#f032e6', '#42d4f4']
for label, colour in zip(med7.pipe_labels['ner'], seven_colours):
    col_dict[label] = colour

options = {'ents': med7.pipe_labels['ner'], 'colors':col_dict}

negex = Negex(med7, ent_types=["DISEASE", "NEG_ENTITY"], name="negex",
              neg_termset={'pseudo_negations': ['no further', 'not able to be', 'not certain if', 'not certain whether', 'not necessarily',
                                                'without any further', 'without difficulty', 'without further', 'might not', 'not only',
                                                'no increase', 'no significant change', 'no change', 'no definite change', 'not extend', 'not cause', 'neither', 'nor'],
                           'preceding_negations': ['absence of', 'declined', 'denied', 'denies', 'denying', 'no sign of', 'no signs of', 'not',
                                                   'not demonstrate', 'symptoms atypical', 'doubt', 'negative for', 'no', 'versus', 'without',
                                                   "doesn't", 'doesnt', "don't", 'dont', "didn't", 'didnt', "wasn't", 'wasnt', "weren't", 'werent',
                                                   "isn't", 'isnt', "aren't", 'arent', 'cannot', "can't", 'cant', "couldn't", 'couldnt', 'never', 'neither', 'nor'],
                           'following_negations': ['declined', 'unlikely', 'was not', 'were not', "wasn't", 'wasnt', "weren't", 'werent', 'neither', 'nor'],
                           'termination': ['although', 'apart from', 'as there are', 'aside from', 'but', 'except', 'however', 'involving', 'nevertheless', 'still', 'though', 'which', 'yet', 'neither', 'nor']},
              extension_name='',
              chunk_prefix=[]
)
med7.add_pipe("negex", config={"ent_types":["DISEASE", "NEG_ENTITY"]})
text = """77 yo M pt here to discuss Heart rate and BP in office is 192/80 HR is 102 pt states at 3:15pm BP was 170/79 and HR was 114   Patient presented with wife C/o HTN, elevated HR, and Right flank pain Reported wife gave Lasix 20 mg BID in fear of water retention Pmhx CKD4 Sees Nephrology, last OV 5/2020, follow up scheduled 8/2020 Reported HR elevated 112 at home   Reported unable to afford clobetasol cream to treat psoriasis on scalp and elbows   PROBLEM  LIST: Patient Active Problem List Diagnosis   Diabetes mellitus     Aortic atherosclerosis     HTN (hypertension)   Diabetic neuropathy     Microalbuminuria   Diabetic peripheral vascular disorder     Diabetic nephropathy associated with type 2 diabetes mellitus     CKD (chronic kidney disease) stage 4, GFR 15-29 ml/min     Homocysteinemia     Refill clinic medication management patient   Anemia, chronic renal failure, stage 4 (severe)     Chronic systolic congestive heart failure     Anxiety   Hyperparathyroidism due to renal insufficiency     Hypertension associated with type 2 diabetes mellitus     Moderate episode of recurrent major depressive disorder     PVD (peripheral vascular disease)     History of prostate cancer   RUQ pain   Psoriasis    PAST MEDICAL HISTORY: Past Medical History: Diagnosis Date   BPPV (benign paroxysmal positional vertigo) 1/9/2019   Bradycardia 6/11/2019   CKD (chronic kidney disease) stage 3, GFR 30-59 ml/min   1/24/2019  GFR on 9/14/2018: 28 GFR on 11/13/2018: 34 GFR on 1/14/2019: 34 GFR on 05/21/2019 :34   CKD (chronic kidney disease) stage 4, GFR 15-29 ml/min   9/24/2018   Hospital discharge follow-up 12/9/2019   Prostate cancer   6/18/2018   Refill clinic medication management patient 5/13/2019   PAST SURGICAL HISTORY: Past Surgical History: Procedure Laterality Date   ANGIOPLASTY  08/02/2018  L leg   ANGIOPLASTY  06/13/2018  R leg   colonoscopy  05/26/2015  Internal hemorrhoids, otherwise normal   egd  05/26/2015  normal, mild chronic gastritis   FAMILY HISTORY: Family History Problem Relation Name Age of Onset   Cancer Son      testiular   Heart Disease Sister   Stroke Brother    SOCIAL HISTORY: Social History  Socioeconomic History   Marital status: Married   Spouse name: Not on file   Number of children: 3   Years of education: Not on file   Highest education level: Not on file Occupational History   Not on file Social Needs   Financial resource strain: Not on file   Food insecurity:   Worry: Not on file   Inability: Not on file   Transportation needs:   Medical: Not on file   Non-medical: Not on file Tobacco Use   Smoking status: Never Smoker   Smokeless tobacco: Never Used Substance and Sexual Activity   Alcohol use: Yes   Comment: Occasionally   Drug use: No   Sexual activity: Not on file Lifestyle   Physical activity:   Days per week: Not on file   Minutes per session: Not on file   Stress: Not on file Relationships   Social connections:   Talks on phone: Not on file   Gets together: Not on file   Attends religious service: Not on file   Active member of club or organization: Not on file   Attends meetings of clubs or organizations: Not on file   Relationship status: Not on file   Intimate partner violence:   Fear of current or ex partner: Not on file   Emotionally abused: Not on file   Physically abused: Not on file   Forced sexual activity: Not on file Other Topics Concern   Military Service Not Asked   Blood Transfusions Not Asked   Caffeine Concern Yes   Occupational Exposure Not Asked   Hobby Hazards Not Asked   Sleep Concern Not Asked   Stress Concern Not Asked   Weight Concern Not Asked   Special Diet Not Asked   Back Care Not Asked   Exercises Regularly No   Bike Helmet Use Not Asked   Seat Belt Use Not Asked   Performs Self-Exams Not Asked Social History Narrative   Not on file  Social History  Tobacco Use Smoking Status Never Smoker Smokeless Tobacco Never Used  Social History  Substance and Sexual Activity Alcohol Use Yes  Comment: Occasionally  Social History  Substance and Sexual Activity Drug Use No   Immunization History Administered Date(s) Administered   Influenza Vaccine (High Dose) >=65 Years 12/04/2018   Influenza Vaccine (Unspecified) 10/12/2012   Influenza Vaccine >=6 Months 10/12/2012   Pneumococcal 13 Vaccine (PREVNAR-13) 12/10/2015   Pneumococcal 23 Vaccine (PNEUMOVAX-23) 11/04/2009, 02/07/2014, 11/12/2016   Td 11/04/2009   Tdap 11/04/2009    CURRENT  MEDICATIONS: Current Outpatient Medications on File Prior to Visit Medication Sig Dispense Refill   cilostazol (PLETAL) 100 MG tablet TAKE 1 TABLET BY MOUTH TWICE A DAY 180 tablet 3   [DISCONTINUED] citalopram (CELEXA) 10 MG tablet Take 2 tablets (20 mg) by mouth daily. 90 tablet 3   [DISCONTINUED] citalopram (CELEXA) 20 MG tablet TAKE 1 TABLET BY MOUTH ONCE DAILY FOR DEPRESSION 90 tablet 3   [DISCONTINUED] clobetasol propionate (TEMOVATE) 0.05 % cream Apply to affected area twice a day 45 g 1   cloNIDine (CATAPRES) 0.1 MG tablet Take 1 tablet (0.1 mg) by mouth 3 times daily as needed (if SBP > 160). 270 tablet 3   clopidogrel (PLAVIX) 75 MG tablet TAKE 1 TABLET BY MOUTH EVERY DAY 90 tablet 3   [DISCONTINUED] epoetin alfa (PROCRIT) 10000 UNIT/ML injection Procrit 10,000 unit/mL injection solution   felodipine (PLENDIL) 10 MG tablet TAKE 1 TABLET BY MOUTH EVERY DAY 90 tablet 4   furosemide (LASIX) 20 MG tablet Take 1 tablet (20 mg) by mouth daily as needed (edema). 90 tablet 2   glipiZIDE (GLUCOTROL) 10 MG tablet TAKE 1 TABLET BY MOUTH TWICE DAILY FOR DIABETES 180 tablet 0   hydrALAZINE (APRESOLINE) 25 MG tablet TAKE 2 TABLETS BY MOUTH TWICE A DAY 360 tablet 1   [DISCONTINUED] hydrALAZINE (APRESOLINE) 25 MG tablet Take 25 mg by mouth 3 times daily.  4   Insulin Degludec (TRESIBA) 100 UNIT/ML SOLN 15 Units. 15 units   [DISCONTINUED] Insulin Degludec 100 UNIT/ML SOPN 15 units daily 9 mL 2   losartan (COZAAR) 50 MG tablet Take 1 tablet (50 mg) by mouth 2 times daily. Hold dose for systolic blood pressure less than 100. 180 tablet 3   Misc. Devices MISC C-pap setting at 9 cm H2O  Dx: Sleep Apnea 1 each 0   [DISCONTINUED] prazosin (MINIPRESS) 1 MG capsule Take 1 capsule (1 mg) by mouth 3 times daily. 90 capsule 11   simvastatin (ZOCOR) 20 MG tablet TAKE 1 TABLET BY MOUTH EVERY DAY 90 tablet 3  No current facility-administered medications on file prior to visit.  Outpatient Medications Marked as Taking for the 7/23/20 encounter (Office Visit) with Diaz, Anarella, NP Medication Sig Dispense Refill   Insulin Degludec (TRESIBA) 100 UNIT/ML SOLN 15 Units. 15 units   ALLERGIES: Allergies Allergen Reactions   Sulfa Drugs Swelling and Cough    REVIEW OF SYSTEMS: Review of Systems All other systems reviewed and are negative. refer to HPI   PHYSICAL EXAM:  07/23/20 1657 07/23/20 1718 BP: 192/80 160/80 Pulse: 102 86 Resp: 18 Temp: 99  F (37.2  C) SpO2: 96%  Body mass index is 27.28 kg/m .  Ht Readings from Last 1 Encounters: 07/23/20 5' 6" (1.676 m)  Wt Readings from Last 1 Encounters: 07/23/20 76.7 kg (169 lb)     Physical Exam Vitals signs and nursing note reviewed. Constitutional:    Appearance: Normal appearance. He is well-developed. HENT:    Head: Normocephalic and atraumatic. Eyes:    Conjunctiva/sclera: Conjunctivae normal. Neck:    Musculoskeletal: Normal range of motion. Cardiovascular:    Rate and Rhythm: Normal rate and regular rhythm. Pulmonary:    Effort: Pulmonary effort is normal.    Breath sounds: Normal breath sounds. Abdominal:    Palpations: Abdomen is soft.    Tenderness: There is no tenderness. There is no right CVA tenderness. Musculoskeletal: Normal range of motion. Skin:    General: Skin is warm. Neurological:    Mental Status: He is alert and oriented to person, place, and time. Psychiatric:    Mood and Affect: Mood normal.    Behavior: Behavior normal.    Thought Content: Thought content normal.    Judgment: Judgment normal.      ASSESSMENT & PLAN:  Luis was seen today for other.  Diagnoses and all orders for this visit:  RUQ pain Assessment & Plan: Active Negative abd exam Labs ordered VSS Stay hydrated Cont to monitor Follow up prn results  Orders: -     CBC w/ Diff Lavender; Future -     Comprehensive Metabolic Panel Green; Future  Psoriasis Assessment & Plan: Active Ordered Clobetasol solution apply ad Avoid allergens Stay hydrated Cont to monitor Follow up prn  Orders: -     clobetasol propionate (TMOVATE) 0.05 % solution; Apply 1 mL topically 2 times daily. Use a small amount as directed     ICD-10-CM ICD-9-CM 1. D71 pain R10.11 789.01 CBC w/ Diff Lavender    Comprehensive Metabolic Panel Green 2. Psoriasis L40.9 696.1 clobetasol propionate (TMOVATE) 0.05 % solution                """
doc = med7(text)
[(ent.text, ent.label_) for ent in doc.ents]

negated_concepts = []
for e in doc.ents:

    if e._.negex is True:
        negated_concepts.append(e.text.lower())
        print(e.text, e.label_)

print(negated_concepts)

Answer: No need for negex, just add your neg_termset to the pipeline config:
neg_termset={'pseudo_negations': ['no further', 'not able to be', 'not certain if', 'not certain whether', 'not necessarily',
                                                'without any further', 'without difficulty', 'without further', 'might not', 'not only',
                                                'no increase', 'no significant change', 'no change', 'no definite change', 'not extend', 'not cause', 'neither', 'nor'],
                           'preceding_negations': ['absence of', 'declined', 'denied', 'denies', 'denying', 'no sign of', 'no signs of', 'not',
                                                   'not demonstrate', 'symptoms atypical', 'doubt', 'negative for', 'no', 'versus', 'without',
                                                   "doesn't", 'doesnt', "don't", 'dont', "didn't", 'didnt', "wasn't", 'wasnt', "weren't", 'werent',
                                                   "isn't", 'isnt', "aren't", 'arent', 'cannot', "can't", 'cant', "couldn't", 'couldnt', 'never', 'neither', 'nor'],
                           'following_negations': ['declined', 'unlikely', 'was not', 'were not', "wasn't", 'wasnt', "weren't", 'werent', 'neither', 'nor'],
                           'termination': ['although', 'apart from', 'as there are', 'aside from', 'but', 'except', 'however', 'involving', 'nevertheless', 'still', 'though', 'which', 'yet', 'neither', 'nor']}

med7.add_pipe("negex", config={"neg_termset": neg_termset, "ent_types":["DISEASE", "NEG_ENTITY"]})


Bluetooth Low Energy: RFDuino is not detected

Question: I'm trying to program an App to establish a basic communication over BLE between an Android Phone and an RFDuino. The RFDuino is just advertising and can be detected by the "BLE Scanner" App.
Below is the draft code for the activity, that is supposed to detect BLE devices.
The problem is, that no devices are detected. The Debug Log shows, that the method "onLeScan" is not even called once...
I'm running out of Ideas and would be thankful for every hint :-)
package de.tuhh.et5.serialcommunicator;

import (...)

public class BLEActivity extends AppCompatActivity {
    private static final long SCAN_PERIOD = 10000;
    private int REQUEST_ENABLE_BT = 1;
    public final static String TAG = "BLE_Activity"; // Tag for the LOG

    private BluetoothAdapter ble_adapter;
    private boolean scanning;
    private Handler ble_handler;
    private BLE_DeviceListAdapter BLE_DeviceListAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        d("on Create");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ble);

        TabHost tabHost=(TabHost)findViewById(R.id.tabHost);
        tabHost.setup();

        TabHost.TabSpec t1=tabHost.newTabSpec("Tab1");
        t1.setContent(R.id.tab1_layout);
        t1.setIndicator("Devices");
        tabHost.addTab(t1);

        BLE_DeviceListAdapter = new BLE_DeviceListAdapter();

       ListView ble_list = (ListView)findViewById(R.id.BLE_DeviceListView);
        ble_list.setAdapter(BLE_DeviceListAdapter);

        ble_handler = new Handler();
        // get a bluetooth adapter from the bluetooth manager
        final BluetoothManager bluetoothManager =
                (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        ble_adapter = bluetoothManager.getAdapter();

        // Check if BLE is supported by the Android device
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            Toast.makeText(this, "BLE Not Supported",
                    Toast.LENGTH_SHORT).show();
            finish();
        }

        // Enable bluetooth
        if (ble_adapter == null || !ble_adapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }

    }

    // menu stuff
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        d("menu inflates");
        // Inflate the menu; this adds items to the action bar if it is present.
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.ble_menu, menu);

        if (scanning) {
            menu.findItem(R.id.scanning_start).setVisible(false);
        } else {
            menu.findItem(R.id.scanning_start).setVisible(true);
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.scanning_start:
                d("scan pressed");
                BLE_DeviceListAdapter.clear();
                ble_scan(true);
                break;
        }
        return true;
    }

    private void ble_scan(final boolean en){
        d("Scan start");
        // stopLeScan and startLeScan are deprecated since Android 5.0, but still work.
        // to offer a compatibility down to Android 4.3 the old methods are used
        if (en){
            ble_handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    d("scan timer finished");
                    scanning = false;
                    ble_adapter.stopLeScan(ble_callback);
                    invalidateOptionsMenu();
                }
            },SCAN_PERIOD);
            scanning = true;
            ble_adapter.startLeScan(ble_callback);
        }else{
            scanning = false;
            ble_adapter.stopLeScan(ble_callback);
        }
        invalidateOptionsMenu();
    }

    private BluetoothAdapter.LeScanCallback ble_callback = new BluetoothAdapter.LeScanCallback(){

        @Override
        public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord){
            d("onLeScan");
            runOnUiThread(new Runnable(){
                @Override
                public void run(){

                    BLE_DeviceListAdapter.addDevice(device);
                    BLE_DeviceListAdapter.notifyDataSetChanged();

                }
            });
        }
    };

    // This class lists the elements in an ble device entry as defined in "ble_device_entry.cml"
    // It is needed in the BLE_DeviceListAdapter class
    private class ViewHolder {
        TextView name;
        TextView device_id;
        TextView device_adress;
    }

    // #####################################################
    // private Class BLE_DeviceListAdapter
    //
    // Adapter to handle found BLE Devices
    // #####################################################

    private class BLE_DeviceListAdapter extends BaseAdapter{

        private ArrayList<BluetoothDevice> ble_devices; // holds found devices
        private LayoutInflater ble_inflater;            // layout inflater

        public BLE_DeviceListAdapter(){
            super();
            // Init
            ble_devices = new ArrayList<>();
            ble_inflater = BLEActivity.this.getLayoutInflater();
        }

        // method to add a device
        public void addDevice(BluetoothDevice ble_device){
            // device is added, if it is not already in the list
            if (!ble_devices.contains(ble_device)){
                ble_devices.add(ble_device);
            }
        }

        // Mandatory, returns device at position ...
        @Override
        public BluetoothDevice getItem(int position){
            return ble_devices.get(position);
        }

        // clear list..
        public void clear(){
            ble_devices.clear();
        }

        // Mandatory: Not needed, therefore just a dummy
        @Override
        public long getItemId(int i) {
            return i;
        }

        // Mandatory: returns size of list
        @Override
        public int getCount() {
            return ble_devices.size();
        }

        // Mandatory: creates and returns view with a device entry
        @Override
        public View getView(int i, View view, ViewGroup viewGroup ){

            ViewHolder viewHolder; // create view holder

            // if the view does not already exist:
            if (view == null){

                view = ble_inflater.inflate(R.layout.ble_device_entry, null);// inflate view
                viewHolder = new ViewHolder(); // create a ViewHolder
                // Connenct the ViewHolder elements to layout elements
                viewHolder.name = (TextView)findViewById(R.id.BLE_sName);
                viewHolder.device_adress = (TextView)findViewById(R.id.BLE_sAdress);
                viewHolder.device_id = (TextView)findViewById(R.id.BLE_sID);
                view.setTag(viewHolder); // Add the ViewHolder as a Tag to the view
            }else{
                // if the view already exists
                viewHolder = (ViewHolder) view.getTag(); // get Tag from view to populate ViewHolder
            }
            // get BLE Device
            Log.d("test", "hier so....");
            BluetoothDevice device = ble_devices.get(i);
            // get device name
            final String deviceName = device.getName();
            // assign device name to ViewHolder Object
            if (deviceName != null && deviceName.length() > 0){
                viewHolder.device_id.setText(deviceName);
            }else viewHolder.device_id.setText(R.string.unknown_ble_device);
            // assign more values
            viewHolder.device_adress.setText(device.getAddress());
            viewHolder.name.setText(R.string.unknown_ble_device);
            d("before return view");
            return view;
        }

    }
    // #####################################################
    // End Adapter
    // #####################################################

    public void d(Object msg) {
        Log.d(TAG, ">==< " + msg.toString() + " >==<");
    }

    public void e(Object msg) {
        Log.e(TAG, ">==< " + msg.toString() + " >==<");
    }

}

Answer: Ok, it seems i just messed up the permissions. I did not have the runtime permission for the location. I thought the manifest based permission are enough if one does not exclusevliy target Android 6.xx . Now I have problems with the view holder and stuff, but thats another Story :-).
Anyways thanks for the Solution @MarkusKauppinen!
Answer: The scanning code looks okay in my opinion.
Some things to check:
Did you debug/log to check that options menu works and ble_scan() gets called?
Did you debug/log to check that startLeScan() returns true?
The onLeScan() callback is not called if no devices were found.
Since you are scanning for 10 seconds, the RFDuino should advertise itself often enough/for long enough that at least one advertising cycle always occurs within the 10 second window.
All Android versions will need these permissions:
android.permission.BLUETOOTH

android.permission.BLUETOOTH_ADMIN

Additionally Android 6.x (Marhsmallow) and later also need:
android.permission.ACCESS_COARSE_LOCATION

And if you are writing code targeting just 6.x and higher you need to use the new runtime permission model instead of the old manifest file based.
On some devices running Android 6.x the system wide "Location" setting must be ON. See: onLeScan from BluetoothAdapter.LeScanCallback not called in Android Marshmallow
And then of course some of the older discussions may have some useful hints.
Comment: Hey! Thanks for the input! I'll look into it first thing tomorrow!
Comment: Hey! ble_scan is called, startLescan returns true, and all the permissions are set. onLeScan is still not called, and no device is listed. The RFDuino is advertising in intervalls of 500ms, and i can detect the RFDuino with other apps. I already (at least I think so :-) ) considered all threads dealing with this topic. Location service is on, and since I want a compabilitiy to Android 4.3, i use the manifest.


How the time signature affects how to play a melody

Question: I was playing on my clarinet the song Memory from the musical, Cats.  It is written in 12/8 time. Although I know what that means -- the equivilent of 12 eight notes in a bar, I don't understand how it affects the rhythm. Would I play it differently if it were 4/4 time?
Answer: Yes. Is there a difference between 2/4 and 4/4 explains this using 2/4 and 4/4. However, this is a little different because it is compound meter. 12/8 has four beats divided into three equal parts. It would be counted like this:

1 2 3 4 5 6 7 8 9 10 11 12

The primary accent is on the first beat, the secondary accent is on the seventh, and there are two subordinate accents on beats four and ten.
4/4 would be completely different because it is simple meter.

1 2 3 4

There are four beats with accents on the first and third. If Memory was arranged in 4/4 time, it would most likely be arranged in triplets (one set per beat). This would naturally change the accents to fall on the (original) first and seventh beats with the fourth and tenth being almost non-accented. Also, if played at the same tempo as the original, the beats' duration would be a third of the original.
This would give the piece a completely different feel assuming the conductor interprets it correctly.
Comment: I can accent as many beats as I want to in both 4/4 and 12/8.  Other time signatures too!
Comment: I disagree.  If you're playing in 12/8 at a tempo where it is reasonable to feel it in  4 (i.e. the dotted quarter note gets the beat), the end result is the same as if it was in 4/4 with each beat subdivided into triplets.  The difference is in the notation, and the choice is one of convenience.  They are equivalent.
Comment: I was assuming the beats would be divided into their natural durations. 4/4 will sound like 2/2 if each measure is divided into two half-notes.
Comment: @American Luke - your examples are fine, and the two are virtually the same. Every tune will accent slightly differently in response to the phrasing of the melody itself. Your two examples are showing that in 4/4 the accents are nearly the same as they would be if each of the 4 beats was split into triplets - as in 12/8.The subordinate emphases on 2 and 4 in 4/4 become those shown at 4 and 10 in 12/8.
Comment: 12/8 has four accented beats. 4/4 only has two. 12/8 will also have a more triplet-like feel to it.
Comment: ["an accent is an emphasis placed on a particular note, either as a result of its context or specifically indicated by an accent mark"](http://en.wikipedia.org/wiki/Accent_(music)). Context being the meter. Every time signature has conventional downbeats. E.g.: 3/4, `**1** 2 3`; 4/4, `**1** 2 *3* 4`;
Comment: I agree with charlieparker here - instead of 12/8, you could easily re-write the piece in 4/4 and notate all the eighths as triplets.  Just want to throw in that there are *several* ways to notate the same type of sound, and though it is inherently pointless to argue the merits of one method over another, the OP's question is good since it addresses performance tendencies of either.
Comment: "every time signature has conventional downbeats" -- your use of the term downbeat is incorrect and even if replaced with the correct term (accent) this explanation is simplistic and amateurish. "Context being the meter" -- this is a really superficial conception of context; there is so much more to context in music than meter and some have even argued that meter is inherently misleading and/or anathema to a rich conception of musical organization (e.g. Trevor Wishart, On Sonic Art).
Comment: The 12/8 emphasis you mention would imply duple time. It would rather be an emphasis every three quavers. 12/8 is quadruple time not duple.
Answer: There's a tricky subtlety in time signatures like 12/8, but I'll do my best to explain!
Unless it's in with some odd time signatures, 12/8 can be split up in a few ways if we disregard feel that I'll explore here, all having 12 8th notes (bear with me, there multiple parts to this answer)

3 groups of 4 eighth notes. (3/2)
this would mean that the way to think is in minims/half notes, 3 of them to be precise, because that's when each new group would begin.  However, the convention to mark 3 minims is 3/2 as the time signature. same notes and time, but a different stress.  here's how that would sound stress wise
Mem - - ry - - - All A Lone in the|Moon - - Light - -
6 groups of 2 eighth notes(6/4)
this would mean that the way to think is in crotchets/quarter notes, 6 of them to be precise, The in this case would be to mark 6 crotchets as 6/4.Like before, here's how that would sound.
Mem - - ry - - - All A Lone in the|Moon - - Light - -

note that in the above 2 options, the stresses fall in weird places, out of sync with the words. The song sounds very odd if the words you put stress on are "A" and "In"(though it does sound pretty funny). now for the difference between 6/8 and 12/8, which is more subtle
In Compound times like 6/8 and 12/8 we think of the beats in threes.  6/8 is 2 groups of 3 quavers/eighth notes or - 1 and a 2 and a. 12/8 is 4 groups of 3 quavers/eighth notes or - 1 and a 2 and a 3 and a 4 and a.
I know what you may be thinking, 12/8 is just 2 lots of 6/8.  At least that's how I thought about them for a long time!  look again at the stresses in bold that I've mentioned above.  the first one in each group is the 1st beat of the bar and the strongest.  the second is also a strong beat of the bar, but slightly weaker than the first.  In 4/4 This is the same thing the 1 and 3 in 1 2 3 4|1 2 3 4.
So now if we apply this heavy handed explanation of mine to the words, in 6/8 you would have:
mem - - ry - -| - All A Lone in the|Moon - - Light- - -| - - - - - -
and in 12/8 you would have:
mem - - ry - - - All A Lone in the|Moon - - Light- - - - - - - - -
The difference is, that in 12/8 your stresses happen less often, here giving the music a softer quality.  If you try emphasising on the bold syllables you'll find that the 12/8 stresses flow far more naturally than the 6/8 stresses do.
To take it one step further, perhaps into speculation, the Strongest first beat in 12/8 falls on the syllables Mem, and moon which are also the two longest held notes in the music.  In 6/8, they would also fall on Lone and Light which are intended to be shorter passing notes rather than spotlights.  From a lyrical perspective, lone and light are the weaker/less important ideas in the bar, so you put them on the weaker beats and make them shorter to give way for the stronger ideas.  Then the strong ideas get more space(in this case a dotted crotchet of more space!)
I hope that wasn't too ott of an answer, great question!
Answer: There is, in my opinion, and those of seasoned musicians I've discussed this with, no difference between the two as far as emphasis is concerned. Every tune will have its own 'feel' rhythmically, and apart from the 'standard'  - beat no. one is usually the most important/ emphasised  beat,12/8 is just a version of 4/4 with a triplet feel.
Often swing tunes are written out in 4/4 with the instruction at the head stating a triplet feel has to happen. If 12/8 was different, then why would they be written in 4/4 ? Probably to make life easier for both the writer and the reader.
Every muso. will have played tunes in,say, 4/4 that differed in the feel from one to another.Reggae, for example, is 4/4, but the feel is rather different from most other 4/4 tunes.
My answer may not be technically correct, but as far as practical playing and performance is concerned, there we are. Isn't that what this site is about ?
Comment: I think it depends on the composer also.  There's a song called king kong written by  Frank Zappa which is in 3/8.  For all intents and purposes it is essentially in 6/8 and would be just as easy to notate that way.  But he went to the trouble of making it 3 to get his point across about where the emphasis falls.   I imagine some composers are less strict about the time sig and some are more strict,  we'll need to ask Andrew Lloyd Webber!
Answer: At the risk of getting slated for extending the subject :-)
Look at the 5th bar of the melody.  The bar in 10/8 time.  This works beautifully IF you take notice of the tempo indication, dotted quarter = 50.  If, however, you choose too fast a tempo (as many do) it becomes an awkward oddity and you'll probably give up on it and slip back into 12/8.
And, all the rest of you - stop showing off!  Yes, 12/8 CAN be subdivided in all sorts of ways.  But we aren't playing a Hungarian folk dance, we're playing "Memory" from "Cats".  It's a slow 4 beats in the bar, each beat subdivided into three.  You could write it in 4/4 with triplet eighths, or in 12/8 with straight eights.  No difference whatsoever.
"Memory" chooses 12/8.  Beethoven, in the "Moonlight" sonata slow movement chooses 4/4 with triplets. (And look how he overlays a dotted-eighth, sixteenth rhythm in the melody. Maybe evidence that "Memory" is a good piece, "Moonlight" a great one?)
Comment: Look at an Urtext of Beethoven's "Moonlight" sonata and you'll see that it is really in 2/2 time -- the time signature is a C with a vertical line through it.  (Don't trust the von Bulow edition.)  It has two beats per measure -- two very slow beats, each with 6 triplets.
Comment: Not necessarily that slow.  This is an interesting slant - watch it all if you can stand Zander being over-charismatic, or cut to the chase around 23' 25"
https://www.youtube.com/watch?v=hZIC2f0fMKY
Comment: Beethoven is said to have played it at quarter note = 60.  At that tempo it becomes a funeral march, 30 bps.  There is a similar passage in Don Giovanni at about that tempo.
Answer: OK, first lets address the most basic part of your question - There is a mathematical difference between 4/4 and 12/8.  So no you cannot treat it as 4/4.  You could treat it as 3/2, but I'll get to that in a bit.  I'm thinking (hoping) you actually know this but mis-communicated.
For those who don't understand the math of music, the time signature is basically a fraction to show how many whole notes are in a measure.  You can do some division to reduce a time signature to it's most basic elements.  So 4/4 can be reduced to 1/1 (i.e. 1) which means one whole note per measure.  3/4 means 3/4ths of a whole note, 1.5 half notes (a dotted half note), or three quarter notes in one measure.  12/8, means 12 eighth notes, or six quarter notes, 3 half notes or 1.5 whole notes (dotted whole) in a measure.
As for the stylistic interpretation - the main reasons for leaving an "unreduced" fraction as the time signature are:

Common practice (everyone knows 4/4, who's heard of 1/1?) - clearly not the case for 12/8, but 4/4, 3/4, and 6/8 are fairly common.
To indicate what note is the "primary" note and all tempo indications are referring to.  i.e. 120 beats per minute in 12/8 is saying there are 120 eighth notes per minute, but in 3/2 would mean 120 half notes - 1/4 the speed.  Though this could also be reduced
Musicians are an odd lot and like to leave things in odd time signatures for the heck of it.  At least that sounds a lot better than saying they were tripping on something when they wrote it... OK, I'm mostly joking about that one.

Arguments about emphasis are completely false.  6/8 is commonly conducted in either 2 or 6 major beats and can be conducted in 1 or 3 also.  Even 4/4 often has the highest emphasis on 1 and secondary emphasis on 3, but can be 4 equal beats.  Really the style of emphasis should not be interpreted from the time signature.  If not spelled out in accents, that is usually divined from the style (march, waltz, etc.) and other artistic interpretation elements.
Comment: I do not think your "mathematical" claim is correct at all: time signatures are not fractions. 12/8 does not mean "12 divided by 8", it means 4 beats of 3/8 notes, i.e. dotted crotchets. Composers (Carl Orff for example) sometimes notate the time signature with the appropriate note symbol underneath, so this would be 4/(dotted crotchet). There are rare exceptions, but then the composer will usually add the different breakup: e.g. 4/8 : 3/8 : 3/8 : 2/8.
Comment: I'm not saying it means "12 divided by 8" but it can be viewed as a fraction.  What makes you think it's 4 beats of 3 eighth notes (assume that's what you meant)?  It could be 3 beats of 4 eighth notes or 12 beats of 1 eighth note (literally that's what it actually is).  That's why I list the various permutations of 6/8, which is much more common.
Comment: 4/4 time means 4 beats per measure and one beat is a quarter note.  3/4 time means 3 beats per measure and one beat = a quarter note.  6/8 time would be 6 beats per measure and one beat = 1/8 note so there would be six beats per measure.  I don't see how you can reduce 4/4 time to 1/1 time.
Answer: 12/8 is very much different from 4/4 time. Although they are both quadruple time the one (4/4) is simple quadruple time with one beat being a crotchet and the other is compound quadruple time with one beat consisting of a dotted crotchet.
This leads to pulses that are very much different. You would in compound quadruple time usually have emphasis on the first quaver of the dotted crotchet beat and in simple triple time, it would usually be the first quaver of a crotchet beat.
There is also in 4/4 time can be a emphasis on the first beat and third beat which you would not usually get with compound time signatures as that emphasis would imply dotted minim beats.
Answer: Meter has to do only with measurement. 8th note triplets in 4/4 time is identical metrically to 12/8 meter.
How you play the notes is a matter of context, preference or convention. There are many concurrent factors that can influence this.
Comment: That's silly. Convention might influence the interpretation of certain meters, but that doesn't make it a designation of "feel", whatever that means.
Comment: http://music.stackexchange.com/a/5625/1678. Meter is not only the measurement, but it defines the feel of the music. Perhaps a computer might interpret the two the same, but when played right, they will be accented differently.
Comment: For example, if I play three bars of music in 4/4 and the same music spread over four bars of 3/4, I will play the two phrases quite differently even though the notes are the same.
Comment: I maintain my disagreement with @American Luke, and side with tjb1982 on this one.  4/4 triplet feel = 12/8.  You'll often encounter music in 4/4 with a description to the effect of "12/8 afro-cuban feel" or "12/8 shuffle", and it is notated in 4/4 to make it easier to sight read.
Comment: @AmericanLuke This argument is weak. Study Guillaume de Machaut, Carnatic music (or even Brahms) for countless examples of why. In a word, isorhythm. Meter and accent are often correlated, but they are not by any means fixed.


How do I record my drums onto computer with roland td1kv?

Question: I am using Roland TD1KV electronic drum kit. The manual says that you can easily record your drums and transfer it into a computer using a "standard USB cable", "sold separately". What do they mean by "standard usb cable"? Unfortunately there are no videos of how to connect roland td1kv to your computer.
 This is what the manual says
<code>TheTD-1KV is not just fun to play by itself—it's also a great way to makemusic with your computer. Included is a built-in USB-MIDI interface,making it simple to communicate with music software via just a USBcable, with no extra hardware needed. Maybe you'll transfer your playinginto your computer-b
</code>
Answer: You will need a USB cable and some recording software.
There are several different types of USB cables as seen here
It looks to me that you need a type B on the drum end most likely a type A on the computer end.
Then you will need a midi capable recording program such as pro tools, finale, reason, etc.
Comment: Thanks. I use ubunut. Any midi capable program available on ubuntu?
Comment: I now use Ardour


hook_form_alter hiding field only in the form

Question: I have a content type with fields added from the core module and I want to hide some fields in the edit form, but not in the page node.
I've tried with
$form['my_field']['#access'] = FALSE; in my custom module, but that hides the field in the node page too.
Is there any other way to hide the field only in edit form?
My approach was to wrap some fields into a two columns. Here's what I've tried:
  <?php
    /*
     * Implements hook_form_alter().
     */

    function my_module_form_alter (&$form, &$form_state, $form_id) {
         switch ($form_id) {

          case 'custom_node_form':

          $form['column_left'] = array(
          '#prefix' => '
',
          '#suffix' => '
',
            );

           $form['column_left']['custom_field'] = $form['custom_field'];
           $form['custom_field']['#access'] = FALSE;
         break;
       }
    }

Unfortunately it's disabling into the page node too. I'm using Display suite for the full content and I'm pretty much sure that the field is not hidden from there.
Comment: case 'content_type_form': is mising ?
Comment: hook_form_alter cannot hide it on the node page
Comment: I forgot to copy that line, but in my module is already created. I have some difficulties in stackexhange with copying the codes and with the color codes. :)
Comment: @pico34 Somehow it's hiding in the node page too. Let's say when I'm adding a new content, filling the title field and when I save the content, the title is missing in the node page. If I remove $form['column_left']['title_field'] = $form['title_field'];
  $form['title_field']['#access'] = FALSE; it's ok, but the whole approach is to wrap the fields in columns.
Comment: I guess [this](https://drupal.org/project/field_hidden) module can help you.
Answer: Have you checked
admin/structure/types/manage/my_content_type/display

Your field is probably hidden here.
Otherwise, hook_form_alter is only for form you are right
An other attribute is :
$form['my_field']['#disabled'] = TRUE;

Comment: I'm using Display suite and the field is not hidden from there. I have a textfield and $form['my_field']['#disabled'] = TRUE; is only disabling the input form. Anyway I've added more info in my thread.
Answer: If you simply want it not to show on your edit form, modify your theme css file
.element_class {
  display: none;
}

Comment: bad idea if field is confidential, disable css reveals it
Comment: Yes, that's right. Using CSS is not the right solution in this case.
Answer: Use hook_form_alter to set the disabled property TRUE for the form field:
$form['field_name']['#disabled'] = TRUE;

Please refer to: Is it possible to hide fields on node edit form?


Find the Cosets of Subgroup $\langle 3 \rangle $ of $\mathbb{Z}$

Question: "A Book of Abstract Algebra" presents the following exercise:

Describe the cosets of the subgroups:
The subgroup $\langle 3 \rangle $ of $\mathbb{Z}$

Given that $H=\langle 3 \rangle $, I tried to figure out the cosets:
$$H=\lbrace 0,1,2 \rbrace$$
$$H+1=\lbrace 1,2,0 \rbrace$$
$$H+2=\lbrace 2,0,1 \rbrace$$
Since $H=H+1=H+2$, it seems to me that there's a single coset.
Please confirm, clarify or correct my attempt at figuring out the cosets of $\langle 3 \rangle$.
Comment: What makes you think that $H = \{0, 1, 2 \}$?
Comment: Is $<3>$ the same as $\mathbb{Z}_3$?
Comment: $\langle 3 \rangle$ in $\Bbb Z$  is the subgroup of all integer multiples of 3. It is not a finite set.
Answer: $H\ne\{0,1,2\}$, $H=\{3n:n\in\Bbb Z\}$. That should help.
Comment: So a sample of $H=\lbrace 0, 3, 6, ... \rbrace$. So, $H+1 = \lbrace 1,4,7,... \rbrace = \lbrace 1 \rbrace$. $H+2 = \lbrace 2, 5, 8 \rbrace = \lbrace 2 \rbrace$. At $H+3=H$. So, the cosets of $H$ are $H, H+1, H+2$. Is that right?
Comment: Yes, that's the idea.
Comment: Thank you. And `that's the idea` means it's correct? Could you please let me know if I'm not properly and fully answering the exercise? It's self-study, not homework for school.
Comment: Yes, This is correct.
Answer: $H$ is the subgroup generated by $3$, that is, the subset of $\Bbb Z$ of the numbers that can be obtained adding or substracting $3$. This is
$$H=\{\ldots,-9,-6,-3,0,3,6,9,\ldots\}$$


Can mayonnaise actually be a good instrument?

Question: Everyone knows what one iconic scene from SpongeBob, where Patrick asks Squidward a question:

Is mayonnaise an instrument?

To which he responds:

No, Patrick, mayonnaise is not an instrument.

I've already seen Context Sensitive use mayonnaise as an instrument in his song Karlson Vibe, but when used correctly, is it a good instrument? And if so, is it a good intro to drumming?
Comment: Whether a particular instrument is 'good' or not is a matter of opinion and those kind of questions are off topic.
Comment: There are better sauces of musical sounds than mayonnaise, surely? Tomtomato ketchup comes to mind... As well as bassic white sauce.
Comment: Welcome! Take a second to look over [the topics that are covered here](https://music.stackexchange.com/help/on-topic), and how to avoid [opinion-based answers](https://music.stackexchange.com/help/dont-ask). The problem with this question as-is is not the fact that it takes a silly idea seriously (yes, Squidward has an overly reductive and narrow-minded definition of "instrument"), but the word "good." If you'd like, you might be able to edit this into an on-topic question, by asking the sort of things that get fact-based answers, like "how should I splat the mayo to get the sound I want?"
Comment: How are we to know that the video linked here employs mayonnaise as an instrument?
Comment: @phoog Mayonnaise is used as a snare in the song, as shown here: https://www.youtube.com/watch?v=4-Dv53or4ZU.
Comment: [Maybe](https://www.youtube.com/watch?v=yiJUDIFu8dk).
Comment: I suppose the requito version would be mayonaiminorase?
Comment: Oh my goodness, that's disgusting.  Now I would like to know if you want a serious philosophical answer about the meaning of music and "found objects" in modern art and whatnot, or something else.
Comment: Have you ever tried getting a tune out of an egg banjo? [imnsho, this question is the merest hint above trolling & ought to be closed by now.]
Comment: I wonder if some kind of xylophone-like mayonnaise dipping instrument can be constructed from little cans with mayonnaise in it. You only need amplification, or a good hearing.. the resulting plop-plop sounds won't carry far, I suppose.
Answer: Just to be pedantic, the instrument on the video is a sampler in a DAW, and the "mayonnaise" part is a heavily processed sample of slapping a blob of mayonnaise on table.
Usually "drumming" is understood as the art of percussion by hitting objects with sticks or other implements, and since these are not involved I would not consider this a good introduction. Points for creative trolling and surviving for a hour without closing the question, though.
Comment: I was not even trolling, I was actually curious. I'm so weird.


Integration of mixed sin and cos functions - can't find it

Question: I can't remember the question that was posted around Feb 2nd,2022
I presume that it has been deleted by some reasons
The question was :
$$
\int \frac{\sin (\cos x)}{\cos(\sin x)} dx
$$
can anyone answer, or find the question?
*edit :
So my answer was (didn't signed it up) (well not "my" answer")
$$
\frac{\sin(\cos x)}{\cos x}\log_{e}|\sec (\sin x) + \tan (\sin x)|
$$
process :
let $$t = \sin x$$
then the question can be fixed as :
$$\int \frac{\sin (\cos x)}{\cos t} dx$$
also, $dt = dx \cos x$,
the question can be fixed again to :
$$
\int \frac{\sin(\cos x)}{\cos t} \frac{1}{\cos x} dt$$
$$= \frac{\sin(\cos x)}{\cos x}\int \sec t dt$$
$$= \frac{\sin(\cos x)}{\cos x}\log_{e}|\sec t + \tan t|$$

and finally,
$$\frac{\sin(\cos x)}{\cos x}\log_{e}|\sec (\sin x) + \tan (\sin x)|$$
am I right? If I am right, can I fix it easier? If I am wrong, why?
Comment: Check by differentiation! You take $\frac{\sin(\cos(x))}{\cos(x)}$ out of the  integral, but $x$ depends on $t$
Comment: Are you sure that the problem was not a definite integral (probably from $0$ to $\pi$)  ?
Comment: @MaximilianJanisch I fixed my question
Comment: @ClaudeLeibovici When I saw it lastly, it wasn't. The writer could have changed it
Comment: May I confess that your steps look strange (at least to me).
Answer: I do not think that your result is correct.
Being lazy, what I did is a series expansion of the integrand
$$\sin (\cos (x)) \sec (\sin (x))=\sin (1)+\frac{\sin (1)-\cos (1)}{2}  x^2-\frac{2 \sin (1)+5 \cos (1)}{24}x^4 +O\left(x^6\right)$$
Then, doing the same with your expression  and differentiating it,
$$\sin (1)+\frac{3(\sin (1)-\cos (1))}{2} x^2 +\frac{6 \sin (1)-25 \cos (1)}{24} x^4 +O\left(x^6\right)$$


How i can resolve this error, it will occur when i was called a function through button

Question: Error
" _ctx.hello is not a function
TypeError: _ctx.hello is not a function
at onClick._cache.<computed>._cache.<computed> (webpack-internal:///./node_modules/babel-loader/lib/index.js??clonedRuleSet-40.use[0]!./node_modules/vue-loader/dist/templateLoader.js??ruleSet[1].rules[3]!./node_modules/vue-lo
ader/dist/index.js??ruleSet[0].use[0]!./src/components/Home.vue?vue&type=template&id=8dc7cce2:11:55)
    at callWithErrorHandling (webpack-internal:///./node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js:285:18)
    at callWithAsyncErrorHandling (webpack-internal:///./node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js:293:17)
    at HTMLButtonElement.invoker (webpack-internal:///./node_modules/@vue/runtime-dom/dist/runtime-dom.esm-bundler.js:425:82) "

This is my code
<template>

Hello from Home component

    <button v-on : click="hello('hello call')">
        Click
    </button>

</template>

Answer: The property should be methods instead of method. It's an object that contains the methods you want to define for your Vue component. You have a comment block that's not properly closed in the template section.
Solution:
<template>

Hello from Home component

    <button v-on:click="hello('hello call')">Click</button>

</template>


Force directory hosting as a Client with index.htm present?

Question: I'm asking about the client side.
Is it possible to get a directory listing from an apache if I know listings are allowed but there's a index.htm in this directory?
Answer: You can remove index.htm from the DirectoryIndex directive.
Comment: I'm not in control of that Server. That's what I meant with client side.
Comment: In that case, no. It would be a pretty bad thing security-wise if the client could control what the server serves in that way.


How to do a disappearing elements for right side this same as it's working for left side

Question: I'm trying to make the overflow to the right hidden yet not working.
Basically, I want the items to be hidden when animated to the right just like animated to the left.

$("#left_btn").click(function(){
       $("#container").animate({
                left: '+=200px'
            }, 'slow');
    })

        $("#right_btn").click(function(){
        $("#container").animate({
                left: '-=200px'
            }, 'slow');
    })
#container{

  position: absolute;
  left: 180px;
  bottom: 150px;
  top: 40px;

}

#image_one_div {
  position: relative;
  float:left;

}

#image_two_div {
  position: relative;
  float:left;

}
#image_three_div{
  position: relative;
  float:left;

}

#image_one_div, #image_two_div, #image_three_div {

  width: 60px;
  height: 60px;
  background-color: red;
  margin-left: 3px;
}

<button id="right_btn">
left
</button>
<button id="left_btn">
right
</button>

Right now animations to the right make the items to go above one another. How can this issue be solved? I would appreciate any suggestions
Answer: You have to use overflow: hidden; for #container dom element and you have to set a right of #container by proper value for you. It has to work well.

$("#left_btn").click(function(){
       $("#container").animate({
                left: '+=200px'
            }, 'slow');
    })

        $("#right_btn").click(function(){
        $("#container").animate({
                left: '-=200px'
            }, 'slow');
    })
#container{

  position: absolute;
  left: 180px;
  right: 180px;
  bottom: 150px;
  top: 40px;
  overflow: hidden;
}

#image_one_div {
  position: relative;
  float:left;

}

#image_two_div {
  position: relative;
  float:left;

}
#image_three_div{
  position: relative;
  float:left;

}

#image_one_div, #image_two_div, #image_three_div {

  width: 60px;
  height: 60px;
  background-color: red;
  margin-left: 3px;
}

<button id="right_btn">
left
</button>
<button id="left_btn">
right
</button>

Comment: thanks that work on this case but when I applied the same method on my local project it didn't work.
Comment: you have to set a right for #container element too. I changed my answer. Check it out.