How to invoke autodialog module close method in autodialog.js file using ajax_command_invoke

Question: I have form that loads in modal using autodialog module and I have two buttons inside the form the close and save button. What I am trying to achieve is to just close the modal when the close button is clicked. I can do this using jQuery but what I wanted to do is use ajax_command_invoke to invoke autodialog close to close the modal. so far this what I have done, but I can't make it work maybe I am doing it wrong.

function example_autodialog_close_form_submit($form, &$form_state) {
  switch($form_state['clicked_button']['#value']) {
    case 'Closed':
      $commands[] = ajax_command_invoke('.autodialog-content', 'dialog', array('close'));
      break;
    case 'Save':
      // Insert data in database.
      break;
  }
  return array('#type' => 'ajax', '#commands' => $commands);
}

Using jQuery, this one work but what I wanted is use
  ajax_command_invoke to invoke auto dialog close.

$('#autodialog-close').click(function() {
  $('.autodialog-content').dialog('close');
});

Some code snippet in autodialog module autodialog.js file.

  Drupal.ajax.prototype.commands.autodialog = function (ajax, response, status) {
    var options = {
      title: response.title,
      width: 500,
      modal: true,
      closeText: Drupal.t('Close'),
      close: function () {
        $(this).dialog('destroy').remove();
      }
    };
    $.extend(options, response.options);

    // Close previous dialog
    if (options.closeprev) {
      $('.autodialog-content').dialog('close');
    }

    // Create dialog content
    var $dialogContent = $('' + response.content + '').appendTo('body');

    // Open dialog. Not $dialog.dialog() because it causes problems with inline scripts for jQuery 1.4.
    $('#' + response.dialog_id).dialog(options);

    // Remove focus from first tabbable element
    $dialogContent.closest('.ui-dialog').focus();

    // Close dialog when clicked outside
    $('.ui-widget-overlay:last').click(function (event) {
      if ($(event.target).hasClass('ui-widget-overlay')) {
        $dialogContent.dialog('close');
      }
    });

    Drupal.attachBehaviors($dialogContent);
  }
Comment: Can't see any problem with jQuery solution. Though would be good to do it the Drupal way. The code inside the snippet is also doing a Jquery implementation. So still I will consider the initial solution you posted above.
Answer: Finally I made it work.
Instead of using asaf module (This module is used to AJAX-ify form submissions) - not aware of this one, just notice it appending its own ajax class. thought that autodialog already made the submit button ajaxified. In combo with autodialog I make my form api submit button ajaxified.
here's my working code
Form submit buttons.

  $form['closed'] = array(
    '#type' => 'submit',
    '#value' => 'Closed',
    '#attributes' => array('class' => array('btn btn-block btn-default btn-sm')),
    '#ajax' => array(
      'callback' => 'ajax_example_submit',
    ),
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Save Changes',
    '#ajax' => array(
      'callback' => 'ajax_example_submit',
    ),
  );

Ajax callback

function ajax_example_submit($form, &$form_state) {
  $commands = array();
  switch($form_state['clicked_button']['#value']) {
    case 'Closed':
      $commands[] = ajax_command_invoke('.autodialog-content', 'dialog', array('close'));
      break;
    case 'Save Changes':
      drupal_set_message('Saved Changes');
      $commands[] = ajax_command_invoke('.autodialog-content', 'dialog', array('close'));
      break;
  }
  return array('#type' => 'ajax', '#commands' => $commands);
}


How can we increase tableview cell height based on UIfields content sizes

Question: Hi i am new for iOS and in my project i am adding two UIButtons and one UITextView on UITableViewCell and here UITextView is growing based on content size because data is coming from services.
My requirement is based on textSize - cell height must be increase for this. I have written some code but it's not working. What did i do here wrong? Please help me i have tried to do this since long time but i did not get result.
my code:-
- (void)viewDidLoad {
    [super viewDidLoad];

    tableList = [[UITableView alloc]init];
    tableList.translatesAutoresizingMaskIntoConstraints = NO;
    tableList.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    tableList.dataSource=self;
    tableList.delegate=self;
    tableList.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    [tableList registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
    [self.view addSubview:tableList];

    NSDictionary * views = NSDictionaryOfVariableBindings(tableList);

    NSArray * horizentalConstraint = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[tableList]-0-|" options:0 metrics:nil views:views];

    NSArray * verticalConstraint = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[tableList]-0-|"options:0 metrics:nil views:views];

    [self.view addConstraints:horizentalConstraint];
    [self.view addConstraints:verticalConstraint];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return 10;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return UITableViewAutomaticDimension
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *cellIdentifier = @"Cell";

    UITableViewCell *Cell =[tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    Cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];

UITextView * aboutText = [[UITextView alloc]init];
        aboutText.font = [UIFont fontWithName:@"Bitter-Regular" size:15.0f];
        aboutText.translatesAutoresizingMaskIntoConstraints = NO;
        aboutText.backgroundColor = [UIColor darkGrayColor];
        aboutText.scrollEnabled = NO;
        [Cell.contentView addSubview:aboutText];

        UIButton * button1 = [[UIButton alloc]init];
        button1.translatesAutoresizingMaskIntoConstraints = NO;
        button1.backgroundColor = [UIColor redColor];
        [Cell.contentView addSubview:button1];

        UIButton * button2 = [[UIButton alloc]init];
        button2.translatesAutoresizingMaskIntoConstraints = NO;
        button2.backgroundColor = [UIColor orangeColor];
        [Cell.contentView addSubview:button2];

        NSDictionary * views = NSDictionaryOfVariableBindings(aboutText,button1,button2);

        NSArray * formulaH = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[aboutText]-10-|"
                                                                     options:0
                                                                     metrics:nil
                                                                       views:views];

        NSArray * button1H = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[button1]-10-|"
                                                                     options:0
                                                                     metrics:nil
                                                                       views:views];

        NSArray * button2H = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[button2]-10-|"
                                                                     options:0
                                                                     metrics:nil
                                                                       views:views];

        NSArray * verticalspacing = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-5-[aboutText]-10-[button1(30)]-10-[button2(30)]"
                                                                            options:0
                                                                            metrics:nil
                                                                              views:views];

        [Cell.contentView addConstraints:formulaH];
        [Cell.contentView addConstraints:button1H];
        [Cell.contentView addConstraints:button2H];
        [Cell.contentView addConstraints:verticalspacing];

        aboutText.text = @"Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.";

return Cell;

}

Answer: This behaviour of tableview is called dynamic self sizing of tableviewcell. Set up your constraints of buttons and textview as given in picture. Disable textview scrolling.
Add the following in viewDidLoad()
tableView.estimatedRowHeight = 44.0;
tableView.rowHeight = UITableViewAutomaticDimension;

Comment: well i am not using here prototype cell and that to i am adding contraints programatically you please guide me in that way
Comment: Just try tableView.estimatedRowHeight and tableView.rowHeight in viewDidLoad(). Also don't forget to disable textview scrolling. You don't need to write heightForRowAtIndexPath method.
Answer: In nutshell, you need to implement heightForRowAtIndexPath: method, get reference to your model to get the text, calculate the text size and then return the height of the cell accordingly.
This blog will walks you through the programatic way of doing this.


SQLLoader Strange Behavior

Question: I am using sqlloader to import pdf files to the database as blobs. The control file is as follows
LOAD DATA
INFILE *
INTO TABLE pdf_files
APPEND
FIELDS TERMINATED BY ','
(
    pdfid   char(20),
    pdf_year     char(4),
    pdf_province    char(2),
    pdf_load_location       char(100),
    pdf_file        lobfile (pdf_load_location) TERMINATED BY EOF
)
BEGINDATA
test-form-en,2012,QC,/home/oracle/TestForms/forms/en/test-form.pdf,

Then I got error messages in the log:
Record 1: Rejected - Error on table PDF_FILES.
ORA-00001: unique constraint (SCOTT.SYS_C0011439) violated

I checked the constraint SCOTT.SYS_C0011439 as follows
select * from user_constraints where constraint_name='SYS_C0011439';

Then I found constraint SYS_C0011439 is actually on an irrelevant table 'T2032'. This table has nothing to do with table pdf_files which I want to import data. And the constraint is the not null check constraint.
Anybody knows why sqlloader gets some irrelevant table/constraint checked when I tried to load data to just one specific table? Thanks
Comment: This might be because of a foreign key

Can you please provide the complete output of :

select * from user_constraints where constraint_name='SYS_C0011439';
Answer: Got the same problem again and this time found the reason. There is already an data entry (blob with the specified pdf location) in the database for the rejected record.

SQLLoader Strange Behavior


Can not access the company web site

Question: Trust all you guys doing well today. I have a question.  My company website www.miracle-adventure.com cannot be accessed from within the company network.  I have a win2k8 R2 DC installed.  The domain is also miracle-adventure.com where server name is miracledc01.  Is there a way I can configure the users in the company network can access the company website.  The users can access other web sites without any issue....
Appreciate any assistance....
Comment: And that again proves why the [name of an AD domain](http://serverfault.com/questions/76715/windows-ad-domain-naming-recommendations/473530) shouldn't be set to your internet DNS domain name.
Comment: @HBruijn, Seriously? I never thought about that before... Thank you for pointing that out....do you have a "Solution"?
Comment: That link has actually quite a lot pointers about the hoops you have to jump through to make to deal with that bad design choice... Including: *This causes you to be forced to manually copy records from the Internet DNS (like `www`) into the Active Directory DNS zone to allow "external" names to resolve.*
Comment: @HBruijn, Tell me about it....& then You learn! :) Thanks again, I'll check
Comment: OK so all this are informative... How do I correct the issue presently I have at hand?
Answer: Hi guys so I manage to access our company web site despite our AD been the same.  I Installed Web Server Role and That took care of it.  Now every one can go to the our web site wit ease... :)

Can not access the company web site


What is the expectation of one random variable divided over another (both independent)?

