Add a custom submission handler to a form

Question: How can I add a custom form submission handler?
I tried adding $form['#submit'][] = 'mymodule_form_submit'; or $form['actions']['submit']['#submit'][] = 'mymodule_form_submit'; to hook_form_alter().
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\HttpFoundation\Request;

function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'node_trends_form' || $form_id == 'node_trends_edit_form') {
    foreach (array_keys($form['actions']) as $action) {
      if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
        $form['actions']['submit']['#submit'][] = 'mymodule_form_submit';
      }
    }
  }
}

function mymodule_form_submit(array $form, FormStateInterface $form_state){
    //die("why won't this execute? :(");
    drupal_set_message("Why won't this message show?");
}

It seems drupal_set_message() is not called. I also tried rebuilding the cache, but the function is still not called.
I am using Drupal 8.2.3.
Comment: You should show the full implementation of `hook_form_alter()`, or it's a bit harder to tell you what you are doing wrong. Also, you should say which form you are trying to alter.
Comment: @kiamlaluno I add my hook_form_alter.
Comment: what's your code still $form['actions']['submit']['#submit']? Try replace ['submit'] with [$action].
Answer: If you use hook_form_node_form_alter() maybe use example code:
function MYMODULE_form_node_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  foreach (array_keys($form['actions']) as $action) {
    if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
      $form['actions'][$action]['#submit'][] = 'mymodule_form_submit';
    }
  }
}

and for the submit function use:
function MYMODULE_form_submit(array $form, \Drupal\Core\Form\FormStateInterface $form_state){
  //die("I'm not getting run, why :(");
  \Drupal::service('messenger')->addMessage("Why won't this message show?");
}

Comment: See https://www.drupal.org/node/1901216 and https://www.drupal.org/node/2068063 for more context on why that loop is necessary
Comment: Each form has different structures. So there is no specific answer.
Comment: `$form['actions'][$action]['#submit'][]` which documentation are you viewing? or did you make a typo? In this [hook_form_alter](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Form%21form.api.php/function/hook_form_alter/8.2.x) doc it says `$form['actions']['submit']['#submit'][]`.
Comment: No, it's [hook_form_BASE_FORM_ID_alter()](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Form%21form.api.php/function/hook_form_BASE_FORM_ID_alter/8.2.x)
Comment: Interesting, yeah maybe he needs to loop through the actions. Although, in this other Q [How do you implement a custom submit handler in hook_form_alter()?](http://drupal.stackexchange.com/questions/96529/how-do-you-implement-a-custom-submit-handler-in-hook-form-alter) its suppose to work the way he is doing it.
Comment: This solution work but I think it should work using $form_state->setSubmitHandlers($submitHandlers); no idea why it's not working.
Answer: Creating a custom webform handler plugin for drupal 8.
This document assumes you've already installed and enabled webform and webform-ui
1) Create your webform.
    - Go to structure -> webforms and press the "+ Add webform"  button.
    - You can either use the ui or use yaml, that's up to you.
    example yaml for a one field form that takes an email address:
email:
  '#type': email
  '#title': email
  '#title_display': invisible
  '#placeholder': 'ENTER YOUR EMAIL'
  '#attributes':
    class:
      - my-ip

The indentation is important for yaml so make sure you get it right. indents are spaces.
Now save your form.
2) Creating a webform handler plugin
Next we can create a new plugin which will show up in the "Emails/Handlers" section when editing the webform. I will call it myhandler, you can call it what you want,  provided you replace all mentions of myhandler with the name you pick.
a) Create a new folder for your plugin, do this in your drupal root (referred to here as /var/www/html/) in the following subfolder:
        /var/www/html/modules/Custom/myhandler
b) Create a new file in the above directory called myhandler.info.yml in this file goes the following:
name: My Form Handler
description: handles form submits, does something with them.
package: Custom
type: module
version: 1.0
core: 8.x

3) Create a src directory in your module directory, eg:  /var/www/html/modules/Custom/myhandler/src
    in src create Plugin
    in Plugin create WebformHandler
(this can be achived in one go using
mkdir -p /var/www/html/modules/Custom/myhandler/src/Plugin/WebformHandler/

which will make the entire structure in one go using the -p flag to mkdir.)
4) Create a new file /var/www/html/modules/Custom/myhandler/src/Plugin/WebformHandler/MyFormHandler.php
in that file goes the following php code, i've left the config form setup in so you can see how to configure your plugin if needed.
<?php
namespace Drupal\myhandler\Plugin\WebformHandler;

use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Serialization\Yaml;
use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\webformSubmissionInterface;

/**
 * Form submission handler.
 *
 * @WebformHandler(
 *   id = "myhandler_form_handler",
 *   label = @Translation("MyHandler form handler"),
 *   category = @Translation("Form Handler"),
 *   description = @Translation("Do something extra with form submissions"),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_SINGLE,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 * )
 */
class MyFormHandler extends WebformHandlerBase {

     /**
       * {@inheritdoc}
       */

     public function defaultConfiguration() {
        return [
            'submission_url' => 'https://api.example.org/SOME/ENDPOINT',
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
        $form['submission_url'] = [
            '#type' => 'textfield',
            '#title' => $this->t('Submission URL to api.example.org'),
            '#description' => $this->t('The URL to post the submission data to.'),
            '#default_value' => $this->configuration['submission_url'],
            '#required' => TRUE,
        ];
        return $form;
    }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {
    // Your code here.
        // Get an array of the values from the submission.

        $values = $webform_submission->getData();

        // Get the URL to post the data to.
        $post_url = $this->configuration['submission_url'];

        $message = "MyHandler got form data:".print_r($values,1);
        \Drupal::logger('myformhandler')->error($message);

        return true;
 }
}
?>

5) Enable your MyHandler module (using drush or extend menu) and then rebuild your drupal cache ( "drush cr" from anywhere under your drupal root (/var/www/html here) would do that if you use drush )
6) edit your webform, go to "Email / Handlers" and click on "+ Add Handler" button
    You should see your plugin listed, click Add Handler, you should now see a box asking for the submission url.  click Save button.
   If something doesn't look right, or it isn't working, check the apache error log, you might find something helpful there.
