Is Regression and Classification "Inherently" Based on Probability?

Question: From a classical perspective, I have outlined some examples of models in which Probability seems to play an "inherent role" in Regression and Classification:

As a simple example, suppose we have some data (e.g. heights of students: 175 cm, 181 cm, 162 cm, etc.) . If we assume that this data comes for a Normal Probability Distribution, we could use the Likelihood Function of a Normal Distribution to estimate the specific Normal Distribution (i.e. the mean and standard deviation) that would have been "most likely" (i.e. optimal) to produce this data.

Regression: As a slightly more involved example, when we are working with Regression Models, we are interested in optimizing the "conditional expectation of the response given the covariates", provided we assume some underlying Probability Distribution. In many aspects, this is just like the first example - in most cases, we assume that the difference between the Actual Response and the Predicted Response (i.e. "error") is Normally Distributed - effectively, this Normal Distribution has a mean of "b0 + b1x1..." . We are now trying to find out the optimal values of these beta regression coefficients provided some underlying Probability Distribution.

Classification: In Classification problems, a regression model tries to learn a "optimal hyperplane" that separates the data such that the resulting error is minimized. When a new data point appears, the model will calculate the probability that this new data point belongs to any of the classes - and the the class corresponding to the highest of these probabilities will be assigned to this new point.

The above models are generally more closely related to Probability Distributions compared to models such as Neural Networks. However, I am not sure if Neural Networks for Regression and Classification tasks still operate under the following premise:  Given a specific input (i.e. combination of covariates), we would like to identify the response for this input that has the highest probability "conditional" on this observed input.
For models such as Neural Networks:

Do Neural Networks have an inherent Probability component?  Can we say that the predictions being made by some specific Neural Network model is "probabilistically the most likely response" given some observed inputs - Or does the notion of Probability have no real relevance here?

In a very general case for a classical MLP Network, suppose that for some specific input, a Neural Network predicts that the response is 17.6 : It would be wrong to imagine some probability distribution associated with this response and the expectation of this probability distribution being 17.6?

Thanks!
Note: I am aware of some general ideas in Machine Learning that involve Probability such as "PAC Theory" and "Empirical Risk Minimization" - but I am interested in learning whether models such as Neural Networks have an inherent probabilistic interpretation when making predictions (as do Regression Models). I am thinking that perhaps all Statistical Decision Theory (e.g. optimal classification label for a new observation, optimal prediction for a new observation) might have an inherent probabilistic interpretation, regardless of the Machine Learning model being used?
Comment: Neural networks can be understood to parameterize probability distributions because we design them that way. There are certain network designs that either do not or cannot represent probability distributions.
Comment: @AryaMcCarthy Would you provide a link to a network design that **cannot** represent a (possibly degenerate or non-degenerate) probability distribution? This is be quite interesting for personal study.
Answer: Christopher Bishop called his classic book Pattern Recognition and Machine Learning because what machine learning algorithms do is find patterns in the data and identify those patterns at prediction time. It proved to work very well as an automated solution for solving many different practical problems.
However, if you think about it, why if you collected a bunch of samples, and trained an algorithm on them, does it allow you to generalize the results to the samples you didn't see? To do this, you need to assume that your training data is a sample that comes from a broader population, and shares common characteristics with the population, so you can extrapolate your results to the rest of the population. Probability theory and statistics provide formal theoretical frameworks for doing exactly this.
As stated in the other answers, not every model predicts probabilities or expected values, not every loss directly translates to a likelihood function, but on theoretical grounds, we think of all those models using probability theory language because it allows us to connect the samples with the population. Most statistical models were designed in probabilistic terms from the beginning. For other algorithms that were not, on theoretical grounds we will still use probabilistic language to reason about them.
Answer: How you interpret the model's predictions depend on the model and the data. Some losses take the form of a conditional expectation, but not all losses.

Quantile regression estimates a conditional quantile (e.g. conditional median) instead of the conditional mean.

Not all neural networks use loss functions that are based in probability. An example that I've worked with is the triplet-loss network, which seeks to map data in the same class to a vector representation that is far away from the vector representations of all other classes.

Neural networks are not unique in being unrelated to probability. SVMs are not directly related to a probability model. Instead, the model training is motivated by optimizing a separating hyperplane. (But sometimes researchers will transform the signed distance from the hyperplane to a probability -- but this is not innately connected to training an SVM.)
Comment: How you interpret the model's predictions depend on the model and the data. Some losses take the form of a conditional expectation, but not all losses.
Comment: +1 [quasi-likelihood](https://en.m.wikipedia.org/wiki/Quasi-likelihood) is another example. It is a nice example because it relates very explicitly to 'not being a true probability'.
Comment: Thank you for your reply! In a very general case for a classical MLP Network, suppose that for some specific input, a Neural Network predicts that the response is 17.6 : It would be wrong to imagine some probability distribution associated with this response and the expectation of this probability distribution being 17.6? Thank you so much!
Comment: Thank you again for your reply! I remember I once heard someone talk about Statistical Decision Theory in which Classification and Regression Tasks were described through the framework of "selecting a response (for some input) that maximizes the expected value of the conditional probability" ... however, I might be remembering wrong...
Answer: In a certain sense a lot of models are allowing some sort of probabilistic interpretation even when they do not directly optimize a probability.
Many models are, for instance, optimised via some learning method that involves a probabilistic cross validation step. They optimize an estimate of parameters via trial-and-error and select the one that most often leads to a low cost. This estimate is probably close to the true value that is estimated.
Anything for which a standard error can be computed or estimated can be interpreted as probabilistic. Although sometimes the probability is not exactly computed, for instance just a variance is estimated.


Executing controllers methods from a library in codeigniter

Question: i have a question, i am developing a library for Codeigniter to create Job Queues with workers and delayed queue (Codeigniter-JobQueue). But i have a question...
... How can i perform or execute controller's methods inside this library? It will be awesome to know this.
The library is taking "controller, method, params" to transform after to "http://www.example.com/controller/method/params".
Thanks, and if you want to help me to develop, you are welcome. ;)
Answer: Use curl. If you however expect a return variable from controllers method, then C in your MVC is not designed properly.
Answer: Curl is a way to go. Controllers should output content and not return a variable. If you are scheduling any job, the library should call the URL itself. You could use the cli mode of codeigniter.
http://ellislab.com/codeigniter/user-guide/general/cli.html


host mirroring on multiple VM (unique VNETid/uuid)

Question: We want to mirror all traffic going in/out port vnet0, and we want to send it to bridge port vnet2 (where we have a traffic monitoring application) and make sure traffic from vnet2 is excluded on tcpdump running on vnet2
I am using bond0 mirroring to mirror traffic from all the VM present to new VM(vnet2) "tc filter add dev bond0 parent ffff: protocol all u32 match u8 0 0 action mirred egress mirror dev vnet2
tcpdump trace collected at vnet2 should have traces from all the VM except traces from vnet2
Answer: get the IP of new VM by below command:
-> ifconfig | grep -Eo 'inet (addr:)?([0-9].){3}[0-9]' | grep -Eo '([0-9].){3}[0-9]' | grep -v '127.0.0.1'
-> sudo tcpdump -w test.pcap not host


Resulting shapes when partitioning the constraint matrix $\boldsymbol{A}$ in linear programming

Question: \begin{equation}
\boldsymbol{A} =
\begin{bmatrix}
{1}_n^\top \otimes \mathbb{I}_m \\  \mathbb{I}_n  \otimes  {1}_m^\top
\end{bmatrix} \in \mathbb{R}^{(m+n)\times mn}
\end{equation}
If the above matrix is partitioned as follows, are the dimensions shown below correct?
\begin{equation}
\boldsymbol{A}' =
\begin{bmatrix}
{1}_n^\top \otimes \mathbb{I}_m
\end{bmatrix} \in \mathbb{R}^{m\times mn}
\end{equation}
\begin{equation}
\boldsymbol{A}'' =
\begin{bmatrix}
\mathbb{I}_n  \otimes  {1}_m^\top
\end{bmatrix} \in \mathbb{R}^{n\times mn}
\end{equation}
If not, have I misinterpreted the steps to partitioning a block matrix? Can you then show how it can be corrected?
Answer: I would assume that $\otimes$ is the Kronecker product and that $A'$ refers to the first set of rows of $A$ (and not a transpose, as that notation is also often used - so that is not your question, I assume), i.e., that
$$
A=\begin{pmatrix}A'\\A''\end{pmatrix}
$$ Also, $1_n$ is an $n$-dimensional column vector, so that $1_n^\top$ is $(1\times n)$.
Then, the results follow from the definition of a Kronecker product, which say that the row dimension of $C\otimes D$ is the product of the row dimensions of $C$ and $D$, and likewise for the column dimension. Since $1_n^\top$ has row dimension 1 and $\mathbb{I}_m$ has row-dimension $m$, ${1}_n^\top \otimes \mathbb{I}_m$ has row-dimension $m$. The same reasoning leads to $n$ rows for $A''$, so $n+m$ rows in total.
Since $1_n^\top$ has $n$ columns and $\mathbb{I}_m$ has $m$, the column dimension is, analogously, $mn$.
Comment: the column dimension is indeed $mn$, please see my edit
Comment: so what I wrote is right, or did I get the columns $mn$ shape wrong
Comment: in the answer to the following question, i try to correct someone else's take on $A'$ and $A''$'s column dimension. hope you also agree there, although I see now I misled them by incorrectly stating what $A$'s dimensions were in the comments due to a faulty source, which I then re-state in a later comment https://math.stackexchange.com/questions/3929230/linear-programming-with-a-second-decision-variable-in-the-constraint-vector
Comment: Assuming you refer to the penultimate comment there, yes, the column dimension should also be $mn$.


Group Module: Join & Remove users from user account/profile 2?