Question: Suppose I have $X,Y$, which are independent random variables.
Why is it that $E(\frac{X}{Y}) = E(X)E(\frac{1}{Y})$?
Also, why is it that $E(X^2Y^2)=E(X^2)E(Y^2)$? How is it that the square of an independent random variable is also independent in relation to $Y$ or $Y^2$? Thanks!
Comment: Assuming that the expectations exist (cf. Paul Staab's comment on his answer), the [law of the unconscious statistician](http://en.wikipedia.org/wiki/Law_of_the_unconscious_statistician) gives $$\begin{align}E\left[\frac{X}{Y}\right]&=\int\int\frac{x}{y}f_{X,Y}(x,y)\,dx\,dy\\&= \int\int\frac{x}{y}f_X(x)f_Y(y)\,dx\,dy\\&=\int xf_X(x)\,dx\int \frac{1}{y}f_Y(y)\,dy\\&=E[X]E\left[\frac{1}{Y}\right]\end{align}$$
Comment: Let $W=\frac{1}{Y}$. Is $W$ independent of $X$?
Answer: Basically, if $X$ and $Y$ are independent, then also $f(X)$ and $g(Y)$ are independent if $f$ and $g$ are measurable functions:
$$\eqalign{
P(f(X) \in A,\ g(Y) \in B) &= P\left(X \in f^{-1}(A),\ Y \in g^{-1}(B)\right) \\
& =  P\left(X \in f^{-1}(A)\right) \ P\left(Y \in g^{-1}(B)\right) \\
& = P\left(f(X) \in A\right) \ P\left(g(Y) \in B\right).
}$$
In particular all continuous functions (like the $f(x)=1/x$ and $f(x)=x^2$ in your examples) are Borel-measurable, and hence also $X$ and $1/Y$ as well as $X^2$ and $Y^2$ are independent.
Comment: i have assumed your answer in my proof for the independence between $X$ and $Z$. Thanks!
Comment: Of course, this only holds when 'independence' and $1/Y$ are well defined, e.g. $X$ and $Y$ as well as $f(X)$ and $g(Y)$ live in the same space and $Y > 0$.
Comment: g(X) in the first paragraph of the answer should read g(Y)
Comment: @RossXV right, I corrected it. Thanks for spotting it.
Answer: let $Z=\frac{1}{Y}$, then we have:
\begin{equation}
E(XZ) = \int \int XZ p(X,Z) \mathrm{d}x \mathrm{d}z
\end{equation}
but $X$ and $Z$ are independent, so $p(X,Z) = p(X)p(Z)$ we have
\begin{equation}
E(XZ) = \int \int x .z . p(X=x).p(Z=z) \mathrm{d}x \mathrm{d}z
\end{equation}
which can be arranged as:
\begin{equation}
E(XZ) = \int x . p(X=x) \mathrm{d}x \int z.p(Z=z) \mathrm{d}z = E(X)E(Z)
\end{equation}
using the same argument you can show that $E(X^2Y^2) = E(X^2).E(Y^2)$
does that help?
Comment: I believe that "but $X$ and $Z$ are independent" is the statement the O.P. is asking about.  The answer by Paul Staab directly addresses that issue in full generality.


Does $\mathbb{F}_2$ have a finite free resolution as an $\mathbb{F}_2[\mathbb{Q}]$-module?

Question: If $k$ is a field with 2 elements and $\mathbb{Q}$ is the additive group of rational numbers, is there a finite resolution of $k$ as $R=k[\mathbb{Q}]$ module?
By "finite" I mean a chain complex $$X=  R^{n_1}\rightarrow R^{n_{2}}\rightarrow \dots \rightarrow R^{n_{j}}\rightarrow k $$
where $R^{n}$ is a free generated R-module of dimension $n$.

Edit: It will be fine if one can find a finite resolution of finitely generated projective $R$-module.
Comment: What action of $\mathbb{Q}$ are you considering on $k$? The trivial one?
Comment: @CaptainLama I use the standard augmentation homorphism $t: R\rightarrow k$ (homomorphism of rings), in particular the action of $Q$ on $k$ is trivial.
Comment: I assume you mean your chain complex to be exact and to start and end with $0$?  Otherwise such a chain complex exists trivially but doesn't have anything to do with what people would normally call a "resolution".
Answer: No.  Indeed, $k$ is not even finitely presented, so there does not exist any exact sequence $$R^m\to R^n\to k\to 0$$ where $m$ and $n$ are finite.  (Note that the existence of such a sequence with finitely generated free modules is equivalent to the existence of one with finitely generated projective modules, since a finitely generated projective module is a summand of a finitely generated free module.)
More generally, let us show that if $k$ is any nonzero commutative ring and $G$ is any group that is not finitely generated, then $k$ is not finitely presented as a $k[G]$-module.  It suffices to show that the kernel $I$ of the augmentation $k[G]\to k$ is not finitely generated.  Since $I$ is generated by the elements $g-1$ for $g\in G$, if it were finitely generated then it would be generated by finitely many such elements $g_1-1,\dots,g_n-1$.  Let $H$ be the subgroup of $G$ generated by $g_1,\dots,g_n$.  Let $M$ be the free $k$-module on the coset space $G/H$.  The left action of $G$ on $G/H$ gives a $k[G]$-module structure on $M$, with the quotient map $G\to G/H$ of $k$-sets inducing a surjective $k[G]$-module homomorphism $f:k[G]\to M$.  Moreover, $h-1$ is in the kernel of $f$ for all $h\in H$, so the kernel of $f$ contains $I$ so $f$ induces a surjective homomorphism $k\cong k[G]/I\to M$.  Since $k$ is free of rank $1$, this means $M$ is free of rank at most $1$.  But $M$ is free on $G/H$, so we must have $H=G$.  Since $H$ was generated by $g_1,\dots,g_n$, this means $G$ is finitely generated.
Comment: In the second part, I'm using the fact that if a module is finitely presented (say by generators $A$ with relations $B$), then any finite generating set $A'$ has a finitely generated set of relations.  This is just because it suffices to give the relations $B$ when you express each element of $A$ in terms of $A'$, plus relations that say each element of $A'$ is what you get by first writing each element of $A$ in terms of $A'$ and then writing each element of $A'$ in terms of those elements of $A$.
Comment: (This argument is extremely general and works for any sort of algebraic structure--if one finite presentation exists, then for *any* finite generating set you only need a finite set of relations.)
Comment: Your comment is effectively a proof of Schanuel's lemma, in the case of free modules!  I see that it is intuitive enough that you might want to omit it.
Comment: It is a good thing I never thought of your proof 20 years ago when I started my PhD.  A lot of my early papers were based on a technique that I came up with while justifying Schanuel's lemma to myself a different way!


Bruteforce word generator using ascii table and one loop

Question: How can I create a 'word generator' - in java - that gives me all possible combination of characters within a range of the ascii table and with a certain length or less.
What I did so far is an absolut mess and not a nice solution. It can generate me words in a range of characters (in this example from 48 to 57) but it has a fixed word length of 4.
for (int i = 48; i < 58; i++) {
    for (int j = 48; j < 58; j++) {
        for (int k = 48; k < 58; k++) {
            for (int l = 48; l < 58; l++) {
                String bruteword = "" + (char) i + (char) j + (char) k + (char) l;
            }
        }
    }
}

I hope you guys understand what I mean. Sorry for mistakes, always hard for me to express such stuff in english.
Answer: Recursion could help here. Suppose you say that words(min, max, n) gives you a list of all words n long with characters between min and max. You can implement that by saying that if n = 0, the only word is the empty string; otherwise, you have all the words made by appending each possible character to words(min, max, n - 1).
List<String> words(char min, char max, int n) {
   List<String> ret = new ArrayList<String>();
   if(n == 0) {
      ret.add("");
      return ret;
   }
   for(String word : words(min, max, n - 1)) {
      for(char c = min; c <= max; ++c) {
         ret.add(word + c);
      }
   }
   return ret;
}

Edit:
Iterative solution that also generates all possibilities less than the requested length:
List<String> words(char min, char max, int n) {
   List<String> ret = new ArrayList<String>();
   ret.add("");
   int start = 0;
   for(int length = 1; length <= n; ++length) {
      int end = ret.size();
      for(int i = 0; i < end; ++i) {
         for(char c = min; c <= max; ++c) {
            ret.add(ret.get(i) + c);
         }
      }
      start = end;
   }
   return ret;
}

Edit:
If you don't want to save the words, you definitely need recursion, because you are basically using the stack in place of the list:
void words(char min, char max, int n) {
   for(int i = 0; i <= n; ++i) {
      wordsRecursive("", min, max, i);
   }
}

void wordsRecursive(String base, char min, char max, int n) {
   if(n == 0) {
      System.out.println(base);
   } else {
      for(char c = min; c <= max; ++c) {
         wordsRecursive(base + c, min, max, n - 1);
      }
   }
}

Comment: (For that matter, you don't even really need recursion; you could wrap this all up in a loop from 0 to n, starting with the base case list)
Comment: hey thanks alot. You are awesome pal. Is there any possiblity to do it without the ArrayList? I do not need to save those words really, just to check them against another word and then throw them away. But I really do appreaciate the effort!
Comment: Thanks alot. guess I will stick to the solution with the iteration. Thanks for your work! You helped me out alot! Internet cookies for you.


app:cornerRadius doesn't work for MaterialButton

Question: <com.google.android.material.button.MaterialButton
            android:id="@+id/button_tour"
            app:cornerRadius="20dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginHorizontal="30dp"
            android:layout_gravity="center_horizontal"
            android:text="Take a tour"/>

I added a material button in my android project, when i try to set round corner using app:cornerRadius, i find it doesn't work at all.
Comment: give some height and width to your button
Comment: You can write style for this
Answer: Just use material theme .change parent of AppTheme in styles to some  material theme likeTheme.MaterialComponents.Light.NoActionBar.because material components require a material theme.

Comment: That works! Thank you so much! It has confused me a whole day.
Answer: Try this:
add this style for outline material button

then add this style to your button:
    <com.google.android.material.button.MaterialButton
    android:id="@+id/button_tour"
    style="@style/Widget.MaterialComponents.CardView"
    app:cornerRadius="20dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginHorizontal="30dp"
    android:layout_gravity="center_horizontal"
    android:text="Take a tour"/>

Answer: Create a new drawable source such as follows
<shape android:shape="rectangle">

     <corners android:radius="20dp" />

</shape>

and set it as background to your MaterialButton
Comment: The question is about MaterialButton - this answer is for classic Android Button


How to pass project number to manifest.json

Question: I am building a web push WordPress plugin and I want to pass project number from form input field to manifest.json file
which is included in index.php as
<link rel="manifest" href="/manifest.json">

Answer: Disclaimer: I'm the author of this plugin.
Instead of building your own from scratch, you could contribute to the already existing https://github.com/mozilla/wp-web-push.
If you want to build your own, you can check the source of that plugin out to see how we have implemented it.
We've built a class to handle it: https://github.com/marco-c/wp-web-app-manifest-generator.
Answer: You cannot pass any param to the manifest.json. You must genarate it as a static file when the form is submitted.
Here's the code that we have used for the Pushpad plugin:
if (file_exists ( ABSPATH . 'manifest.json' )) {
  $oldManifestJson = file_get_contents ( ABSPATH . 'manifest.json' );
} else {
  $oldManifestJson = '{}';
}
$data = json_decode ( $oldManifestJson, true );

$data ['gcm_sender_id'] = $settings ['gcm_sender_id'];
$data ['gcm_user_visible_only'] = true;
$newManifestJson = json_encode ( $data );
if ( is_writable ( ABSPATH . 'manifest.json' ) || !file_exists ( ABSPATH . 'manifest.json' ) && is_writable ( ABSPATH ) ) {
  file_put_contents ( ABSPATH . 'manifest.json', $newManifestJson );
} else {
  // display an error
}

Comment: BTW If you don't want to build from scratch and you are ok to use a service like Pushpad, feel free to fork the project on Github (https://github.com/pushpad/pushpad-wordpress) and add your improvements. I'd also be happy to merge any pull request on the main repo
Comment: But I just want to send custom notifications from admin side of the plugin send notification page
Comment: A suggestion, with this code you can't support all possible WordPress configurations (many installations can't write files directly). You might want to use the class that I mentioned in my reply or build your own manifest generator on top of the class https://github.com/marco-c/WP_Serve_File, or draw inspiration from the code in WP_Serve_File.


Counting the number of unique formulas in an excel sheet

Question: I have a big workbook with 50+ worksheets and I would like to count the number of unique formulas in the workbook. I used the inbuilt to find option to find '=' but this returns duplicate formulas due the drag option in excel. Any ideas would be appreciated.
Thanks.
Answer: This is a sliiightly different answer than you may be expecting, but if you go to the FORMULAS ribbon, -->Formula Auditing section --->Show Formulas, it will change all cells so that they display what's actually in the formula bar, instead of what the simplification of that formula is.
Using this is often the simplest way to check for what formulas are actually present in a workbook.
As for counting the 'unique' formulas you are using, that's possible, but could you clarify why you want it? What will you be using that information for? If you explain your needs a little more clearly someone could likely provide a more useful solution.
Comment: Also, define "UNIQUE" formula. ie: is "=A1+B1" the same in your mind as "="B1+B2?" Or are you looking to see which FUNCTIONS are being used? Like, you want to know that somewhere uses VLOOKUP, and somewhere uses SUMIFS, etc.
Comment: thanks for the help. I would like to know how many formulas I have so as to make a rough estimate as to how many lines of equivalent lines of mathematica code I would need if I were to rewrite all the formulas. In my case A1+ B1 is similar to B1+B2.


Django crispy-forms dynamic label_class and field_class

Question: I'm trying to create a form layout with a few fields that are of a different size than the other fields.  What is the best way to do this using crispy-forms?
For example, I'm laying out the form in rows where most of the rows have two fields but occasionally a single field will occupy the whole row.
--------------------------------------------------
| First Name            | Last Name              |
--------------------------------------------------
| User Name             | Email                  |
--------------------------------------------------
| Bio                                            |
--------------------------------------------------

In the example layout above, each field is composed of a label and the text input in the actual HTML (I just didn't know how to show this in the question).  I'm using Bootstrap 3 so on the first two lines I want the labels to have a class of 'col-sm-2' and the input fields to have a class of 'col-sm-4' so that when rendered, they show up with two fields per row (i.e. 12 columns).  However, for the third row with the "Bio" field, I want the input field to be "col-sm-10' to take up the whole row.
Here is some sample code that is close enough that someone may be able to help.
self.helper = FormHelper(self)
self.helper.form_tag = False
self.helper.form_class = 'form-horizontal'
self.helper.label_class = 'col-sm-2'
self.helper.field_class = 'col-sm-4'
self.helper.layout = Layout(
    MultiField(
        'Profile Information',
        Div('first_name', 'last_name'),
        Div(css_class='clearfix'),
        Div('username', 'email'),
        Div(css_class='clearfix'),
        Div('bio', css_class='col-sm-10'),
    ),
)

I've tried using several different combinations of Div, Field, and Row and using combinations css_class and wrapper_class as well as trying to create "custom" attributes but nothing works to give me the layout that I want.   I've even tried several different combinations of nested Div(Field) type structures but nothing worked.
There doesn't seem to be a way to dynamically change the helper.field_class for just the "Bio" field row.  It seems really wrong to resort to using the HTML method but that's all I can think to do for this as this point.
What is the right way to do this using crispy-forms?
Answer: I have a similar function (designed for bootstrap 2) that gets you part of the way there; it doesn't work with horizontal-forms like you requested, but you are able to generate dynamic rows:
from crispy_forms import helper
from crispy_forms import layout

def addBootstrapRow(helper, firstField, numFields, wrapperClasses):

        # set classes used for all fields if only one provided
        if type(wrapperClasses) in [str, unicode]:
            wrapperClasses = [wrapperClasses]*numFields

        # find first field, apply wrapper_class for each
        first = helper.layout.index(firstField)
        for i, cls in enumerate(wrapperClasses):
            helper[first+i].wrap(layout.Field, wrapper_class=cls)

        # put all these fields into a row
        helper[first:first+numFields].wrap_together(layout.Div, css_class="row-fluid")

To get a format similar (but not identical) to the one in your question, you can do this:
class MyForm(ModelForm):

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.helper = helper.FormHelper(self)
        addBootstrapRow(self.helper, 'first_name', 2, "span6")  # all fields same
        addBootstrapRow(self.helper, 'username', 2, ["span4", "span8"])  # fields diff.
        addBootstrapRow(self.helper, 'bio', 1, "span12")

Might not your exact solution, it may help others that stumble upon this question at least (like me).
Answer: Problem
From what I have found, there isn't any simple solution to this problem.
In 2014, a GitHub issue regarding setting the label_class individually for each field was created. However, this issue was closed by the crispy forms developers as out-of-scope.
In 2021, a GitHub pull request with changes allowing label_class and field_class on individual fields was created. However, this PR was closed due to inactivity of the PR author.
Possible solutions
The answers in this question may help you with the problem. One possible solution could be to create a custom field template - see this answer.


How can I delete nodes when an arbitrary date has past?

Question: I have a situation where future events will be posted to the website in question. These future events are a content type with a date field using the date module.
I wish to automatically delete these events once their date has past. I'm assuming that rules should do this but I have searched and I am struggling to find a way to do this.
Comment: Is it important to delete or would un publishing be ok. If so check the 'scheduler' module.
Answer: You can use the hook_cron to solve your problem
<code>function mymodule_cron(){
  _mymodule_delete_nodes();
}

function _mymodule_delete_nodes(){
  //select all nodes from type X where date expired
  //node_delete($nid);
}
</code>
See hook_cron for further information


Piano For a Tight Budget

Question: I really want to learn to play the piano, but an actual piano is too expensive for me, plus I don't have enough space for one.
What is the best replacement for a piano? I mean, what other instrument can I get that is similar enough to a piano, but not as big and costly? A keyboard?
Thanks a lot.
Comment: If you don't need to move it around, a standard electric piano should be an option.  They're not bigger than a full keyboard.
Comment: Please edit to add more details. You mention space and money constraints, actual numbers would help. I like the answers and I want the question to be better.
Comment: Perhaps a [stage piano?](http://en.wikipedia.org/wiki/Stage_piano)
Comment: You should definitely buy a stage piano if you have the money, but I'd also recommend trying to find a place to practice that already has a piano, if possible. There might be a college willing to let you rent a key to one of their practice rooms or something. (It's probably a stretch, but worth a shot.)
Comment: I don't think stage pianos are compatible with "tight budget", in general. Ruggedness and high quality sounds add to the cost.
Answer: Electric piano should do the trick. Make sure it has "weighted" or "Hammer Action" keyboard so it feels mechanically similar to a real piano. Other nice features would be

Decent pair of build in speakers so you don't need an external amplifier (for home)
Headphone jack so you can practice at night with driving the family nuts
Drum machine and/or sequence build in so you can play along "in-time" and have a build in metronome
Reasonable light weight so you can take it along and play with other people (unless you want "piece of furniture")

Yamaha, Kawai, Kurzweil, etc. are all good choices (no endorsement intended, just some pointers)
Comment: I'd like to suggest Roland. While Yamaha still works with tone sampling, Roland uses algorithms to simulate what a real piano would sound like. Good answer though.
Comment: Do you know what an "electric piano" is? It has actual strings inside and pickups. Google for "Fender Rhodes" for instance. Synthesizers often have an "Electric Piano" patch (perhaps more than one) since it's one of the sounds sought after by keyboard players (or needed to reproduce the keyboard sound heard in some classic tune).
Answer: I'm going to assume you're on a really tight budget, and that you're a complete beginner.
Get on eBay, Craigslist, your local small ads paper, etc. and look for a second hand electronic keyboard.
Don't worry about high quality piano sounds. Don't worry about weighted keys.
Do make sure the keys aren't stupidly small. Do make sure there are at least 60 keys. Do make sure it's "velocity sensitive" (that is, hitting a key harder makes a louder sound).
You should be able to find something for under US$50, and probably much less. There are 20-year-old keyboards that will be good enough for your immediate needs, as long as they're not broken.
A "keyboard controller" may be a good compromise for you, but be aware what you're getting into. These do not make a sound themselves - they send signals to a computer or a midi device. However, that means they can be cheaper, if you already have a computer that you're happy to use for the purpose. One downside of this is that there can be preparation time (plugging the keyboard in, booting the computer, loading the music software), that gets in the way of spur-of-the-moment practice.
This instrument would not be a good substitute for a piano in the long run, but it will let you get started on learning the basics. You should borrow time on other people's real pianos (school/church/teacher/friends/etc.), so you know the differences between your "toy" practice instrument and a real piano.
While you're practising and learning with your electronic keyboard, save up some money towards a "serious" instrument.
Alternatively, you may find you can make the music you want using an electronic instrument, and there's nothing wrong with that.
Comment: Going second hand is a great suggestion. But if your aim is to learn piano (as opposed to keyboard synth) then I would say a full-sized weighted keyboard is essential, otherwise you will be learning the wrong touch from the beginning. I would also avoid anything with less than 76 keys but most weighted keyboards will have at least 76 keys anyway.
Answer: An electric or digital piano is a good choice. Here are some key points you need to know:

Go for the largest number of keys (88 keys is the standard).
A hammer-action/weighted feature is very important since most training, such as the Hannon exercises, are traditional and include proper hand gestures, positions, etc.  Here for more info.
A built-in metronome is also very important.  But no worries, almost all e-pianos today have metronome installed on it.
Velocity sensitivity - the harder you press, the louder it sounds.

NOTE: BEWARE OF CONTROLLER KEYBOARDS Unless you are familiar with them and know how to use them, then avoid controller keyboards.  But learning how to use them has a lot of technicalities that you should know --they are not your typical "Plug-and-Play" keyboards.
http://madsenstudios.com/info/a-guide-to-buying-an-digital-piano/
Answer: Some advice -- don't just buy something to meet your current needs, but think about whether you will outgrow your keyboard as you improve your playing.  The prices have really come down and you can get a grand piano quality sound and weighted keyboard for less than $600.  The weighted keyboard is important because you may need to play a real piano, and will not be prepared for the heavier feel of the keyboard.   If the enhanced sound and extra features are not important to you, you can get one for around $450.
Check out yourtube for reviews and comparisons, such as the Yamaha P45 and P115 (not meant as an endorsement).
Answer: If your desire is to learn play the "piano" then definitely look for a hammer action digital piano, even second hand if on a tight budget.
Comment: Welcome to Music SE. Can you elaborate on this answer? It currently doesn't add any advice that is not already present in existing answers. When you have earned more reputation points, you will be able to upvote answers that you agree with instead of making redundant posts.

Piano For a Tight Budget


Software to diagnose (ping) a network over 24h?

Question: We've been experiencing a lot of problems with our current office's internet connection lately: slowdowns, packet losses, huge ping times, etc.
(Un)fortunately, this is not happening all the day, just a few minutes here and there, several times a day, but that makes our working day a pain.
As Murphy's law dictates, when the IT guy pops up, the internet works just fine, ping is good, bandwidth is normal.
As they won't do anything more for us without further proof of failure, is there a good and simple tool (on whatever platform) that will monitor the connection for 24h (pinging Google every second, for example) and display the results as a graph of the ping time + packet losses at anytime of the day?
I gave a try PingPlotter, but that didn't work as intended for me.
Comment: What's wrong with PingPlotter?
Comment: Most monitoring software will do this to at least some extent, but @Zoredache's suggestion of smokeping is probably the best-known standalone tool and is pretty much tailor-made for your issue.
Answer: I would setup a copy of smokeping on some system on your network. It doesn't ping every second, and you probably don't need it do.  Instead it will periodically send out a burst of ~20 pings at the same time, and then count how many respond, and how fast each returns.  The results are graphed.
Here is results for my a system at home, over my Comcast connection, to something at work.  The missed packets and latency is on the Comcast side.
Answer: If you have access to a linux machine then mtr may do what you want. mtr combines the functionality of the traceroute and ping programs in a single network diagnostic tool
This is the kind of output you get when run in report mode. You could just leave it running and gather statistics over any period of time.
mtr -r -c 10 google.com
HOST: host1.lan                   Loss%   Snt   Last   Avg  Best  Wrst StDev
  1. ns.lan                        0.0%    10    0.3   0.5   0.3   0.6   0.1
  2. 192.168.1.254                 0.0%    10   81.2  76.0  66.9  89.1   8.3
  3. 94-192-160-1.zone6.bethere.c 60.0%    10  2335. 1419. 1024. 2335. 620.4
  4. 10.1.3.245                   80.0%    10   17.3  17.6  17.3  17.9   0.4
  5. 10.1.2.169                   90.0%    10   28.1  28.1  28.1  28.1   0.0
  6. ???                          100.0    10    0.0   0.0   0.0   0.0   0.0
  7. 188.8.131.52                70.0%    10   23.5  23.6  23.4  23.8   0.2
  8. ???                          100.0    10    0.0   0.0   0.0   0.0   0.0
  9. ???                          100.0    10    0.0   0.0   0.0   0.0   0.0
 10. ???                          100.0    10    0.0   0.0   0.0   0.0   0.0
 11. ???                          100.0     8    0.0   0.0   0.0   0.0   0.0
 12. 18.104.22.168                0.0%     5   29.1  29.2  28.7  29.8   0.4

Comment: I have often run `mtr` as an hourly cron job in report mode to diagnose network problems.  Running with intervals of 30 or 60 seconds is often adequate.  This results in minimal impact on the network, but can give good results for periodic problems.
Comment: Very good, `mtr` is definitely a good piece of software to find where the problem in the network lies!
Answer: You could just dump the output of ping to a file (ie ping google.com > pings.txt) and review the latency times. No graph, but works on basically every platform and should provide ample proof of any problems the network is experiencing.
Comment: I'm aware of the `ping` option, but I'm actually looking for a way to display that on a timechart!
Comment: You really haven't given a good reason as to why. Your objective is to prove latency issues according to your Question, what do pretty graphs have to do with that?
Comment: To check out at what time of the day this happens. They'll do the job of finding any time pattern in that!
Comment: Start the ping at midnight (00:00:00) and with the standard 1 second between pings, and you'll have one data point for every second in the day (86400 through 00:00:00 the next morning) - "They" can find the pattern in that too :-)
Comment: I'm afraid that they won't even bother having a look at 86400 lines of text, even less trying to make a graph out of it :)
Comment: This is what I will do, in Python.  I need to have an email alert to my phone whenever pings to my main router in-house gets too large.  And I will write a log file with min/max over the day, plus any over-1000ms alerts.  If I had it store all the output like you describe then I would use gnuplot to make visual output as a .PNG for daily summaries.  But it is the occasional failing router that I am trying to catch.
Answer: Pingdom has a free service that may do what you need.
Comment: Good point indeed, that helped me figure out that the problem was not the actual internet connection of the building, but the poor Wi-Fi connection that they impose to connect our office network to the building router!
Comment: Of course Pingdom can't tell you anything about your internal network.. Something that monitors from the inside out would probably be more appropriate to troubleshoot their issue
Comment: Well I guess that is one valid vantage point.. However the issue could certainly be an ISP issue, so external monitoring could help in that instance.
Comment: Good point. Perhaps a ping monitor on their gateway router's public IP? If the issue is with the router itself or maybe a routing issue with the ISP that would work.
Answer: Nagios is an open source server monitoring tool that has the ability to monitor servers. I know that for SNMP monitors you have to configure things on the device being monitored but for simple ping monitors you shouldn't.
Here in our office we use WhatsUp Gold to monitor all our servers. It does have a ping monitor that does exactly what you're wanting. It's a pricey product ($2000+) which makes it a ridiculous solution to your problem, but they do have a free 30 day trial that you could install, gather data, and hopefully figure out your problem.


QuickLook framework not working properly in iOS 10 (with Xcode 8.0 beta 3) to display .csv file

Question: I have developed and updated a medical application for cardiac ultrasound since 2011. One feature of the app is a user-generated document library for documents, images, and movies, all displayed using QuickLook.framework. QuickLook has functioned well until now with iOS 10. At this point .csv files (generated by the app to store calculated data) display as simple text (including the commas) instead of as a spreadsheet. I have not found any Apple documentation to explain this change in behavior. The log in Xcode shows no error messages when displaying a .csv file.
I am using the iOS Simulator at this point to test my app with iOS 10. However, I have verified that the El Capitan (10.11.5) version of QuickLook opens a .csv file in the simulator library on the desktop without a problem, with the expected spreadsheet format. Therefore, I do not suspect any problem with the .csv files that my app is producing.
I suspect this problem with .csv display is a bug in iOS 10, but with no resolution after 3 beta releases, I am concerned that the problem persists. Any help would be much-appreciated. My hope is that there will not be a need to adopt a new document display method, since QuickLook has worked so well for several years now.
Of note, my app does not use any Swift code.
Comment: In this specific instance, this is already fixed, but in the future please do not wait until the third beta to file a bug at bugreport.apple.com!
Comment: Still do you have the issue?
Comment: Fortunately the problem was fixed with release of Xcode 8.0 beta 4.
Answer: iOS 10 is still in beta and will be in beta until at least the second half of September.
One of the main advices there is while testing beta software is to test it on the real device with something like iOS 10 Public Beta build installed.
If you are 100% positive that this is a consistent, well repeatable bug on Apple's side (not on your own or any other 3rd-party library you might use) consider filing a radar.
Concerning your specific problem, as far to my knowledge, Apple didn't make any significant changes to the QuickLook functionality in iOS 10, but once again, you can prove me wrong, by carefully browsing through all the latest changes in the official iOS 10 changelog.


Change image brightness using JSlider

Question: <code>        slider.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent e) {

            int val = slider.getValue();

            for(int x = 0; x < image.getWidth(); x++) {
                for(int y = 0; y < image.getHeight(); y++) {

                        image.setPixel(x, y, image.getPixel(x, y).brighter());
                        frame.repaint();
                }
            }
        }
    });