7) Test your form - make a submission to the form, and then check the watchdog log (drush ws), you should see the values sent to it. They might be truncated in the output you see, don't panic, it's all there.  What you do with this now is up to you.
Hope this helps someone. I cobbled it together from stuff I found around the place and wrote it into a single document. Thanks to the others who got me here.
Comment: If I get it right, the one minor thing that's missing in the above code for the handler to work correctly is the submitConfigurationForm() method, consisting of `parent::submitConfigurationForm($form, $form_state);` and `parent::applyFormStateToConfiguration($form_state);`.
Comment: This is a great comment, but it doesn't answer @Yuseferi's question since his question is about Drupal form handling in general, not the webform module.
Comment: @Hendrik No, you don't need it. I've created a new handler with only a `submitForm()` function and it works. All other functions are situated in the base class and I have no needs to override they. By the way: a quite nice a simple solution once you figure it out ;-)
Comment: Bumped this down as the question isnt relating to webform.
Comment: Many in the global web development industry sometimes mean any " tag appearing in an HTML page" as webform in general – probably to emphasize its contrast against any other kind of implementations of taking data from users (eg. some installed software's built-in input interface).

In the narrower scope of Drupal terminology however the terms "webform" and "form" are greatly different, therefore clearly distinguishing them is important to not confuse beginners with this topic. Thus I downrated your answer.
Answer: if using hook_form_BASE_FORM_ID_alter in Drupal 8 core 8.4.3, I found the ways of adding the custom submit handler didn't work. This worked for adding the submit handler function name:
$form['#submit'][] = 'mymodule_submit_handler';

In another situation, using hook_form_FORM_ID_alter in Drupal 8.4.5, I found the above did not work for adding the custom submit handler. Instead, this worked:
$form['actions']['submit']['#submit'][]  = 'mymodule_submit_handler';

Comment: This is true. $form['actions']['submit']['#submit'][]  = 'mymodule_submit_handler'; is the only way to get this work.
Comment: same thing, need to use $form['actions']['submit']['#submit'][]
Comment: This is the correct answer. You change the actions on the widget, not the form.


Next.JS App Router, protected routes, and hiding a layout flicker

Question: I'm using Next.js 13.4.12 and Firebase auth in my application and I want to protect all routes behind /dashboard. I am using the App Router (not the old Pages Router).
My questions:

How can we protect routes with server side logic/middleware (see Edge runtime issue details below)?
How can we protect client components/pages without a "layout" flicker if we are using React context to determine user authentication status?

I'd like to use middleware to protect the routes, but it would require using the firebase-admin sdk. Next.JS middleware uses the Edge runtime though and it does not support Node.JS APIs so the firebase-admin sdk does not work. You get this error:
Error: The edge runtime does not support Node.js 'os' module
Ideally, it would function similar to the way next-auth handles it, except we would use the firebase-admin sdk to validate the user's token:
// middleware.ts

export { default } from "next-auth/middleware"

export const config = { matcher: ["/dashboard/:path*"] }

The other alternative is to protect routes on the client side using something like this:
// /src/app/dashboard/page.tsx

'use client';
...

const Dashboard = () =\> {
const { user } = useAuthContext()
const router = useRouter()

    useEffect(() => {
      if (user == null) router.push("/auth/login");
    }, [user]);

return (
\
My Protected Page\

);
};

export default Dashboard;

With the app router, because I have a layout defined in my layout.tsx file, the dashboard layout flickers before the router pushes the user to the login page.
Thanks!
Comment: Can you add the code from your `useAuthContext()` function?
Comment: You could just show a loader while the user is read from the context and check in the useEffect.
Comment: To get rid of the flicker you can move the AuthGuard to the layout file and wrap the whole layout, but you have to make the layout a client component using the use client directive. It would be better if we could use the firebase admin sdk within middleware.
Answer: just wanted to mention that there is a library out there, that aims at what I believe, this exact use case. https://github.com/awinogrodzki/next-firebase-auth-edge


What is a B-flat major chord doing in the key of A minor?

Question: The piece is Chopin's waltz in A minor op. 34 no. 2, measure 70:

We seem to be in the key of A minor due to the cadences in measures 71  and 73.  But B-flat major is not in the key of A minor (right?).  Is there a concept in music theory that explains this or is it just an irregularity?  I must be missing something.
Link to full score on IMSLP.
Comment: There's nothing in 'the rules' - there are no 'rules'! that say anything shouldn't be wherever it is. Just because it's not 'in key' (whatever that might be) does not mean it can't be played. Does it sound o.k? Fine, then!
Answer: This is a very common concept known as the Neapolitan chord.
In short, the Neapolitan chord is typically a major chord built on the lowered second scale degree; you'll occasionally see/hear it called the ♭II. It's also commonly in first inversion, so you'll also occasionally hear it called the "Neapolitan six(th)," the "six" indicating the figured bass for a first-inversion chord.
The Neapolitan chord functions as a predominant, often moving to V immediately afterwards (as it does in this example).
In the A minor of this example, scale-degree 2 is normally B♮, but lowering it one half step gives us B♭, the Neapolitan scale degree.
Comment: Suggested edit: add a link to this youtube video which explains exactly what you're talking about with examples: https://www.youtube.com/watch?v=_0fWoa5jUBM
Comment: @Kevin Why? Since when is YouTube a normative reference? A reference to a well-know composition, or a citation from a widely accepted textbook or dictionary, might be nice, but YouTube has no more status in this discussion than this answer, or indeed this question.
Comment: @user207421 - It was just a suggestion, since it illustrates exactly what this answer is talking about with examples.  It's a lot easier to *hear* an example alongside the score than it is to simply *see* a score and try to picture it.
Comment: @user207421 I just watch the video and to be honest, the extent of my music experience is a few years of concert band in a small high school but I have to say it was broken down very well. I think it's a great addition to Richard's answer for someone who wants more background.
Answer: The "Neapolitan chord" answer deserves to be the accepted answer, but I'd like to add another use for Bb in Amin.
The bII can be used as a tritone substitution for the V, and particularly the V7.  In Amin, for example, E7 resolves to Amin (or Amaj, but here Amin) basically because E7 has G# and D, but Bb7 also has Ab and D (assuming G# and Ab are the same note on your instrument), so you can resolve Bb7 to Amin.  This is much more common in jazz than in music of Chopin's era, so I'm sure that's not what Chopin is doing in your example, but it's sometimes the right answer to the title of the question.
Answer: The chord sequence C - Bb - F (or variations on it) is common in modal music where the scale more often uses the minor 7th. It's also a frequent element of rock music, for example in the song Can't get enough of your love.
The relative major/minor relationship between C major and A minor should be clear, of course.
Answer: In addition to the other answers, there is a more general concept of full tone and semitone chord movement in chord changes in general. This is frequently employed as a major triad or one of its inversions. Often, the bass note sometimes is and sometimes is not a part of the harmonic triad. You also often see the inverse of this, where only the base note moves in full tone or semitone steps while the harmony sticks to the primary chords of the key with a more pedestrian chord progression (e.g., ii-V-I or vi-ii-V-I). This happens a lot in jazz but you also see it in rock, pop and classical.
I'm not sure of any theoretical basis for this other than that it's really just progressive movement along the chromatic scale in the case of semitone movement and the diatonic scale in the case of full tone movement.
From a compositional perspective, it's a relatively simple matter to just try a semitonal or full tone chord change within the context of the song you are writing and just "see" if it "works" in the context of whatever song you happen to be composing.


Como configurar o AutoIncrement do PostgreSQL usando o EF Core

Question: Tenho um mapeamento de uma tabela (Entity Framework Core 2.0) no qual o campo Id precisa ser AutoIncrement.
O problema é que o PostgreSQL está iniciando com valor alto e muitas vezes fica saltando para sequências muito altas, tipo, incrementando de 10 em 10.
O que estou fazendo de errado? Gostaria que fosse iniciado com 0 e fosse autoincrementando.
(
public class ProfissaoMap : IEntityTypeConfiguration<Profissao>
{
    public void Configure(EntityTypeBuilder<Profissao> builder)
    {
        builder.ToTable("Profissao");

        builder.HasKey(p => new {p.Id});

        builder.Property(p => p.Id)
            .ForNpgsqlUseSequenceHiLo()
            .IsRequired();

        builder.Property(p => p.Id)
            .HasColumnName("ProfissaoId")
            .HasColumnType("integer")
            .IsRequired();

        builder.Property(p => p.Descricao)
           .HasColumnName("Descricao")
           .HasColumnType("character varying(50)")
           .IsRequired();

        builder.Property(p => p.PadraoSistema)
          .HasColumnName("PadraoSistema")
          .HasColumnType("boolean");

    }
}

Comment: Por que tem isso `builder.HasKey(p => new {p.Id});`? Não deveria ser `builder.HasKey(p => p.Id);`? Não deve ter relação com o problema descrito, mas estranhei.
Comment: Uma vez, segui um exemplo na net que ensinava a usar o new... Funciona das duas maneiras @hkotsubo rsrsssrs
Answer: Seguindo a documentação do Entity Framework Core, você pode utilizar o seguinte
.ValueGeneratedOnAdd();
builder.Property(p => p.Id)
        .ForNpgsqlUseSequenceHiLo();
        .ValueGeneratedOnAdd();
        .IsRequired();

Para mais informações segue:
https://docs.microsoft.com/en-us/ef/core/modeling/generated-properties
Answer: O PostgreSQL nao e o problema, e sim essa classe que ".ForNpgsqlUseSequenceHiLo()"

Quando o intervalo está esgotado, um novo intervalo é alocado. Em
  termos práticos, isso usa uma sequência que é incrementada por algum
  valor grande (100 por padrão), permitindo que o aplicativo insira 100
  linhas de forma autônoma.

em outras palavras se tiver alguma tipo de timeout o ForNpgsqlUseSequenceHiLo vai pular algumas casas do id e para inserir.
Eu tenho projeto generico vc pode dar uma olhada e alterar o seu projeto, estou usando o framework mas e facil de alterar para o core, caso queira: Postgres Generic Repository
Comment: Obrigado @HudsonPH! :)


Dynamic JQuery Form Submit for Multiple Forms

Question: I have PHP that searches a database and then echoes an html form for each result found. These are loaded via AJAX into the main HTML page into a div on document load.
Now I want to have listeners for each of these forms submitting. They all have the same inputs.
Each form has an incremental ID of processor (processor1, processor2, processor3, and so on).
So, depending on the results, it could be as little as one form or 50 forms. Is there a dynamic way of doing a form submit function rather than writing countless repetitive functions?
Comment: what do you mean by "*doing* form submit function"?
Comment: $("#processor1").on( "submit", function( event ) {
Answer: If you have
<form id="form1">
<form id="form2">

You can use a class selector
<form id="form1" class="forms">
<form id="form2" class="forms">

In jQuery:
$(function() {
 $('.forms').submit(function(e){
   e.preventDefault(); //Prevent submit
   console.log($(this)); //Current form submiting

   //Make ajax call for current form
 })
})

If u you need extra data for each form, you can use data atributte
<form id="form2" class="forms" data-myattr="myvalue">

And get it
...
$(this).data('myattr'); //myvalue
...

Comment: $(this) is the current form object.
You can use $(this).find("selector") to search elements in the form.
Comment: If I wanted to use input values for only the submitted form, would I do this?  $("this .inputclass").val(); instead of $("#form1 .inputclass").val();
Comment: `$(this).find('.inputclass').val()` will do.
Answer: If using classes is (for some reason) not an option, you can also use 'starts with' selector:
$('#processor*').submit(function (e) {
    e.preventDefault();
    ...
});

Note that the above function should be called as a callback to AJAX function that loads the forms.


What are notations to express uniqueness in formulae and diagrams?

Question: I am familiar with the notation $\exists\,!$ to express both existence and uniqueness.  For example $$\;\;\exists\,!x\!:\!P\,(x)\;\;$$ means "there exists a unique $x$ such that $P\,(x)$ holds", for some predicate $P\,$.

Is there some similarly compact notation to denote only uniqueness (i.e. without simultaneously asserting existence)?

In other words, is there a similarly compact, "easy-to-parse" way to express the assertion "$P\,(x)$ holds for at most one $x$"?*
There is a somewhat analogous question for category-theoretic diagrams.  I have seen the convention of using a dashed (or dotted) arrow to indicate the universality of the corresponding morphism (see, for example, Algebra by Mac Lane and Birkhoff).  Some authors extend this convention to indicate existence-and-uniqueness (e.g. see Turi's Category Theory Lecture Notes).  Hence, I see the dashed arrow as the "diagrammatic cousin" of $\exists\,!\,$.  Now, suppose we are making some diagram $\mathcal{D}$ featuring objects $A$ and $B$, say.

Is there some convention to graphically represent the assertion "there is at most one morphism $\alpha$ from $A$ to $B$ [such that diagram $\mathcal{D}$ commutes]"?

Thanks!
*Of course, the immediate guess ("back-forming" from $\exists\,!$) is that the lone $!$ serves this purpose.  Thus the assertion above would be expressed with $$!\, x\!:\!P\,(x).$$  I see no immediate problems with using $!$ for this purpose (with the possible exception of cases where the context includes many factorials) but I have never seen such usage, and I would prefer to adopt a notation that has at least some currency, even if it does not complement the $\exists\,!$ form as nicely as $!$ does.
Comment: Why use a notation, which is likely to be cryptic if it is not standard, when words will be more pleasant to read and more precise in meaning?
Comment: Sorry, I beg to differ.  At any rate, this is a matter of taste, and I would not like to take the conversation in that direction; for those who prefer to avoid notation, my question is of little interest.
Comment: I have not seen hypercompact notation for "there is at most one $x$" in research papers in logic, or indeed anywhere else.
Comment: In some programming languages `!=` is used for negation of being equal. Hence you can misfire as saying "there does not exist ...." Besides, you are doing nothing but an overload of the readers *temporary mental capacity* by writing quite definite concepts by ambiguous notation which can be described by exactly one word.
Answer: The notation $\exists^{=n}_xP(x)$ might be useful for you, that means that there exists exactly $n$ entities $x$ for which $P(x)$ is true.
Using this notation, $\exists^{=1}_xP(x)$ means the same than $\exists!_xP(x)$
and $\exists^{=0}_xP(x)$ would mean that there is no such entity $x$.
Thus, what you are looking for would be $\exists^{\le1}_xP(x)$ which could be defined as
$\exists^{\le1}_xP(x) :\Leftrightarrow \exists^{=0}_xP(x) \vee  \exists^{=1}_xP(x)$


Geometry of robust linear model

Question: $L_2$ minimisation has a very nice geometric explanation as projection onto a subspace of the appropriate size. Is there a similar "real explanation" for any of the approaches to robust regression?
Edit: For example Huber's M estimates of regression and Yohai's MM estimator of regression.
Comment: @user603 I must have misread the docs then, my mistake. I skimmed them and saw "white estimator"
Comment: @ssdecontrol Feel free to write about the geometry of whitened errors too. I've tried to broaden the question to allow as many interesting answers as possible.
Comment: I think that you ought to define and even outline, the robust regression. For there exist not one type of "robust" regression. Reader would prefer your description/synopsis to reading an external document.
Comment: @ttnphns How about this: is there a geometric description of _any_ of the robust regression models?
Comment: @isomorphismes the problem is that "robust" is a generic term. But based on the documentation for `rlm`, it seems like you're asking about regression with robust standard errors like the Huber-White estimator. If you can clarify, this will be a good question and I'll be interested in the answer.
Comment: @ssdecontrol I'm asking about things along the lines of median polish, not like a trimmed `lm`. BTW please, What other types besides these two am I missing out on?
Comment: @isomorphismes it's not that there are other "types," it's that you can use the word "robust" to mean something like quantile regression, which is robust to outliers.
Comment: @isomorphismes: there are two other robust estimators of regression. All three -MM,LTS,S- are strongly related. For all three, it is advised to have a look at the 'robustbase' package (check for 'ltsReg()' and 'lmrob()' therein). Quantile regression is not robust in the sense that its breakdown point is essentially $0$ (that is why I hesitate to cite it in my answer)
Comment: @user603 But quantile is not really considered robust in the same way that `data %>% winsorise %>% lm` is. Right? I mean quantile regression is estimating _more_ things, not estimating the one thing more safely.
Comment: @isomorphismes I was hoping to hear about it myself! And by the way, I didn't mean Winsorizing, I meant the heteroskedasticity-robust variance estimator often attributed to Huber and White. And to think I was asking _other_ people to define their terms...
Comment: @isomorphismes: yes, we perfectly agree: quantile regression is not robust in the sense that it fails to protect against so called bad leverage outliers. That is why I didn't mention it in my answer proper but as a side note to say that there are also higher group of equivariance OLS don't belong to. Note that there *are* high breakdown regression methods that are monotone equivariant.
Comment: @ssdecontrol The winsorisation remark was directed at someone else on a different topic.
Answer: Yes! Robust regression has a clear geometric interpretation.
One can think about the geometry of an estimator by looking at the group of equivariance to which it belongs. Quick example;
Example  scale estimator $S(x)$ (the usual variance, $\sigma^2(x)$, and the median absolute deviation, $\mbox{mad}(x)$, are two cart bearing members of this group) are  equivariant  to multiplications of the data by a constant:
$$S(\alpha x)=|\alpha|S(x),\quad\alpha\in\mathbb{R}$$
In other words, the group of equivariance defines the transformations of the data which, in some sense, you don't need to care about when using the estimator because when such a transformation is applied to the data, the estimator changes with the data 'in the natural way'.
These groups of equivariance also have bearing on important properties of the estimators such as consistency.

Likewise, a regression estimator $T(\pmb x,y)\in\mathbb{R}^p$ is characterized by at least two group of equivariance:

$T(\pmb x,y)$ is regression equivariant:
$$T(\pmb x,y+\pmb\beta'x)=T(\pmb x,y)+\pmb\beta,\quad\pmb\beta\in\mathbb{R}^p$$
$T(\pmb x,y)$ is affine equivariant:
$$T(\pmb x\pmb A,y)=\pmb A^{-1}T(\pmb x,y)$$
for any non singular matrix $\pmb A\in\mathbb{R}^{p\times p}$.
This implies that $T(\pmb x,y)$ is residual admissible: the regression estimates only depend on the data through the vector of residuals.

The regression estimator estimated by rlm, like the usual OLS estimators, all satisfy affine and regression equivariance.

Note that there exist some robust regression estimators that belong to group of equivariance to which OLS doesn't belong (e.g. that have in this sense a stronger geometry than OLS). Think of invariance to monotone transformations that holds for quantile-based estimators such as the $\mbox{mad}(x)$ (and in the case of monotone transformation of the responses for quantile regression) but not for the variance (or the usual OLS estimators).

Geometry of robust linear model


Finding the average GPS point

Question: I need to write a program to find the average GPS point from a population of points.
In practice the following happens:

Each month a person records a GPS point of the same static asset.
Because of the nature of GPS, these points differ slightly each month.
Sometimes the person makes a mistake and records the wrong assest at a completely different location.
Each GPS point has a certainty weight (HDOP) that indicates how accurate the current GPS data is.  GPS points with better HDOP values are preferred over lower ones.

How do I determine the following:

Deal with data with 2 values vs. a single value like age. (Find the average age in a population of people)
Determine the outliers. In the example below these would be [-28.252, 25.018] and [-28.632, 25.219]
After excluding the outliers, find the average GPS point in this it might be [-28.389, 25.245].
It would be a bonus if can work the "weight" provided by HDOP value for each point.
Comment: This answer is similar enough to help you with the averaging of the points, http://stats.stackexchange.com/questions/2493/managing-error-with-gps-routes-theoretical-framework/2497#2497, it is simple to incorporate weights in that framework. I would think you would be able to use some simple heuristics to identify outliers, but that doesn't preclude you from taking a more empirical approach like Stephan suggested.
Answer: One of the problems with multivariate data is deciding on, and then interpreting, a suitable metric for calculating distances, hence clever but somewhat hard-to-explain concepts such as Mahalanobis distance. But in this case surely the choice is obvious - Euclidean distance. I'd suggest a simple heuristic algorithm something like:

Calculate the (unweighted) centroid of the data points, i.e. the (unweighted) means of the 2 coordinates
Calculate the Euclidean distance of all the readings from the centroid
Exclude any readings that are further than a certain distance (to be determined based on your experience and knowledge of the technology, or failing that a bit of trial and error cross-validation - 100m, 1km, 10km??)
Calculate the weighted average of both coords of the remaining points, weighting by the inverse of the HDOP score (or some monotonic function of it - i had a quick look at the wikipedia page linked in the question and think maybe you don't need such a function but i'd need to study it further to be sure)

There are clearly several ways to make this more sophisticated, such as down-weighting outliers or using M-estimators rather than simply excluding them, but I'm not sure whether such sophistication is really necessary here.
Answer: Rob Hyndman recently posed a question about detecting outliers in multivariate data. The answers may provide a couple of possible approaches (and otherwise, you may want to put the question of finding 2-d outliers in a separate question).
And you can average your remaining GPS data component by component - add all the first components up and divide by the number of points, that will give you the first component of the average. Same with the second components.
This averaging can be weighted by HDOP. Sum up the products of the first component, multiplied with the corresponding HDOP score, and divide the sum by the sum of the HDOP scores. Same with the second components.
I'll take the liberty of removing the "normal-distribution" tag...
Comment: Thanks @Stephan Kolassa, this will already help towards finding a solution.
Answer: Call the HDOP the independent variable. Use this for weighting later on. So you have sets of co-ordinates - call this (x1,y1); (x2,y2), etc...
First ignore outliers. Calculate the weighted averages of the x co-ordinates as [(x1*h1)+(x2*h2) +....+ (xn*hn)] / [sum(h1,h2,...,hn)] where h1,h2,... is the HDOP value. Do the same for the y co-ordinates. This will give a fairly accurate average value for each co-ordinate.
Dealing with outliers can be a bit tricky. How do you know if they are outliers or not? Strictly you need to determine a statistical fit to the observations and within a confidence interval determine if they are genuine or not. Looking at the question the Poison Distribution does come to mind. But this is probably a lot of work and I'm sure you don't want to go into this. Maybe use an approximation? Say you assume that the average co-ordinate value is a good mean to use. Then determine a value for the standard deviation. I think the standard dev or the poison distribution is 1/(mean). Then approximate using the normal distribution and a 95% confidence interval. Say if an observation is outside the interval (mean-*1.645*std dev ; mean + 1.645*std dev) then it is an outlier? Give this a go. Maybe go do a bit of reading on the poison distribution and incorporate the HDOP value into this?

Finding the average GPS point


Why can I change dict values by referencing keys but not the values themselves?

Question: Here, is my code:
# Write your add_ten function here:
def add_ten(dic):
  for key, val in dic.items():
    dic[key] += 10
  return dic
# Uncomment these function calls to test your  function:
print(add_ten({1:5, 2:2, 3:3}))
# should print {1:15, 2:12, 3:13}
#print(add_ten({10:1, 100:2, 1000:3}))
# should print {10:11, 100:12, 1000:13}

This works, however initially I did:
for val in dick.values():
    val += 10

Using visualizer, this added 10 to the value, but the value was not saved. Why?
Comment: Because `val` is simply a temp variable which will be overwritten during the next loop iteration. You don't want to change `val` but the value in the dictionary. That's why your solution does not work.
Comment: Because some objects are mutable while others are immutable. In your case, integers are not mutable, so the content of the dct can only be changed by assignment - and you want to assign the new value to the dict and not to some other variable name, pointing to the same immutable object.
Comment: Can you please change your dictionaries name?
Comment: `val += 10` is short for `val = val.__iadd__(10)`. Since `int.__iadd__` is not implemented, Python falls back to `val = val.__add__(10)`. As a result, you are only assigning a new value to the name `val`, rather than mutating the object stored in the `dict` that `val` refers to.
Answer: In this loop:
for val in dick.values():
    val += 10

val is not a reference to a mutable value in the dictionary. val += 10 is implemented as val = val + 10 -- you are reassigning the local variable val rather than modifying the original dictionary value that it was initialized with.


Simple Multivariate Bayesian Method in Python

Question: I am trying to follow the Bayesian method described in this text. The python notebook goes through the example of creating two Poisson functions describing a change in SMS frequency at some point tau.
But I want to explore multivariate methods, so instead will start  with simply two time changes (tau1 and tau2) with three exponentials (lambda1, lambda2, lambda3). As described in the text, I can create the exponential multivariate lambdas_ as follows:
import pymc as pm
alpha = 1.0/count_data.mean()

lambdas_ = pm.Exponential("lambda_1", alpha, size=3)
tau = pm.DiscreteUniform("tau", lower=0, upper=n_count_data, size=2)

My simple and obvious (not to me!) mistake occurs in defining the deterministic lambda_ function
@pm.deterministic
def lambda_(tau=tau, lambdas_=lambdas_):
    out = np.zeros(n_count_data)
    out[:tau[0]] = lambda_[0]  # lambda before tau is lambda1
    out[tau[0]:tau[1]] = lambda_[1]  # lambda between tau1 and tau2 is lambda2
    out[tau[1]:] = lambda_1[2] # lambda after tau2 is lambda3
    return out

I am wondering if this is the proper method for determining the expectations based on the posteriors, as in determining when are we in the regime of which lambda and particularly for determining idx2 which seems odd to use a product (otherwise i get the numpy complaint of using a.any() or a.all() if i just do tau_samples[:,0] <= day < tau_samples[:,1]):
# tau_samples, lambdas_samples contain
# N samples from the corresponding posterior distribution
N = tau_samples.shape[0]
expected_texts_per_day = np.zeros(n_count_data)
for day in range(0, n_count_data):
    # ix is a bool index of all tau samples corresponding to
    # the switchpoint occurring prior to value of 'day'
    ix1 = day < tau_samples[:,0]
    ix2 = np.prod([tau_samples[:,0] <= day, day < tau_samples[:,1]],axis=0)
    ix3 = tau_samples[:,1] <= day
    # Each posterior sample corresponds to a value for tau.
    # for each day, that value of tau indicates whether we're "before"
    # (in the lambdas_[0] "regime"), "between" (in the lambdas_[1] "regime") or
    #  "after" (in the lambdas_[2] "regime") the switchpoint.
    # by taking the posterior sample of lambda1/2/3 accordingly, we can average
    # over all samples to get an expected value for lambda on that day.
    # As explained, the "message count" random variable is Poisson distributed,
    # and therefore lambda (the poisson parameter) is the expected value of
    # "message count".
    expected_texts_per_day[day] = (lambdas_samples[ix1,0].sum()
                                   + lambdas_samples[ix2,1].sum()
                                   + lambdas_samples[ix3,2].sum()) / N

I would appreciate any feedback, thank you for your time and guidance. I have pasted the full code below
import json, matplotlib
s = json.load( open("bmh_matplotlibrc.json") )
matplotlib.rcParams.update(s)

%matplotlib osx
from IPython.core.pylabtools import figsize
import numpy as np
from matplotlib import pyplot as plt
figsize(11, 9)

import scipy.stats as stats

figsize(12.5, 3.5)
count_data = np.loadtxt("txtdata.csv")
n_count_data = len(count_data)
plt.bar(np.arange(n_count_data), count_data, color="#348ABD")
plt.xlabel("Time (days)")
plt.ylabel("count of text-msgs received")
plt.title("Did the user's texting habits change over time?")
plt.xlim(0, n_count_data);

import pymc as pm

alpha = 1.0 / count_data.mean()  # Recall count_data is the
                               # variable that holds our txt counts

lambdas_ = pm.Exponential("lambda_", alpha, size=3)
tau = pm.DiscreteUniform("tau", lower=0, upper=n_count_data, size=2)

@pm.deterministic
def lambda_(tau=tau, lambdas_=lambdas_):
    out = np.zeros(n_count_data)
    out[:tau[0]] = lambdas_[0]  # lambda before tau is lambda1
    out[tau[0]:tau[1]] = lambdas_[1]  # lambda between tau1 and tau2 is lambda2
    out[tau[1]:] = lambdas_[2] # lambda after tau2 is lambda3
    return out

observation = pm.Uniform("obs", lambda_, value=count_data, observed=True)
model = pm.Model([observation, lambdas_, taus])

mcmc = pm.MCMC(model)
mcmc.sample(40000, 10000, 1)

lambdas_samples = mcmc.trace('lambdas_')[:]
tau_samples = mcmc.trace('tau')[:]

import random
r = lambda: random.randint(0,255)
cols=[]
[cols.append('#%02X%02X%02X' % (r(),r(),r())) for i in range(5)]

figsize(8.5, 14)
# histogram of the samples:

ax = plt.subplot(511)
ax.set_autoscaley_on(False)

plt.hist(lambdas_samples[:,0], histtype='stepfilled', bins=30, alpha=0.85,
         label="posterior of $\lambda_1$", color=cols[0], normed=True)
plt.legend(loc="upper left")
plt.title(r"""Posterior distributions of the variables
    $\lambda_1,\;\lambda_2,\;\lambda_3,\;\tau_1,\;\tau_2$""")
plt.xlim([0, 30])
plt.xlabel("$\lambda_1$ value")

ax = plt.subplot(512)
ax.set_autoscaley_on(False)
plt.hist(lambdas_samples[:,1], histtype='stepfilled', bins=30, alpha=0.85,
         label="posterior of $\lambda_2$", color=cols[1], normed=True)
plt.legend(loc="upper left")
plt.xlim([0, 30])
plt.xlabel("$\lambda_2$ value")

ax = plt.subplot(513)
ax.set_autoscaley_on(False)
plt.hist(lambdas_samples[:,2], histtype='stepfilled', bins=30, alpha=0.85,
         label="posterior of $\lambda_3$", color=cols[2], normed=True)
plt.legend(loc="upper left")
plt.xlim([0, 30])
plt.xlabel("$\lambda_3$ value")

plt.subplot(514)
w = 1.0 / tau_samples[:,0].shape[0] * np.ones_like(tau_samples[:,0])
plt.hist(tau_samples[:,0], bins=n_count_data, alpha=1,
         label=r"posterior of $\tau_1$",
         color=cols[3], weights=w, rwidth=2.)
plt.xticks(np.arange(n_count_data))

plt.legend(loc="upper left")
plt.ylim([0, .75])
plt.xlim([20, len(count_data) - 20])
plt.xlabel(r"$\tau_1$ (in days)")
plt.ylabel("probability");

plt.subplot(515)
w = 1.0 / tau_samples[:,1].shape[0] * np.ones_like(tau_samples[:,1])
plt.hist(tau_samples[:,1], bins=n_count_data, alpha=1,
         label=r"posterior of $\tau_2$",
         color=cols[4], weights=w, rwidth=2.)
plt.xticks(np.arange(n_count_data))

plt.legend(loc="upper left")
plt.ylim([0, .75])
plt.xlim([20, len(count_data) - 20])
plt.xlabel(r"$\tau_2$ (in days)")
plt.ylabel("probability");

figsize(12.5, 5)
# tau_samples, lambdas_samples contain
# N samples from the corresponding posterior distribution
N = tau_samples.shape[0]
expected_texts_per_day = np.zeros(n_count_data)
for day in range(0, n_count_data):
    # ix is a bool index of all tau samples corresponding to
    # the switchpoint occurring prior to value of 'day'
    ix1 = day < tau_samples[:,0]
    ix2 = np.prod([tau_samples[:,0] <= day, day < tau_samples[:,1]],axis=0)
    ix3 = tau_samples[:,1] <= day
    # Each posterior sample corresponds to a value for tau.
    # for each day, that value of tau indicates whether we're "before"
    # (in the lambdas_[0] "regime"), "between" (in the lambdas_[1] "regime") or
    #  "after" (in the lambdas_[2] "regime") the switchpoint.
    # by taking the posterior sample of lambda1/2/3 accordingly, we can average
    # over all samples to get an expected value for lambda on that day.
    # As explained, the "message count" random variable is Poisson distributed,
    # and therefore lambda (the poisson parameter) is the expected value of
    # "message count".
    expected_texts_per_day[day] = (lambdas_samples[ix1,0].sum()
                                   + lambdas_samples[ix2,1].sum()
                                   + lambdas_samples[ix3,2].sum()) / N

plt.plot(range(n_count_data), expected_texts_per_day, lw=4, color="#E24A33",
         label="expected number of text-messages received")
plt.xlim(0, n_count_data)
plt.xlabel("Day")
plt.ylabel("Expected # text-messages")
plt.title("Expected number of text-messages received")
plt.ylim(0, 60)
plt.bar(np.arange(len(count_data)), count_data, color="#348ABD", alpha=0.65,
        label="observed texts per day")

plt.legend(loc="upper left");

Comment: Can you clarify what your question is here? Also, please paste in whatever information is necessary to understand your question. People aren't going to want to go & read something else to be able to answer your question.
Comment: thank you for your suggestions, i've added the full code and explained my issue of determining the expectation based on posterior samples.
Answer: Your PyMC code looks correct - can you confirm that the model converges well too? There's no point in computing statistics on top of your posteriors if your model hasn't converged yet.
Assuming it has converged, your calculation of the expected value looks good, and your use of prod look fine. Alternatively, you could do

(tau_samples[:,0] <= day) * (day < tau_samples[:,1])

Does that help?


Drupal Commerce: How to manage different payments (a total amount can be pay in different shares and the user can choose in how many shares)

Question: I´ve just installed the Drupal Commerce module in D7, and after watching the video tutorials I think it´s fairly complex, maybe it´s just too much for what I want to do.
I´ve this site where we only sell e-courses. Each course has a total cost, but people can pay just a small part to get enrolled.
The problem is that people have a minimum to pay, but they can pay a bit more if they want, so even is the total price is fixed, I get people to pay different amounts of money each time.
In example:
Course A costs 1000.
To get enrolled you have to pay 100, and then 100 per month (those are recurring payments).
Now, one student can pay 200 when he enrolls, and then after that he can, if he wants, to pay in 200 shares instead of 100 shares. Maybe he can pay 300 to get enrolled and then shares of 100 each.
How may I manage that with Drupal Commerce? Is it possible?
Thanks!
Answer: There is Commerce Installments

Commerce Installments allows you to create installment payments for
  products in a Drupal Commerce store.

Make sure you read Issues for Commerce Installments


Docusign send envelope from template not showing tabs (node)

Question: I'm trying to send an envelope from a template in a webhook listener. I'm using node.js with .mjs files. When I send the envelope via the docusign dashboard it has the tabs - full name, SSN, phone number, address. But when the API sends the envelope, it has those words but no fields next to them. This is a problem because we need that info and there's nowhere for the signer to input it. What could be causing the tabs to not appear when the envelope is sent from the api?
Here's the code to create an envelope and use a template (based off docs):
import docusign from 'docusign-esign';

export function makeEnvelope(args){

  // Create the envelope definition
    let env = new docusign.EnvelopeDefinition();
    env.templateId = args.templateId;

  // Create template role elements to connect the signer and cc recipients
  // to the template
  // We're setting the parameters via the object creation
    let signer1 = docusign.TemplateRole.constructFromObject({
        email: args.signerEmail,
        name: args.signerName,
        roleName: 'signer'});

  // Create a cc template role.
  // We're setting the parameters via setters
    let cc1 = new docusign.TemplateRole();
    cc1.email = args.ccEmail;
    cc1.name = args.ccName;
    cc1.roleName = 'cc';

  // Add the TemplateRole objects to the envelope object
    env.templateRoles = [signer1, cc1];
    env.status = 'sent'; // We want the envelope to be sent

    return env;
}

export async function useTemplate(args) {

    let dsApiClient = new docusign.ApiClient();
    dsApiClient.setBasePath(args.basePath);
    dsApiClient.addDefaultHeader('Authorization', 'Bearer ' + args.accessToken);
    let envelopesApi = new docusign.EnvelopesApi(dsApiClient);

  // Make the envelope request body
    let envelope = makeEnvelope(args.envelopeArgs);

  // Call Envelopes::create API method
  // Exceptions will be caught by the calling function
    let results = await envelopesApi.createEnvelope(
      args.accountId, {envelopeDefinition: envelope});

    return results;
};

Here's the code for the webhook listener where I call useTemplate (please excuse the commented out code and the console logs - I'm still in the midst of figuring it all out):
import express from 'express';
import { useTemplate } from '../request/docusign/docusign-methods.mjs';
import opportunities from '../request/prosperworks/opportunities.mjs';
import people from '../request/prosperworks/people.js';
import customFields from '../request/prosperworks/custom-fields.mjs';
import { findTemplateIdByCohortName } from '../request/docusign/templates.mjs';
import { findSentEnvelopesByStudentEmail, voidEnvelope, findTemplateFromEnvelopeTemplateUri } from '../request/docusign/envelopes.mjs';
import { createJWT, getAccessTokenFromJWT } from '../request/docusign/token.mjs';
import { getAccessToken } from '../request/quickbooks/tokens.mjs';
import { findCustomerByEmail } from '../request/quickbooks/customer.mjs';
import { createCustomer } from '../request/quickbooks/customer.mjs';
import { createInvoice, sendInvoice } from '../request/quickbooks/invoice.mjs';
import { findItemByName } from '../request/quickbooks/item.mjs';

const router = express.Router();

export default router
  .post('/copper/opportunity/updated', express.json(), async (req, res, next) => {
    const { body } = req;
    console.log('webhook received', body);
    if(!Object.keys(body.updated_attributes).length) return res.send('irrelevant webhook');
    const cohortChanged = !!body.updated_attributes?.custom_fields?.['94620']
    console.log('cohort changed?', cohortChanged);
    const interviewScheduledToAccepted = !!(body.updated_attributes?.stage?.[0] === 'Interview Scheduled' && body.updated_attributes?.stage?.[1] === 'Accepted')
    console.log('interview scheduled to accepted?', interviewScheduledToAccepted);
    const fullConditional = cohortChanged || interviewScheduledToAccepted;
    console.log('full conditional', fullConditional);
    if(fullConditional) {
        try {
            const jwt = await createJWT();
            const docusign_access_token = await getAccessTokenFromJWT(jwt);
            const opportunity = await opportunities.get(body.ids[0]);
            const cohortId = opportunity?.custom_fields?.find(field => field.custom_field_definition_id === 94620)?.value || null;
            const cohortName = customFields.getCohortNameById(cohortId);
            console.log('cohort name', cohortName);
            const templateId = await findTemplateIdByCohortName(cohortName, docusign_access_token);
            const person = await people.findById(opportunity.primary_contact_id);
            const email = person.emails[0].email;
            console.log('email', email);
            const { name } = person;
            // if(interviewScheduledToAccepted) {
            //     const quickbooks_access_token = await getAccessToken();
            //     let customer = await findCustomerByEmail(email, quickbooks_access_token);
            //     if(customer === null) {
            //         customer = await createCustomer(cohortName, person, quickbooks_access_token);
            //     };
            //     console.log('customer', customer);
            //     const product = await findItemByName('Deposit', quickbooks_access_token);
            //     const invoice =  await createInvoice(customer, product, cohortName, quickbooks_access_token);
            //     const sentInvoice = await sendInvoice(email, invoice.Invoice.Id, quickbooks_access_token)
            //     console.log('sent invoice', sentInvoice);
            // }
            const sentEnvelopes = await findSentEnvelopesByStudentEmail(email, docusign_access_token);
            await Promise.all(
            sentEnvelopes.filter(envelope => {
                return envelope.emailSubject.includes('Enrollment Agreement');
            })
            .map(envelope => {
                if(envelope.status === 'sent') return voidEnvelope(envelope.envelopeId, docusign_access_token);
            })
            );
            const sentEnvelopesTemplates = await Promise.all(
                sentEnvelopes
                .filter(envelope => {
                    return envelope.status !== 'voided'
                })
                .map(envelope => {
                    return findTemplateFromEnvelopeTemplateUri(envelope.templatesUri, docusign_access_token);
                })
            );
            const templateAlreadyUsedCheck = sentEnvelopesTemplates.reduce((outerAcc, templateArr) => {
                if(templateArr.reduce((innerAcc, template) => {
                    if(template.templateId === templateId) innerAcc=true;
                    return innerAcc;
                }, false)) {
                    outerAcc=true;
                }
                return outerAcc;
            }, false);
            if(templateAlreadyUsedCheck) return res.send('envelope already sent');
            const envelopeArgs = {
            templateId: templateId,
            signerEmail: email,
            signerName: name
            }
            console.log(envelopeArgs);
            const envelope = await useTemplate({
                basePath: process.env.DOCUSIGN_BASE_PATH,
                accessToken: docusign_access_token,
                accountId: process.env.DOCUSIGN_ACCOUNT_ID,
                envelopeArgs
            });
            return res.send(envelope);
        }
        catch(err) {
            console.log(err.message);
            next(err);
        }
    } else {
        return res.send('irrelevant webhook');
    }
  });

Comment: does your template use "signer' as the role name? placeholder recipients has a name and it must match what you use when you use the templateRoles in your code
Comment: That was totally it! Thanks a bunch
Answer: Inbar Gazit figured it out - it turns out I had student as the role name in the template and signer as the role name in my code so that's why it wasn't working.


Show that $\cos^n{\theta}\leq\cos{n\theta},\theta\in[0,\frac{\pi}{2}],n\in]0,1[$.

Question: Show that $\cos^n{\theta}\leq\cos{n\theta},\theta\in[0,\frac{\pi}{2}],n\in]0,1[$.
Can I use Taylor's polynomial?
Comment: Hint: Compare the derivatives of each function.
Answer: The "standard" method of solving these sorts of questions is the mean value theorem.
Let $n \in ]0,1[$ be fixed, and let $\theta \in [0, \pi / 2]$. Now consider the function
$$ f(x) = \cos n x - \cos^n x$$
Now apply the mean value theorem for the function $f$ at end points $x_1 = 0$ and $x_2 = \theta$. Once you have done this, consider why this (with a little bit more footwork) proves the statement!


AxImp Generated Reference

Question: I've recently been working on a C#/VS2008 project which requires 3 ActiveX controls. I created a .NET wrapper using AxImp.exe for the controls, and added them as references to my project.  The code had been working without any trouble for a few days.
Yesterday, I pulled a clean version from our version control server (the wrapper DLLs were included, but not the ActiveX controls themselves), and when I attempted to run the program, I get a COMResultException with HRESULT = REGDB_E_CLASSNOTREG(0x80040154) during the InitializeCompnent call of the parent form.
Any clues on what might have happened to cause this?
Answer: Not sure what "clean version" means but clearly the GUIDs in the interop library no longer match the GUIDs used by the ActiveX controls.  Getting 0x80040154 is the result, it can no longer find the ActiveX registry keys.
Controlling the build process and keeping the ActiveX controls in sync with the interop wrappers is pretty important or you'll be battling this problem long-term.  Generating them ought to be associated with building the controls.  This can be especially a problem if the controls were created in VB6.  It is quick to assign new GUIDs unless you setup its binary compatibility feature.
Comment: How do the GUIDs for the ActiveX controls change?  I would have thought that they would stay the same (but then again, I don't know much of anything about ActiveX GUIDs). Also, is there a way to use the "Add Reference..." dialog to generate the ActiveX control, and would that solve the GUID update problem? When I attempt to use it, the Ax* namespace/classes don't show up. Forgive my ignorance, I'm pretty new at this
Comment: I don't know, talk to the guys that maintain the ActiveX controls.  Changing GUIDs is a requirement in COM if the public interface changed, it avoids DLL Hell.  The bad kind, not this kind.  No, you need aximp.exe if you want to put the control on a form.
Comment: So how can you check the CLSID the Interop DLL is looking for?  When I pause the debugger, I see something promising in the control->base->clsid, but I figure it could be something else.  I removed the references from my project, unregistered the OCX, deleted the Interop DLLs, re-registered the OCX, then used AXIMP to regenerate the DLLs, then re-add the reference, and still no dice.  Is there any way to confirm which ActiveX control it is trying to load, and likewise check to see if it is registered appropriately?
Comment: Are you running the 64-bit version of Windows?
Comment: Yes, I am.  (I'm using the AxImp.exe in C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin, since the one in the x64 doesn't appear to work).  The program is being compiled as x86.
Comment: You'd better double-check the Platform Target setting, also for the Release configuration.  And make sure you use the right version of Regsvr32.exe to register the controls, the 32-bit version is in c:\windows\syswow64.  More here: http://stackoverflow.com/questions/1889941/64-bits-stuff-for-c-development/1890173#1890173
Comment: That was the problem - the clean check-out blew away the platform setting I had been using.  Thanks for all of the help!
Comment: Score one for psychic debugging.

AxImp Generated Reference


Configure separate port for Jboss Admin Console

Question: We want to configure our jboss server behind a firewall. We want to allow access only to our web application.
Is there any way to configure separate port for jboss admin-console, jmx-console?
Answer: Yes, if you use mod_jk_ajp  to map to a Jboss slave, then you can use the JKUnmount  directive to unmount the jboss applications that you dont want served.
So, the rough idea is:
JKMount  /myapp   mainworker
JKUnmount /admin-console
JKUnmount /jmx-console

Mod_jk, if configured that way, in theory, won't forward requests to JBoss for those unmounted applications.  I haven't tried this though.
This is similar to what some people do with mod_rewrite:
# dont proxy files (or app) located at/in: /images /stylesheets /javascripts
RewriteRule "^/(images|stylesheets|javascripts)/?(.*)" "$0" [L]


Why does no one use the notation $f(x)^2$?

Question: It seems to me that "$f(x)^2$" couldn't mean anything other than "$[f(x)]^2$", so there shouldn't be any ambiguity involved, but people always tend to put an extra pair of brackets around the "$f(x)$" everywhere I see it squared. Is there a reason for this?
Comment: Perhaps because some people think $f (x)^2$ could mean $f (x^2)$. This is reasonable when $x$ is some big complicated expression like $\sum \frac{x^n}{n!}$...
Comment: Isn't the usual notation "$f^2(x)$?"
Comment: I think $f(x)^2$ just *looks* quite ugly (maybe because I don't immediately see what's being squared exactly at a glance)... That's certainly the reason why *I* prefer extra brackets.
Comment: @Sam But it's not ugly for a programmer. ;)

For me it's definitely $f(x)\,f(x)$
Answer: The primary concern is that the parenthesized quantity will be viewed as squared, rather than the function. There can be ambiguity when you're unsure of whether the person is being sloppy by considering the argument as squared and just leaving off the brackets around $(x)^2$.
Comment: Not sure, though, if anyone worth reading would be making *that* kind of mistake. ha ha, just my opinion though.
Comment: Sure, in publications. If I'm handed a set of notes though, there's no telling what kind of shorthand conventions may be in use.


How to change view mode of view row using hook_views_pre_render?

Question: Is it possible to change the view mode of a view result in hook_views_pre_render?
For example I have 3 different view modes (teaser, teaser-full, teaser-short). The goal is to have the view repeat these 3 teaser templates in the view page/listing, but I'm firstly struggling to change the view mode at all.
I tried the below, but it doesn't seem to do anything.
function themename_views_pre_render(ViewExecutable $view) {
  foreach ($view->result as $index => $row) {
    $view->row_index = $index;
    $view->rowPlugin->options['view_mode'] = 'teaser';
  }
}

Note: If I drop a breakpoint into the code, it is being hit. But still gets rendered out as default view mode.
Comment: After adding the function, did you do a cache rebuild? If you drop a breakpoint into the code, is the code being hit?
Comment: @Kevin yes it is being hit, but still gets rendered out as default view mode.
Answer: I was able to change the view mode in the hook_views_pre_execute() hook. I believe _views_pre_render() is too late.
function custom_module_views_pre_execute(ViewExecutable $view) {
  // Some logic to determine view mode...

  $view->rowPlugin->options['view_mode'] = 'list';
}

Comment: We can change the field view mode like this https://drupal.stackexchange.com/a/290310/36948
Answer: I wasn't able to get custom_module_views_pre_execute(ViewExecutable $view) example to work.
After inspecting with xdebug, I was able to use this:
function custom_module_preprocess_views_view(&$variables) {
  /** @var \Drupal\views\ViewExecutable $view */
  $view = $variables['view'];
  if ($view->id() == 'view_name' && $view->current_display == "display_name") {
    if (count($view->result) == 1) {
      // Change view mode to teaser when there is only 1 item.
      $variables['rows'][0]['#rows'][0]['#view_mode'] = 'teaser';
    }
  }
}

Answer: The Views Parity Row solves this problem. Worked well for my needs, I just wanted a different view mode for first row item so had to apply this patch for Drupal 8. Works well for other use cases.
Answer: You could do it using the Views UI:

Install Entity API module
Make Fields your format

Since you have Entity API, you can add Rendered Entity as a field.

Select your view mode.

Add more render entity fields for your other view modes (repeat steps 3 and 4).


Evaluating power series

Question:
How do I evaluate the power series
$$\sum_{n = 1}^{\infty}\dfrac{n}{9^{n}}$$
without using the formula for infinite geometric series?

I am interested in an approach which doesn't make use of infinite geometric series.
Any help would be highly appreciated. New approaches are most welcomed. Thanks.
Comment: I think all approaches will more or less involve calculating infinite geometric series.
Comment: But, even if you want you can not apply infinite geometric formula because $q$ is not a constant.
Comment: Just for curiosity - why is a geometric series forbidden? For me this sounds like a question on elementary number theory forbidding the use of prime numbers.
Comment: See [this](https://math.stackexchange.com/questions/30732/how-can-i-evaluate-sum-n-0-inftyn1xn).
Comment: I'm looking for some new approaches to evaluate the series.
Comment: I'm not sure how this helps to evaluate my series, it would be very nice if you could elaborate by answering to the question. I highly appreciate your time and efforts. Thanks.
Answer: I'm not sure about the exact value, but you can compare it to the integral, which converges since $|\frac{1}{9}|<1$, $\int_{0}^{\infty}x a^x dx$, which will be of the same order, and then derive the difference using Bernoulli polynomials.
Comment: Can you please elaborate how? I highly appreciate your time and efforts. Thanks
Comment: Can you please elaborate more?
Comment: I think my solution is incorrect tbh; for some reason, although it should be the case, the integrand is not $xa^x$
Comment: I mean they must be of the same order by Euler-Maclaurin formula, but they are not for some reason: https://en.wikipedia.org/wiki/Euler%E2%80%93Maclaurin_formula
Comment: I see, Any other approach?
Answer: Check with induction that the partial sum is
$$\sum_{k=1}^N \frac{k}{9^k} = \frac{9 - 9^{-N}(8N+9)}{64}$$
Evaluate the limit when $N$ goes to infinity and you get the result.
Comment: Just to be honest, as @DavidMitra pointed out in the reference, there is a known formula for partial sums of series like this, and this result is derived using "geometric series results". However you could pretend to be blind and use induction on a formula that comes from heaven and you are done lol.
Comment: This approach rather seems to be very naive
Comment: lmao Thanks anyways
Answer: Notice that $x \frac{d}{dx} \frac{1}{1-x} = \sum_{i=0}^{\infty}ix^i $. So differenciating you get $$x \frac{d}{dx} \frac{1}{1-x} = \frac{x}{(1-x)^2}$$ Substituting $x= \frac{1}{9}$ you get required answer.
Comment: How is this not using the geometric series? Don't you need to know in advance that $\frac 1{1-x}=\sum_{i\geq 0} x^i$?
Comment: Yeah this does uses geometric series :(
Comment: Well you can compute derivatives in zero...however not complete, but in general I do not see why one should restrain from using a basic identity such as the geometric series to use more involved methods (you also need to prove that your convergence radius of the Taylor expansion is greater than $1/9$ which involves study of analytic functions...)
Answer: Denote $A=\sum_{n\geq 1} n9^{-n}$, $B=\sum_{n\geq 2} n9^{-n}$, $C=\sum_{n\geq 1} 9^{-n}$, $D=\sum_{n\geq 2} 9^{-n}$. You have the closed system
$$
A=B+\frac 19,\quad 9B-A=C,\quad C=D+\frac 19,\quad 9D=C,
$$
which gives the value of $A$. Of course, as a byproduct of the computation one also gets the value of the geometric series $C$.
Comment: Seems like all approaches are using geometric series
Comment: well at least here we are not using the result, but deriving it.

Evaluating power series


How to detect height of text box based on incoming text?

Question: The TextInput for this.state.UserDescription can vary from 1 line to 4-5 depending on how much a user describes themselves. This is fixed as it is loaded, the user cannot edit this TextInput.  However, the userDescGrid box stays a fixed height no matter what the description, so if the user enters 1 line, theres a lot of empty space below it.
How can i detect, based on the number of lines that will be presented, the right height of box to present (or have it automatically adjust the box height value or flex value)?
Remember that this will change and needs to be adaptable to different phone devices too.
<View style={styles.userDescGrid}>
                  <TextInput style={{color: 'green', fontWeight: 'bold'}}
                     value={this.state.UserName}
                     editable = {false}
                     multiline = {false}
                  />
                  <TextInput style={{color: 'green', fontSize: 13,}}
                     value={this.state.UserDescription}
                     editable = {false}
                     multiline = {true}
                     maxHeight = {80}
                  />
                  <TextInput style={{color: 'green', fontSize: 13,}}
                     value={this.state.Weblink}
                     editable = {false}
                     maxHeight = {20}
                  />
</View>

const styles = StyleSheet.create({

 userDescGrid: {
    flex: 3,
    paddingTop: 2,
    backgroundColor: 'black',
    paddingLeft: 10,

  },
})

Comment: For multiline textbox, the normal practice is to say fix the height to 3 lines , and then that will be fine because if the user enters more than 3 lines the system will show a scrollbar. If the user enters less than 3 lines, then yes there will be white space left, but it is fine because once the user submits the data, your APP should use TEXT instead of TEXTINPUT to display the submitted data on screen which will not be showing the extra lines.
Answer: I think in this instance you may want to consider using a monospaced font. If you do that then you can determine the number of characters (this.state.UserDescription.length) for a line of text. The height may look something like...
height: Math.ceil(this.state.UserDescription.length / numberOfCharactersAMonospaceFontUsesInOneLine) + "unit of measurement";


What is the Drupal's way of wrapping fields inside a field?

Question: It seems that many Drupal gurus disfavor using Field Collection module to wrap fields inside a field. They say it's not the Drupal's way of doing it.
In my current scenario, I need a single field with before & after image subfields. I also need a recipe ingredients field, with ingredient name, unit size (using taxonomy reference) and serving amount subfields.
What is the preferred Drupal's way of doing such a thing? Should you have to code an entirely custom module for each field type?
Update
It seems that the ideal approach is to use a custom field type. Optionally you can use Drupal modules to group fields, such as Composed Field and Multifield, and not-so-favored, architecturally cumbersome, Field Collection. Another solution is to create a content-type for each group of fields and use Entity Reference to reference the field to it.
Ideally I'd like to see an example of a custom field type which implements a text and an image field, or something similar.
Comment: It sound like you really need a new entity type.
Comment: @MPD how would you go about doing it. Should I create an entity with the attached fields and then reference it to it?
Answer: You can try https://drupal.org/project/composed_field

The Field collection uses a different approach for creating composed fields. Here are the main differences between this module and the "Field Collection":
  The host field created by "Field Collection" is in fact an entity that gets attached to the fieldable entities (nodes, taxonomy, comment, commerce products, etc). So, although you attach a Field Collection through the Field UI, what is being attached is not a field but an entity.
Once you get your new entity (host field) attached to your fieldable entity (node, comment, taxonomy, commerce product, etc) then you have to attach the fields ( what would be the subfields ) into the host field ( Field Collection entity).
Each subfield is actually a field on its own, that is, from the database point of view, each subfield is a single field.
"Composed Field" on the other hand attaches a field (host field), not an entity, to your fieldable entities (node, comment, taxonomy, commerce product, etc) through the Field UI. At the end of the day, even if you set a field with say 4 subfields, you will end up having only one field and a single value saved into the database.
Unless you have a very specific use case need "Composed Field" should do what you need with less effort and less resources.

One more module availabel to achive the similar task is https://drupal.org/project/multifield but it is currently in unstable status

This project seeks to provide a true compound field solution for Drupal 7. As much as I love Field collection, it still has to save actual entities, and can cause performance problems due to having to load all the referenced field collection entities on node, or parent entity load.
Comment: BTW I agree with what you're saying - I won't let field collection near a project, it's cumbersome and doesn't integrate well with a lot of things. I always create a custom field type when I need that functionality, I don't think there's an alternative
Comment: I am aware of the other modules. My question was rather - what is the correct way of doing it? What do the big guys do?
Comment: @timofey Who are these "big guys" and why are you convinced they don't use field collection? You must have quite a few sources for this, can you share them? Surely they haven't just said "that's not the Drupal way" without offering the alternative?
Comment: @Clive - I cannot remember the exact sources, but for example in http://drupal.stackexchange.com/questions/4034 Dave Reid said "isn't that how Drupal usually works", when asked for a field grouping solution. I also remember reading that Field Group module dropped the Field Collection module because it didn't see a need for it.
Answer: https://drupal.org/project/composed_field is working fine for wrapping field inside field.
suppose, if you want to set phone no. with country code then
<code>
$cntrcode =  isset($form_state['cntrcode']) ? $form_state['cntrcode'] : '+358';
$pno = isset($form_state['phno']) ? $form_state['phno'] : '';
$passenger->field_phone_number[und][0]['composed'] = array('1' => $cntrcode,'2' => $pno);
</code>
Above code wrapp both contry code and phone no. in single field
Answer: in such cases I change my way of analyzing the project. for example I separate the fields which I need to wrap and create another content type for theme and use entity reference to join theme together! as Drupal's views module is completely integrated with entity reference module, It has worked very nice for me.
Comment: This is somewhat similar to what Field Collection does, without actually involving the module.
Comment: using field group module is another way actually. try using entity reference! I'm sure you will enjoy it...


javaemvreader android example code

Question: I am trying to build an android application to read credit card / Smart card data form a Micro USB Smart Card reader.
When I use this app from google play, it can read all card data successfully using my card reader:
https://play.google.com/store/apps/details?id=com.scdroid.emvdemo&hl=en
According to developer's website they use this library to build this app:
https://code.google.com/p/javaemvreader/
Unfortunately I tried to use the code in it but I am getting Terminal Exception :

sasc.terminal.TerminalException: No provider available

My Code looks like this:

<code>    protected void testSCReader() {
       SmartCard smartCard = null;
       CardConnection conn = null;

       try {
            conn = TerminalUtil.connect(TerminalUtil.State.CARD_PRESENT);
            if(conn == null){
               rawT.append("TerminalUtil.connect returned null");
               return;
            }

            SessionProcessingEnv env = new SessionProcessingEnv();
            env.setReadMasterFile(true);
            env.setProbeAllKnownAIDs(true);
            CardSession cardSession = CardSession.createSession(conn, env);

            smartCard = cardSession.initCard();

            EMVSession session = EMVSession.startSession(smartCard, conn);
            session.initContext();

            for (EMVApplication app : smartCard.getEmvApplications()) {
                    session.selectApplication(app);
                    session.initiateApplicationProcessing(); //GET PROCESSING OPTIONS + READ  RECORD(s)
                    if (!app.isInitializedOnICC()) {
                        //Skip if GPO failed (might not be a EMV card, or conditions not satisfied)
                        continue;
                    }

                    //Be VERY CAREFUL when setting this, as it WILL block the application if the PIN Try Counter reaches 0
                    //Must be combined with a PIN callback handler
                    EMVTerminal.setDoVerifyPinIfRequired(false);
                    session.prepareTransactionProcessing();

                    //Check if the transaction processing skipped some steps

                    if(app.getATC() == -1 || app.getLastOnlineATC() == -1) {
                        session.testReadATCData(); //ATC, Last Online ATC
                    }

                    //If PIN Try Counter has not been read, try to read it
                    if(app.getPINTryCounter() == -1) {
                        session.readPINTryCounter();
                    }

                    if(!app.isTransactionLogProcessed()) {
                        session.checkForTransactionLogRecords();
                    }

                    //testGetChallenge (see if the app supports generating an unpredictable number)

                    session.testGetChallenge();

            }

            System.out.println("\n");
            System.out.println("Finished Processing card.");
            System.out.println("Now dumping card data in a more readable form:");
            System.out.println("\n");

            rawT.append("Finished Processing card.");

            //See the finally clause

        } catch (TerminalException ex) {
            ex.printStackTrace(System.err);
            rawT.append(ex.toString());
        } catch (UnsupportedCardException ex) {
            System.err.println("Unsupported card: " + ex.getMessage());
            rawT.append(ex.toString());
            if (conn != null) {
                //System.err.println("ATR: " + Util.prettyPrintHexNoWrap(conn.getATR()));
                System.err.println(ATR_DB.searchATR(conn.getATR()));
            }
        } catch (SmartCardException ex) {
            ex.printStackTrace(System.err);
            rawT.append(ex.toString());
        } finally {
            if (conn != null){
                try{
                    conn.disconnect(true);
                }catch(TerminalException ex){
                    ex.printStackTrace(System.err);
                }
            }
            if (smartCard != null) {
                try {
                  /* int indent = 0;
                    Log.d("FHD_DBG","======================================");
                    Log.d("FHD_DBG","             [Smart Card]             ");
                    Log.d("FHD_DBG","======================================");
                    smartCard.dump(Log.d, indent);
                    Log.d("FHD_DBG","---------------------------------------");
                    Log.d("FHD_DBG","                FINISHED               ");
                    Log.d("FHD_DBG","---------------------------------------");
                    //Log.getPrintWriter().flush();*/
                rawT.append(smartCard.toString());
                } catch (RuntimeException ex) {
                    ex.printStackTrace(System.err);
                }
                Log.d("FHD_DBG","");
            } else if (conn != null) {
            rawT.append(new sasc.iso7816.ATR(conn.getATR()).toString());
            }
        }
}</code>
Comment: Actually today I found that the main issue is that for some reason it is not able to find a class in javax.smartcardio.TerminalFactory library due to which there was a ClassNotFound Exception.
Strange thing is, I did include JDK1.7 library which has javax.smartcardio library, but it still is not visible to compiler???
Can someone explain please?
Comment: any luck with this??
Answer: I received the same problem, java.lang.ClassNotFoundException: javax.smartcardio.TerminalFactory.
This is because javax.smartcardio.* is not available in the java environment which comes with the android java compiler, its available in JRE.
Comment: I found https://play.google.com/store/apps/details?id=sasc.android.smartcard&hl=ru app wich use exactly this library inside plus some classes which is not available in repository. And it works on Nexus 5 (6.0.1) + USB OTG reader.

javaemvreader android example code


Is the expected utility function linear?

Question: Given the definition of the mixed extension of a finite game as in the link below (only first 7 lines):
How to find perfect equilibria in a finite game?
We define the expected utility function in the mixed extension of a finite game (with the same notation in the link) as
$\forall \sigma=(\sigma_1,\cdots,\sigma_n)\in\Delta S,~u_i'(\sigma)=\Sigma_{s\in S}[\Pi_{i\in N}\sigma_i(s_i)]\cdot u_i(s)$, where $s=(s_1,\cdots,s_n)\in S=S_1\times\cdots\times S_n$ and $\sigma_i(s_i)$ is the chance using $s_i$ in $\sigma_i$.
I wonder if such a expected utility function is linear, though others say so. I literally tried to prove it:
Let $\sigma=(\sigma_1,\cdots,\sigma_n)$, $\gamma=(\gamma_1,\cdots,\gamma_n)$, and $\alpha\in\mathbb{R}$, $u_i'(\alpha\sigma+\gamma)=\Sigma_{s\in S}[\Pi_{i\in N}(\alpha\sigma+\gamma)_i(s_i)]\cdot u_i(s)=\Sigma_{s\in S}[\Pi_{i\in N}(\alpha\sigma(s_i)+\gamma(s_i))]\cdot u_i(s)=\Sigma_{s\in S}[\Pi_{i\in N}\alpha\sigma_i(s_i)]\cdot u_i(s)+\Sigma_{s\in S}[\Pi_{i\in N}\gamma_i(s_i)]\cdot u_i(s_i)$.
The problem is in the first part of the last equality $\Sigma_{s\in S}[\Pi_{i\in N}\alpha\sigma_i(s_i)]\cdot u_i(s)$. We can't simply take $\alpha$ out of this expression. So it can't be linear.
Is there any problem above?
Let me give an example here.
Suppose we have 2 players having strategy sets $S_1=\{a_1,a_2\}$ and $S_2=\{b_1,b_2\}$. We then have $\Delta S_1=\{(x,1-x)\in\mathbb{R}^2|0\leq x\leq1\}$, where $x$ is the chance that player 1 uses $a_1$ and $\Delta S_2=\{(y,1-y)\in\mathbb{R}^2|0\leq y\leq1\}$, where $y$ is the chance that player 2 uses $b_1$. For each player $i$, given a strategy profile $\sigma=(x,1-x,y,1-y)\in\Delta S_1\times\Delta S_2$, $u_i'(\sigma)=[x\cdot y\cdot u_i(a_1,b_1)]+[x\cdot (1-y)\cdot u_i(a_1,b_2)]+[(1-x)\cdot y\cdot u_i(a_2,b_1)]+[(1-x)\cdot(1-y)\cdot u_i(a_2,b_2)]$.
Is this illustration of the expected utility function clear to you?
And no, the expressions I mentioned at the beginning does not have any miscalculation like $(x+y)^2=x^2+y^2$.  :)
A different idea comes to me:
Does this linearity of $u_i'(\sigma_1,\cdots,\sigma_n$ mean the linearity only in $\sigma_i$?
That is, for all $i$, if $\sigma_i,\sigma_i'\in \Delta S_i$ and for all $\alpha\in\mathbb{R}$, $u_i'(\sigma_1,\cdot,\alpha\sigma_i+\sigma_i',\cdots,\sigma_n)=\alpha u_i'(\sigma_1,\cdots,\sigma_i,\cdots,\sigma_n)+u_i'(\sigma_1,\cdots,\sigma_i',\cdots,\sigma_n)$, which is proved to be right.
Comment: Sometimes, to prove linearity it is easier to show additivity and homogeneity separately. That is, $f(x+y)=f(x)+f(y)$ and $f(ax)=af(x)$
Comment: @dcs24 yes, but as I mentioned at last, the problem is then to prove $f(ax)=af(x)$. We obviously can't take the coefficient out, right?
Comment: I find it hard to read what you have put down. I don't think your last line is correct, how can you take the product into the sum? Edit that is: you're essentially saying that (x+y)^2 = x^2 + y^2
Comment: Hey, @dcs24, to make my expected utility function more readable, I've edited my question above by adding a simple example.  :)
Comment: yes it is linear in each $\sigma_j$ or multi-linear in $\sigma$ like the determinante of a square matrix is linear in each column
Comment: @RitaTseng sorry my answer in the other question was misleading
Answer: The expected utility is multilinear in the sense that: for every $\sigma \in \Delta(S)$, every $ \alpha_{i}$ and $\beta_{i}$ in $\Delta(S_{i})$ and every $\lambda \in [0,1]$ you have $U_{i}(\sigma_{-i},\lambda \alpha_{i} + (1-\lambda ) \beta_{i}) = \lambda U_{i}(\sigma_{-i},\alpha_{i}) + (1-\lambda )U_{i}(\sigma_{-i},\beta_{i})$.


Criando Annotations customizado em ASP.NET

Question: Possuo um Controller em meu projeto asp.net (Web Service) que preciso fazer uma verificação de token para requisição de cada método. Uma solução que encontrei é criar um método estático e colocar uma chamada a cada começo de cada método. Eu poderia colocar apenas uma vez no construtor do meu Controller mas esse é o problema: nem todos os métodos precisam dessa verificação.
Então gostaria de saber como implementar um Annotations com a implementação da minha verificação e usar o Annotations para validar essas requisições. Caso a requisição for inválida, a requisição é remetida para uma página 404.
Gostaria de um horizonte de como fazer isto, algo como esse pseudo-código abaixo:
@VerificationToken
public List<Produto> getAllProducts(){
  // implementação
}

Answer: Uma solução para isso, seria criar sua CustomAuthorizeAttribute herdando de AuthorizeAttribute
Imagine por exemplo algo como AuthorizeByMe
ficaria assim:

  public class AuthorizeByMeAttribute : AuthorizeAttribute {

      protected override bool AuthorizeCore(HttpContextBase httpContext)
      {
          return true;
      }
  }

e na action/controller

    [AuthorizeByMe]
    public ActionResult Skol()
    {
        //...
        return View();
    }
Comment: Acho que o que ele quer não é bem uma autenticação. É tipo uma validação customizada de token. Derivar o `[Authorize]` funcionaria bem se o projeto dele não fosse um Web Service.
Comment: Não tenho certeza do tipo do projeto, pois a questão menciona um redirecionamento para uma página 404, o que faz pouco sentido para um web-service.
Comment: Só seria válido se no retorno do Web-Service fosse uma call para uma página, e no retorno quando inválido viesse o pedido para a 404
Comment: Miguel Ângelo eu mencionei um retorno 404 mas não necessariamente deve ser 404, pode ser um retorno json customizado informando o cliente que a autenticação via token falhou.
Answer: Em asp.net-mvc, chamamos "Annotations" de Attributes. Assim como os annotations de java, Attributes servem para decorar classes, métodos, propriedades, etc.
Só que um Attribute é uma classe especial que precisa ser chamada por outra pra funcionar. No seu caso, o que você quer é chamar o método, mas antes disso, que seja testada uma condição antes do método. Isso se faz implementando um Proxy Dinâmico, fazendo um override no método Invoke dessa classe de Proxy.
Pretendo colocar uma solução mais completa em breve. Estou inclusive favoritando a questão para voltar nela depois. Em todo caso, você pode usar a solução do @tchicotti e derivar o [Authorize].
Answer: Pode criar um interceptor. O método "InvokeAsync" será sempre chamado antes do seus métodos no controller:
 {
    public class MyInterceptor
    {
        public readonly RequestDelegate _next;

        public MyInterceptor(RequestDelegate next) : base (next) { }

        public async Task InvokeAsync(HttpContext context)
        {
            < seu código >

            await _next(context);

            < seu código >
        }
    }

    public static class MyInterceptorExtensions
    {
        public static IApplicationBuilder UseMyInterceptor(
        this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<MyInterceptor>();
        }
    }

Para registrar o interceptor, altere o arquivo Program.cs:
app.UseMyInterceptor();


is it necessary for the namespace to be the name of the file in c#?

Question: For example, I name my file(console application) 'Hello', so do I have to write namespace Hello?If no, what is the purpose of adding namespace?
Comment: Best practice is to name the files the same as the class (and one top level class per file).  Namespaces should match the directory structure, but it's up to you how to name everything.
Comment: [The **namespace** keyword is used to declare a scope that contains a set of related objects. You can use a namespace to organize code elements and to create globally unique types.](https://msdn.microsoft.com/en-us/library/z2kcy19k.aspx)
Comment: Usually namespace is connected with folders where your file exists. It helps to organize code as @john mention.
Answer: No, the namespace can be anything, they don't have to be the same as the filename. It is good practice to have the namespaces correspond to physical file paths (folders in your solution).
So if you have a file in .\Interfaces\ViewModels\Client, usually the namespace declaration in that file will be:
namespace DefaultNamespaceOfAssembly.Interfaces.ViewModels.Client { ... }

ReSharper even offers to fix up namespaces that are breaking this rule.
The purpose of the namespace is to

modularize your code by putting things that belong together (by functionality for example) in the same namespace,
reduce name collisions. Without namespaces importing an external library would result in hell if it were to contain classes with the same name as classes in your own code.

Probably there are more, but at first thought these come to mind, although these two should already be enough to justify their existance.
Answer:
I name my file(console application) 'Hello', so do I have to write namespace Hello?

No, you can name it whatever you want.
If you're writing a library to be used by other code, and that library is the only (or main) source of types in that namespace, then it would be convenient to users for the DLL to have a name based on the namespace, because then they can easily remember that the UsefulTypes.CoolStuff classes all come from the UsefulTypes.CoolStuff.dll assembly. There's no rule that you have to do this, it can just be convenient if you do.
With applications this isn't anywhere near as useful; end-users don't care what namespaces you use and may not know what a namespace is. It might be useful if the application was a tool for .Net developers, but otherwise not.

If no, what is the purpose of adding namespace?

Exactly what it says; it's a space for names. By putting the names of classes, enums, delegates and structs into a namespace they are separated from other cases of the same name being used in other namespaces. You don't have to make sure that no library you used has something with the same name, unless you are actually going to use that thing with the same name.
When writing an application it keeps stuff from other assemblies out of your way. When writing libraries it's even more important, as it also keeps your stuff out of other people's way.


Design Linked List - Leetcode #707 - getting wrong output

Question: I am trying to solve LeetCode problem 707. Design Linked List:

Design your implementation of the linked list. You can choose to use a singly or doubly linked list.
A node in a singly linked list should have two attributes: val and next. val is the value of the current node, and next is a pointer/reference to the next node.
If you want to use the doubly linked list, you will need one more attribute prev to indicate the previous node in the linked list. Assume all nodes in the linked list are 0-indexed.
Implement the MyLinkedList class:

MyLinkedList() Initializes the MyLinkedList object.
int get(int index) Get the value of the indexth node in the linked list. If the index is invalid, return -1.
void addAtHead(int val) Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.
void addAtTail(int val) Append a node of value val as the last element of the linked list.
void addAtIndex(int index, int val) Add a node of value val before the indexth node in the linked list. If index equals the length of the linked list, the node will be appended to the end of the linked list. If index is greater than the length, the node will not be inserted.
void deleteAtIndex(int index) Delete the indexth node in the linked list, if the index is valid.

Example 1:
Input
["MyLinkedList", "addAtHead", "addAtTail", "addAtIndex", "get", "deleteAtIndex", "get"]
[[], [1], [3], [1, 2], [1], [1], [1]]

Output
[null, null, null, null, 2, null, 3]

Explanation
MyLinkedList myLinkedList = new MyLinkedList();
myLinkedList.addAtHead(1);
myLinkedList.addAtTail(3);
myLinkedList.addAtIndex(1, 2);    // linked list becomes 1->2->3
myLinkedList.get(1);              // return 2
myLinkedList.deleteAtIndex(1);    // now the linked list is 1->3
myLinkedList.get(1);              // return 3

Wondering what's wrong with my LinkedList here.
Can't get it past the input:
["MyLinkedList","addAtHead","addAtHead","addAtHead","addAtIndex","deleteAtIndex","addAtHead","addAtTail","get","addAtHead","addAtIndex","addAtHead"]

[[],[7],[2],[1],[3,0],[2],[6],[4],[4],[4],[5,0],[6]]

with my output as:
[null,null,null,null,null,null,null,null,6,null,null,null]

and the expected output as:
[null,null,null,null,null,null,null,null,4,null,null,null]

This is my implementation:
class DoublyListNode {
    int val;
    DoublyListNode next;
    DoublyListNode prev;

    public DoublyListNode(int val) {
        this.val = val;
        this.next = null;
        this.prev = null;
    }
}

class MyLinkedList {

    DoublyListNode head;
    DoublyListNode tail;

    public MyLinkedList() {
       head = new DoublyListNode(-1);
       tail = new DoublyListNode(-1);

       head.next = tail;
       tail.prev = head;
    }

    public int get(int index) {
        DoublyListNode curr = head;
        int i = 0;

        while(tail != null && index > 0){
            curr = curr.next;
            index--;
        }

        if(index == 0 && curr != null){
            return curr.val;
        }
        return -1;
    }

    public void addAtHead(int val) {
        DoublyListNode newHead = new DoublyListNode(val);
        head.next.prev = newHead;
        head.next = newHead;
        newHead.next = head.next;
        newHead.prev = head;
    }

    public void addAtTail(int val) {
        DoublyListNode newTail = new DoublyListNode(val);

        tail.prev.next = newTail;
        tail.prev = newTail;
        newTail.next = tail;
        newTail.prev = tail.prev;
    }

    public void addAtIndex(int index, int val) {
        DoublyListNode curr = head;

        while(tail != null && index > 0){
            curr = curr.next;
            index--;
        }

        if(index == 0 && curr != null){
            DoublyListNode newNode = new DoublyListNode(val);
            newNode.prev = curr.prev;
            newNode.next = curr.next;
            curr.prev.next = newNode;
            curr.next.prev = newNode;
        }
    }

    public void deleteAtIndex(int index) {
        DoublyListNode curr = head;

        while(tail != null && index > 0){
            curr = curr.next;
            index--;
        }
        if(index == 0 && curr != null && curr.next != null && curr.prev != null){
            curr.prev.next = curr.next;
            curr.next.prev = curr.prev;
        }
    }
}

/**
 * Your MyLinkedList object will be instantiated and called as such:
 * MyLinkedList obj = new MyLinkedList();
 * int param_1 = obj.get(index);
 * obj.addAtHead(val);
 * obj.addAtTail(val);
 * obj.addAtIndex(index,val);
 * obj.deleteAtIndex(index);
 */

Answer: You have chosen to implement a doubly linked list, with two dummy (sentinal) nodes, head and tail.
This is fine, but there are several issues in your code:

In get, addAtIndex and deleteAtIndex, you start with curr equal to head, which means that if the given index is 0, curr will still be that head, while the node at index 0 really is the successor of your head. head doesn't count as node, as it is a dummy node. So you should start with curr = head.next instead of curr = head. As a consequence, in deleteAtIndex, you don't need the last part of the if condition (curr.prev != null), as this is now guaranteed.

In the same three functions you have a loop condition that says tail != null, but this condition is always true. tail never is assigned anything else after its initialisation in the constructor (and it shouldn't). The loop condition should instead test curr != null.

In addAtHead you have wired the nodes incorrectly. The assignment head.next = newHead; should happen after newHead.next = head.next;, because as you have it now, you make newHead.next to become equal to newHead, introducing a cycle in your list.

In addAtTail the order of assignments is also in the wrong order. You make newTail.prev equal to newTail, introducing a cycle.

In addAtIndex there are two wrong assignments. The first two would attempt to exclude curr from the list, but it should become the neighbor of the new node. Therefore you should do newNode.next = curr; instead of newNode.next = curr.next;. curr.next.prev = newNode; is also wrong, as this link should not be updated. It could even lead to an exception, because curr could be equal to the tail node, which has a null for its next field. Instead you should do curr.prev = newNode;

Not a problem, but in get you have declared an unused variable i. You can drop it.
Here is your code with the above corrections applied to it (see comments in code):
class DoublyListNode {
    int val;
    DoublyListNode next;
    DoublyListNode prev;

    public DoublyListNode(int val) {
        this.val = val;
        this.next = null;
        this.prev = null;
    }
}

class MyLinkedList {
    DoublyListNode head;
    DoublyListNode tail;

    public MyLinkedList() {
        head = new DoublyListNode(-1);
        tail = new DoublyListNode(-1);

        head.next = tail;
        tail.prev = head;
    }

    public int get(int index) {
        DoublyListNode curr = head.next; // This is the node at index 0

        while (curr != null && index > 0) { // Corrected loop condition
            curr = curr.next;
            index--;
        }

        if (index == 0 && curr != null) {
            return curr.val;
        }
        return -1;
    }

    public void addAtHead(int val) {
        DoublyListNode newHead = new DoublyListNode(val);
        // Fixed the order of the assignments:
        newHead.next = head.next;
        newHead.prev = head;
        head.next.prev = newHead;
        head.next = newHead;
    }

    public void addAtTail(int val) {
        DoublyListNode newTail = new DoublyListNode(val);
        // Fixed the order of the assignments:
        newTail.next = tail;
        newTail.prev = tail.prev;
        tail.prev.next = newTail;
        tail.prev = newTail;
    }

    public void addAtIndex(int index, int val) {
        DoublyListNode curr = head.next; // This is the node at index 0

        while (curr != null && index > 0){ // Corrected loop condition
            curr = curr.next;
            index--;
        }

        if (index == 0 && curr != null) {
            DoublyListNode newNode = new DoublyListNode(val);
            newNode.prev = curr.prev;
            newNode.next = curr; // Corrected assignment
            curr.prev.next = newNode;
            curr.prev = newNode; // Corrected assignment
        }
    }

    public void deleteAtIndex(int index) {
        DoublyListNode curr = head.next; // This is the node at index 0

        while (curr != null && index > 0) { // Corrected loop condition
            curr = curr.next;
            index--;
        }
        if (index == 0 && curr != null && curr.next != null) { // Removed obsolete condition
            curr.prev.next = curr.next;
            curr.next.prev = curr.prev;
        }
    }
}

As a next step, you could try to remove some code repetition, as you have essentially the same loop in three of these methods.
Comment: Ah yes, I'm not the question asker and didn't look closely at the code but I see your point now
Comment: I don't quite understand the assignment of `curr = head.next` in `get`. If a get(0) is called, wouldn't that mean your implementation will be returning get(1) instead since it is getting the next node in the list rather than the first one?
Comment: What you call the first one is the `head` node. It is a dummy node you have created. It doesn't count as a node that really has data. Realise that your list implementation already starts with creating two nodes (`head` and `tail`) even though it should be regarded as an empty list.
Comment: Did that answer your question?