Question: I added an entityreference to the user's Account so users can select what group they want to join (checkboxes). They check it and via a rule, it automatically adds them to that group. I did this for multiple Group Types.
Now i need it to remove user (unsubscribe) from group if "unchecked". Right now users keep on getting added if they select a new checkbox, but they are not removed from the previous group.
How can the we remove them from the now unchecked group and add them to the newly checked rule?
I found how to delete all group subscriptions on one rule. However, it removes all subscriptions, even those not found in this entityreference. How can we limit to add/remove users from only these group types?
Willing to pay for support on this issue.
Thank you.
Comment: D7 ? is this functionality required when the user saves their account profile , as really Rules will only get you so far the only real way to get you exact what you need is custom code in a custom module but you need to provide more in question like where is the action take place, and screen shots of rules ect or you will not get an anwser that is right for you.
Comment: @TaggartJensen:  why do you think "*the only real way to get you exact what you need is custom code in a custom module*"? IMO it's perfectly doable what OPer is asking for in a custom rule (so no need for a *custom module* ...
Comment: I personally don't like having Raw php in a rule but yes you can do it this way. and i admit i have done it this way too so go for it
Answer: I solved this. :)
I used the views_rules module to create a view that filtered a list of exactly what i needed (filtering the group type per user).
I then created a rule:

Before saving a user account
Condition if previous is equal to new saved (Negate). So it will only run if there are changes in the field in question.
Added View Loop i created. Add action > Delete entity mid from the view loop.

Done. This deletes or unsubscribes any unchecked boxes/groups.
Now to create any new memberships/subscriptions to selected groups...
I added condition...
-If field empty... do nothing
-Else
-Loop the field in question (gmem_created)
-Create new entity of type group membership
-Save a data value
Data: [gmem-created:group], Value: [account:field-yourgroup]
-Save a data value
Data: [gmem-created:user], Value: [account]
-Save entity
Entity: [gmem-created], Force saving immediately: true


Are two weak instruments better than one weak instrument?

Question: From my understanding, when using IV regression to eliminate confounding effects, we prefer to have a single strong instrument, over multiple weak instruments which can lead to bias.
My question is, what happens in the case of a single instrument vs multiple (e.g., two) weak instruments.
I ran an arbitrary simulation with 15,000 observations, and noticed that the two instruments actually had a lower bias in their estimate and lower standard error. Is this a surprising result? What is the intuition behind this?
Comment: Could you make it more precise what do you mean by "weak" and "strong" instruments? Tell us more about your data.
Answer: Nothing surprising about this. The standard error of an estimator diminishes with a square root of the sample size. So if you take more measurements and average them, you would always be better than with fewer samples. The same phenomenon was observed outside of statistics, James Surowiecki described in his book the wisdom of the crowd, who quotes many experiments where averaging opinions of many people, even if lacking expertise, often
gave better results than the predictions by experts.


Android RSS Feed parsing and running app as service

Question: I am making an app for my college where we have to parse RSS feed and display it. I am using SAX Parser to parse it and its working smoothly. Now I want two functionality in my app. First of all I want to run it as a service so that it may notify users about new events i.e new updates from RSS and how should I differentiate between the old RSS feed parsed and the new one so that I can show only the new updates.
Please give a overview on how can I implement these two things.
Answer: I don't know about the first question (how to make it a service) but I've done the second in a past life. The way I went about it was:

Compute the hash (sha1) from the title (you might want add other fields too)
Store the hash into a database along with time stamp
If the hash matches the entry in the database don't add it
if (3) fails add to database
Display everything in the database in descending order of timestamp (latest first)
Comment: I was also thinking adding to the database. But adding after hashing is new. Will try it for sure
Comment: a hash (sha1) is exactly 20 bytes in length. So you save a lot of space.
Comment: I am hosting my xml file on my webserver. Is there any place where I can host it so that I can update it every few hours? Logging into the webserver every now and then is not possible.
Comment: You mean the feed xml? Generally these are generated automatically by some kind of cms. Wordpress is one example. When there are new posts, the feed xml is automatically updated. I don't know how to do this manually. When I had to do this, I was to read feeds which were generated by a particular web site. I don't know how it was generated.


Como imprimir um fomulario contendo tabelas (grade) via c#

Question: estou precisando gerar uma impressão de carnê de crediario parecido com este que se encontra em anexo. Não tenho a minima ideia de como fazer isso, qual ferramenta usar. Alguem poderia me dar uma dica?
Muito obrigado.
Answer: Você poderá fazer isso utilizando o PrintDocument. O evento _PrintPage do objeto PrintDocument possui como parâmetro PrintPageEventArgs que possibilita desenhar Strings e Linhas no seu documento para impressão.
Para escrever Strings no documento para impressão utilize:
e.Graphics.DrawString(string S, font Font, Brush brush, PointF point);

Para desenhar linhas utilize:
e.Graphics.DrawLine(Pen pen, Point pt1, Point pt2);

Recomendo a leitura dos seguintes artigos:
Como imprimir documentos - Macoratti:
http://www.macoratti.net/09/09/c_prn1.htm
Como imprimir documentos - MSDN:
https://docs.microsoft.com/pt-br/dotnet/api/system.drawing.printing.printdocument.print?view=dotnet-plat-ext-3.1
Função DrawLine MSDN:
https://docs.microsoft.com/pt-br/dotnet/api/system.drawing.graphics.drawline?view=dotnet-plat-ext-3.1
Comment: Davi, muito obrigado pela ajuda. Abraço.


Find Delta, given Epsilon $\lim_{x\to 10} \sqrt {19-x}=3, \epsilon=1$

Question: $$\lim_{x\to 10} \sqrt {19-x}=3\\ \epsilon=1
$$
Here's what I did: $$ -1<\sqrt {19-x}-3<1 \\ 2<\sqrt {19-x}<4\\ 4 < 19-x< 16\\ -15<-x<-3\\15>x>3$$
15 is the nearest value from $x_0= 10$ $$15-10>x-10>3-10\\5>x-10>-7$$
So $\delta$ is 5
I don't if this is right though, please help?
Comment: Silly mistake $16-19=25?$
Comment: but, even then, $\delta$ would still be 5 right?
Comment: You forgot to change the $25$ in the 2nd last line
Comment: is 5 the right answer now
Comment: Once you have the inequality $3<x<15$, you know that you can choose $\delta=\min(15-10, 10-3)=5$, or any other smaller positive number.
Answer: You have to find $\delta>0$ such that the following implication holds
$$
|x-10|<\delta\Rightarrow |\sqrt{19-x}-3|<1.
$$
Note that
$$
|\sqrt{19-x}-3|<1\ \Leftrightarrow\ 3<x<15\ \Leftrightarrow\ -7<x-10<5
$$
Therefore, for $\delta=5$ you get
$$
|x-10|<5\ \Leftrightarrow\  -5<x-10<5\
\Rightarrow\ -7<x-10<5\ \Leftrightarrow\ |\sqrt{19-x}-3|<1
$$
so
$$
|x-10|<5\Rightarrow |\sqrt{19-x}-3|<1
$$
as requared.
Comment: so $\delta = 5$?
Comment: correct, but this is not the only option, you may choose for instance $\delta=4$.
Comment: @boaz That's really the critical idea it's so hard to get students to understand when they first start proving limits rigorously-that $\delta$ and $\epsilon$ are real valued variables defined in a range by inequalities. They're no different then when they had to solve equations in x and y in high school algebra and there was a parameter giving more then one possible answer. The only difference is that now instead of an exact equation with a parameter, there's an inequality that determines the range of accepted values. This is very hard to get students to understand.


What does "version lock" exactly mean?

Question: I just read the main article about Semantic versioning 2.0.
"Version lock" is part of the "dependency hell" issue and explained like this:

In systems with many dependencies, releasing new package versions can
quickly become a nightmare. If the dependency specifications are too
tight, you are in danger of version lock (the inability to upgrade a
package without having to release new versions of every dependent
package).