</code>
So this is my ChangeListener which I use to change the brightness of the image.
It works decent and the image gets brighter. The problem I'm having is that it doesn't matter what way I move the slider because it gets brighter either way.
The way I want it work is that the image should only get brighter when the slider is moved to the right.
Comment: What is the type of the variable `image`?
Comment: It's a BufferedImage
Comment: Possible duplicate of [How can I control the brightness of an Image?](https://stackoverflow.com/questions/46797579/how-can-i-control-the-brightness-of-an-image)
Answer: You never use the value of val. Why not do something like this: image brightness slider Java
<code>for(int x = 0; x < image.getWidth(); x++) {
     for(int y = 0; y < image.getHeight(); y++) {
         Color color = new Color(image.getRGB(x, y));
         int r, g, b;
         val = slider.getValue();
         r = ((color.getRed() + (val/20)) % 255);
         b = ((color.getBlue() + (val/20)));
         g = ((color.getGreen() + (val/20)) % 255);
         if(b > 255) b = 255;
         color = new Color(r, g, b);
         image.setRGB(x, y, color.getRGB());
    }
}
</code>
I tested this on a background, not pixel by pixel, and the starting color was blue. You would have to change the code above based on the starting color, because brightness is increased by adding more color. Blue has a starting value of (0, 0, 255), so you cannot add any more blue to increase brightness.
Comment: Can't get it to work. For me it doesn't change the brightness it just turns the image black..

Change image brightness using JSlider


Pre image of compact is closed & continuity

Question: Let the function $f: \mathbb{R}\rightarrow \mathbb{R }$ be bounded on bounded set have the property that $ f^{-1}(K)$ is closed whenever $K $ is compact . prove  $f$ is continuous
We known that if pre image of closed set is  closed then $f$ is continuous
I take $F$ closed set in $\mathbb{R}$   need to prove   $ f^{-1}(F) $  is closed
Set is closed  if its complement is open    how to proceed  further
Comment: $R = \mathbb R$?
Answer: Consider a restriction $f:[i,i+2]\rightarrow \mathbb{R}$ Since $f$
is bounded on bounded set, then we can assume that $f :
[i,i+1]\rightarrow [a,b]$. For any closed set in $[a,b]$, it is
compact set. Hence preimage of $f$ is closed. Hence the restriction
is continuous. This holds for all $i$ so that $f$ is continuous on
$\mathbb{R}$
Answer: I'll explain two arguments.
Elementary one: consider a sequence $\{x_{n}\}$ in $\mathbb{R}$ converging to a point $x$. Our aim is to show that $L:=\{\textrm{limit points of}\,\, \{f(x_{n})\}\}$ equals $\{f(x)\}$. First,  since $\{x_{n}\}$ is bounded, so is $\{f(x_{n})\}$. Then Heine-Borel theorem tells us that $L$ is nonempty.
Now take any subsequence $\{x_{n_{k}}\}$ of $\{x_{n}\}$ such that $f(x_{n_{k}})$ converges to a value $l$. Then $K_{M}:=\{l\} \cup \{f(x_{n_{k}})\}_{n=M}^{\infty}$ is a compact set, so its preimage $f^{-1}(K_{M})$ is closed. Thus, $x$, the limit point of $\{x_{n}\} \subseteq f^{-1}(K_{M})$, also belongs to $f^{-1}(K_{M})$. Sending $M \rightarrow \infty$, we conclude $f(x) = l$. Thus, any element of $L$ equals $f(x)$. This ends the proof.
Fancier words: given a closed set $K$, we consider $K_{r} = K \cap ([-r-1, -r] \cup [r, r+1])$: $\{K_{r}\}$ are compact sets such that $\cup_{r} K_{r} = K$. We know that $f^{-1}(K_{r})$ is closed for each $r$. Although union of arbitrary closed sets need not be closed, union of locally finite collection of closed sets (it means that inside any bounded set, you see only finitely many such closed sets) is closed in general. Since $f$ sends bounded sets to bounded sets, $\{K_{r}\}$ are indeed locally finite and $K = \cup_{r} K_{r}$ is closed.


Singleton database.php

Question: If I have a database.php class (singleton) which reads and writes information for users of my web application, what happens when simultaneous requests for the same database function is called?
Is it possible that the database class will return the wrong information to other users accessing the same function at the same time?
What other similar problems could occur?
Answer:
what happens when simultaneous requests for the same database function is called?  Is it possible that the database class will return the wrong information to other users accessing the same function at the same time?

Absolutely not.
Each PHP request is handled entirely in it's own process space.  There is no threading, no application server connection pool, no shared memory, nothing funky like that.  Nothing is shared unless you've gone out of your way to do so (like caching things in APC/memcached).
Every time the application starts, your Singleton will get created.  When the request ends, so does the script.  When the script exits, all of the variables, including your Singleton, go away with it.

What other similar problems could occur?

Unless you are using transactions (and if you're using MySQL, using a transaction-safe table type like InnoDB), it is possible that users could see partial updates.  For example, let's say that you need to perform an update to three tables to update one set of data properly.  After the first update has completed but before the other two have completed, it's possible for another process to come along and request data from the three tables and grab the now inconsistent data.  This is one form of race condition.
Comment: In other words, a Singleton does not help with ACID

Singleton database.php


Is there an example of a Lipschitz function of a Gaussian vector for which $f(Z)-\mathbb{E}[f(Z)]$ is not sub-Gaussian

Question: Definitions:
A random variable $X$ is called sub-Gaussian with parameter $\sigma^2$ if there exists $\sigma \in \mathbb{R}$ such that
$$\forall \lambda \in \mathbb{R} \quad \mathbb{E}[e^{\lambda X}]\le e^{\frac{\sigma^2 \lambda^2}{2}}$$
A function $f:\mathbb{R}^n\to\mathbb{R}$ is called $L$-Lipschitz if $|f(X)-f(Y)|\le L \|x-y\|$.
Note:Usually, We take the $L_2$-norm for the RHS.

Theorem:
If $Z_1,Z_2,\dots,Z_n$ are standard normal variables ($Z_i\sim \mathcal{N}(0,1)$), and $f:\mathbb{R}^n\to\mathbb{R}$ is a $L$-Lipschitz function, then $f(Z)-\mathbb{E}[f(Z)]$ is sub-Gaussian. (Taken from Concentration of Measure 3 by Jarosław Błasiok, Page 21)

Question:
Assume that we apply the same $L$-Lipschitz function $f:\mathbb{R}^n\to\mathbb{R}$ on $Z_1,Z_2,\dots,Z_n$ such that $Z=(Z_1,Z_2,\dots,Z_n)\sim\mathcal{N}(0,\Sigma)$, meaning that the random variables are normal (but not standard) and we may have $\mathbb{E}[Z_i Z_j] \neq 0$ for some $i,j$.
Can we define $f$ such that $f(Z)-\mathbb{E}[f(Z)]$ is no more sub-Gaussian?
To clarify: We can define $f$ and $\Sigma$ (the covariance matrix of the Gaussian random vector) as we would like to. The question says: "Can we select $f$ and $\Sigma$ such that $f(Z)-\mathbb{E}[f(Z)]$ is not sub-Gaussian?"

My work:
I've found out that the theorem may not hold if $f$ is Lipschitz but not convex (in this link, page 212). However, I believe in my case, reaching a counterexample should be much easier. I couldn't find any theorem which states that if the variables $Z_i$ have correlation, then $f(Z)-\mathbb{E}[f(Z)]$ is sub-Gaussian. So, I thought maybe if we define $Z_i$'s somehow that they are correlated, then the counterexample could be made. The difficulty for me is that for each Lipschitz function that I define, I should prove that
$$
\forall \sigma\in\mathbb{R} \quad \exists \lambda \in \mathbb{R} \quad \mathbb{E}[e^{\lambda (f(Z)-\mathbb{E}(f(Z))}] \gt e^{\frac{\sigma^2 \lambda^2}{2}}
$$
And proving this is where I can't proceed further. I'm not sure but maybe my approach is wrong.
Note: There is a related question here, and also another one here.
Answer: If $Z_i\sim N(,\Sigma)$ then $Z_i=\Sigma^{1/2}Y_i$ are $N(0,1)$, where $\Sigma^{1/2}$ is any square root of $\Sigma$.  So $f(Z_1,\dots,Z_n)=(f\circ g)(Y_1,\dots,Y_n)$, where $g$ is multiplication by $\Sigma^{1/2}$.
Clearly $f\circ g$ is still Lipschitz. If $\lambda$ is the largest eigenvalue of $\Sigma$, the Lipschitz constant is bounded above by $L\sqrt{\lambda}$.
So, no. But you do need to take the extra factor of $\sqrt{\lambda}$ into account, especially if you're going to look at a collection of $f$s and $Z$s that might have different $\Sigma$s.
Comment: Thanks for the answer. However, I still have difficulties understanding what you wrote. Would you please clarify: 1) What do you mean by "any square root of $\Sigma$"? (since $\Sigma$ is a matrix) 2) What does your last sentence mean? ("you do need to take ..."), does it mean that there is a $\lambda$ for which we can show that $f(Z)-\mathbb{E}[f(Z)]$ is not sub-Gaussian? 3) I believe you meant $Y_i = \Sigma^{1/2} Z_i$ when you wrote $Z_i=\Sigma^{1/2} Y_i$. Is that true?


Word VBA: "Ambiguous Name Detected" for ActiveX Labels

Question: I have a Word document originally created on a Windows 7 32-bit machine, that is now giving me problems since switching to Windows 7 64-bit.  Both systems are running Word 2010 (v14.0.7173.5000, 32-bit).  The Word document has many ActiveX Labels, and a large macro which links each ActiveX Label to a specific cell in an Excel document.  This way I update the Excel file, and I run the Word macro to update all the labels.
Here is how the ActiveX Labels look in VBA when the Word document is opened on a Win7 x86 machine:

However when the document is opened on a Win7 x64 machine, the Labels are renamed with a "1" at the end:

Because there have been no changes to my VBA code itself, if I run the macro I get the error message "Object library invalid or contains references to object definitions that could not be found".  If I try and fix the Labels by removing the "1", I get an "Ambiguous Name Detected" error message.
If I re-save the file with the extra "1" in the Label, the new Labels are retained and visible when opened on a Win7 x86 machine. That same machine is then able to remove the extra "1", but if I try to do the same on a Win7 x64 machine I get the "Ambiguous Name Detected" error message again.
Does anyone know what is causing this problem, and also how to fix it?
Comment: Have you tried fixing the handlers to *add* the `1` and then saving (a copy of) the document?
Comment: Not yet. Is there an easy way to do that instead of selecting each label one by one from the pull down menu (like in my screenshots)?
Comment: My VBA code is under the Microsoft Word Object for "ThisDocument", rather than a module.  Is that a problem?
Comment: Makes no difference, I'm talking about the editor itself - [this toggle button](https://i.stack.imgur.com/TMYzJ.png) (see the tooltips on these two buttons).
Comment: OK there's no difference for me between Procedure View and Full Module View.  I can see my entire VBA code, but I can't change my ActiveX labels unless I select them one at a time from the pulldown (in the Properties - ThisDocument window pane).  I'll have to try this Rubberduck program to see if it helps me out.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/126647/discussion-between-wongnog-and-mats-mug).
Answer: Seems your controls need to have their names fixed/changed. You can do this manually in design mode.
Or you can update your code so that instead of this:
ThisDocument.ai_oos_01.Caption = "whatever"