However, I need to better understand this sentence.
Lets say, I have a library A (version 1) that uses another library B (version 1)
A v1 -> B v1
Now I fix a bug in B. Without Semver 2.0 I would just increase the version of B to v2.
But now I have no other chance to also upgrade A, because even though A did not change, one of its dependencies did.
So A also becomes Av2:
A v2 -> B v2
So the definition of version lock:
"the inability to upgrade a package without having to release new versions of every dependent package".
Should be rephrased to:
"the inability to upgrade a package without having to release new versions of every package that has a dependency on this package".
My first question: Is this correct or is my english too bad to get the sentence right?
Later, I would change my versioning to A v.1.0.0 and B v.1.0.0 and if I fix a bug in B, I will only increase the patch version (B v.1.0.1) and A can stay like it is? Or should A also be updated to v.1.0.1?
My second question: Did I get it right, how Semver can tackle the "version lock" problem?
Comment: While "on this package" seems right in the above context, it would be nonsensical in the context of the SemVer doc.
Answer: No replies yet,
I can answer my question because I asked chat GPT. He replied the following:
Your understanding of the definition of version lock is correct. The original definition you provided was a bit imprecise, and your rephrased version is more accurate.
Regarding your second question, yes, with Semantic Versioning (SemVer) 2.0, you would only need to increase the patch version of B to v1.0.1, and A could stay at v1.0.0, assuming that the bug fix in B is backward-compatible and does not introduce any breaking changes that would affect A.
SemVer provides a clear and standardized way of communicating backward-incompatible changes, new features, and bug fixes between different versions of software packages. This allows developers to specify the minimum and maximum compatible versions of a package that their software depends on, without having to worry about breaking changes or version conflicts.
By following SemVer guidelines, package maintainers can communicate the nature of their changes clearly, and software developers can make informed decisions about when and how to upgrade their dependencies. This reduces the risk of version lock and makes it easier to manage complex software systems with many dependencies.
Then I replied:
But if I fix a bug in B, then this bug will also be fixed in A what should at least increase the patch version of A too or not.
Then he replied:
If you fix a bug in B, and this bug affects A as well, then you should also increase the patch version of A to reflect the bug fix. This is because SemVer specifies that a patch version change should be made for backwards-compatible bug fixes.
In other words, if you release B v1.0.1 with a bug fix, and A depends on B v1.0.1, then you should also release A
Sounds reasonable to me. :)
So maybe the sentence in Semver could be rephrased. :-D
Comment: ChatGPT answers are forbidden here. I don't totally disagree with this answer, but it doesn't really get at the nuances involved.  Also, the phrasing in the SemVer intro makes perfect sense to me and StackOverflow is not the right forum for that debate, [semver/semver/issues](https://github.com/semver/semver/issues) is.

What does "version lock" exactly mean?


How to load a node edit form using Ctools module in Drupal 7

Question: I am trying to load a node edit form into a modal frame using Ctools.  The following is the function I am using.  So far the $op = 'view' part is working fine, but I cannot get the node edit form to load when $op = 'edit'.  I have searched for the better part of the day, but I cant find anything about how to load node forms in a modal frame using Ctools in Drupal 7.
function namecards_modalframe_node($op, $nid, $js = FALSE) {
  $output = '';
  switch ($op) {
    case 'view':
      if ($js) {
        ctools_include('ajax');
        ctools_include('modal');
        $output .= theme('namecards_download_cvs_link', $nid);
        // Create table showing contact's information
        $table_structure = namecards_get_table_data($nid);
        $output .= theme('table', array('header' => $table_structure['header'], 'rows' => $table_structure['rows'], 'attributes' => $table_structure['attributes']));
        $output .= theme('namecards_download_cvs_link', $nid);
        // Add close button to bottom of page.
        return ctools_modal_render(t('Details'), $output);;
      }
      else {
        $output .= theme('namecards_download_cvs_link', $nid);
        // Create table showing contact's information
        $table_structure = namecards_get_table_data($nid);
        $output .= theme('table', array('header' => $table_structure['header'], 'rows' => $table_structure['rows'], 'attributes' => $table_structure['attributes']));
        $output .= theme('namecards_download_cvs_link', $nid);
        // Add close button to bottom of page.
        $form = drupal_get_form('namecards_modalframe_close_button_form');
        $output .= drupal_render($form);
        return $output;
      }
      break;

    case 'edit':
      // Include 'node.pages.inc' in order to be able to use node functions
      module_load_include('inc', 'node', 'node.pages');
      //      form_load_include($form_state, 'inc', 'node', 'node.pages');
      $node = node_load($nid);

      if ($js) {
        ctools_include('ajax');
        ctools_include('modal');
        $form_state = array(
            'ajax' => $js,
            'title' => t('Edit'),
            'build_info' => array(
                'args' => array(
                    'node' => $node,
                ),
            ),
        );
        return ctools_modal_form_wrapper('namecards_some_form', $form_state);
      }
      else {
        $node_edit_form = node_page_edit($node);
        return drupal_render($node_edit_form);
      }
      break;
  }
}

Each time I click on the link, the modal frame opens but it is blank (accept for the loading animation).  At the same time a js alert box appears containing the following:
An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows.
Path: /namecards/modalframe/node/edit/4585/ajax
StatusText: OK
ResponseText:
drupal7
@import url("http://drupal7/modules/system/system.base.css?lylwzg");
@import url("http://drupal7/modules/system/system.menus.css?lylwzg");
@import url("http://drupal7/modules/system/system.messages.css?lylwzg");
@import url("http://drupal7/modules/system/system.theme.css?lylwzg");
@import url("http://drupal7/misc/vertical-tabs.css?lylwzg");
@import url("http://drupal7/modules/contextual/contextual.css?lylwzg");
@import url("http://drupal7/modules/comment/comment.css?lylwzg");
@import url("http://drupal7/modules/field/theme/field.css?lylwzg");
@import url("http://drupal7/sites/all/modules/namecards/namecards.css?lylwzg");
@import url("http://drupal7/modules/node/node.css?lylwzg");
@import url("http://drupal7/modules/search/search.css?lylwzg");
@import url("http://drupal7/modules/user/user.css?lylwzg");
@import url("http://drupal7/sites/all/modules/views/css/views.css?lylwzg");
@import url("http://drupal7/sites/all/modules/ctools/css/ctools.css?lylwzg");
@import url("http://drupal7/modules/shortcut/shortcut.css?lylwzg");
@import url("http://drupal7/modules/toolbar/toolbar.css?lylwzg");
@import url("http://drupal7/themes/garland/style.css?lylwzg");
@import url("http://drupal7/themes/garland/print.css?lylwzg");
Skip to main content
Home
Hello drupal7
Log out
Administrative toolbarDashboard (View and customize your dashboard.)
Content (Administer content and comments.)
Structure (Administer blocks, content types, menus, etc.)
Appearance (Select and configure your themes.)
People (Manage user accounts, roles, and permissions.)
Modules (Extend site functionality.)
Configuration (Administer settings.)
Reports (View reports, updates, and errors.)
Advanced help
Help (Reference for usage, configuration, and modules.)
Hide shortcuts
Add content
Find content
Performance
Edit shortcuts
drupal7
Main menuBooks
Home
Namecards
Secondary menuMy account
Log out
Configure block
Search form
Search
Navigation
List links
Edit menu
Configure block
Add content
Development
List links
Edit menu
Configure block
Devel settings
Empty cache
Entity info
Execute PHP Code
Field info
Function reference
Hook_elements()
Menu item
PHPinfo()
Rebuild menus
Reinstall modules
Run cron
Session viewer
Theme registry
Variable editor
You are hereHome
Configure block
Powered by Drupal

Would appreciate any suggestions on how to get this working.
Comment: If you figured out the solution, please post it as an answer and mark it accepted for future visitors to benefit
Comment: I worked out how to do it.  I finally can across an answer with an example in the issues queue of the Ctools module.  Anyone else struggling with this should check out the discussion [here](http://drupal.org/node/1209472).
Comment: Am also getting a same error using in ctools_modal_text_button in custom module for viewing the user profile edit page
Answer: I used the following code in a resent project, hope this helps:
Add this code to custom_module.module:
/**
 * Implementation of hook_menu().
 */
function custom_module_menu() {
  $items = array();

  // @see node_menu in node.module:
  // @todo Remove this loop when we have a 'description callback' property.
  // Reset internal static cache of _node_types_build(), forces to rebuild the
  // node type information.
  node_type_cache_reset();
  foreach (node_type_get_types() as $type) {
    $type_url_str = str_replace('_', '-', $type->type);
    $items['modal/node/add/' . $type_url_str . '/%ctools_js/%'] = array(
      'title' => $type->name,
      'title callback' => 'check_plain',
      'page callback' => 'custom_module_node_page_add',
      'page arguments' => array($type->type, 4, 5),
      'access callback' => 'node_access',
      'access arguments' => array('create', $type->type),
      'description' => $type->description,
      'file' => 'custom_module.pages.inc',
    );
  }
  $items['modal/node/%node/edit/%ctools_js/%'] = array(
    'title' => 'Edit',
    'page callback' => 'custom_module_node_page_edit',
    'page arguments' => array(2, 4, 5),
    'access callback' => 'node_access',
    'access arguments' => array('update', 2),
    'weight' => 0,
    'type' => MENU_LOCAL_TASK,
    'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
    'file' => 'custom_module.pages.inc',
  );

  return $items;
}

add the following to custom_module.pages.inc:
 /**
  * Page Callback - Modal: Add Node
  */
function custom_module_node_page_add($type, $js, $force_page_reload = FALSE) {
  // Fall back if $js is not set.
  if (!$js) {
    return drupal_goto('node/add/' . str_replace('_', '-', $type));
  }

  // Get node form defaults.
  global $user;
  $types = node_type_get_types();
  $node = (object) array(
    'uid' => $user->uid,
    'name' => (isset($user->name) ? $user->name : ''),
    'type' => $type,
    'language' => LANGUAGE_NONE
  );

  $title = t('Create @name', array('@name' => $types[$type]->name));

  custom_module_node_form($node, $title, $force_page_reload);
}

/**
 * Page Callback - Modal: Edit Node
 */
function custom_module_node_page_edit($node, $js, $force_page_reload = FALSE) {
  // Fall back if $js is not set.
  if (!$js) {
    return drupal_goto('node/' . $node->nid . '/edit/');
  }

  $type_name = node_type_get_name($node);
  $title = t('Edit @type @title', array('@type' => $type_name, '@title' => $node->title));

  custom_module_node_form($node, $title, $force_page_reload);
}

/**
 * Build the Modal Form.
 *
 * @param object $node
 *   The node Object in edit case. In Add case it's only a pseudo node object.
 * @param string $title
 *   The Modal Popup Title.
 * @param boolean $force_page_reload
 *   Indicates if page should be reloaded after form submission.
 */
function custom_module_node_form($node, $title, $force_page_reload = FALSE) {
  $commands = array();

  ctools_include('node.pages', 'node', '');
  ctools_include('modal');
  ctools_include('ajax');

  $form_state = array(
    'title' => $title,
    'ajax'  => TRUE,
    'build_info' => array(
      'args'  => array($node),
    ),
  );

  $commands = ctools_modal_form_wrapper($node->type . '_node_form', $form_state);

  if (!empty($form_state['executed']) && empty($form_state['rebuild'])) {

      // overwrite commands.
      $commands = array();

      ctools_add_js('ajax-responder');
      $commands[] = ctools_modal_command_dismiss();
      // if (t('Delete') == $form_state['values']['op']) {
      //   $commands[] = ctools_ajax_command_redirect('modal/node/' . $node->nid . '/delete/ajax/reload');
      // }
      // else
      if ($force_page_reload) {
        $commands[] = ctools_ajax_command_reload();
      }
  }

  // add CSS class to Modal-Frame
  $commands[] = ajax_command_invoke('#modalContent', 'addClass', array('custom-module-node', 'custom-module-node-form'));

  print ajax_render($commands);
  exit;
}

Comment: This solution looks great, but I can't get it working.
Is that all I need to do. Make a new module and put this 2 files in there. (and my module.info off course)
Modal forms is enabled, but when I go to an node/add/mytype page nothing happens, the page opens like before, not in a modal. The same behaviour of node/%/edit, no modal.
I also tried modal/node/add/, but this page could not be found.
This solution should redirect all node/add pages to a modal, right?
Comment: I'm having the same issue. Not quiet understanding what else needs to be done. I do have my .info file that loads the custom module. Everything seems to be working. I just don't know how to get a link to open with module, like Add Node of a specific Content type.
Answer: Here's how to make a module from Lars Schroeter code (below).
Put both files (custom_module.module & custom_module.pages.inc) in a folder named custom_module. Of course, both files must begin with <?php. Then create the required custom_module.info file. Something like this will do.
name = "Node edit modal"
description = "How to load a node edit form using Ctools module in Drupal 7."
package = "Modal Gallery"
core = 7.x
files[] = custom_module.module

dependencies[] = "ctools"

Put the .info file in the custom_module folder. Put the folder in sites/all/modules. Go to your modules pages and enable it. Then, create a link on a test page. For example
Create content (node/add)

Thanks Lars, the code really helped me get going!
Comment: Can you link to the original code? I can't see how custom_module.pages.inc will be loaded using your code
Comment: I tried adding `Create content (node/add)` after getting this custom module set up. But shows `The requested page "mysite/node/node/add/nojs` could not be found.'. So I removed the extra 'node' and it just opens a normal window with the list of all my Node Content Types. I'm not understanding how you can get it to successfully call the function in my custom module to have a specific link to open a modal form.


What is the difference between a manager and a coach in case of a football team?

Question: What is the difference between a manager and a coach in case of a football team?
These two terms are used frequently and interchangeably.
Answer: As you said in question these terms are used interchangeably. From Wikipedia:

In association football, a manager is an occupation of head coach in the United Kingdom responsible for running a football club or a national team. Outside the British Isles and across most of Europe, a title of head coach or coach is predominant.

and also,

The title of manager is almost exclusively used in British football. In the majority of countries where professional football is played, the person responsible for the direction of a team is awarded the position of coach or "trainer". For instance, despite the general equivalence in responsibilities, Bobby Robson was referred to as the manager of England, while Joachim Löw was described as the head coach of Germany (Germany also has a team manager role that is subordinate to the head coach and that is filled by Oliver Bierhoff).

However, the difference between these terms can be understood as:

A manager is a part of a football team who has complete authority over the running and functioning of the team. He has the autonomy to choose his supporting staff, along with the provision to add players to the team if he deems it necessary.
and, a head coach is only given the responsibility of ensuring his team putting a good performance in the match they are playing. That includes the likes of choosing a first team and training the players in specific sets of routines required for their position in the team. The management of the team is under the club board.

Tottenham Manager Pochettino, in his interview accurately put what the difference is in the two roles1, 2,
3.

Pochettino has explained: "If you are the manager, you decide many things about the club. But if you are a head coach, your responsibility is to play better, try to improve the players and to get positive results.
"At Southampton, I was a manager. My responsibility was not only to coach the team. With Tottenham, I am a head coach.  A head coach is head of your department. My department is to train the team."

Also, when former Sunderland head coach Paolo Di Canio got sacked after just 13 games in charge in September 2013 . He stated illustrating differences between roles of these two:

"Not one of those [players] was bought by me. Roberto De Fanti and Valentino Angeloni were the two responsible for that technical error, with the maximum support from the chairman, which is Ellis Short. But I didn't bring in one player. I asked for them to bring in 80 per cent British footballers."

At last, many websites1, 2 even premierleague.com use these two terms interchangeably and shows Antonio Conte as a manager of the club Chelsea F.C., while the official website lists Conte as a head coach.

For comparison against manager considering coach as head coach.
What's the difference between a coach and a manager?
Football (soccer) :What is the difference between football coach and football manager?
Antonio Conte asked who Chelsea will sign... here's his response
Answer: The short answer is that these 2 terms have equivalent meanings in football. And whenever you read one of these words in a sports article, most of the times, authors don't distinguish between terms and don't emphasize any specific meaning.

The long answer is that the term "manager" is frequently used in the UK to distinguish between a "normal coach" and a "a coach who also has responsibilities of a sporting director (director of football)" - a "manager". In continental Europe, however, the terms "(head) coach" or "trainer" are more prevalent, and in addition, many clubs have explicit sporting director positions.
The exact difference can be best understood by reading Mauricio Pochettino's explanation:

If you are the manager, you decide many things about the club. But if
  you are a head coach, your responsibility is to play better, try to
  improve the players and to get positive results.
At Southampton, I was a manager. My responsibility was not only to
  coach [train] the team. With Tottenham, I am a head coach.  A head coach is
  head of your department. My department is to train the team.

But again, the main difference is that in the UK, people use "manager" and in the rest of Europe, people prefer "(head) coach". Here are the demonstrative examples from official websites of some biggest clubs:

Zinedine Zidane - Real Madrid - not UK - "coach"
Ernesto Valverde - Barcelona - not UK - "coach"
Massimiliano Allegri - Juventus - not UK - "head coach"
Jupp Heynckes - Bayern Munich - not UK - "head coach"
José Mourinho - Manchester United - UK - "manager"
Jürgen Klopp - Liverpool - UK - "manager"
Comment: ++, "most of the times, authors don't distinguish between terms and don't emphasize any specific meaning" and ignore me for using Pochettino's example as I was already writing my answer.
Comment: Nice research. Pochettino would be proud of himself.
Comment: Some of the difference expressed here is relatively recent (as in post 1970), as  the new management structures with titles like director of football have appeared in UK football.
Answer: Great distinction between the two roles of Manager and Coach.  Take aways are that Manager has overall Strategic responsibility for the Club's affairs reporting to the Board.  The Coach's role is more Tactical, focusing on mental / psychological and physical preparation of the team for optimum performance as a system or unit, to the specific tactics needed against a specific opponent  This would include individual fitness and skill development of each player, as well as ensuring that there is a coherent (scientific) system of play, which ensures the best results, being mindful to identify the best positional placements on the field, also drills for attack and defence, as well as winning and recovery tactics, planned and executed in conjunction with the Manager.  The coach must have capacity to stand in for the Manager, in the event that the manager is absent.
These two roles would ideally be supported by such functions as the Team Medic, who ensures optimum health of the team, and attends to players in recovery from injury; also a Team Psychologist for morale boost, to build mental toughness at both individual and Team level, so that they can outlast their opponents, or bounce back when forced onto their book foot..
Comment: Welcome to Sport Stack Exchange. The question refers to the manager and coach of a specific team; I am not aware of any manager who would be responsible for the entire club's performance, except where the club has only one team anyway. Can you tailor your answer more specifically to the question as asked here?


High chart with diffrent series data

Question: I want to create a chart with different series data. I have a poll with several question and every question has different options.
I tried to use this code :
$(function () {
$('#c_chart').highcharts({
    chart: {
        type: 'column'
    },
    xAxis: {
        categories: [
            'Question 1',
            'Question 2',
        ],
        crosshair: true
    },
    yAxis: {
        min: 0,
        title: {
            text: 'Rainfall (mm)'
        }
    },
    tooltip: {
        headerFormat: '{point.key}
',
        pointFormat: '
{series.name}: 	' +
            '{point.y:.1f} mm
',
        footerFormat: '
',
        shared: true,
        useHTML: true
    },
    plotOptions: {
        column: {
            pointPadding: 0.2,
            borderWidth: 0
        }
    },
    series: [{
        name: [['Option1', 'Option2']],
        data: [49.9, 56]

    }, {
        name: 'Option3',
        data: [83.6]

    }
    ]

});});

How can I create this chart like following image:
Chart
Comment: How about 1 series per option? Then just fill in the values for that option, per question, in `data`.
Comment: @HalvorStrand How can I do this ? :)
Comment: You can use x index per each point, like in the example: http://jsfiddle.net/29wws4bt/, is that correct?
Answer: my english is basic but, i try to splain rigth?
try to look this links, im not very sure if you need to move something in plotOptions:{} or chart:{}
the other options not draw the chart. i found this links, i'll hope help you
http://www.highcharts.com/docs/chart-design-and-style/design-and-style
http://api.highcharts.com/highcharts#plotOptions.bar.dataLabels
grettins, from mexico :)
Answer: $(function () {
$('#container').highcharts({

    chart: {
        type: 'column'
    },

    title: {
        text: 'Questions Answers'
    },

    xAxis: {
        categories: ['Question1', 'Question2', 'Question3', 'Question4', 'Question5']
    },

    yAxis: {
        allowDecimals: false,
        min: 0,
        title: {
            text: 'Option Ticked'
        }
    },

    tooltip: {
        formatter: function () {
            return '' + this.x + '
' +
                this.series.name + ': ' + this.y + '
';
        }
    },

    plotOptions: {
        column: {
            stacking: false
        }
    },

    series: [{
        name: 'Option1',
        data: [5, 3, 4, 7, 2]
    }, {
        name: 'Option2',
        data: [3, 4, 4, 2, 5]
    }, {
        name: 'Option3',
        data: [2, 5, 6, 2, 1]
    }, {
        name: 'Option4',
        data: [3, 0, 4, 4, 3]
    }]
});

});