You do this:
FixControlNameAndSetCaption "ai_oos_01", "whatever"

Just grab this procedure and put it in a standard module (e.g. Module1):
Public Sub FixControlNameAndSetCaption(ByVal controlName As String, ByVal newCaption As String)
    Dim wordShape As InlineShape
    For Each wordShape In ThisDocument.InlineShapes
        With wordShape.OLEFormat.Object
            If Left$(.Name, Len(controlName)) = controlName Then
                If .Name <> controlName Then .Name = controlName
                .Caption = newCaption
                Exit Sub
            End If
        End With
    Next
End Sub

Now, if the controls' .Name matches the specified controlName exactly, only the .Caption will change (which is what your code is currently supposed to be doing). If the controls' .Name would match the specified controlName if that pesky numeric suffix wasn't there, then it renames the control to the specified controlName, which effectively "cures" your control names.
HOWEVER, if you have legit/expected control names Foobar01 and Foobar012, then I don't have a solution other than to strongly recommend you avoid numeric suffixes when naming things, and give things meaningful/descriptive names, always.
The implication of not referring to ThisDocument.ai_oos_01 directly, is that your code still compiles and runs if the objects somehow get renamed again (I suspect document corruption, or someone duplicated all the controls and/or deleted the original ones, perhaps by accident).


What's the global, general word that stands for "center tone of a song"?

Question: There are many words which means "center tone of a song", but each word seems to have its own limitation of usage.

Tonal Center
Key Center

I heard (and was told) that these are the terms for tonal music and it's not appropriate to use them in other realm of music.
For modal music I often see these words:

Modal Tonic
Final (Finalis)

But then, what about other kind of music?

(1) A song not clearly belonging to either "Tonal" or "Modal"
A wholetone scale song, for example, can have a "center" by emphasizing one of the scale notes. But it's controversial whether this kind of songs belong to tonal or modal.
Or recent EDM has some crazy wobble bass solo with pitch bend,  yet there's a "center" where you can feel at home.
Wobble basses are played often in Phrygian mode, but again it's hard to judge if I should call it "modal music".
(2) Traditional Ethnic Music
Although ethnic musics often don't fit to western major/minor key theory, they still have their own harmony system and usually have "center" somewhere.

I'm not at all trying to discuss categorizing them into "Tonal" or "Modal" (It'll make no one happy).
I just wonder if there is not a common, global, inclusive term which simply stands for "center tone of the song" regardless of the style of music, which you can use without worrying about these fruitless categorization matter.
I think the best general word is "Tonic", but some even say that tonic also is a word for tonal music.
Do I have no choice but to use lengthy expressions like "center tone of the song" or "a tone where you can feel at home, feel that the phrase ends"?
Comment: If you said "tonic" or "tonal center" in any of the contexts you've described, I would immediately understand what you were talking about, and it wouldn't sound strange to me. Words mean what we agree they mean. So it's not like using "tonic" outside the context of a strict major key will cause your speech to crash with a syntax error!
Answer: In my answers here I tend to use home note if I want to avoid any implications as to what kind of music I'm talking about. It sounds a bit childish and not very technical, but perhaps that is why it doesn't seem to have any unwanted implications about the type of music.
I don't personally assume much about the type of music if I read 'tonic' or 'tonal centre' - if it does imply that the music is 'tonal', what that in turn means can be rather uncertain anyway...
Comment: We used this in early band many many years ago. My dad accidentally taught it to me when he taught me rock music "You gotta come back to the ones, do all the fancy solo crap you want but when the drummer's gonna crash that cymbal you better be on your one."
Answer: I've heard "tonal center". I know you said you've heard that that's only for tonal music, but I'd argue that it's fine to say a modal piece has a tonal center. Tonic is a term that I hear more often in tonal music.
As long as there is a discernable center, I think it's perfectly acceptable to say "tonal center", even when the piece has more of a mode-based thing going on. Modes, after all, still have well-defined tonalities, and even though they lack functional harmony (for the most part), they still have a center, which means to me that "tonal center" applies.
Answer: I've always heard it referred to as the tonic. A lot of the (traditional-based) music I play is centred on drones and/or modes, and tonic is the easiest way of expressing the 'note that the melody centres around'.
Answer: As far as a "common, global, inclusive term for something as sensory and subjective as "the center tone of a song", I think the question is too vague as presented.  Most questions appealing to esthetic judgment cannot be answered in any absolute sense.
If rephrased more operationally, it might ask, "What tone or frequency would be the least dissonent overlaid continuously during a song?",
then the answer, at least in Western music, would be the root or tonic of the song's key -- leaving only ambiguity about which octave of the root note sounds least objectionable, and at what volume.


Vlookup with multiple values

Question: So, i have a table, with a several modules in the first column and in the second column the different processes existing in that module. It looks something like this:

Now I have created a data validation list of the unique unique modules, so a list with Module A, Module B, and Module C.
When I select a module from that list, I want all the processes, belonging to the module to appear next to the dropdown list in separate cells. It would be a 'nice-to-have' if the processes appear underneath each other.
I have tried various things with index and vlookup etcetera, but I cannot find a way to fix it.
Answer: If you have Office 365 Excel then use this array formula:
=TEXTJOIN(",",TRUE,IF($A$2:$A$7 = D2,$B$2:$B$7,""))

This is an array formula and needs to be confirmed with Ctrl-Shift-Enter when exiting edit mode.  If done correctly then excel will put {} around the formula.

If you do not have Office 365 Excel then put this code in a module attached to the workbook and use as described above.
Function TEXTJOIN(delim As String, skipblank As Boolean, arr)
    Dim d As Long
    Dim c As Long
    Dim arr2()
    Dim t As Long, y As Long
    t = -1
    y = -1
    If TypeName(arr) = "Range" Then
        arr2 = arr.Value
    Else
        arr2 = arr
    End If
    On Error Resume Next
    t = UBound(arr2, 2)
    y = UBound(arr2, 1)
    On Error GoTo 0

    If t >= 0 And y >= 0 Then
        For c = LBound(arr2, 1) To UBound(arr2, 1)
            For d = LBound(arr2, 1) To UBound(arr2, 2)
                If arr2(c, d) <> "" Or Not skipblank Then
                    TEXTJOIN = TEXTJOIN & arr2(c, d) & delim
                End If
            Next d
        Next c
    Else
        For c = LBound(arr2) To UBound(arr2)
            If arr2(c) <> "" Or Not skipblank Then
                TEXTJOIN = TEXTJOIN & arr2(c) & delim
            End If
        Next c
    End If
    TEXTJOIN = Left(TEXTJOIN, Len(TEXTJOIN) - Len(delim))
End Function

To get them to appear in separate cells one below the other use this formula in the first cell and copy down enough to cover the longest list:
=IFERROR(INDEX(B:B,AGGREGATE(15,6,ROW($A$2:$A$7)/($A$2:$A$7=$D$2),ROW(1:1))),"")

Comment: Thanks for the quick reaction, but I want the processes to appear in separate cells, the nicest way for me would be if they appear underneath each other..
Comment: Then that is what you should say in your original post.
Comment: For some reason, it only displays '0' in my cells, I'm figuring out why.
Comment: @NickKuipers Not sure why it would be `0` unless there are matches in A and B is empty.  Also do not us full column reference, only reference the cells in A:B that have data.  And make sure ALL the references are absolute.
Comment: OK, just saw your edit Scott, and turns out my aggregate formula is virtually identical.  When I was writing my formula I actually paused and thought about it for a moment.  Is there any advantage of using ROW(1:1) over ROW(A1)?
Comment: @ForwardEd no, It is just preference.

Vlookup with multiple values


How to add column next to Seaborn heat map

Question: Given the code below, which produces a heat map, how can I get column "D" (the total column)
to display as a column to the right of the heat map with no color, just aligned total values per cell? I'm also trying to move the labels to the top. I don't mind that the labels on the left are horizontal as this does not occur with my actual data.
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
%matplotlib inline
df = pd.DataFrame(
      {'A' : ['A', 'A', 'B', 'B','C', 'C', 'D', 'D'],
       'B' : ['A', 'B', 'A', 'B','A', 'B', 'A', 'B'],
       'C' : [2, 4, 5, 2, 0, 3, 9, 1],
       'D' : [6, 6, 7, 7, 3, 3, 10, 10]})

df=df.pivot('A','B','C')
fig, ax = plt.subplots(1, 1, figsize =(4,6))

sns.heatmap(df, annot=True, linewidths=0, cbar=False)
plt.show()

Here's the desired result:

Thanks in advance!
Answer: I think the cleanest way (although probably not the shortest), would be to plot Total as one of the columns, and then access colors of the facets of the heatmap and change some of them to white.
The element that is responsible for color on heatmap is matplotlib.collections.QuadMesh. It contains all facecolors used for each facet of the heatmap, from left to right, bottom to top.
You can modify some colors and pass them back to QuadMesh before you plt.show().
There is a slight problem that seaborn changes text color of some of the annotations to make them visible on dark background, and they become invisible when you change to white color. So for now I set color of all text to black, you will need to figure out what is best for your plots.
Finally, to put x axis ticks and label on top, use:
ax.xaxis.tick_top()
ax.xaxis.set_label_position('top')

The final version of the code:
import matplotlib.pyplot as plt
from matplotlib.collections import QuadMesh
from matplotlib.text import Text

import seaborn as sns
import pandas as pd
import numpy as np
%matplotlib inline

df = pd.DataFrame(
      {'A' : ['A', 'A', 'B', 'B','C', 'C', 'D', 'D'],
       'B' : ['A', 'B', 'A', 'B','A', 'B', 'A', 'B'],
       'C' : [2, 4, 5, 2, 0, 3, 9, 1],
       'D' : [6, 6, 7, 7, 3, 3, 10, 10]})

df=df.pivot('A','B','C')

# create "Total" column
df['Total'] = df['A'] + df['B']

fig, ax = plt.subplots(1, 1, figsize =(4,6))

sns.heatmap(df, annot=True, linewidths=0, cbar=False)

# find your QuadMesh object and get array of colors
quadmesh = ax.findobj(QuadMesh)[0]
facecolors = quadmesh.get_facecolors()

# make colors of the last column white
facecolors[np.arange(2,12,3)] = np.array([1,1,1,1])

# set modified colors
quadmesh.set_facecolors = facecolors

# set color of all text to black
for i in ax.findobj(Text):
    i.set_color('black')

# move x ticks and label to the top
ax.xaxis.tick_top()
ax.xaxis.set_label_position('top')

plt.show()

P.S. I am on Python 2.7, some syntax adjustments might be required, though I cannot think of any.
Comment: Using python 3.10, matplotlib version 3.5.1: Everything works except for `qm.set_facecolor = facecolor`. I also tried `qm.set_facecolor(facecolor)` and `qm.facecolor = facecolor` but in both cases the new face colors do not change. The plot is displayed with black text but no change to the backgrounds. What else do I need to do to make the plot use the new color array?
Comment: Same problem here. Also, If the difference between the total and the other values is too big, it will show up one part completely "clear" and the other part completely "dark"


Convert Certificate to X.509


2 x Mono vs 1 x Stereo Quality