High chart with diffrent series data


What are the properties of MLE that make it more desirable than OLS?

Question: This question seems fundamental enough that I'm convinced it has been answered here somewhere, but I haven't found it.
I understand that if the dependent variable in a regression is normally distributed, maximum likelihood and ordinary least squares produce the same parameter estimates.
When the dependent variable is not normally distributed, the OLS parameter estimates are no longer equivalent to MLE but they are still Best (minimum variance) Linear Unbiased estimates (BLUE).
So, what are the properties of MLE that make it desirable beyond what OLS has to offer (being BLUE)?
In other words, what do I lose if I can't say my OLS estimates are maximum likelihood estimates?
To motivate this question a little: I'm wondering why I would want to choose a regression model other than OLS in the presence of a clearly non-normal dependent variable.
Comment: Depends what you want from the model.  Econometricians commonly want average in-sample marginal effect estimates, and OLS provides these (so long as you aren't bothered by additive separability assumptions).  But if you want a model that describes other features of the underlying phenomenon, OLS won't work as well.  For example, you might be interested in prediction out of sample, or want better estimates of uncertainty.
Comment: It is worth mentioning that OLS is more sensitive to outliers, because the objective function uses squared error (so the problem gets worse the more extreme the deviation).  This is why 'robust regression' techniques like M-estimation use MLE instead of OLS.
Comment: If the error term is not normal then t tests and F tests of coefficients may unreliable.  Extreme skewness and extreme outliers are a particular problem.  As practical matter this makes correct model specification harder, contributing to possible bias in the coefficient estimates (from miss-specification), and poor out of sample performance.
Answer: As you move sufficiently far away from normality, all linear estimators may be arbitrarily bad.
Knowing that you can get the best of a bad lot (i.e. the best linear unbiased estimate) isn't much consolation.
If you can specify a suitable distributional model (ay, there's the rub),
maximizing the likelihood has both a direct intuitive appeal - in that it "maximizes the chance" of seeing the sample you did actually see (with a suitable refinement of what we mean by that for the continuous case) and a number of very neat properties that are both theoretically and practically useful (e.g. relationship to the Cramer-Rao lower bound, equivariance under transformation, relationship to likelihood ratio tests and so forth). This motivates M-estimation for example.
Even when you can't specify a model, it is possible to construct a model for which ML is robust to contamination by gross errors in the conditional distribution of the response -- where it retains pretty good efficiency at the Gaussian but avoids the potentially disastrous impact of arbitrarily large outliers.
[That's not the only consideration with regression, since there's also a need for robustness to the effect of influential outliers for example, but it's a good initial step]

As a demonstration of the problem with even the best linear estimator, consider this comparison of slope estimators for regression. In this case there are 100 observations in each sample, x is 0/1, the true slope is $\frac12$ and errors are standard Cauchy. The simulation takes 1000 sets of simulated data and computes the least squares estimate of slope ("LS") as well as a couple of nonlinear estimators that could be used in this situation (neither is fully efficient at the Cauchy but they're both reasonable) - one is an L1 estimator of the line ("L1") and the second computes a simple L-estimate of location at the two values of x and fits a line joining them ("LE").

The top part of the diagram is a boxplot of those thousand slope estimates for each simulation. The lower part is the central one percent (roughly, it is marked with a faint orange-grey box in the top plot) of that image "blown up" so we can see more detail. As we see the least squares slopes range from -771 to 1224 and the lower and upper quartiles are -1.24 and 2.46. The error in the LS slope was over 10 more than 10% of the time. The two nonlinear estimators do much better -- they perform fairly similarly to each other, none of the 1000 slope estimates in either case are more than 0.84 from the true slope and the median absolute error in the slope is in the ballpark of 0.14 for each (vs 1.86 for the least squares estimator). The LS slope has a RMSE of 223 and 232 times that of the L1 and LE estimators in this case (that's not an especially meaningful quantity, however as the LS estimator doesn't have a finite variance when you have Cauchy errors).
There are dozens of other reasonable estimators that might have been used here; this was simply a quick calculation to illustrate that even the best/most efficient linear estimators may not be useful. An ML estimator of the slope would perform better (in the MSE sense) than the two robust estimators used here, but in practice you'd want something with some robustness to influential points.
Comment: No, symmetry is not sufficient to rescue linear estimation. Consider Cauchy errors, for example. There are any number of adequate estimators but they're all nonlinear in the intended sense.
Comment: Well said. That makes a lot of sense. I assume that linear estimators still work quite well (maybe even better than non-linear estimators) when the dependent variable is non-normal but still symmetric. Is my intuition correct here?
Comment: I have done a little simulation to illustrate this problem (of potentially arbitrarily bad performance) applies to symmetric error distributions -- see my edit. That simulation is for a symmetric error distribution. You can see how disastrous least squares can be in that case. Indeed even a tiny fraction of contamination with something that may have gross errors is a problem for it. Being BLUE may sometimes be of little value at all. If you know something about how your errors behave, it may be a good idea to use that knowledge ... ctd
Comment: ctd...  (via ML, say, even if you supplement it with a little robustness in case you're wrong; like bounding the influence function of the resulting M-estimator) and if you know nothing -- not enough to assume a likelihood at all -- it's not necessarily worth the potential risk in assuming that a linear estimator will be a great choice. I wouldn't say "never use least squares" (I use it fairly regularly yet have been keenly aware of how bad it may potentially perform) --  but BLUE on its own doesn't necessarily imply that it's a good choice.
Answer: In the case of normally distributed data, OLS converges with the MLE, a solution which is BLUE (in that point). Once out of normal, OLS isn't BLUE anymore (in the terms of Gauss-Markov theorem) - this is because OLS looks to minimize the SSR whereas GMT defines BLUE in terms of minimal SE. See more here.
Generally speaking, given that a MLE exists (google for 'MLE failure' or for cases where MLE doesn't exist), it is easier to adjust it, either for minimizing the variance or making it unbiased (and therefore comparable to other estimators).
Comment: The dependent variable doesn't need to be normal for OLS to be BLUE: https://en.wikipedia.org/wiki/Gauss%E2%80%93Markov_theorem
Comment: ... in addition, with normally distributed data, OLS = the MLE, it doesn't converge to it.  Your second paragraph is also quite unclear... easier to adjust the MLE than what?
Comment: OLS is still BLUE outside of normality; the problem is that BLUE (and in particular, the *L*) itself isn't necessarily a useful thing to have.


Django. General design philosophy question: best way to implement "toggleable" separate features in a website

Question: Let's say I want to create a blueprint of an online store that I can sell to potential clients. However, the idea is to make it so that the client chooses features that they want their store to have (from a pre-designated list) and pay only for those features, that way avoiding paying for something they don't need.
So for example, one client wants to have and online store with a Cart, Purchase History, Graphs, Reports. Another one only wants simple registration and cart (but maybe in future they will want me to "enable" other features as well).
My question is: what, in your opinion, is the best way to tackle this problem from a Django developer perspective?
My thoughts:

Create every feature as a separate app and deploy the whole thing commenting out the features that client did not pay for. And when a client wants additional features, I simply go to settings.py and uncomment the app they requested. Can I even make changes on the settings.py file on a live website without restarting it?
Create an admin panel for myself (the superuser) that will have an ability to turn features on or off. So when the client pays for a new feature, I simply go to my admin panel and put a tick mark next to it, and voila! That way I don't have to make changes in settings.py file (and I don't need access to the hosting server, just the django admin panel). Thought I'm not sure how to do this programmatically. I think I need a separate Model with a lot of BooleanFields(?)

What are pros and cons of each approach and what other ways to achieve this can you think of?
Edit 1.
To clarify, this will not be a shopify-style service, but simply a website that I will create separately for each client. But I want to have a blueprint to quickly create one and add/remove features on the fly.
Answer: I would recommend the admin panel approach.  If you plan to launch a service online that many people can access to generate a store front, you don't want to push code changes for a simple thing like adding a feature.  That would get cumbersome and is not a good practice.  Also modifying the settings.py file would typically need to have the web service (i.e. Apache) restarted so the file is reinitialized.
With the admin panel approach, then all you have to do is look up a customer, see what features they have and check boxes.  You could make it more complex of course, especially if a new added feature is going to cost the customer more.  But simply, the admin approach is best, it gives you the flexibility and you don't have to be worried about potentially taking down the site with a code push.


Higher order derivatives: variation of parameters

Question: Higher order of derivatives: variation of parameters?
$$y'''+y' = \tan t, \quad 0 < t< \pi.$$
Use variation of parameters to determine the general solution of the given differential equation.
I know the roots of the characteristic equation are $0$, $-i$, and $i$. But I'm really confused about how to approach the question. I tried doing the Wronskian but because it has a double root, it gave me a weird answer. Can someone please help me?
By the way, the answer of the question is
$$y= c_1 + c_2 \cos t + c_3 \sin t - \ln \cos t - \sin t \ln(\sec t + \tan t).$$
Comment: http://www.math.uah.edu/howell/DEtext/Part3/Var_Parameter.pdf look at page 9, it provides the answer and how to go about it.
Answer: First, let $f = y'$ to transform the equation into a second order equation
$$ f'' + f = \tan(t). $$
The characteristic equation is $\lambda^2 + 1 = 0$ with roots $\lambda = \pm i$. The Wronskian will be
$$ \left| \begin{array}{cc}
\sin(t) & \cos(t) \\
\cos(t) & -\sin(t) \end{array} \right| = -1. $$
Solve this equation using variation of parameters to find the general form of $f$ and then integrate to find $y$.


Serverless flask python application - No module named 'numpy.core._multiarray_umath' when using Numpy

Question: The numpy package fails to import when running in the lambda function after deploying. I am not sure what the issue is but the numpy module simply just fails to finish importing with the following error:
<code>ModuleNotFoundError: No module named 'numpy.core._multiarray_umath'
</code>
the outputted versions are as follows:
<code>* The Python version is: Python3.9 from "/var/lang/bin/python3.9"
* The NumPy version is: "1.22.0"
</code>
I am making use of Serverless Python Requirements in order to add packages to the lambda function.
I have already attempted to change python versions from 3.8 to 3.9 and the numpy versions from 1.23.3 to 1.22.0 but it seems numpy fails to import regardless.
Answer: The issue was being triggered by the numpy module not importing correctly inside of lambda at runtime.
This was caused by the incorrect architecture being used to deploy the lambda function, as my local setup did not match the environment lambda operates in.
I used a docker image to solve this and the module imported properly and the function behaved.


Alinhando botões no NAVBAR

Question: Tenho os seguinte botões na minha navbar:

Horas Pendências

Aferições

Índice OCR

                        <input type="radio" name="options" id="blocos" value="blocos">

                        <input type="radio" name="options" id="lista" value="lista">

                <input type="hidden" id="modoexibicao" />
                <input type="hidden" id="contratocod" />

                @Html.Partial("_LoginPartial")

Estão sendo exibidos da seguinte maneira:

Gostaria que eles ficassem alinhados no centro do navbar. O que fazer ?
Comment: Publiquei uma resposta meio ampla, apesar de você postar o seu cógio html e falar que está usando o bootstrap, ainda faltam algumas informações como css, questão das alturas dos elementos, se da suporte responsivo, etc. caso queira algo mais definido só comentar aqui com estas informações e eu edito minha resposta ^^
Comment: Alinhar verticalmente elementos costuma ser complicado ou requer um layout fixo. Mas se estiver usando flexbox é muito simples: basta usar a propriedade `align-items: center`.
Comment: @AldoFernandesJunior coloquei a div inteira do meu navbar. Espero ter ajudado
Comment: @RaphaelPradodeOliveira Opa beleza, dessa forma consegui já montar o teste ali com a sua própria navbar :). Ja fiz a edição na resposta, espero que tenha ajudado :)
Answer: Há várias formas possíveis de fazer isto, umas mais performáticas que outras.
Seu navbar tem alguma altura fixa? E os botões?
Caso tenham, você poderia adicionar um margin-top com a metade da subtração entra a altura do navbar e a altura do botão.
Você poderia também, em vez de ter os elementos jogados em seu navbar, coloca-los todos em um container a dar os espaços para cima e para baixo com padding ou margin.
Depende da aplicação de seu layout. usando o bootstrap, quando quero inserir novos elementos eu os centralizo verticalmente cor a margin-top, mas tomo muito cuidado para todas as minhas versões de visualizações responsivas, da qual posso trata-las com o @media screen
@edit:
Com o seu código já consegui dar uma ajuda melhor :)
Utilizei da mesma maneira que o Rodorgas havia citado, coloquei a altura em sua div navbar-nav fixa de 50px que é o padrão do navbar do bootstrap, e utilizei display:flex e align-items:center;.

.navbar-nav {height:50px; display:flex; align-items:center;}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Horas Pendências

Aferições

Índice OCR

                        <input type="radio" name="options" id="blocos" value="blocos">

                        <input type="radio" name="options" id="lista" value="lista">

                <input type="hidden" id="modoexibicao" />
                <input type="hidden" id="contratocod" />

Espero ter ajudado.
Comment: Funcionou. Muito obrigado

Alinhando botões no NAVBAR


Reduction map on torsion of elliptic curves

Question: Let $E$ be an elliptic curve over $\mathbb{Q}$ with good reduction at a prime $p$. It is well-known that the map
$$E[N]\to E_p[N]$$
is injective when $p\nmid N$. It is even a bijection since both groups have the same size.
Is anything known when $p\mid N$ ? All the books I've consulted about elliptic curves only consider the case $p\nmid N$.
For example, if $E$ has ordinary reduction, we have that $E[p]\cong(\mathbb{Z}/p\mathbb{Z})^2$ and $E_p[p]\cong \mathbb{Z}/p\mathbb{Z}$, so we could maybe expect a surjection from $E[p]$ onto $E_p[p]$...
Answer: First note that when you say that the reduction map on torsion is isomorphism (if $p \not\mid N$) you have to pass to some suitably large extension of $\mathbb Q$,
since typically the $N$-torsion points are not defined over $\mathbb Q$.
In general (i.e. even if $p \mid N$), if you pass to a suitably large extension of $\mathbb Q$ (depending on $N$), then the reduction map on $N$-torsion will be surjective.  (Using the Chinese Remainder Theorem, one easily reduces to the two
cases when $p \not\mid N$ or $N$ is a power of $p$.  The first case you've already discussed.   The second case can be dealt with e.g. using the point of view of finite flat group schemes, although there is presumably a more elementary treatment;
if this is not discussed in the discussion of formal groups in Silverman, then you
could try looking in Serre's paper on points of finite order on elliptic curves.)


OSX High Sierra Dock on left AND right

Question: I like having the Dock auto hidden on the left side. But when connecting a second screen I would like to have it on the left side of the left screen and on the right side of the right screen.
I don't think this is currently possible from house. Any suggestions (including external tools) to configure this?
Maybe changing it like this depending on which monitor the mouse is?
Thanks,
Kim
Answer: So I wrote an AppleScript which does exactly this. More on Github:
https://github.com/wuestkamp/osx_dock_multi_monitor

OSX High Sierra Dock on left AND right


Making a TFS project read only

Question: I want to make a TFS 2010 project read-only so users can view the info in work items but not add any details or new work items.  I think I need to change the security permission on the project but it's not clear which permission I would change from the Contributors list.
Answer: In my opinion the right way is to alter the group memberships.
Remove all users from the constributors and higher groups and move them to the Readers group.
Answer: Two choices.
Choice 1:  If this is a common pattern where the prevailing default is that folks are restricted, but some people have access (i.e. devs cannot change things but Tech Leads can), modify contributors and create a secondary group (for example, 'Tech Leads') that has the additional read rights.  In this scenario, the Contributors group would contain tech leads, but only specific individuals with the extra rights would be in the Tech Leads group.
Choice 2:  If the prevailing default is normal contributor access, but specific individuals (i.e. external contractors) need to be denied access, and you need to be 100% sure this goes through, regardless of any other group membership, then leave Contributors as is, and add a new group called (in this example) 'Contractors' and DENY specific access as needed.
Like before, everyone is a contrib, but contractors have some absolute limitations imposed on them, and the 'DENY' in the Contractors group overrides the 'Allow' from contrib.  A use case for this would be cases where specific code has to be hidden from external vendors or some other sub-group and needs to be 100% rock solid - just be careful with denies as they will trump any number of allows you inherit from other groups.
Hope that helps!
Addendum:  For restricting or changing rights on workitems, you need to do two things.  First, set up appropriate group mempership (noted above), then in the project, under Team Project Settings -> Areas and Iterations, click the Security button to set this up on a node by node basis (or at the root if you want to do these restrictions project wide).

Making a TFS project read only


Unable to set the value of a SelectControl element

Question: I am trying to get machine-parsable bus schedule data by submitting a form with mechanize.
However, I am stymied by the mechanize syntax for setting
import mechanize
br = mechanize.Browser()
br.open("http://www.planibus.sto.ca/HastinfoWeb/StartTimetableForm.aspx")
br.select_form(name="TimetableQueryForm")
br["RouteDirectionDynamicComboBox$ComboBox_Input"] = "10 OTTAWA" # works fine, it's a TextControl
br["DatePicker$DaysDropDownList"] = ["3"] # This is a SelectControl
### mechanize._form.ItemNotFoundError: insufficient items with name '3'

mechanize._form.ItemNotFoundError: insufficient items with name '3' looks like it needs a list, but when I enter more than one item in the list (which makes little sense, given that this is a date picker) I get:
mechanize._form.ItemCountError: single selection list, must set sequence of length 0 or 1
I thought that my original ["3"] was a sequence of length 1?
Thanks for your attention. I'm probably missing something obvious...
Edit: note that the '3' above is just one value, and the web site allows values for the next two weeks in its UI, so depending on when you see this, the list of allowable values will change. Just substitute the '3' with one of the allowable values... Still doesn't work for me...
Answer: 3 isn't one of the available select options, the options I see are
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>

So try br["DatePicker$DaysDropDownList"] = ["4"] and your code should work.
Edit: I've actually tried looking at the page in question with mechanize, try this
import mechanize
br = mechanize.Browser()
br.open("http://www.planibus.sto.ca/HastinfoWeb/StartTimetableForm.aspx")
br.select_form(name="TimetableQueryForm")
select = br.form.controls[8] # DatePicker$DaysDropDownList
select.possible_items()
>>> []

There aren't any options, I imagine that javascript is used to populate them after the page has loaded. Unfortunatly mechanize doesn't support javascript, try using Selenium Webdriver to scrape the data you need.
Comment: Yeah, the question was asked yesterday when "3" was a valid answer :-) I tried with (say) "10" and I get the same error
Comment: Selenium Webdriver is just too cool. I spent a few minutes with it and it looks like it will be a much better solution to my problem. And it was trivial to install with easy_install selenium. Thanks!
Comment: Great, glad to help. Look into pip, it's better than easy_install. `easy_install pip; pip install somepackage`


Is English the official language for international sport events?

Question: There are specific languages official for every sports (i.e. soccer/cricketboxing) / sport events (olympics/world events/continental events)?
I think the mostly used is English, but what about for example South American Games? And other international events?
Is there a rule in this way?
Answer: It depends of the event. For the Olympics, there are two official languages : English and French (which is by its reglementation the most important language of the Olympics). For FIFA, these languages are English, French, but also German and Spanish.
Comment: It varies a bit by sport (athletics, like the Olympics, operates in English and French). The Olympics do have a third "official" language, which is the language of the host nation.
Answer: No, there is no general rule. It depends on the sport and the event. For example, the official language of the Lusophony Games is (unsurprisingly!) Portuguese.


Send PDF to Browser ( as attachment )

Question: I am currently trying to resolve the following issue:
<code>        var fileName = "monthly_report.pdf"
        var document = new Document();
        //DO SOME STUFF WITH THE DOCUMENT

        MemoryStream stream = new MemoryStream();
        doc.Save(stream, SaveFormat.Pdf);
        byte[] bytes = stream.GetBuffer();
        Response.Clear();
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment; filename="+fileName);
        Response.BinaryWrite(bytes);
        Response.End();
</code>
Based on this code I am trying to display an Aspose. Words document converted into an pdf in the browser / trying to create a download dialog in the browser for said document.
When I execute the action there is no error message. The contents of the pdf are then displayed within the response message of the chrome debugger. The response also holds the appropriate size ( 60kb for the pdf ). It simply does not start a download or displays the pdf in the browser and I wonder why that would be.
I also tried an alternative provided by Aspose:
<code>        var resp = System.Web.HttpContext.Current.Response;
        resp.Clear();
        // Create Memory Stream Object
        MemoryStream stream = new MemoryStream();
        doc.Save(stream, SaveFormat.Pdf);
        doc.Save(resp, fileName, ContentDisposition.Attachment,                                SaveOptions.CreateSaveOptions(
        SaveFormat.Pdf));
        resp.End();
</code>
Which leads to the exact same result the pdf being displayed in the response not the browser itself.
The controller action executing this code is called by the ajax statement:
<code>$("#btnReport").click(function () {

            var datum = $("#hiddenDatum").val();

            $.ajax({
                type: "GET",
                url: '@Url.Action("GenerateMonthlyReport", "Reporting")',
                data: { datum: datum},
                success: function (data) {

                }
            });
        });
</code>
Any suggestions to what I am doing wrong would be highly appreciated.
Edit: My research indicates that the ajax call indeed does not work. How can i initiate the file download based on my controller logic?
Comment: Don't use an ajax request for this.
Comment: How can i initiate the download in the javascript then?
Answer: You can't download a file directly using AJAX calls. You can do this though:
<code>$.ajax({
   type: "GET",
   url: '@Url.Action("GenerateMonthlyReport", "Reporting")',
   data: { datum: datum},
   success: function (data) {
      window.location.href = data.filePath; // i.e. '/downloads/file.pdf';
   }
});
</code>
You cannot stream data back to the jQuery handler. Why not just make this a simple get request with a standard HTML anchor?
<code>@Html.ActionLink("Generate Monthly Report", "GenerateMonthlyReport", "Reporting", new { datum = DateTime.Now.ToString("d", new CultureInfo("en-US")})
</code>

Send PDF to Browser ( as attachment )


Adding Numbers in JavaScript

Question: Please advise how to ADD two numbers in JavaScript. I am not sure where I am going wrong here. Not clear how I need to convert string into integers or Numbers.

function add(){
"use strict";
        num1 = parseInt(document.getElementById("firstNumber")).value;
        num2 = parseInt(document.getElementById("secondNumber")).value;

parseInt(document.getElementById("result")).innerHTML =num1+num2;
}
<!doctype html>

<meta charset="UTF-8">
<title>Untitled Document</title>
<link href="MyStyle.css" rel="stylesheet" type="text/css">

<form>
1st Number : <input type="text" id="firstNumber" />

2nd Number: <input type="text" id="secondNumber" />

<input type="button" onClick="add()" Value="add" />

</form>

Total:

<input type="text"/>

Comment: Next time you have a question, break it down to only what is needed to reproduce the problem.  I think with some basic debugging, you would have found the answer on your own.  Use breakpoints in your code, `console.log()`, etc., to inspect values at each step of the way until you see what the issue is.
Answer: You're trying to parse the element as an int, and take the value of the int:
parseInt(document.getElementById("firstNumber")).value

Get the value from the element and parse that as an int:
parseInt(document.getElementById("firstNumber").value)

Also, parsing is unnecessary here (and doesn't really make sense when assigning to the property):
parseInt(document.getElementById("result")).innerHTML =num1+num2;

Just assign the property directly:
document.getElementById("result").innerHTML =num1+num2;

Comment: Don't forget to point out everything wrong with `parseInt(document.getElementById("result")).innerHTML` too
Answer: parseInt(document.getElementById("result")).innerHTML = num1 + num2;

This makes no sense. I'll try to give an overview of the objects and functions you're working with, because one or more of them seems to be being treated as a sort of magic.
Starting with elements:
var firstInput = document.getElementById("firstNumber");
var secondInput = document.getElementById("secondNumber");

document.getElementById is a function that takes a string, finds the element in your document with that id, and returns that element. Here, you've selected two <input> elements, which the above snippet assigns to firstInput and secondInput to distinguish them (<input>s) from numbers.
Each input has a value property, which is a string. Verify this in your browser's console.
console.log(firstInput.value);  // whatever you typed in the first box
console.log(typeof firstInput.value);  // string

Onwards to parsing, then. parseInt is a function that parses a string into a number. You can try it out in your console, too:
var someString = "192";
var someNumber = parseInt(someString);

console.log(someNumber);  // 192
console.log(typeof someNumber);  // number

A quick type recap:

firstInput is an element
firstInput.value is a string
parseInt is a function that takes a string and returns a number

so you can use parseInt(firstInput.value) to get your first input's value as a number. Writing that all out for both inputs,
var firstInput = document.getElementById("firstNumber");
var secondInput = document.getElementById("secondNumber");

var num1 = parseInt(firstInput.value);
var num2 = parseInt(secondInput.value);

Now that you have two numbers, you can add them:
var sum = num1 + num2;

Finally, to put the sum back into the result element, you just have to find that element as usual:
var resultElement = document.getElementById("result");

and assign the sum to its innerHTML.
resultElement.innerHTML = sum;

Recalling that parseInt takes a string and returns a number, now you should realize that no parseInt needs to be involved here. You have a number already – it's sum. No string is involved.
All together with comments for easy reading, with each line performing fewer steps:
// Get <input> elements
var firstInput = document.getElementById("firstNumber");
var secondInput = document.getElementById("secondNumber");

// Parse the text entered in each into numbers
var num1 = parseInt(firstInput.value);
var num2 = parseInt(secondInput.value);

// Find their sum
var sum = num1 + num2;

// Get the output element
var resultElement = document.getElementById("result");

// Display the sum in the output element
resultElement.innerHTML = sum;

Comment: The Total textbox that holds the "result" disappears every time I click on add button. Why?
Comment: @user39531: You're selecting the `` and setting its inner HTML to a new value. The textbox is part of its inner HTML. If you want to change the value displayed in the textbox instead, give *it* the `id="result"` and use `resultElement.value = sum;`.
Answer: var num1 = parseInt(document.getElementById("firstNumber").value);
var num2 = parseInt(document.getElementById("secondNumber").value);

you have to define the variables and correct the parentheses
Comment: My error was closing the parseInteger parenthesis before .value. Thank you
Answer:

function add(){
"use strict";
        var num1 = parseInt(document.getElementById("firstNumber").value);
        //You need to define your variable before use.
        var num2 = parseInt(document.getElementById("secondNumber").value);
        console.log(document.getElementById("firstNumber"));
        //this is a DOM object
        console.log(typeof document.getElementById("firstNumber").value);
        //this is a "string"
        console.log(typeof parseInt(document.getElementById("firstNumber").value));
        console.log(typeof +document.getElementById("firstNumber").value);
        //quickly  by use '+'
        document.getElementById("result").innerHTML =num1+num2;
}
<!doctype html>

<meta charset="UTF-8">
<title>Untitled Document</title>
<link href="MyStyle.css" rel="stylesheet" type="text/css">

<form>
1st Number : <input type="text" id="firstNumber" />

2nd Number: <input type="text" id="secondNumber" />

<input type="button" onClick="add()" Value="add" />

</form>

Total:

<input type="text"/>

Adding Numbers in JavaScript


How to tune Windows 2008r2 and IIS to maximize single file download speeds?

Question: We recently put up an IIS site (on WinSvr 2008r2 running as a Hyper-V guest) that is used almost exclusively for downloading files over the internet.  The data exists as a large collection of .zip files ranging from 1MB - 35GB in size.  We want to allow a lot of downloads during a day (more than 500GB) but have implemented an outbound ASA throttle at 60mbps in order to preserve bandwidth for other uses.  The total link speed is 100mbps.
Here's the interesting part:  While we can serve up multiple downloads to hit the 60mbps cap, we cannot get any single download to exceed 2.5M bytes/sec (20 Mbits/s).  Is there any TCP or IIS tuning we can do to push up individual download speeds? Or something else to look at?
Comment: We've eliminated the download link by successfully downloading the same file from an alternate location where it DLs 1.5-2x faster. Definitely something slow about our setup for a single file.
Comment: Have you checked that you don't have some sort of throttling enabled on the IIS server? Something like: http://blogs.iis.net/rakkimk/archive/2008/04/04/iis7-configure-throttling-for-your-documents-any-mime-type-and-save-bandwidth-costs.aspx ... Also I'd double check that there isn't a misconfiguration on the ASA throttling individual streams at 20mbps
Comment: I'm guessing the client downloading has a >20Mbps download speed capacity for a single download?
Comment: Yes, of course.
Comment: Wrong topic - not needed. As in: 20mbit is very low - unless you did something utterly stupid (bad drivers etc.) that is not a tuning point. I would look for other weak points. like - how fast is the download link. This is NOT a "i need tuning" item. IT should work a lot faster without.
Comment: Thanks,@Zypher.  No bandwidth throttle in IIS at the site level.  The IIS bitrate throttle per mime type is a separate install and we've not added it.  We're checking the ASA config.
Comment: I'm interested to know if you tried to download data from the server by using any protocol other than HTTP, just to see that IIS is acting weird or is it a general server problem. can you use FTP? or use a different HTTP service other than IIS?
Answer: Make sure that IIS doesn't have maxbandwidth set to something wacky.
http://www.iis.net/configreference/system.applicationhost/sites/site/limits
Tell your server's antivirus to ignore .zip files in your web directory.
You might want to experiment with:

Disabling TCP Chimney Offload
Disabling Receive Side Scaling
Disabling Network Direct Memory Access

One or more of these might not be your friend.
http://support.microsoft.com/kb/951037
Comment: :(  I was really hoping the AV thing would be your friend, as it's helped me in the past.
Comment: I tried each of these to no avail as yet.
Comment: FYI - We're running the web server in a Hyper-V VM.  So chimney offload doesn't appear to be supported.
Comment: Oh, yes.  You're right, it's not, to my knowledge.  [edit]  Well.  If I recall correctly, I was told that in VMware, they'd have to turn it off for every VM in that vlan;  I'm not sure about Hyper-V.
Comment: Hello, I have same problem on server 2022 and IIS 10. Compared to nginx is like IIS is limited to 100-200 mbps speeds while nginx uses full network speed. Did you found solution? I'm surprised it doesn't work out of the box. I also asked question here https://serverfault.com/questions/1121437/iis-serving-files-strange-behavior?noredirect=1#comment1464496_1121437


Update de componentes em tempo real no Angular

Question: Olá, pessoal, tudo bem?
Estou iniciando meus estudos com angular e estou com um problema de implementação. Tenho uma API, desenvolvida por mim, na qual os dados retornados são atualizados a cada 20 segundos no servidor.
Estou montando um frontend com angular. A ideia é atualizar a view do usuário a cada 20 segundos também (ou menos até). Mas existe um requisito funcional da aplicação, que resume-se a notificar (visualmente) o usuário, quando valor de atributo for alterado.
Para um componente renderizado da seguinte forma:

    <app-event
        [id]="event.id"
        [time]="event.time"
        [value1]="event.value1" >
    </app-events>

Sendo uma chamada de exemplo (chamada n)
"events" : [
    {
        "id" : 1
        "time" : 45,
        "value1" : 1.6
    },
    {
        "id" : 2
        "time" : 78,
        "value1" : 1.5
    }
]

Na chamada n+1:
"events" : [
    {
        "id" : 1
        "time" : 46,
        "value1" : 1.5
    },
    {
        "id" : 2
        "time" : 78,
        "value1" : 1.6
    }
]

Os valores de time e value1 foram alterados na api na chamada n+1, portando, preciso alterar a classe do component que ele fora renderizado na chamada n. Eu li sobre questões que envolvem Subject, Observable e outras coisas, mas não ficou tão claro para mim, como executar isso.
Abaixo o código atual dos meus componentes.
events.component.ts
import { Component, OnInit, Input } from '@angular/core';
import { EventsService } from '../../services/events.service';

@Component({
  selector: 'app-events',
  templateUrl: './events.component.html',
  styleUrls: ['./events.component.scss']
})
export class EventsComponent implements OnInit {

  events = []

  constructor(private eventsService: EventsService) { }

  ngOnInit(): void {

    this.eventsService.getEvents().subscribe((data: any[]) => {
      this.events = data
    })

  }

}

events.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, Subject } from 'rxjs'

@Injectable({
  providedIn: 'root'
})
export class EventsService {

  constructor(private httpClient: HttpClient) {

  }

  private API_URL = "http://0.0.0.0:93"

  public getEvents(): Observable<any> {
    return this.httpClient.get(`${this.API_URL}/events/inplay`)
  }
}

events.component.html

    <app-event [event]="event"></app-event>

event.component.ts
import { Component, Input, OnChanges,  } from '@angular/core';
import { SimpleChanges } from '@angular/core'
import { EventsComponent } from '../events.component';

@Component({
  selector: 'app-event',
  templateUrl: './event.component.html',
  styleUrls: ['./event.component.scss']
})
export class EventComponent implements OnChanges {

  @Input() event: any;

  constructor(private eventsComponent: EventsComponent) {

   }

  ngOnInit(): void {

  }

  ngOnChanges(changes: SimpleChanges) {
    console.log(changes)
  }

}

Agradeço.
Comment: Pois é, atualmente essa aplicação está construída em Jquery e faço exatamente assim. Acredito que será a única alternativa.
Comment: Você pode utilizar sockets ao inves de http, ai seu back notifica o front que algo mudou
Comment: Tanto **Subject** como **Behaviour Subject**  são indicados para atualizações de dados entre componentes que necessitam atualizar valores de um componente através de outro componente  e não dados de uma API. Acho que isso é bem simples de resolver inserindo um método `JavaScript` **setInterval()** na chamada do service no arquivo **`events.component.ts`**, isso atualizaria os dados no tempo que for determinado no método, ou, utilizar métodos específicos do `Angular/RXJS` para isso, como o **`timer`**: https://rxjs.dev/api/index/function/timer
Comment: Tudo bem, eu até fiz isso e acabei esquecendo de colocar nos códigos de exemplo. O problema é: Como vou identificar que os dados foram alterados e notificar o usuário (visualmente, uma mudança de classe, por exemplo) dessa alteração?
Comment: Não sei se existem métodos prontos para isso, ou, teria que criar na mão. Mas se não tiver pronto vc consegue comparando os valores dos objetos em **this.events**. Pega o valor atual e verifica se o valor que a atualização trouxe ainda é igual ao atual.
Answer: Se o seu backend ainda não oferece WebSockets ou SSE, vc pode fazer por meio de polling:
public ngOnInit(): void {
    interval(20000).pipe(
        mergeMap(() => this.eventsService.getEvents()),
        distinctUntilChanged((prev, nxt) => prev.time === nxt.time && prev.value1 === nxt.value1),
    ).subscribe(
        evt => console.log(`time or value1 changed`, evt),
    )
}

Se o seu backend oferecer SSE, você poderia deixar a lógica de comparação nele e no frontend só receber os eventos:
public ngOnInit(): void {
    const eventSource = new EventSource('url/do/sse');
    eventSource.onmessage = (event: MessageEvent) => {
        console.log(`received server event`, event);
    };
}


How to keep other columns when using aggregate in R?

Question: I have a dataframe, p4p5, that contains the following columns:
p4p5 <- c("SampleID", "expr", "Gene", "Period", "Consequence", "isPTV")

I've used the aggregate function here to find the median expression per Gene:
p4p5_med <- aggregate(expr ~ Gene, p4p5, median)

However, this results in a dataframe with the columns "expr" and "Gene" only. How can I still retain all the original columns when applying the aggregate function?
UPDATE:
Input (p4p5):
SampleID   expr  Gene        Period  Consequence            isPTV
HSB430    -1.23  ENSG000098  4       upstream_gene_variant  0
HSB321    -0.02  ENSG000098  5       stop_gained            1
HSB296     3.12  ENSG000027  4       upstream_gene_variant  0
HSB201     1.22  ENSG000027  4       intron_variant         0
HSB220     0.13  ENSG000013  6       intron_variant         0

Expected output:
SampleID   expr  Gene        Period  Consequence           isPTV  Median
HSB430    -1.23  ENSG000098  4       upstream_gene_variant  0    -0.625
HSB321    -0.02  ENSG000098  5       stop_gained            1    -0.625
HSB296     3.12  ENSG000027  4       upstream_gene_variant  0     2.17
HSB201     1.22  ENSG000027  4       intron_variant         0     2.17
HSB220     0.13  ENSG000013  6       intron_variant         0     0.13

Comment: `aggregate()` doesn't return every column by design: the output of this function is the result of an aggregation and you can't combine it with the raw data (even conceptually). If you want the aggregation to be done on every column, you have to specify that explicitly
Comment: Please include some example data from `p4p5` in your question. The short answer is: you would need to join the aggregated data back to the original. Or yo could use `dplyr` to `group_by`, then `mutate` the data.
Comment: So something like the following?
 ```p4p5_med <- p4p5 %>% select(Gene, expr, SampleID, Period, isPTV) %>%
    group_by(Gene) %>%
    mutate(Median = median(expr))
```
I tried this but it gives me the same median value for everything.
Comment: Yes - I wrote my answer before seeing your comment and the output is from your example input. If there are different values for `expr` and > 1 value for `Gene`, the medians by group should be different.
Answer: I'd use dplyr for this:
library(dplyr)

p4p5 %>%
  group_by(Gene) %>%
  mutate(Median = median(expr, na.rm = TRUE)) %>%
  ungroup()

  SampleID  expr Gene       Period Consequence           isPTV Median
  <chr>    <dbl> <chr>       <int> <chr>                 <int>  <dbl>
1 HSB430   -1.23 ENSG000098      4 upstream_gene_variant     0 -0.625
2 HSB321   -0.02 ENSG000098      5 stop_gained               1 -0.625
3 HSB296    3.12 ENSG000027      4 upstream_gene_variant     0  2.17
4 HSB201    1.22 ENSG000027      4 intron_variant            0  2.17
5 HSB220    0.13 ENSG000013      6 intron_variant            0  0.13

Comment: When I run that, it retains all the columns but posts the same median value across all rows
Comment: This output is from your example data, so you must be doing something different.
Comment: Anybody have a base R approach?


Showing that $M_{\tau}$ and $M_{\tau \land n}$ are integrable

Question: Let M be a martingale and $\tau$ be a stopping time with $P(\tau < \infty)=1$
Show $M_{\tau \land n}$ (i) and $M_{\tau}$ (ii) are integrable:
i) Since we have no supremum stating that $\sup \limits _{n}E(\vert M_{ n}\vert)<\infty$, I can only estimate  $E(\vert M_{\tau \land n}\vert)$ from above by $\sup\limits_{i=\tau , n }E(\vert M_{i}\vert)<\infty$ but this is contingent on the fact that I prove that $E(\vert M_{\tau}\vert)<\infty$ for which I am yet to find an assured solution.
Comment: $M_{\tau}$ need not be integrable. Where did you finds this question?
Comment: I thought $M_{\tau}$ would be integrable. Since it is not then my proof of (i) does not hold
Answer: Answer for first part: $|M_{\tau \wedge n}| \leq |M_1|+|M_2|+\cdots +|M_n|$ so $E|M_{\tau \wedge n}| \leq E|M_1|+E|M_2|+\cdots +E|M_n| <\infty$.
(There is no reason why $E|M_{\tau }|< \infty$. A counterexample can be found in many books dealing with stopping times).