Question: Two-channel Stereo sound can be provided by two Mono cables, or a single Stereo cable.
What differences, whether significant or not, are there between pairing each voltage lead with its own ground lead versus sharing a single ground lead between [an arbitrarily large number of] audio channels?
Below I include details of my thoughts that raised the question.
Mono cables each transmit one channel and each have two leads: voltage and ground. Using mono cables, the number of channels (N) can be increased arbitrarily by using a matching number of N Mono cables, for a total of 2N leads.
Each Stereo cable can by itself provide two audio channels with only three leads: voltage L, voltage R, and a single ground lead (shared between channels L and R), effectively providing the same throughput with one less lead than the Mono configuration, which makes me wonder what [functionally inconsequential] differences there are between 1 x Stereo quality vs 2 x Mono quality.
Furthermore, 4-lead cables (such as stereo headphones + mic over a single bus) provide 3 channels using 4 leads: voltage L, voltage R, voltage M (mic), and one single ground lead shared by all three channels!
Assuming there is no quality loss when channels share a ground lead, then a Mono-only multi-channel configuration wastes half its leads save one (N-1).
Comment: Once you're inside the amp., isn't it all grounded to the chassis anyway?
Answer: There is no significant difference between two unbalanced mono connections and a single stereo connection. However, with two mono lines you have the option of making both balanced, which is usually a good idea for longer connections. With single-cable stereo, this is typically not possible because suitable 5-lead connectors aren't available (at least not widespread).
Comment: In professionell sound balanced cables are used. The signal is sent as one hot and one cold. The cold is inverted compared to the hot. Ground is only used for the sceeen. For microphones the connectors are generally three pin XLR ( personally I preferr the Neutrik brand ). The Calle and connectors can additionally be used to provade phantom power to the microphone at 48Volt and a few milliamps.  For stereo mics we tend to use 5pin XLR contacts and 4 wire plus screen cable but there are a number of variants.
Comment: Would you delve more deeply into the concept of 'balance' please? I am fairly certain am missing some key factor in understanding what you mean exactly.
Comment: https://en.wikipedia.org/wiki/Balanced_line
Answer: Most RCA stereo cables are 4-lead, and consist of 2 mono cables connected only by their outer insulation. This type of cable usually has a figure-8 crosssection. Every signal wire has its own ground in a coax configuration: signal wire in the middle, and the ground as a shield around it. This is done to reduce crosstalk.
3-lead stereo cables are used in some headphones (usually small in-ear types), in DIN cables (long obsolete), and maybe SCART (also obsolete). These have two signal wires with the ground wrapped around both of them. Because the two signals are not separated by a ground, they are more susceptible to crosstalk (signal from one channel leaking into the other) than dual-mono cables.

2 x Mono vs 1 x Stereo Quality


Weird behavior with Constructor and Class. Application hangs `forever` on Constructor

Question: UPDATE NOTE: After Debugging, I asked another question with the results: Class Constructor fails throwing Exception on Class Loading
First, I could not think of a better name for my question, what I'm about to ask is just that: WEIRD BEHAVIOR. If you think of something more appropriate please edit.
Now, I'm going to try to simplify this as much as I can, sadly I can't give away the code which is giving me the problems.
I have a Class A, a Class B and a Class Z.
Class A and B are very very similar, both have a constructor with the same params, and each have a method which invokes a SOAP web service, one to do Operation A, and the other to do Operation B.
Now,what's the problem? Class Z instantiates both Class A and Class B and then on someMethod() calls the object's method to do Operation A and B respectively.
For some reason the constructor of ClassB doesn't seem to be called, and no System.out.println() prints anything from the moment the Constructor is called, the program hangs forever, i mean it, it never throws and exception or continues to do anything. Look how on the first line of Class A and Class B I print a flag, it does not print for ClassB.
WHAT I'VE TRIED

On ClassZ I changed the order for Class A and B -> RESULTS: It hangs on the same place and now not even Class A constructor and method gets called
On ClassB I commented everything, and started de-commenting each instruction one by one, starting with the Constructor and then with MethodB, here's where I got stuck and came here, because what I found makes no sense for me nor anybody at my workplace. RESULTS ->
2.1 If I comment everything on methodB but the return false in the end and leave the Constructor as is, it continues execution normally
2.2 If I de-comment everything on 2.1 plus just the part from methodB where it invokes the operationB from the WebService and checks it's result, it continues execution normally
2.3 If I de-comment a little bit more, when I start playing around with the database, it hangs.
I checked the number of Connections to the Database, it still has many available

What has me confused is, if it's something Database related, why does it hangs like that at the constructor?
GENERAL FACTS

I'm using JDBC to connect to a MySQL Database
I have everything around try{}catch(Exception e){} and I'm printing everything on e, but it just doesn't print anything, no exception is thrown.

Here's what they look like:
CLASS A:
// ClassA.java

public ClassA{
    private UserInfo user;
    private WebServiceADelegate port;
    private Connection conn;

    public ClassA (UserInfo user, Connection conn) throws Exception {
        System.out.println("CLASS A CONSTRUCTOR");
        this.user = user;
        this.conn = conn;
        this.port = new WebServiceAService().getForwardingPort();
    }

    public boolean methodA(List<String> list){
        // Check some stuff on database using this.conn
        // Get the values to invoke SOAP service using this.conn
        status = port.operationA(values);
        if(status > 0)
            return true;
        return false;
    }

}

CLASS B:
// ClassB.java

public ClassB{
    private UserInfo user;
    private WebServiceBDelegate port;
    private Connection conn;

    public ClassB (UserInfo user, Connection conn) throws Exception {
        System.out.println("CLASS B CONSTRUCTOR");
        this.user = user;
        this.conn = conn;
        this.port = new WebServiceBService().getForwardingPort();
    }

    public boolean methodB(List<String> list){
        // Check some stuff on database using this.conn
        // Get the values to invoke SOAP service using this.conn
        status = port.operationB(values);
        if(status > 0)
            return true;
        return false;
    }

}

CLASS Z:
// ClassZ.java

public ClassZ{
    private Connection conn;
    // ...
    // ...
    public boolean someMethod (){
        System.out.println("GONNA CALL CONSTRUCTOR ClassA");
        ClassA webservice = new ClassA(user, conn);
        System.out.println("GONNA CALL METHOD FROM ClassA");
        if (!webservice.methodA(list) ){
            return false;
        }

        System.out.println("GONNA CALL CONSTRUCTOR ClassB");
        ClassB webservice2 = new ClassB(user, conn);
        System.out.println("GONNA CALL METHOD FROM ClassB");
        if (!webservice2.methodB(list) ){
            return false;
        }
        return true;
    }
}

The last output when it hangs it's always: "GONNA CALL CONSTRUCTOR ClassB"
Thanks!
UPDATE:
I debugged my app and got to fix it, however it's still really strange. Tomorrow I'll elaborate more to see if somebody can tell me what was going on.
Long story short: I was importing javax.persistence.NoResultException on ClassB, and on some point inside methodB i was doing try{}catch(NoResultException nre){ //...}… For some reason when the JVM was calling the ClassLoader before calling the Constructor it was throwing the aforementioned Exception and the behavior from that point was just weird and the execution ended.
There are threads involved, that's why I though it hang, it didn't hang, the Thread ended and I didn't notice.
An additional note: ClassB IS NOT using JPA, and the import as well as the catch for it were incorrectly there, some really old code that managed to survive. However I think it doesn't justify the error.
I asked another question, one with the findings of the Debugging. You might check it in Class Constructor fails throwing Exception on Class Loading
Comment: Go with a debugger and tell us where it hangs. When I should bet then I would say that some call to the webservice hangs which does not return. But better you tell us on what line of code your program hangs.
Comment: @FabianBarney Well I surely haven't tried with a debugger, the test environment I'm  using is anything but good. I'll see what I can do tomorrow, but from my flags I'd say it hangs on the `new ClassB(user, conn);`
Comment: I would say that you are behind a **proxy** and when you create the WebService it is trying to reach the WSDL **without proxy** configuration hanging your application ;)
Comment: Does it hang forever? Have you left it say 5 mins to see what happens?
Comment: @FranciscoSpaeth The WSDL is reachable from the machine, I ping the IP and also download the WSDL with wget and there's no problem. Thanks, I'll add that to the question. Also, notice that ClassA does work without problem, and the WSDL is on the same server as the one from ClassB
Comment: @DaveHowes I have left it for 30 minutes with no response.
Comment: could you reach it with: `curl -x "" "wsdl address"`? -x removes the proxy, because wget could take default proxy configurations...
Comment: @FranciscoSpaeth `curl -x "" "wsdl address"` had success.
Comment: strange, from my point of view its time to execute a debugging ;)
Comment: @FranciscoSpaeth I'm on it. I'll come back with the results.
Comment: @FranciscoSpaeth I just edited my question with an update. I found the problem and fixed it, however I still don't understand what's going on.
Comment: @FranciscoSpaeth I asked another question, one with the findings of the Debugging. You might check it in http://stackoverflow.com/questions/11738383/class-constructor-fails-throwing-exception-on-class-loading
Answer: Well, hard to say with the infos provided, but some hints what I would check:

First use a debugger and step into the constructor whatever to be really sure where it hangs. Knowing it's the constructor call is not enough. Step into it.
There is a good chance that a webservice call hangs. So you call a webmethod and it does not return forever. So your program hangs forever.
The hang can be anything but when you deal with databases there is a good chance that the hang comes from a database lock. You can easily produce dead locks here when you do not commit/rollback properly.

Some wild guesses but maybe it helps ...
Comment: Thanks Fabian, 1. I did, check my UPDATE on the question. 2. I checked everything related to the WS, in the worst case it would throw a timeoutException. 3. No, the database was operating ok, if there's a deadlock MySQL jdbc driver throws an Exception because MySQL can detect the deadlocks (at least on InnoDB Engine), been there.
Comment: MySQL can only detect db internal dead locks. It is still possible that your program waits for a current statement that needs a lock that you should have better released before on another connection. But this is not released, because your program hangs on a statement that needs the lock...
Comment: And the WS does not necessarily timeout when there's a connection keep-alive.
Comment: I asked another question, one with the findings of the Debugging. You might check it in http://stackoverflow.com/questions/11738383/class-constructor-fails-throwing-exception-on-class-loading
Answer:
The application didn't hang forever. This piece of code was running in another thread so when its execution failed it finished without me noticing.
The problem was in fact when calling the constructor. I didn't have the class javax.persistence.NoResultException on my classpath so the JVM ClassLoader couldn't find it when creating the instance and when checking for dependencies it crashed.
Finding out what was the problem was difficult even debugging because I had a lot of
try{}catch(Exception e){} but even though the ClassLoader.loadClass() of the JVM ClassLoader says it throws an Exception (ClassLoader.loadClass() signature is: public Class<?> loadClass(String name) throws ClassNotFoundException) it was actually throwing a NoClassDefFoundError, which DOES NOT EXTEND EXCEPTION, it extends Throwable, and therefore was not being catch by my catch(Exception e){}, I had to do catch(Throwable t){}.
As of why was it throwing something different, it's because how Java's internals class loading works. It's a bit more complicated than just calling loadClass. It has to load, link, verify and initialize it. At some point it is supposed to throw a NoClassDefFoundError when calling defineClass(). More on this can be found on the Execution part of the JLS

For a more detailed answer on what was heppening, check my other question regarding this issue after debugging and the accepted answer Class Constructor fails throwing Exception on Class Loading


Determining order of poles.

Question: I'm having some trouble understanding how to tell the order of poles. I understand simple cases I've seen online, but how about in something like ($z^{2}+1$)/($z^{3}-1)$? There's a pole at 1 and I think its of order 1. My questions arise when I split it into the form f(z)=g(z)/$(z-z_{0})^{m}$. In this case would g(z)=($z^{2}+1$) and have ($z^{3}-1)^{-1}$?
Comment: A general method is to calculate $\lim_{z\to z_0} (z-z_0)^ng(z)$ and determine the smallest $n$ for which this limit is finite. That $n$ is the order of the pole.
Answer: Your rational function factors as $$\frac{z^2+1}{(z-1)(z-\omega)(z-\omega^2)}$$ where $\omega=e^{2i\pi/3}$. So it has poles of order one at $1,\omega,$ and $\omega^2$: the order of a pole is just the multiplicity of the zero of the denominator at that pole, assuming you've cancelled common factors.

Determining order of poles.


pthread_attr_setaffinity_np does not return or throw an error

Question: I'm trying to start a couple of threads, each on it's own core (4 cores -> 4 threads e.g.).
Pin the threads to their cores looks like:
pthread_t thread_objs[cpu_count];
pthread_attr_t attr;
cpu_set_t cpus;
pthread_attr_init(&attr);

for (unsigned int t = 0; t < cpu_count; t++) {
    pthread_t new_thread;
    CPU_ZERO(&cpus);
    CPU_SET(t, &cpus);
    if(pthread_attr_setaffinity_np(&attr, sizeof(cpu_set_t), &cpus)) {
        std::cerr << "fatal: could not set affinity" << std::endl;
        return 1;
    }
    if(pthread_create(&thread_objs[t], &attr, start_routine, NULL)) {
        std::cerr << "fatal: thread creation failed" << std::endl;
        return 1;
    }
}

for (unsigned int t = 0; t < cpu_count; t++) {
    pthread_join(thread_objs[t], NULL);
}

Ẁhile testing, I figured out that the first call of pthread_attr_setaffinity_np never returns. I waited several hours, but nothing happened.
Used  glibc is ldd (Ubuntu GLIBC 2.23-0ubuntu9) 2.23.
Comment: The first call should set your affinity to cpu zero, right? Is something else already running there with higher priority? Are you running this in a cgroup? Anything else that could affect scheduling and affinity? If the call never returns, presumably your thread isn't getting scheduled any more ...
Comment: The posted snippet is called from the main thread, which is creating other threads, one for each core. There is no other thread, which could affect scheduling and affinity. Why should the calling thread never be scheduled again?
Comment: FWIW, it works for me, on Ubuntu 14. I have 12 cores, and as long as cpu_count is lower than 13, all is fine. If I increase cpu_count over 12, pthread_create fails (since affinity is set to a non-existing CPU, probably).
Comment: Crazy, tested it on three different machines - all with the described result.
Comment: _no other thread which could affect_ you mean **nothing** is running on this machine? No other process, no kernel threads? How are you starting the program?
Comment: What happens if you start the thread and then move _that_ to its target affinity, instead of migrating the main thread multiple times? What happens when you run under `strace -f`?  What happens if you run from `1 ... cpu_count` instead?
Comment: I will add an answer with my working code, try to compile and run that and see if setaffinity blocks, I cannot see why it should.
Comment: Can you post a [MCVE](https://stackoverflow.com/help/mcve) and include the commands used to compile & link the program. Also details on the platform(s) you ware running on.
Answer: Below I post my code (basically the same as in the question), it works for me on Ubuntu (actually Goobuntu) 14 with a 12-core machine. Reduce nr of CPUs variable to get it to run on a machine with fewer cores.
#include <pthread.h>

#include <unistd.h>

#include <iostream>

using std::cerr;
using std::cout;

const int cpu_count = 12;
pthread_t thread_objs[cpu_count];
pthread_attr_t attr;
cpu_set_t cpus;

void* start_routine(void*)
{
    sleep(2);

    return 0;
}

int main()
{
    pthread_attr_init(&attr);

    for (unsigned int t = 0; t < cpu_count; t++) {
        pthread_t new_thread;
        CPU_ZERO(&cpus);
        CPU_SET(t, &cpus);

        cout << "Nr of set cpus in set: " << CPU_COUNT(&cpus) << '\n';

        if(pthread_attr_setaffinity_np(&attr, sizeof(cpu_set_t), &cpus)) {
            std::cerr << "fatal: could not set affinity" << std::endl;
            return 1;
        }
        if(pthread_create(&thread_objs[t], &attr, start_routine, NULL)) {
            std::cerr << "fatal: thread creation failed" << std::endl;
            return 1;
        }
    }

    for (unsigned int t = 0; t < cpu_count; t++) {
        pthread_join(thread_objs[t], NULL);
    }

    cout << "Joined all threads, ending!\n";
}


Ruby - iterate tasks with files

Question: I am struggling to iterate tasks with files in Ruby.
(Purpose of the program = every week, I have to save 40 pdf files off the school system containing student scores, then manually compare them to last week's pdfs and update one spreadsheet with every student who has passed their target this week. This is a task for a computer!)
I have converted a pdf file to text, and my program then extracts the correct data from the text files and turns each student into an array [name, score, house group]. It then checks each new array against the data in the csv file, and adds any new results.
My program works on a single pdf file, because I've manually typed in:
f = File.open('output\agb summer report.txt')
agb = []
f.each_line do |line|
  agb.push line
end

But I have a whole folder of pdf files that I want to run the program on iteratively. I've also had problems when I try to write each result to a new-named file.
I've tried things with variables and code blocks, but I now don't think you can use a variable in that way?
Dir.foreach('output') do |ea|
  f = File.open(ea)
  agb = []
  f.each_line do |line|
    agb.push line
  end
end

^ This doesn't work. I've also tried exporting the directory names to an array, and doing something like:
a.each do |ea|
  var = '\'output\\' + ea + '\''
  f = File.open(var)
  agb = []
  f.each_line do |line|
    agb.push line
  end
end

I think I'm fundamentally confused about the sorts of object File and Dir are? I've searched a lot and haven't found a solution yet. I am fairly new to Ruby.
Anyway, I'm sure this can be done - my current backup plan is to copy my program 40 times with different details, but that sounds absurd. Please offer thoughts?
Answer: You're very close. Dir.foreach() will return the name of the files whereas File.open() is going to want the path. A crude example to illustrate this:
directory = 'example_directory'
Dir.foreach(directory) do |file|
  # Assuming Unix style filesystem, skip . and ..
  next if file.start_with? '.'

  # Simply puts the contents
  path = File.join(directory, file)
  puts File.read(path)
end

Comment: Better: Use `File.join` to get the full path.
Comment: Cheers! 90% of my beginner Ruby problems seem to be trying to do a thing with the wrong sort of data type, and this would be an example of that...
Answer: You can use Dir.new("./") to get all the files in the current directory
so something like this should work.
file_names = Dir.new "./"

file_names.each do |file_name|
  if file_name.end_with? ".txt"
    f = File.open(file_name)
    agb = []
    f.each_line do |line|
      agb.push line
    end
  end
end

btw,  you can just use agb = f.to_a  to convert the file contents into an array were each element is a line from the file.
file_names = Dir.new "./"
file_names.each do |file_name|
  if file_name.end_with? ".txt"
    f = File.open file_name
    agb = f.to_a
    # do whatever processing you need to do
  end
end

Comment: Oooh fancy. f.to_a is really convenient and easy to understand - I am new to this, so some of the more abstract ways of pushing things in and out of files break my brain.
Answer: Use Globbing for File Lists
You need to use Dir#glob to get your list of files. For example, given three PDF files in /tmp/pdf, you collect them with a glob like so:
Dir.glob('/tmp/pdf/*pdf')
# => ["/tmp/pdf/1.pdf", "/tmp/pdf/2.pdf", "/tmp/pdf/3.pdf"]

Dir.glob('/tmp/pdf/*pdf').class
# => Array

Once you have a list of filenames, you can iterate over them with something like:
Dir.glob('/tmp/pdf/*pdf').each do |pdf|
  text = %x(pdftotext "#{pdf}")
  # do something with your textual data
end

If you're on a Windows system, then you might need a gem like pdf-reader or something else from Ruby Toolbox that suits you better to actually parse the PDF. Regardless, you should use globbing to create a file list; what you do after that depends on what kind of data the file actually holds. IO#read and descendants like File#read are good places to start.
Handling Text Files
If you're dealing with text files rather than PDF files, then something like this will get you started:
Dir.glob('/tmp/pdf/*txt').each do |text|
  # Do something with your textual data. In this case, just
  # dump the files to standard output.
  p File.read(text)
end

Answer: if you assign your target folder like this /path/to/your/folder/*.txt it will only iterate over text files.
2.2.0 :009 > target_folder = "/home/ziya/Desktop/etc3/example_folder/*.txt"
 => "/home/ziya/Desktop/etc3/example_folder/*.txt"
2.2.0 :010 > Dir[target_folder].each do |texts|
2.2.0 :011 >     puts texts
2.2.0 :012?>   end
/home/ziya/Desktop/etc3/example_folder/ex4.txt
/home/ziya/Desktop/etc3/example_folder/ex3.txt
/home/ziya/Desktop/etc3/example_folder/ex2.txt
/home/ziya/Desktop/etc3/example_folder/ex1.txt

iteration over text files is ok
2.2.0 :002 > Dir[target_folder].each do |texts|
2.2.0 :003 >     File.open(texts, 'w') {|file| file.write("your content\n")}
2.2.0 :004?>   end

results
2.2.0 :008 > system ("pwd")
/home/ziya/Desktop/etc3/example_folder
 => true
2.2.0 :009 > system("for f in *.txt; do cat $f; done")
your content

your content

your content

your content

Ruby - iterate tasks with files


My proof regarding composition of permutations came to the same conclusion as the answer sheet, but through different methods. Is it valid?

Question: Let $S_3$ be a set of all permutations of elements in $\{1,2,3\}$. Prove that there doesn't exist f $\in S_3$ where $\{f,f^2,f^3,f^4,f^5,f^6\} = S_3$.
Where $f^n = f \circ f \circ \:... \circ \:f$ $n$ times.
The proof in the answer sheet goes about proving this by showing that $f \circ g \neq g \circ f$ for any $g \in S_3$. However my reasoning was like so:
All permutations of $\{1,2,3\}$ are of order $2$ or $3$, and therefore there are at most $3$ unique permutations for any $f^n$ where $f \in S_3$. However the number of unique permutations of $\{1,2,3\}$ is $3! = 6$.
Therefore $\{f,f^2,...,f^n\}$ does not contain all permutations of $\{1,2,3\}$, and so $\{f,f^2,...,f^n\} \neq S_3$ for any $f$ and any $n$.
Is my reasoning correct?
Answer: That looks reasonable to me; such an $f$ would need to have order 6, and you can show there is no such $f$.
There is a very minor flaw in your argument: it is not true that all permutations of $\{1,2,3\}$ have order 2 or 3.  There is one exception...
Comment: Oh, the identity permutation?