What's the best way to implement a single tri-state checkbox within angularjs?

Question: Is there a simple way to place a single tri-state checkbox on a web-page and bind it to a boolean model so the latter can take true, false or null values?
The closest solution I found so far is http://jsfiddle.net/HB7LU/454/ but it has a flaw when setting up an initial view state (as there is no way to get a model value during first rendering). Any other suggestions deal with multiple child checkboxes and solves the problem by watching on them.
Answer: http://jsfiddle.net/xJhEG/ I made it in a commercial project. Tristates are true, false, null (not "unknown")
.directive('indeterminate', [function() {
    return {
      require: '?ngModel',
      link: function(scope, el, attrs, ctrl) {
        var truthy = true;
        var falsy = false;
        var nully = null;
        ctrl.$formatters = [];
        ctrl.$parsers = [];
        ctrl.$render = function() {
          var d = ctrl.$viewValue;
          el.data('checked', d);
          switch(d){
          case truthy:
            el.prop('indeterminate', false);
            el.prop('checked', true);
            break;
          case falsy:
            el.prop('indeterminate', false);
            el.prop('checked', false);
            break;
          default:
            el.prop('indeterminate', true);
          }
        };
        el.bind('click', function() {
          var d;
          switch(el.data('checked')){
          case falsy:
            d = truthy;
            break;
          case truthy:
            d = nully;
            break;
          default:
            d = falsy;
          }
          ctrl.$setViewValue(d);
          scope.$apply(ctrl.$render);
        });
      }
    };
  }])

Comment: Is this browser dependent? I could only see that it changes from true to false (same as having no directive or change handler)?! Tested via IE11.
Comment: Thanks. I forked your directive and created a tri-state directive with 2 checkboxes. http://jsfiddle.net/laurilubi/dj6gkzrg/2/
Answer: Here my Fiddle, starting from TruongSinh and changing
http://jsfiddle.net/xJhEG/25/
without
var truthy = true;
var falsy = false;
var nully = null;

Answer: You have take advantage of the indeterminate state of <input type="checkbox">.
MDN web docs:
There exists an indeterminate state of checkboxes, one in which it is not checked or unchecked, but undetermined. This is set using the HTMLInputElement object's indeterminate property via JavaScript (it cannot be set using an HTML attribute).
PLUNKER: TRISTATE DIRECTIVE
HTML

    <input type="checkbox" ng-model="state" indeterminate /> {{state}}

DIRECTIVE
app.directive('indeterminate', function() {
  return {
    restrict: 'A',
    scope: {
      model: '=ngModel'
    },
    link: function(scope, el, attrs, ctrl) {
      var states = [true, false, undefined];
      var index = states.indexOf(scope.model);
      setIndeterminate();

      el.bind('click', function() {
        scope.model = states[++index % 3];
        setIndeterminate();
      });

      function setIndeterminate() {
        scope.$applyAsync(function() {
          el[0].indeterminate = (scope.model === undefined);
        });
      }
    }
  };
});

Comment: This seems more simple and native solution compared to the other provided solutions. If I were to be @user32412, I would have accepted this as the answer.
Answer: I've created directive, which you can use.
Three-state checkbox AngularJS Directive on GitHub
There is also a post, how it was built: Creating Angular Directive "Three-state checkbox
You can try a DEMO
And the directive looks like that:
angular.module("threeStateCheckbox", [])
    .directive("threeStateCheckbox", ['$compile', function($compile){
        return {
            restrict: "A",
            transclude: true,
            require: 'ngModel',
            link: function(scope, element, attrs, ngModel){
                var states = [true, false, null];
                var classNames = ["checked", "unchecked", "clear"];
                scope.click = function(){
                    var st;
                    states.map(function(val, i){
                        if(ngModel.$modelValue === val){
                            st = states[(i+1)%3];
                        }
                    });
                    ngModel.$setViewValue(st);
                    ngModel.$render();
                };
                scope.tscClassName = function(){
                    var className;
                    states.map(function(val, i){
                        if(ngModel.$modelValue=== val){
                            className = classNames[i];
                        }
                    });
                    return className;
                };
                element.attr("class", "tri-sta-che ");
                element.attr("ng-click", "click()");
                element.attr("ng-class", "tscClassName()");
                element.removeAttr("three-state-checkbox");
                $compile(element)(scope);
            }
        };
    }]);

Answer: Because all previous answers don't work since AngularJS 1.7 (the checkbox model only allows boolean values now and everything else gets converted to boolean), I now found a solution that works until v1.8:
Thanks to @The.Bear for the base.
To use it, simply include <tristate label="someOptionalText" ng-model="yourVariableToBindTo" /> and the corresponding directive.

var app = angular.module('tristatedemo', []);

app.controller('MyCtrl', function() {
  this.state = null; //initial state
});

app.directive('tristate', function() {
  return {
    restrict: 'E',
    scope: {
      model: '=ngModel',
      label: '@'
    },
    template: '<input type="checkbox" /> {{label}}',
    link: function(scope, el, attrs, ctrl) {
      var states = [true, false, null];
      var index = states.indexOf(scope.model);
      setIndeterminate();

      el.bind('click', function() {
        scope.model = states[++index % 3];
        setIndeterminate();
      });

      function setIndeterminate() {
        scope.$applyAsync(function() {
          var cb = el.find('input')[0];
          cb.checked = scope.model;
          cb.indeterminate = (scope.model === null);
        });
      }
    },
  };
});
<!DOCTYPE html>

  {{(ctrl.state === null) ? "null" : ctrl.state}}

  <tristate label="abc" ng-model="ctrl.state" />


Lambda Calculus factorial

Question: I have a few exercises for my study subject computability theory. One of this is:
Please, write term for function $f(n) = n!$
I don't know how start doing it. Maybe someone can help with this example or maybe someone can send me where in net I can find material for this topic.
Comment: What primitives are you using?  Are you doing something like church encoding of numerals?  Do they expect you to use a fixed point operator to avoid recursion?
Comment: Can you define the factorial recursively ?
Comment: @YvesDaoust in this exercise? The only content of this task is a short sentence, write a term
Comment: Are you able to define the factorial recursively ? Or do you ignore what a factorial is ?
Answer: If we exploit the iteration that we get for free from the Church numerals, we don't need to do our own fixpoints, so we can get through a lot easier than DanielV's solution.
If we create a function $F$ such that
$$ \underbrace{F(F(\cdots(F}_n (1,1))\cdots)) = (n+1,n!) $$
then the factorial of $k$ is the second element of the pair that results from $k\; F\; (1,1)$
The standard representation of the ordered pair $(A,B)$ is $\lambda g.g A B$,
so this means that
$$ ! = \lambda k. k\;F\;(\lambda g.g\,1\,1)\;(\lambda ab.b) $$
So we need to define $F$. It must satisfy the definition (in ordinary arithmetic notation)
$$ F(a,b) = (a+1, a\times b) $$
which we can translate directly to lambda notation using known successor and multiplication constructions for Church numerals as
$$ F = \lambda p.p (\lambda a b g. g \; (\lambda f x.f(afx))\; (\lambda f.a(bf))) $$
Now all there is left is to expand the definitions of  $F$ and $1$, and we get
$$ ! = \lambda k. k
 \; \Bigl(\lambda p.p\bigl(\lambda abg.g\;\bigl(\lambda fx.f(afx)\bigr)\;\bigl(\lambda f.a(bf)\bigr)\bigr)\Bigr)
 \; \bigl(\lambda g.g\, (\lambda h.h)\, (\lambda h.h)\bigr)
 \; \bigl(\lambda ab.b\bigr)
$$

Using this technique we can write any primitive recursive function -- or, in programming terms, every FOR program -- in a quite natural way without ever using an explicit fixpoint combinator. In contrast to the recursion schema DanielV uses, the results will be typable in System F.
Comment: Ah yes this is much more straightforward, probably what the book intended.
Comment: Minor oops: I forgot to unpack the pair given as input to $F$. Fixed now.
Comment: I think for evaluating $Fp = \langle g, g(\text{Succ}(1^\text{st}p))(\times (1^\text{st}p)(2^\text{nd}p))\rangle$  you might have gotten the $p,g$ terms a little out of order.  F isn't a pair until after a pair is applied to it.  I got    $$F = \langle p~g,~ g \langle f~x,~f(p\langle a~b,~a\rangle fx)\rangle  \langle f,~p\langle a~b,~a\rangle (p\langle a~b,~b\rangle f)\rangle \rangle $$ that's a really nice technique though, I appreciate you showing it.
Comment: @DanielV: No, I think it is right now. $p$ is the incoming pair. We split that up into $a$ and $b$, and then produce the output pair $\lambda g.(\cdots)$. Then $g$ will be whatever the _consumer_ of the output pair does with its elements. (Note, I just now renamed a $h$ to $p$, but the structure is the same).
Comment: @DanielV: Your term looks like it would also work; I just pick the $p$ apart once and for all before I wait for the $g$ to come in, rather than at each point where I need to project from it.
Comment: I think if you did that the way I think you are saying, it would beta reduce to what I got (something of the form $\langle p \langle g,~g(\dots)(\dots)\rangle \rangle$ but I'm not seeing how at the moment.
Comment: @DanielV: The equivalence of those two forms depends on $p$ actually behaving like an ordered pair; otherwise it matters whether we say $\lambda p.p(\lambda abg.\cdots)$ or $\lambda pg.p(\lambda ab.\cdots)$
Answer: So a factorial is:
$$n! = \text{ if } (n \leq 1) \text{ then } 1 \text{ else } n \times (n - 1)!$$
or in prefix form:
$$!n = \leq n 1 1 (\times n (! (- n 1)))$$
A lambda calculus expression satisfying
$$Fx \triangleright Jx ( F (P x) )$$
is
$$F  = \langle y, \langle G x, Jx ( G (P x) ) \rangle  y^2\rangle ^2$$
(using $a^2$ to represent $(aa)$).  Here $J$ represents your sentinal conditions, value, and wrapper around the recursive return, and $P$ represents the predecessor function.  So translating $\leq x 1 1 (\times n ! (- n 1))$ into  $Jn ( F (P n) )$ you get
$J = \langle n r, \leq n 1 1 (\times n r)\rangle $
So altogether, you get:
$$\begin{align}
! &= \langle y, \langle G n, Jn ( G (P n) ) \rangle  y^2\rangle ^2
\\&= \langle y, \langle G n, \langle n r, \leq n 1 1 (\times n r)\rangle n ( G (P n) ) \rangle  y^2\rangle ^2
\\&= \langle y, \langle G n, \leq n 1 1 (\times n ( G (P n) )) \rangle  y^2\rangle ^2
\end{align}$$
Now to look up the church encoding https://en.wikipedia.org/wiki/Church_encoding of $1$, $\leq$, $\times$, and $P$:
$$\begin{align}
     1 & = \langle f x, fx\rangle                                                                    \\
\times & = \langle m n f, m(nf)\rangle                                                               \\
     P & = \langle nfx, n\langle g h, h(gf)\rangle  \langle u,x\rangle \langle u,u\rangle \rangle    \\
  \leq & = \langle m n, Z (- m n)\rangle                                                             \\
     Z & = \langle n, n \langle x, \bot \rangle  \top \rangle                                         \\
 \bot  & = \langle a b, b\rangle                                                                     \\
  \top  & = \langle a  b, a\rangle                                                                    \\
     - & = \langle m n, n P m\rangle                                                                 \\
\end{align}$$
So putting it all together:
$$\begin{array} {rcl}
 ! &=& \langle y, \langle G n, \leq n 1 1 (\times n ( G (P n) )) \rangle  y^2\rangle ^2
\\ &=& \langle y, \langle G n, \langle m n, Z (- m n)\rangle  n 1 1 (\times n ( G (P n) )) \rangle  y^2\rangle ^2
\\ &=& \langle y, \langle G n, Z (- n 1) 1 (\times n ( G (P n) )) \rangle  y^2\rangle ^2
\\ &=& \langle y, \langle G n, Z (Pn) 1 (\times n ( G (P n) )) \rangle  y^2\rangle ^2
\\ &=& \langle y, \langle G n, \langle n, n \langle x, \bot \rangle  \top \rangle  (P n) 1 (\times n ( G (P n) )) \rangle  y^2\rangle ^2
\\ &=& \langle y, \langle G n, P n \langle x, \bot \rangle  \top  1 (\times n ( G (P n) )) \rangle  y^2\rangle ^2
\\ &=& \langle y, \langle G n, P n \langle x, \langle a b, b\rangle \rangle  \langle a  b, a\rangle  1 (\times n ( G (P n) )) \rangle  y^2\rangle ^2
%
\\ &=& \left \langle y, \left \langle G n, \begin{array} {l}
\langle nfx, n\langle g h, h(gf)\rangle  \langle u,x\rangle \langle u,u\rangle \rangle  n \langle x, \langle a b, b\rangle \rangle  \langle a  b, a\rangle  1 \\
(\times n ( G (\langle nfx, n\langle g h, h(gf)\rangle  \langle u,x\rangle \langle u,u\rangle \rangle  n) ))
\end{array} \right\rangle  y^2 \right\rangle ^2
%
\\ &=& \left \langle y, \left \langle G n,  \begin{array} {l}
n\langle g h, h(g\langle x, \langle a b, b\rangle \rangle )\rangle  \langle u,\langle a  b, a\rangle \rangle \langle u,u\rangle  1 \\
(\times n ( G (\langle fx, n\langle g h, h(gf)\rangle  \langle u,x\rangle \langle u,u\rangle \rangle ) ))
\end{array}\right\rangle  y^2\right\rangle ^2
%
\\ &=& \left \langle y, \left \langle G n, \begin{array} {l}
n\langle g h, h(g\langle x, \langle a b, b\rangle \rangle )\rangle  \langle u,\langle a  b, a\rangle \rangle \langle u,u\rangle  1 \\
(\langle m n f, m(nf)\rangle  n ( G (\langle f x, n\langle g h, h(gf)\rangle  \langle u,x\rangle \langle u,u\rangle \rangle ) ))
\end{array}\right \rangle  y^2\right\rangle ^2
%
\\ &=& \left \langle y, \left \langle G n, \begin{array} {l}
n\langle g h, h(g\langle x, \langle a b, b\rangle \rangle )\rangle  \langle u,\langle a  b, a\rangle \rangle \langle u,u\rangle  1 \\
 (\langle f, n( G (\langle fx, n\langle g h, h(gf)\rangle  \langle u,x\rangle \langle u,u\rangle \rangle )       f)\rangle  )
\end{array}\right \rangle  y^2 \right\rangle ^2
%
\\ &=& \left \langle y, \left \langle G n, \begin{array} {l}
n\langle g h, h(g\langle x, \langle a b, b\rangle \rangle )\rangle  \langle u,\langle a  b, a\rangle \rangle \langle u,u\rangle  \langle f x, f x\rangle \\
 (\langle f, n( G (\langle f x, n\langle g h, h(gf)\rangle  \langle u,x\rangle \langle u,u\rangle \rangle )  f)\rangle  )
\end{array}\right\rangle  y^2 \right \rangle ^2
%
\\ &=&
\left \langle y, \left \langle G n, \begin{array} {l}
n\langle g h, h(g\langle x, \langle a b, b\rangle \rangle )\rangle  \langle u,\langle a  b, a\rangle \rangle \langle u,u\rangle  \langle f x, f x\rangle \\
 (\langle f, n( G (\langle f x, n\langle g h, h(gf)\rangle  \langle u,x\rangle \langle u,u\rangle \rangle )  f)\rangle  )
\end{array}\right\rangle  (yy) \right \rangle  \\
%
& &\left \langle y, \left \langle G n, \begin{array} {l}
n\langle g h, h(g\langle x, \langle a b, b\rangle \rangle )\rangle  \langle u,\langle a  b, a\rangle \rangle \langle u,u\rangle  \langle f x, f x\rangle \\
 (\langle f, n( G (\langle f x, n\langle g h, h(gf)\rangle  \langle u,x\rangle \langle u,u\rangle \rangle )  f)\rangle  )
\end{array}\right\rangle  (yy) \right \rangle
%
\end{array}$$
And that is the complete unabstracted lambda expression representing a factorial with church encoding.
Comment: Is $\langle a,M\rangle$ your notation for $\lambda a.M$?
Comment: @HenningMakholm IIRC the notation is from Dijkstra, although I read about it from Knuth. Otherwise yes.

Lambda Calculus factorial


extra drone 0.5 github check on all my PRs?

Question: I keep getting an extra check on my PRs titled
continuous-integration/drone

that never has a detail popup. I don't have any webhooks beyond the drone 0.5 installation.
How can I turn this off, or is it a known issue?
Answer: I am guessing this is because you are using protected branches, with continuous-integration/drone as a required check. GitHub will automatically add required checks (with no detail) when the PR is first created.
In 0.5 the check name changed to continuous-integration/drone/pr
I believe the solution is therefore to remove continuous-integration/drone from the required check, and then add the newer continuous-integration/drone/pr value.
Comment: of course! Yes the /drone one is added automatically, so I just removed it and changed to /drone/pr everywhere


Ajax form in block, how do I reliably load the include file?

Question: It is an ajax form, so as soon as the ajax runs there is a 500 error with 'Fatal error: Call to undefined function, yhivebooking_form_validate() in ...
It is an ajax callback, but goes through /system/ajax which isn't a menu item and therefore, I can't load the include.
<code>/**
* Implements hook_block_view()
*
* @param string $delta
* @return array
*/
function yhivebook_block_view($delta = '') {
  $block = array();

switch ($delta) {
 case 'yogahive_book' :
  module_load_include('inc', 'yhivebook', 'yhivebook_booking_form');
  $block['subject'] = t('Book a class with a YogaHive pass');
  $block['content'] = drupal_get_form('yhivebook_booking_form');
}

return $block;
}
</code>
Answer: You need to use form_load_include() in your form definition. So at the top of the function yhivebook_booking_form(), add the following:
<code>form_load_include($form_state, 'inc', 'yhivebook', 'yhivebook_booking_form');
</code>
Comment: OK - it works. I followed your drupal comments through previously and tried form_load_include() in the block hook. Made no sense to me - and having it in the form hook seems like voodoo. I guess it is adding the file to some sort of form cache. Thanks.


Fundamental theorem of algebra in modular arithmetic

Question: suppose you have a polynomial $P(x) = a_0+a_1x+...+a_kx^k$.
How can you prove that at most $k$ numbers satisfy $P(x) \equiv 1 \mod n$ ?
To me this looks like the fundamental theorem of algebra, however, in modular arithmetic. Yet, I don't see why the theorem would apply here as well.
Thanks in advance.
Comment: You mean $P(x) = 0 \pmod{n}$, I guess.
Comment: Does it really make a difference? Why would the constant $a_0$ matter?
Answer: This is only true if $n$ is a prime.
If you take $n = 15$, for instance, the polynomial $x^{2} - 1$ has the four roots $1, 4, 11, 14$ modulo $n$.
When $n = p$ is a prime, you exploit the fact that $\mathbb{Z} / p \mathbb{Z}$ is a field, and recycle the usual proof.
I wouldn't call it the fundamental theorem of algebra, though, as that refers to the fact that a non-constant polynomial splits in linear factors in $\mathbb{C}[x]$.


how to import fromPromise from RxJS 6.2.1 in node 10.4.1

Question: I'm trying to use fromPromise in a node.js script following the first example from https://www.learnrxjs.io/operators/creation/frompromise.html (code also here: https://jsfiddle.net/btroncone/upy6nr6n/)
Since I'm using node 10.4.1, I can't use import but need to use require instead.
I was able to import mergeMap with this line:
var mergeMap = require('rxjs/operators').mergeMap;

instead of
import { mergeMap } from 'rxjs/operators';

The problem is to import fromPromise. The example shows this line:
import { fromPromise } from 'rxjs/observable/fromPromise';
I tried all the following options without success:
var fromPromise = require('rxjs/observable/fromPromise');
var fromPromise = require('rxjs/observable/fromPromise').fromPromise;
var fromPromise = require('rxjs/observable');
var fromPromise = require('rxjs/observable').fromPromise;
var fromPromise = require('rxjs').fromPromise;

Comment: `fromPromise` is now just `from` and is imported from `'rxjs'`.
Comment: Did you try var fromPromise = require('rxjs').fromPromise;
Comment: Thanks @cartant. I solved the problem by using this line: `var from = require('rxjs').from;`
Answer: You just use require('rxjs').from;. In rxjs@6 formpromise is no more exported.
Comment: That does not work, because node.js does not support `import` natively, or at least I could not make it work, but that's beyond this question. Thanks.
Comment: Above I have written typescript syntax you can convert into nodejs required syntax like you have mentioned in questions comment.I have updated my answer.
Answer: As specified by @cartant, the answer is:
var from = require('rxjs').from;

fromPromise is now just from.


Spring Hibernate transaction - read only vs read write

Question: I am facing a weird problem with Spring Boot(2.3.7) + PostgreSQL v12 (row level security) + Hibernate (5.x).
Here are the steps that I am executing

A procedure accepts an input variable and creates temporary table. The variable is then inserted in temporary table.
Spring Advice which executes for all @Service annotation and invokes a procedure with a variable (call it custom_id).
@Transactional attribute is specified on all @Service classes.
PostgreSQL row level security has been enabled on the tables being queried and updated.
Row level security applies filter based on the variable stored (custom_id value) in temporary table.
All update, select, insert operations are executed using custom implementation of JpaRepository (interface based)

This works fine as long as there are only select operation performed on the database. But starts to fail with code having a combination of select and updates. The code simply fails with a message as it is not able to locate the temporary table.
I enabled trace for Spring transaction and found that there are few statements like

No need to create transaction for XXX

While code that performs update operation has statements like

Getting transaction for XXX

After searching for a while, I realised that SimpleJpaRepository has @Transaction with readonly flag set to true. This results in SELECT operation getting executing in transaction less mode.
Procedure
create or replace procedure proc_context(dummy_id uuid) AS $context_var$
declare

begin

create temp table if not exists context_metadata
(
dummy_id uuid
)
on commit drop;

insert into context_metadata values(dummy_id);

end;
$context_var$ LANGUAGE plpgsql;

ERROR
Following error is logged in console
ERROR: relation "context_metadata" does not exist

What I tried

Tried implementing custom transaction manager and explicitly invoking the procedure to set the temporary variable value (Didn't work). Refer below

    protected void prepareSynchronization(DefaultTransactionStatus status, TransactionDefinition definition) {

    super.prepareSynchronization(status, definition);

    if (status.isNewTransaction() || status.isReadOnly() || status.isNewSynchronization()) {

    UUID someID = ....;

    Query query = entityManager.createNativeQuery("CALL proc_context(?);");

    query.setParameter(1, someID);

    query.executeUpdate();

    }

    }

Tried setting @Transactional notation with readonly set to false on all repositories.

What I am looking for?
Unfortunately due to this behaviour, the row-level security implementation is not working in my code. Is there any way to disable read-only transactions using a global property OR provide me with any hint to overcome this problem?
Comment: It won't run without a transaction it will run in a readonly transaction. The readonly part is only a hint for hibernate to omit the dirty checking. Also if there already is a transaction (which should be the case as you state yourself you annotated your services with `@Transactional` then it shouldn't matter as there is already an ongoing transaction).
Comment: That is where I am getting lost. I could figure out from logs that there is only one transaction and the code to create/populate temporary table is being executed. The update query simply fails complaining the temporary table doesn't exist.
Answer: Finally, I could figure out after 2 days of battle. The problem was multi-faceted.

I noticed hibernate.transaction.flush_before_completion property set to true in application.properties file. I had to remove that property.
Developer had written a very messy code to update the entity attributes (Was performing select, then creating new instance, populating attributes and then calling save method). All this ruckus to update one single attribute.

Tested the code and everything worked fine.


Mysql - reorder / reset position key

Question: I have a MySQL table with position key (65,000 records). I deleted, updated some rows in the middle of the table. Now I have, for example, something like this in the position 1 - 6 - 2 - 9

id
category
position

1
1
1

2
1
6

3
2
2

4
2
9

I want to reset / reorder the position key

id
category
position

1
1
1

2
1
2

3
2
1

4
2
2

How can I reset position where category = 1
and where category = 2?
Comment: @yusuf hayırsever yes, but I have `#1064 - Something is wrong in your syntax` I put it on phpmysql console. I changed source_table to photographs.
Comment: can you try again?
Comment: @yusuf hayırsever same `#1064 - Something is wrong in your syntax` maybe I'm doing something wrong?
Answer: Try this:
UPDATE source_table
JOIN ( SELECT id, ROW_NUMBER() OVER (PARTITION BY category ORDER BY position) position
       FROM source_table ) subquery USING (id)
SET source_table.position = subquery.position

mysql> SHOW VARIABLES LIKE "%version%"; 5.7.24 – sagittarius

UPDATE source_table
JOIN ( SELECT t1.id, COUNT(t2.id) position
       FROM source_table t1
       JOIN source_table t2 ON t1.category = t2.category
                           AND t1.position >= t2.position
       GROUP BY t1.id ) subquery USING (id)
SET source_table.position = subquery.position;

fiddle

if position is duplicated everything crashes – sagittarius

UPDATE source_table
JOIN ( SELECT t1.id, COUNT(t2.id) position
       FROM source_table t1
       JOIN source_table t2 ON t1.category = t2.category
                           AND (    t1.position > t2.position
                                 OR (     t1.position = t2.position
                                      AND t1.id >= t2.id ))
       GROUP BY t1.id ) subquery USING (id)
SET source_table.position = subquery.position;

fiddle
Comment: @Thank you for your answer, how to use it? In the mysql console I have `#1064 - Something is wrong in your syntax`
Comment: @sagittarius Specify **PRECISE** MySQL version.
Comment: @Akina `mysql> SHOW VARIABLES LIKE "%version%";` `5.7.24`
Comment: @sagittarius You should have started your question with this information! wait... done.
Comment: @Akina Now it is no error, but everywhere position is `1` `category = 1 position 1,1,1,1 category = 2 position 1,1,1,1` and it should be `category = 1 position 1,2,3,4 category = 2 position 1,2,3,4`
Comment: @sagittarius Misprint. Fixed. PS. And I do not see the info about server version in your question yet...
Comment: @Akina it works, but if I have on position twice the same number `2,2` then it will replace everything with `2`.
Comment: @sagittarius Add check by `id` to the joining condition if positions are equal.
Comment: @Akina now as i have everywhere `1` in `category =1  I have everywhere 34, in category =2 everywhere 14`
Comment: @sagittarius Create a fiddle with your data and query similar to the fiddle in the answer and provide a link.
Comment: @Akina `https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=10f6de9932402a47264cfe595088296b`
Comment: @Akina I don't know if I presented it well to you, if position is duplicated everything crashes
Answer: UPDATE source_table t1
INNER JOIN
(
   SELECT id,category,position, ROW_NUMBER() OVER (PARTITION BY category
       ORDER BY position) position2
       FROM source_table
) t2
    ON t2.id = t1.id
SET
    t1.position = t2.position2

I think this code is easy to understand and apply.
Comment: While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. [From Review](/review/low-quality-posts/27780780)

Mysql - reorder / reset position key


If we primarily use LSTMs over RNNs to solve the vanishing gradient problem, why can't we just use ReLUs/leaky ReLUs with RNNs instead?

Question: RNNs as in: Recurrent Neural Networks
LSTMs as in: Long-Short Term Memory Units
ReLU as in: Rectified Linear Units
Leaky ReLU as in: Modified ReLUs that don't "die" when negative values are inputted.
In practice, machine learning practitioners rarely use vanilla RNNs, citing the vanishing gradient problem (where gradients almost die off after not too many time steps because they are small numbers multiplying by each other a lot, making it basically impossible to train) as the reason. LSTMs are known to solve this problem through their more complex architecture that enable for additive relationships between gradients instead of multiplicative; the latter is the culprit of the vanishing gradient problem.
However, with ANNs, ReLUs are known to solve this problem well, given that their gradient is either "off" (0) or "on" (1). Leaky ReLUs have a small gradient instead of being "off". They solve the problem because the gradients do not saturate.
So, why do we need to have such a complex model like LSTMs when RNNs + ReLU should be able to solve the problem? Is it just that LSTMs perform much better, and we don't have great reasoning as to why?
Comment: I am not the downvoter but this question is currently automatically flagged as low quality for its length and content. Could you spell out some abbreviations, and use the question to body to give a little bit of background to the problem and what your reasoning is, rather than just restating the question title? (You don't need to write a mini-essay but one advantage of putting a couple of sentences down is that it would be easier for future readers to search and find your answer - with the question only phrased once, they need to get very close to your wording to find it.)
Comment: Whoever downvoted—care to explain? Would be much more beneficial to everybody.
Comment: @Silverfish Done
Answer: I think there's some confusion here. The reason you have vanishing gradients in neural networks (with say, softmax) is wholly different from RNNs. With neural networks, you get vanishing gradients because most initial conditions make your outputs end up on either the far left or far right of your softmax layer, giving it a vanishingly small gradient. In general it's difficult to select proper initial conditions, so people opted to use leaky ReLu's because they don't have the above problems.
Whereas with RNN's, the problem is that you are repeatedly applying your RNN to itself, which tends to cause either exponential blowup or shrinkage. See this paper for example:
On the difficulty of training recurrent neural networks: https://arxiv.org/abs/1211.5063
The suggestions of the above paper are: if the gradient is too large, then clip it to a smaller value. If the gradient is too small, regularize it via a soft constraint to not vanish.
There's a lot of research on LSTMs, and plenty of theories on why LSTMs tend to outperform RNNs. Here's a nice explanation: http://r2rt.com/written-memories-understanding-deriving-and-extending-the-lstm.html#fnref2
Comment: Note that the version of the first paper that you linked to is not the most up to date one. [This](http://proceedings.mlr.press/v28/pascanu13.pdf) is the most up to date (and this is actually the only version that appears when you [search for the paper's name in google scholar](https://scholar.google.co.il/scholar?hl=en&as_sdt=0%2C5&q=On+the+difficulty+of+training+recurrent+neural+networks)).
Comment: Also, IIUC Hinton's explains in https://www.coursera.org/lecture/neural-networks/why-it-is-difficult-to-train-an-rnn-kTsBP (around minute 3) that the cause for vanishing gradients is the same for typical feedforward networks and RNN, while the problem is bigger in RNN, as they tend to have much more layers (when they are unfolded) than typical feedforward networks.


ng-if to hide all elements in page except 1

Question: I have several divs on my page which use an ng-if to show. My issue is that certain elements are duplicates.
What I would like to do is use another expression in the ng-if for this example i added below (hideMultiplePost) to hide these duplicate elements and my idea is to identify them by adding a class which uses the post id since the duplicate elements share the same id.

 0 && hideMultiplePost(post.id)">

 0 && hideMultiplePost(post.id)">

Can someone put me in the right direction in using an expression (hideMultiplePost) where I check for duplicate classes and exclude them from the frontend but leave one them as I don't want to exclude them all.
Comment: Do you need to display the duplicates? Or can you exclude them within the controller directly in the array/object?
Comment: Exclude them but not all. Amended the last paragraph to be clear. Also I dont want to exclude them from the array just from the frontend thats why I decided the best option would be to target classes
Comment: instead of excluding them from the array maybe you can add a flag on each object indicating if it is a duplicate or not. With this way you can have an `ng-if="post.duplicated"` that takes care of hiding the duplicated items
Comment: Thanks Akis but I can't amend the api. The only thing that I can recognise from a post being duplicate is its id
Answer: You could use the existing 'unique' filter supplied by angular UI.
The unique filter allows you to supply a field in your model that should be unique. I assume that all of your posts have a id and that this id is unique. You can filter out multiple posts based on this field.
After the applied filter, you can still use your ng-if statement to check if the post contains any categories.
Check the snippet for more info on how to use it.

angular
  .module('app', ['ui.filters']);

angular
  .module('app')
  .controller('PostListController', PostListController);

function PostListController() {
  var vm = this;
  vm.posts = getPosts();
}

function getPosts() {
  return [{
    "id": 1,
    "title": "Post Title",
    "content": "Post content here"
  }, {
    "id": 2,
    "title": "Post Title",
    "content": "Post content here"
  }, {
    "id": 3,
    "title": "Post Title",
    "content": "Post content here"
  }, {
    "id": 4,
    "title": "Post Title",
    "content": "Post content here"
  }, {
    "id": 5,
    "title": "Post Title",
    "content": "Post content here"
  }, {
    "id": 3,
    "title": "Post Title",
    "content": "Post content here"
  }, {
    "id": 4,
    "title": "Post Title",
    "content": "Post content here"
  }];
}

        #{{ post.id }} {{ post.title }}

{{ post.content }}

Comment: ...so include an entirely extra library for a simple filter?
Comment: Thanks and that would work but I am not being clear apologies. I am getting duplicate ids because I have multiple data and I am combining them together on a single page.

So I have multiple divs each with ng-repeat which call w different apis. since the ids on each api will conflict I want to show only 1 thats why the only way to do the exclusion is by excluding classes unless this info gives you guys a better idea.
Comment: What format is the data, how do you combine them, and how are you displaying it on the page?
Comment: @fraccus: You're right, to include angularUI if it was not yet included it will add too much overhead. But for what I've seen, in many projects it is already included.
Comment: Change the code in the initial post. hope this helps.
Comment: @Jason: Is everything managed by the same controller, or multiple controllers?
Comment: @MenzoWijmenga same controller.
Comment: @Jason Okay, I will update this answer with a additional snippet. One moment.
Comment: @Jason almost finished updating this one. But I see your answer is sufficient. Thanks :)
Comment: @MenzoWijmenga Thanks. Any input you want to give is welcome and will make sure I give credit as I love to learn new things.
Answer: If you cannot control the data in, then you can remove dupes using a filter. I have assumed it's an ng-repeat, but you can edit for your own use. More detail in fiddle.

      {{item.id}}: {{item.name}}

Edit:
Concat the two sources (postList and postListV2) in your controller, and then use the filter to dedupe:
function MyCtrl($scope) {
    $scope.postList = postList;
    $scope.data = $scope.postList.concat(postListV2)
}

More info in the fiddle:
http://jsfiddle.net/Lvc0u55v/7736/


How do I store a string in ArrayField? (Django and PostgreSQL)

Question: I am unable to store a string in ArrayField. There are no exceptions thrown when I try to save something in it, but the array remains empty.
Here is some code from models.py :
# models.py
from django.db import models
import uuid
from django.contrib.auth.models import User
from django.contrib.postgres.fields import JSONField, ArrayField

# Create your models here.
class UserDetail(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    key = models.CharField(max_length=50, default=False, primary_key=True)
    api_secret = models.CharField(max_length=50)
    user_categories = ArrayField(models.CharField(max_length = 1000), default = list)

    def __str__(self):
        return self.key

class PreParentProduct(models.Model):
    product_user = models.ForeignKey(UserDetail, default=False, on_delete=models.CASCADE)
    product_url = models.URLField(max_length = 1000)
    pre_product_title = models.CharField(max_length=600)
    pre_product_description = models.CharField(max_length=2000)
    pre_product_variants_data = JSONField(blank=True, null=True)
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

    def __str__(self):
        return self.pre_product_title

I try to save it this way:
        catlist = ast.literal_eval(res.text)
        for jsonitem in catlist:
            key = jsonitem.get('name')
            id = jsonitem.get("id")
            dictionary = {}
            dictionary['name'] = key
            dictionary['id'] = id
            tba = json.dumps(dictionary)
            print("It works till here.")
            print(type(tba))
            usersearch[0].user_categories.append(tba)
            print(usersearch[0].user_categories)

        usersearch[0].save()
        print(usersearch[0].user_categories)

The output I get is:
It works till here.
<class 'str'>
[]
It works till here.
<class 'str'>
[]
[]

Is this the correct way to store a string inside ArrayField?
I cannot store JSONField inside an ArrayField, so I had to convert it to a string.
How do I fix this?
Comment: Changes would be reflected only after `save()` right?
Comment: `usersearch[0].save()
print(usersearch[0].user_categories)`

gives

`It works till here.

[]
It works till here.

[]
[]
`
Last `[]` shows that it is still empty. I'll update my question.
Comment: what is `usersearch`? What I wonder is whether you get back the same (python) object every time for `usersearch[0]` or does it give a new python instance loaded from the database?
Comment: I use the `key` to find the user. `usersearch` gives list of objects of class ``
Answer: Solution to the append problem.
You haven't demonstrated how your usersearch[0] I suspect it's something like this:
usersearch = UserDetail.objects.all()

If that is so you are making changes to a resultset, those things are immutable. Try this you will see that the id is unchanged too:
usersearch[0].id = 1000
print usersearch.id

But this works
usersearch = list(UserDetail.objects.all())

and so does
u = usersearch[0]

Solution to the real problem
user_categories = ArrayField(models.CharField(max_length = 1000), default = list)

This is wrong. ArrayFields shouldn't be used in this manner. You will soon find that you need to search through them and

Arrays are not sets; searching for specific array elements can be a
  sign of database misdesign. Consider using a separate table with a row
  for each item that would be an array element. This will be easier to
  search, and is likely to scale better for a large number of elements

ref: https://www.postgresql.org/docs/9.5/static/arrays.html
You need to normalize your data. You need to have a category model and your UserDetail should be related to it through a foreign key.
Comment: glad to have helped


test of proportions, but only want to test the proportion between 2 samples

Question: I have a questionnaire with X possible answers (only 1 answer is allowed) an a sample size N.
I want to perform a test of whether answer 1 is more likely than answer 2 for example, regardless of the proportion of the other 3 answers.
I can model that with a multinomial distribution but wondering if there is an easier way to test this.
Answer: Look only at the $n$ questionnaires with answer 1 or 2. (Other questionnaires have no relevant information.)
A Success occurs if that answer is 1. Suppose there are $s$ successes. Then test whether P(Success) is greater than $p=1/2,$
Example: If $n = 30, s=21,$ then reject $H_0: p=1/2$ vs. $H_a: p>1/2$ at the 5% level because the P-value is $0.021 < 0.05 = 5\%.$
sum(dbinom(21:30, 30, .5))
[1] 0.02138697

An approximate normal test (say, for cases in which $n$ exceeds a dozen) rejects at level 5% if
$Z = \frac{s - n/2}{\sqrt{n/4}} = \frac{2s - n}{\sqrt{n}} \ge 1.645.$
In the example, that's $Z = 2.19 > 1.645,$ so reject at 5%.

Addendum: You say you are not interested in proportions of counts for the remaining categories,
but maybe you would feel more comfortable doing
a chi.squared test to see if data are consistent
with all five categories being equally likely.
If those counts are recorded in the vector ANS,
then we can do a chi-squared test with null hypothesis
$H_0: p_1=p_2=\cdots=p_5$ against the alternative
that not all five answers are equally likely.
ANS = c(21, 9, 12, 27, 31)
chisq.test(ANS)  # equal probs assumed, if no
                 # other alternative given

        Chi-squared test for given probabilities

data:  ANS
X-squared = 17.8, df = 4, p-value = 0.00135

At this point we 'know' (significance level below 1%)
there are differences among the $p_i.$ Ad hoc, tests
can investigate where the differences lie. Because
we were interested in 1 vs 2 from the start, we do
that ad hoc test first, as below. Notice that only the counts 21 (for 1s) and 9 (for 2s) are used.
chisq.test(c(21,9))

        Chi-squared test for given probabilities

data:  c(21, 9)
X-squared = 4.8, df = 1, p-value = 0.02846

This amounts to a test of $p_1 = p_2$ against the two-sided alternative. It is rejected at the 3% level. Has
anything of interest to you been tested or revealed by this
more complicated two-step procedure? (From what you say in your Question, I guess not.)
One potential difficulty is that the overall chi-squared test would sometimes falsely mask an interesting difference
between 1 and 2.
ANS2 = c(21, 9, 15, 16, 14)
chisq.test(ANS2)$p.val
[1] 0.2942

[Looking at 1a and 2s among 60 questionnaires with respective probabilities $(.75, .25)$ the power of detecting a difference between the two answers is about 98%.
By contrast, looking at all five questions among 150 questionnaires with
respective probabilities $(.3, .1, .2, .2, .2, .2)$ is about 91%.]
Comment: Yeah I understand that if i disregard the other outcomesm its jsut a binomial test, but wonder whats the proper justification of why I can throw away the other questionnaires.Intuitively makes sense
Comment: The questionnaires without 1's or 2's provide no information about the relative frequencies of 1's and 2's. // You asked if there's an 'easier way', and I gave you one. Why are your unhappy? //  Suppose M&M candies rarely put in a piece that's black or white, with a compact car as prize for finding a white one and an expensive vacation as a prize for finding a black one. If you want to know whether winning a car or a vacation is more likely, you're only interested in the few packets containing a white or black piece.


How can I make it so that users can add content to my site?

Question: I have created a custom content type for my site that takes three fields. I then created a view that displays only that content type in a grid form. I need to know how to allow users to add content based in the form of my custom content type so that they can add things that will directly be added to the custom view I made. (Essentially the view makes a grid that displays rows of 3 images in each row. The images when clicked on will then take the user to a page that gives a description of what the image is along with a few other things.) Does anyone know what I can do with this, or if there is a much easier way to do this that I am totally missing?
Thanks for the help!
Comment: Can I suggest editing your question a bit? I think you're providing way too much superfluous information.  I believe your question is: "How do I let anonymous users submit content?" is that correct?
Answer: You only have to provide access to anonymous user to add content for the content type that you have created. For that go to permission page of Drupal:

admin/people/permissions

Check the following check boxes for anonymous user.

Basic (your content type) page: Create new content
Basic(your content type) page: Edit own content
Comment: But bear in mind that if you let anonymous users post content, then assuming this is a public site you will have a massive problem with spam. You can set the content type to be unpublished by default, but then someone will have to review the submissions before publishing them.
Answer: Content access is the module you need, this module helps handling content type permission, nice and clean.

This module allows you to manage permissions for content types by role
  and author. It allows you to specifiy custom view, edit and delete
  permissions for each content type. Optionally you can enable per
  content access settings, so you can customize the access for each
  content node.
Comment: No, I don't think OP needs that here. Drupal core allows you to control create permissions for each content type.
Answer: For the content type that has the fields on it, allow the anonymous user role the ability to create new nodes. This is located at /admin/people/permissions.


Antiderivative of 3/x

Question: The equation is $$\frac{1}{5} - \frac{3}{x},$$ rewritten as $$\frac{1}{5} - 3x^{-1}.$$ So the anti-derivative should  be $$\frac{1}{5}x - 3\frac{x^0}{0} + C,$$ which doesn't exist. Can anyone help?
Comment: Remember that the rule of the anti-derivative of $x^n$ _doesn't work_ for $n = -1$?  What is the anti-derivative of $\frac{1}{x}$?
Comment: Try to go to the FAQ section and read quickly there the directions to write properly mathematics in this site with LaTeX. It may well be you're seeing something on your paper nad writing something else here, and that's why you keep on getting a wrong answer.
Answer: Hint: Antiderivative of $\frac{1}{x}= \ln x$
Comment: For some reason, I'm getting a wrong answer online: (1/5)x - 3*ln x + C, but is this correct?
Comment: @Foxic: Not quite, actually. The antiderivative of $\frac1x$ is actually $\ln|x|$, so you'll replace $\ln x$ with $\ln|x|$ in your expression. Otherwise, yes, that's correct.
Comment: So would it be 3x*ln x?
Comment: Your second term can be written as $3 \cdot \frac{1}{x}$.  What is the rule for integrating a constant times a function?
Comment: No. $\int \frac{3}{x}dx=3\int \frac{1}{x}dx=3\ln x$
Comment: cf(x) = cf'(x)? So it would be 3*ln x? Edit: nvm, ty adam
Comment: @Foxic yes, it is

Antiderivative of 3/x


Qual é o local correto para armazenar as mensagens de validação em um projeto .NET?

Question: Estou criando uma classe relativamente simples, mas incluí algumas validações em suas propriedades.
public class Sala : EntidadeBase
    {
        #region Enums

        public enum StatusSala
        {
            Disponivel,
            Reservada,
            Inativa,
            Bloqueada
        };

        #endregion

        #region Propriedades

        public string Nome { get; private set; }
        public int Capacidade { get; private set; }
        public StatusSala Status { get; private set; }

        #endregion

        #region Contrutores

        public Sala(string nome, int capacidade, StatusSala status) : base()
        {
            SetNome(nome);
            SetCapacidade(capacidade);
            SetStatus(status);
        }

        #endregion

        #region Métodos

        #region SettersPrivados

        private void SetNome(string nome)
        {
            ValidacaoDominio.Validar()
                .Quando(string.IsNullOrEmpty(nome), "O nome não pode ser vazio")
                .Quando(!string.IsNullOrEmpty(nome) && nome.Length < 3, "o nome deve ter pelo menos 3 caracteres")
                .DispararValidacao();

            Nome = nome;
        }

        private void SetCapacidade(int capacidade)
        {
            ValidacaoDominio.Validar()
                .Quando(capacidade < 1, "Capacidade da sala Inválida")
                .DispararValidacao();

            Capacidade = capacidade;
        }

        private void SetStatus(StatusSala status)
        {
            ValidacaoDominio.Validar()
            .Quando(!Enum.TryParse(typeof(StatusSala), status.ToString(), out var retorno), "Status Inválido")
                .DispararValidacao();

            Status = status;
        }

        #endregion

        #region Publicos

        public void AlterarNome(string nomeAlterado)
        {
            SetNome(nomeAlterado);
        }

        public void AlterarCapacidade(int capacidadeAlterada)
        {
            SetCapacidade(capacidadeAlterada);
        }

        public void AlterarStatus(StatusSala statusAlterado)
        {
            SetStatus(statusAlterado);
        }

        #endregion

        #endregion

Por uma questão de organização, não gostaria de deixar uma string fixa nas mensagens de validação, pois algumas podem ser repetidas (exemplo: Nome inválido. Isso pode ser referenciado para qualquer entidade que possua a propriedade Nome) e a possibilidade de fugir do padrão é grande.
Até aonde sei, posso fazer isso via resources ou criar uma classe auxiliar para concentrar essas mensagens.
Inicialmente, concentrei as mensagens em classes estáticas, separando-as por categorias (das mais gerais para as mais especificas), mas nada impede de fazer de outra forma.
Classe para mensagens "gerais":
public class GeralMsgs
    {
        public const string NomeInvalido = "O Nome é invalido";
        public const string NomeMenorTresCaracteres = "O nome deve ter pelo menos três caracteres";
    }

Classe para mensagens especifica da classe Sala:
    public class SalaMsgs
    {
        public const string CapacidadeInvalida = "A capacidade  da sala é inválida";
        public const string StatusInvalido = "O status da sala é inválido ";
    }

Dessa forma, as validações iriam referenciar as constantes
ValidacaoDominio.Validar()
                .Quando(string.IsNullOrEmpty(nome), GeralMsgs.NomeInvalido)
                .Quando(!string.IsNullOrEmpty(nome) && nome.Length < 3, GeralMsgs.NomeMenorTresCaracteres)
                .DispararValidacao();
...
ValidacaoDominio.Validar()
                .Quando(capacidade < 1, SalaMsgs.CapacidadeInvalida)
                .DispararValidacao();
...
 ValidacaoDominio.Validar()
            .Quando(!Enum.TryParse(typeof(StatusSala), status.ToString(), out var retorno), SalaMsgs.StatusInvalido)
                .DispararValidacao();

Do ponto de vista de saúde da aplicação, pensando em escalabilidade e boas práticas, qual é o local correto para concentrar essa mensagens? Deixo dessa forma ou jogo tudo para um arquivo resource do projeto ou tanto faz?
Meu objetivo é sempre tentar fazer da melhor maneira possível, mas sem criar uma arma de raio laser para matar uma formiga, mas também não quero no futuro olhar para o 147 que o Maniero sempre posta e perceber que minha aplicação ou meu mindset me levou para o "Importante é funcionar".
Comment: https://pt.wikipedia.org/wiki/Fiat_147
Comment: eu desde o inicio que sempre usei [esta livraria](https://fluentvalidation.net/) e nunca mais validei nada com tantas linhas de código como mostra :) é simples, cada class fica com a seu validador, ajuda a manutencao no futuro...
Comment: _"147 que o Maniero sempre posta"_ o que é 147?
Comment: kkk o fiat 147 que representa "funcionar é diferente de estar certo"  ->https://pt.stackoverflow.com/a/422626/69359
Comment: @balexandre, eu troquei a validação atual por esse approach, mas usando o Notifique-me, que é um pacote baseado no Flunt, do Andre Baltieri, mas continuo com o mesmo problema que é buscar onde devo incluir as mensagens de validação.
Answer: Nem sempre é fácil responder essas coisas. Eu mesmo já fiz de formas diferentes. Hoje eu gosto de fazer de uma forma que eu nem indico porque precisa uma certa cancha pra fazer certo que é o uso de geração de código. Tudo o que é dado da aplicação e pode ter uma flexibilidade e precisa de um controle centralizado eu coloco no banco de dados e gero código para dar eficiência, o que é conhecido como dicionário de dados (agora tenho preferido o termo dicionário de aplicação por ser algo mais amplo) que não é famoso então ninguém aprende usar.
Fazendo de um jeito mais tradicional e se não precisa ter essa flexibilidade de trocar as mensagens de acordo com a instalação então o uso de resource não é indicado. Aí eu faria mais ou menos como está fazendo. Mas não tenho todas informações para tomar a melhor decisão, sempre pode ter um detalhe, até pequeno, que pode fazer eu mudar de ideia.
Não gosto muito de ter uma classe de mensagens para a classe principal, em geral acho que as mensagens deveriam estar nela mesmo. Uma geral pode fazer sentido. Pode ter certos agrupamentos, aí vai complicando, começa ser difícil saber onde colocar. Por isso que eu prefiro o banco de dados, dá flexibilidade.
Pode ser interessante ter um mecanismo mais sofisticado para pegar as mensagens do que constantes, mas tem que analisar a questão mais profundamente.
Algumas pessoas gostam de abstrair a forma para poder trocar o detalhe de implementação depois, e pode ser uma boa (quando faço geração de código eu tenho isso sem perder eficiência). Se fizer isto não importa de onde vem a mensagem, se é resource, banco de dados, uma fonte própria, variáveis ou constantes e onde está a mensagem. Tem caso que abstração piora a legibilidade do código, mas se for para obter flexibilidade não tem jeito. É fazer a tal da indireção.
Qualquer indireção traz um custo, até uma simples constante, precisa provar o ganho.
Pode estar abusando da abstração para evitar o número mágico.
Todo padrão a se aplicar vira antipadrão se errar na dose.
Não é fácil lidar com isso adequadamente, então se não tiver uma vantagem muito clara pode ser melhor nem fazer algo assim, e deixar as mensagens normais como é padrão.
Eu não sei se esse cuidado todo é tão necessário. Pode ser, não sei seu contexto, não vejo muita gente fazendo (mas não é argumento, podem estar fazendo errado, mas minha percepção é que não precisa tanto assim). Talvez o problema seja tentar fazer com todas mensagens e não apenas alguns casos que façam mais sentido.
Já parou pra pensar que se as pessoas usarem errado pode não resolver nada ou piorar? Se fizerem certo esse mecanismo talvez seja canhão para matar passarinho e aí sai certo de forma mais simples.
Me concentrei na questão das mensagens, a mecânica da validação me parece fora de escopo da pergunta, mas vejo muita gente seguindo receitas que parecem ajudar mas a pessoa nunca viu ganho real e tem problemas que ela nem percebe. Eu gosto de abstrações que trazem vantagem, mas vejo abusos direto.
Manter equilíbrio
A sua preocupação de manter o equilíbrio é louvável, mas também não dá para fazer isto se procurar uma fórmula única que resolva tudo, este é talvez o maior erro que todo desenvolvedor comete hoje em dia. As pessoas não querem fazer o que é mais adequado, querem aprender uma forma e fazer sempre assim. Por isso tem tanta coisa com problema e funciona apesar de não estar certo.
Dentro deste ponto é importante notar que a busca pela perfeição já é uma forma de fazer errado. Sistemas devem resolver problemas, não é aceitável abusar das gambiarras, fazer de qualquer jeito, não ter preocupações, mas também tentar fazer academicamente correto já é um erro do ponto de vista de engenharia. Tem que levar em consideração custo, esforço, e outros problemas que isso pode acarretar, que nem sempre é fácil prever. Depende de experiência.
O erro faz parte do processo de desenvolvimento. Vai errar uma vez, verá o que aconteceu, tentará arrumar e não cometer o mesmo erro na próxima, ainda que cometa outro. Um bom engenheiro vai acumulando essas experiências e fará cada vez melhor. Um mau engenheiro pode até não cometer o mesmo erro na próxima, mas cometerá outro, provavelmente oposto, tentando evitar um erro que aprendeu. Ou seja, a pessoa é seguidora de receita de bolo, ela sempre faz algo que aprendeu sem entender quando aplicar, sem pensar em todas questões. Isto é tão comum hoje em dia que já se tornou raro encontrar quem não faz assim.
Comment: Upvote e marcar como resposta é muito pouco pra esse tipo de resposta....
Esse projeto em sí é só para estudos, mas analisando melhor a sua resposta, o cenário como um todo e pensando na flexibilidade, creio que deixar no Resources é o melhor caminho, já que eu consigo fazer os testes de unidade sem depender do banco(o que poderia ser uma solução interessante também, mas aí teria que mockar as mensagens no meus testes) e de certa forma a ferramenta que uso hoje (.NET) já está preparada para usar o Resources, então o esforço para flexibilizar é muito menor do que eu buscar inventar algo...
Answer: Eu tenho feito toda a validação de domínio através de Exceptions com tipos específicos para cada Entidade (ou Aggregate Root se estivermos falando de DDD).
Dessa forma, fica fácil inclusive de implementar traduções para outros idiomas no futuro, pois as Exceptions recebem apenas os valores, e não a mensagem explícita.
Por exemplo:
public class SalaException: Exception
{
    private SalaException (string message)
       : base(message)
    { }

    public static SalaException CapacidadeDaSalaInvalida()
    {
        return new SalaException("Capacidade da sala Inválida");
    }

    public static SalaException NomeDaSalaNaoInformado()
    {
        return new SalaException("O nome não pode ser vazio.");
    }

    public static SalaException NomeDaSalaInsuficiente(string nome)
    {
        return new SalaException($"Nome inválido ({nome}). O nome deve ter pelo menos 3 caracteres");
    }

    public static SalaException StatusDaSalaInvalido(string status)
    {
        return new SalaException($"Status Inválido: {status}");
    }
}

public class Sala : EntidadeBase
{
    public string Nome { get; private set; }
    public int Capacidade { get; private set; }
    public StatusSala Status { get; private set; }

    public Sala(string nome, int capacidade, StatusSala status) : base()
    {
        SetNome(nome);
        SetCapacidade(capacidade);
        SetStatus(status);
    }

    private void SetNome(string nome)
    {
        if (string.IsNullOrEmpty(nome))
            throw SalaException.NomeDaSalaNaoInformado();

        if (nome.Length < 3)
            throw SalaException.NomeDaSalaInsuficiente();

        Nome = nome;
    }

    private void SetCapacidade(int capacidade)
    {
        if (capacidade < 1)
            throw SalaException.CapacidadeDaSalaInvalida(1);

        Capacidade = capacidade;
    }

    private void SetStatus(StatusSala status)
    {
        if (!Enum.TryParse(typeof(StatusSala), status.ToString(), out var retorno))
            throw SalaException.StatusDaSalaInvalido(status.ToString());

        Status = status;
    }
}

Comment: A solução é até interessante, mas levando em consideração a possibilidade de tradução, o que não é o meu caso, deixar as mensagens da forma que você está deixando não está abrindo motivos para uma alteração nas suas classes?
Eu troquei as validações e agora estou usando um pacote que implementa a Notification  Pattern, dessa forma deixo o meu código bem mais limpo.


Nelder-Mead simplex (fminsearch) and crossvalidation (cvpartition) with a nested function approach - Valid?

Question: I have a binary classification problem with a somewhat balanced training set ( 665 TP 568 TN). SVM is the classifier of choice, and I am trying to optimize the hyperplane parameters $c$ and $g$ using Nelder-Mead simplex (fminsearch) and cross validation following a certain scheme (see below).
I have a feeling that this approach is biased, but I cannot really tell how to conduct it in a better way. Is the codeflow consistent in general? (as I am nesting anonymous functions) What would be a good $c$ and $g$ range that can set in the fminsearch options?
Does it make sense to create the CV partitions once in the beginning, or should I reinit them on each new fminsearch run?
<code>%create cross fold partitions
c = cvpartition(classes,'kfold',kFold);

%minimization function (z = [c,g])
%where minperf is a function doing a crossvalidation with current parameterset summing
%missclassificationrate over all folds (see at bottom)
minfn = @(z)minperf(z,meas,classes,c,opt_mode);

Loop for X optimization rounds and keep best setup

%unconstraint optimization using nelder mead simplex
%to avoid being stuck in local minimum this step is repeated X times and best
%parameters are stored
[searchmin fval] = fminsearch(minfn,randn(2,1));

%after finding C and r a final cross validation is performed for performance
%estimation of final model
finfun = @(xtr,ytr,xte,yte)confusionmat(yte,cross_svm(xtr,ytr,xte,z(1),z(2)));

cm = crossval(finfun,meas,classes,'partition',c)
cm = reshape(sum(cm),2,2)

%the final model is constructed using all data and optimized parameters..
svmStruct = svmtrain(meas,classes,'Kernel_Function','rbf','Autoscale',true,...
   'rbf_sigma',z(1),'boxconstraint',z(2));
</code>
Somehow I have a feeling there is a bias.  Using blind data, performance is worse than what would be expected from the cross validation.  Any suggestions for a good range I can set for $c$ and $r$ as parameters for fminsearch?
<code> %optmode just decides which measure is used for performance evaluation (e.g mcr)
    function out = minperf(z,meas,classes,c,opt_mode)

            fuun =

@(xtrain,ytrain,xtest,ytest)perf_clsf(cross_svm(xtrain,ytrain,xtest,exp(z(1)),exp(z(2))),ytest,opt_mode);

        out = crossval(fuun,meas,classes,'partition',c);

        out = sum(out)/length(out);

    end
</code>
UPDATE:
Thanks for the answer, i recall out was a vector and not a single value..
my perf_cls simply returns this : out = sum(yte ~= ypredte);
More remarks on this?
UPDATE2:
I found that mathworks is exactly proclaiming this method.. maybe they should add the bias remark.. http://www.mathworks.nl/help/bioinfo/ug/support-vector-machines-svm.html#bs3tbev-16
UPDATE3:
Here a final remark, Varma and Simon compared a similar CV approach with another nested CV optimization revealing the bias of the above approach and showing the benefit of using the nested version: http://www.ncbi.nlm.nih.gov/pmc/articles/PMC1397873/
Comment: I think your error is in summing 'out' and dividing by the length - if you are using crossval to calculate MCR, there is no need to sum and divide and the output of crossval will be a the mean MCR across folds, though it is not clear to me exactly what 'perf_clsf' does but I asume it is a sub-function training and testing the SVM
Answer: There is indeed a bias, because you have directly optimised the cross-validation error, so it will give an optimistic estimate of generalisation performance.  Lie all estimators, the error of the cross-validation estimate of the test error has two components, the bias (the error caused by the CV error being systematically wrong) and the variance (the error due to the peculiarities of the sample of data on which it is evaluated).  CV is (approximately) unbiased, so we don't need to worry about that too much.  However it has a finite variance, which means that you would get a slightly different result each time if you evaluated the CV estimate over a different sample of data from the same underlying distribution.  If you directly optimise the CV, you will to some extent be optimising it in ways that depend on the particular sample on which it is evaluated, but this is essentially just meaningless noise.
This is a very common issue in machine learning, but perhaps not as widely appreciated as it should, so I wrote a paper about it, which you can find here:
G. C. Cawley and N. L. C. Talbot, Over-fitting in model selection and subsequent selection bias in performance evaluation, Journal of Machine Learning Research, 2010. Research, vol. 11, pp. 2079-2107, July 2010. (www)
The problem gets worse if you have many hyper-parameters to choose, and can easily result in ending op with an "overtuned" model that generalises quite badly.


Inverse of $x(x+2)$ given $x\ge -1$

Question: Consider the function: $y=x(x+2)$ . Consider its domain to be $x \geq -1$ .
Graphically it makes sense that the inverse of this function is $-1 + \sqrt{x+1}$.
But how to compute it analytically? Thanks
Comment: Complete the square.
Answer: Verbally, since the function $f$ defined by $f(x)=x(x+2) = (x+1)^2-1$, we have that $f$

adds one to its input,
squares the result,
and subtracts $1$.

An inverse function will do the opposite things in the opposite order:

add $1$,
take a positive or negative square root,
subtract $1$.

Since we seek to invert a function whose domain includes arbitrarily large positive numbers, we reason that we will take the positive square root. So $$f^{-1}\left(y\right)=\sqrt{y+1}-1\text{.}$$
Answer: HINT: Multiply to get $y=x^2+2x$ and then use the quadratic formula to solve for $x$.

Inverse of $x(x+2)$ given $x\ge -1$


Printing to Xerox with XSA accounting from Linux

Question: My company has a lot of Ubuntu 12.04 desktops and a new Xerox ColorQube 8900S networked printer.
Using the .ppd file from Xerox I can print to the printer fine, unless XSA accounting is turned on. At this point no jobs are accepted, getting a  "the job was deleted due to invalid accounting IDs"  error printed out.
I have tried to alter the ppd to include the accounting credentials, but to no avail.
I am not well versed in postscript, or .ppd authoring, so I'm stabbing in the dark with scraps of info from Xerox's site and other forums.
I've added this
<code>*%              Generic Accounting
*JCLOpenUI *JCLAccounting/Accounting: PickOne
*OrderDependency: 10.1 JCLSetup *JCLAccounting
*DefaultJCLAccounting: XSAGroup
*JCLAccounting False/Off: ""
*JCLAccounting try1/Try 1: "@PJL COMMENT OID_ATT_ACCOUNTING_INFORMATION <22>0301|0421000<22>;<0A>"
*JCLAccounting XSAGroup/XSA Group Based Accounting: "@PJL COMMENT OID_ATT_ACCOUNTING_INFORMATION_AVP <22>XRX_USERID,0301<22>;<0A>@PJL COMMENT OID_ATT_ACCOUNTING_INFORMATION_AVP <22>XRX_GROUPACCT,1000<22>;<0A>"
*JCLCloseUI: *JCLAccounting
</code>
And installing it in CUPS gives me a new JCL tab in the "Set Printing Defaults" bit. The "Try 1" line is supposed to work - I took this direct from Xerox for this machine. The "XSAGroup" line is from advice on older printers. the 0301 is my user account (PIN) and the 1000 is the group account. The |042 is the required separator.
I've tried ipp://188.8.131.52/ipp and socket://184.108.40.206:9100 - I think both 'work' in terms of talking to the device but both result in the same error.
Can anyone with expertise in .ppd files or Xerox printers help me figure out how to get the userId/accountId successfully submitted to the printer?
Answer: Accordigg to this PDF titled: Xerox Standing Accounting: Tracking Usage by Service Customer Tip it isn't possible.

Linux PPD Operating System  The ability to prompt for a UserID for specific services does not currently exist in the Linux print driver.
The stated Linux procedure uses existing functionality.
For those customers who would like to enable accounting for print and
  copy jobs but do not want to require the user to enter an accounting
  code for their print jobs the following section describes how to
  modify the Linux PPD.
Comment: Thanks for the reminder! Yes, Xerox are awful. We were sold the machine with Linux support but it doesn't exist. However i have managed to craft a PPD file that does enable out Ubuntu machines to print. The user credentials are hard coded in, but that's fine for us. I'll post it up here.
Comment: @artfulrobot - yes you can hard code it. Did you figure out how to disallow the users of the PPD file from seeing these credentials? I believe they're stored in clear text which makes them kinda useless, other than for tracking usage.
Answer: Here's the section I added in the PPD file:
<code>*JCLBegin:"<1B>%-12345X@PJL JOB<0A>"

*% nb. I think the XeroxHavePoorLinuxSupport should be JCLXeroxHavePoorLinuxSupport
*% but if so, the options are not available to applications to select.
*OpenUI *XeroxHavePoorLinuxSupport/Grey or Colour: PickOne
*OrderDependency: 46.0 JCLSetup *XeroxHavePoorLinuxSupport
*DefaultXeroxHavePoorLinuxSupport: monochrome
*XeroxHavePoorLinuxSupport monochrome/Greyscale: "@PJL XCPT <?xml version=<22>1.0<22> encoding=<22>UTF-8<22>?>
  @PJL XCPT <!DOCTYPE xpif SYSTEM <22>xpif-v02074.dtd<22><3E>
  @PJL XCPT <xpif version=<22>1.0<22> cpss-version=<22>2.07<22> xml:lang=<22>en-US<22><3E>
  @PJL XCPT          <job-template-attributes>
  @PJL XCPT <09><09><3C>color-effects-type syntax<3D><22>keyword<22><3E>monochrome-grayscale</color-effects-type>
  @PJL XCPT <09><09><3C>job-accounting-user-id syntax=<22>name<22> xml:space=<22>preserve<22><3E>0301<3C>/job-accounting-user-id>
  @PJL XCPT          </job-template-attributes>
  @PJL XCPT </xpif>"
*XeroxHavePoorLinuxSupport color/Colour: "@PJL XCPT <?xml version=<22>1.0<22> encoding=<22>UTF-8<22>?>
  @PJL XCPT <!DOCTYPE xpif SYSTEM <22>xpif-v02074.dtd<22><3E>
  @PJL XCPT <xpif version=<22>1.0<22> cpss-version=<22>2.07<22> xml:lang=<22>en-US<22><3E>
  @PJL XCPT          <job-template-attributes>
  @PJL XCPT <09><09><3C>color-effects-type syntax<3D><22>keyword<22><3E>color</color-effects-type>
  @PJL XCPT <09><09><3C>job-accounting-user-id syntax=<22>name<22> xml:space=<22>preserve<22><3E>0301<3C>/job-accounting-user-id>
  @PJL XCPT          </job-template-attributes>
  @PJL XCPT </xpif>"
*CloseUI: *XeroxHavePoorLinuxSupport

*JCLToPSInterpreter:"@PJL ENTER LANGUAGE = POSTSCRIPT<0A>"
*JCLEnd:"<1B>%-12345X@PJL EOJ<0A><1B>%-12345X<0A>"
</code>
Nb. 0301 is our accounting code. You'd have to put yours in there.


I am not able to create base classes as per my requirement

Question: Below code is being used for money, it should be BigDecimal but, whenever I am trying to create these classes by synchronizing hbm file it is generating Integer type instead of BigDecimal.
public void setCompanyToUsRate (java.lang.Integer _companyToUsRate) {
        this._companyToUsRate = _companyToUsRate;
    }

I want BigDecimal as argument.
My hbm.xml is as follow :
<property name="SaCode" column="SA_CODE" type="string" not-null="false" length="8" unique="false" update="true" insert="true" />
<property name="Method" column="METHOD" type="string" not-null="false" length="16" unique="false" update="true" insert="true" />
<property name="ServiceTaxIva" column="SERVICE_TAX_IVA" type="integer" not-null="false" length="22" unique="false" update="true" insert="true" />

Comment: How does your hbm file look like?
Comment:

 In property ServiceTaxIva, type is integer but I need BigDecimal.
Comment: @SatishMishra: Edit your post next time, instead of writing such things in a comment!
Answer:   public void setCompanyToUsRate (java.lang.Integer _companyToUsRate) {
        BigDecimal temp = new BigDecimal(_companyToUsRate);
    this._companyToUsRate = temp;
}

Answer: Does it not create the hbm-file correctly if you just use the BigDecimal-Type in your method??
public void setCompanyToUsRate (java.math.BigDecimal _companyToUsRate) {
    this._companyToUsRate = _companyToUsRate; // member has to BigDecimal as well of course
}

If not, you can hand-edit your hbm:
<property name="ServiceTaxIva" column="SERVICE_TAX_IVA" type="big_decimal" not-null="false" length="22" unique="false" update="true" insert="true" />

Actually changing the method signature should already work as expected...
Comment: Actually whne I am creating hbm file by default it is taking integer, once I change its type from integer to big_decimal, it is generating BigDecimal. Actual problem is in creation of hbm file, may be it is problem of templet or snippet. please help.
Comment: @SatishMishra Did you change your method-signature to BigDecimal and it is still generating integer in the hbm? What is your underlying database?


Site-aware cluster migrates VMs to random nodes, not to the preffered site

Question: We have 2 physical host, 4 virtual-node (HyperV Server VMs, 2 on each host) cluster which is running some nested test VMs (using mentioned HyperV Server).
In short it is ment as a lab environment where we are trying to replicate 2 rack (where each rack is the physical host), 4 server site-aware failover cluster. We have mounted iSCSI volume to the all nodes that works as CSV, where the VMs are being stored. We made fault domains where first 2 nodes are on site 1 rack 1 and the left 2 on site 2 rack 2, configured the preffered site to be the site 1. Changed the Get-ClusterGroup for VMs to be the Site 1.

The issue is - when trying to test the failover, VMs migrate to the random sites, not the preferred site 1 nodes. Why is that? Does it have to do something with the storage? (since all nodes use the same CSV and we have to implemet Storage Replica). Am I missing something?
Answer: You need to ...
(1) ... use something like Windows Server 2016 built-in Storage Replica (DR, so active-passive replication only).
https://docs.microsoft.com/en-us/windows-server/storage/storage-replica/storage-replica-overview
Unfortunately it's Datacenter-only feature, there's some Lite version in Windows Server Standard but it's limited to 2TB or so, or you can ...
(2) ... use 3d party block replication tool (is DoubleTake discontinued?), or ...
(3) ... stick with iSCSI provider with own WAN-aware replication. StarWind Virtual SAN (Free?) is a good one.
https://www.starwindsoftware.com/starwind-virtual-san-free
Comment: Datacenter-onlu, so that's why I could not add it on any of my nodes. Thanks.
Comment: We will try to use storage device replication solution as you mentioned in your answer, if that won't work I'll get my hands on StarWind. For now thank you!
Comment: After configuring the storage correctly, will the machines failover to the preferred Sites?
Comment: Yes, if you'll do everything properly SR will failover whole LUN with CSV and VMs running on top of it.
Answer: I've managed to find a solution myself. The problem was that the other nodes had very little free resources left and because of that VMs were migrating to the less-loaded hosts. Anyhow now the preferred site aslong with the failing over to the nodes withing the site before failing over to the other is working fine. Thanks to anyone who helped.


when using fetch, axios, etc.`catch` doesn't handle the error, instead your app crashes

Question: To make sure that our request will be successful, first, we check the internet connection then send our request.
like this:
NetInfo.isConnected.fetch().then(async isConnected=> {
  if(isConnected){
    try {
       let result = await fetch(MY_REMOTE_SERVER);
       console.log("result: ", result)
    } catch (error) {
       console.error("error: ", error);
    }
  }
  else ToastAndroid.show('No internet', ToastAndroid.SHORT);
});

Everything was fine, until I faced this issue: consider a situation in which access to a server for some countries is blocked.
So, although the internet connection is ok, each time I was getting network request failed error.
I couldn't find the problem because expected the catch to print the error, but my app was just crashing.
Now that I know the reason, I don't know how to solve it.
For example, when the connection can't be made I want to alert the user to use a VPN or leave the app because they are in an embargoed country!
On the other hand, what is the point of catch!? if it doesn't catch the error!
thanks.
Comment: that's probably a bug in react-native if it crashes the APP (in my opinion)
Comment: Looking through the source, I couldn't find anything specific that stands out in the implementation, if you can step through the problem with a debugger, you can fix the issue in native for both yourself and others. See [the related source here](https://github.com/facebook/react-native/blob/8d5ac8de766b9e435cbfa9bfa6b8a2b75b0e2a19/ReactAndroid/src/main/java/com/facebook/react/modules/netinfo/NetInfoModule.java#L106).
Comment: @3limin4t0r - I think you fail to understand the nature of the problem - how can an app check for anything if it has **crashed**?
Comment: @JaromandaX I haven't tried it in production mode, but as I'm developing my app, it just keeps crashing with a big red error!
Comment: sounds like a bug in react native if a catch doesn't catch an error - have you searched for such an error in ract native? I mean, there's this https://stackoverflow.com/questions/53456551/react-native-app-crashes-on-network-error with no useful answer - and a bug report https://github.com/apollographql/apollo-client/issues/3810 - opened for 6 months now - looks like react-native simply can't handle such a simple error condition
Comment: @JaromandaX yes, you right I've searched a lot but didn't find any solution for this problem. so asked on StackOverflow maybe someone knows a workaround.
Comment: @Nit thanks for your suggestion, I'll do my best.
Comment: @BlueTurtle Did you find a solution for this problem?
Comment: @RohitKashyap yes, I left an answer for this question, check it out
Answer: Actually this is a mistake on our side, react-native will crash as it encounters console.error.
so by changing the above code to this version you will get rid of the red screen:
NetInfo.isConnected.fetch().then(async isConnected=> {
   if(isConnected){
      try {
        let result = await fetch(MY_REMOTE_SERVER);
        console.log("result: ", result)
      } catch (error) {
        // use "log" instead of "error"
        console.log("error: ", error);
        // or you may want to show a toast on error like
        oastAndroid.show('No internet', ToastAndroid.SHORT)
      }
   }else ToastAndroid.show('No internet', ToastAndroid.SHORT);
});


Cusps in fundamental domains for lattices in $SL_2(\mathbb{R})$

Question: Let $\Gamma\leq SL_2({\mathbb{R}})$ be a Fuchsian group of the first kind (so a lattice). I understand that $\Gamma \backslash SL_2(\mathbb{R})$ is compact $\iff$ $\Gamma$ contains no parabolic elements (conjugates of upper triangular matrices). Let $D$ be a fundamental domain for $\Gamma$ and let $\alpha\in SL_2(\mathbb{R})$ be some element not in $\Gamma$.
I understand that the fundamntal domain for $\Gamma' = \langle \Gamma, \alpha\rangle$ (let's call it $D'$) should be a subset of $D$. Or rather, we should be able to tile $D$ with copies of $D'$.
However what if $\alpha$ is a parabolic element? Then clearly $D'$ needs a cusp, but this seems contradictory to the fact that we can tile the compact region $D$ with copies of $D'$. What's going on here?
Answer: The trouble is that $\Gamma'$ might not be a discrete group, in which case the concept of a "fundamental domain" for $\Gamma'$ is not defined.
If, on the other hand, $\Gamma'$ is a discrete group, then cocompactness of $\Gamma$ implies cocompactness of $\Gamma'$, in which case $\Gamma'$ has a compact fundamental domain, and therefore $\Gamma'$ does not have any parabolic elements; so it wasn't possible for $\alpha$ to be parabolic.
Let me add that the concept of "cocompactness" itself can easily be generalized to indiscrete groups, like this: under the fractional linear action of $SL_2(\mathbb R)$ on $\mathbb H^2$, a subgroup of $SL_2(\mathbb R)$ acts cocompactly if and only if there exists a compact subset whose translates by the subgroup cover the whole of $\mathbb H^2$. Using this definition, if $\Gamma$ acts cocompactly then so does $\Gamma' = \langle \Gamma,\alpha\rangle$, even if $\alpha$ is parabolic.
But there's no contradiction here, because the theorem which asserts "this more general definition of cocompactness implies existence of a compact fundamental domain" is only applicable to discrete groups. As said earlier, an indiscrete group does not even have a fundamental domain.


Trouble on Factorizing

Question: I have trouble factoring $ a^2+ab+b^2 $.
It can be done easily using $\omega$, which is a complex cube root of unity with non-zero imaginary part-
$$ a^2+ab+b^2 = a^2 - \omega ab - {\omega}^2ab+{\omega}^3b^2 = a(a-\omega b) -\omega ^2b(a-\omega b) = (a-\omega ^2b)(a-\omega b) $$
But the following is also a way to factor-
$$ a^2+ab+b^2 = (a+b)^2-ab = (a+b-\sqrt {ab})(a+b+\sqrt {ab}) $$
But why is it that this factorization not so much popular while the one with complex factors is more popular? Can anybody explain me with an example?
What I think is it is probably because $\sqrt{ab}$ can't be real all the time.
Thanks!
Comment: Because $\sqrt{ab}$ is not a polynomial.  When talking about factoring something, it should normally be clear (at least from context if not stated explicitly) what kind of factors are desired.  When the object to be factored is a polynomial, one would generally expect that this is talking about factoring into polynomials.
Comment: Because it involves radicals? And complex numbers usually make calculation easier
Comment: So is $\omega$ is a constituent of a polynomial? (real coefficients)
Comment: @Book Of Flames, it is a coefficient, but it is not a real coefficient.
Comment: @UmbQbify-Key20-, So the coefficients need not be real every time, right?
Comment: @Book Of Flames, it's not necessary. But it depends on the domain of your equation.
Answer: The first factorisation is a product of two linear factors, and it can immediately be seen that the two zeroes of the axpression are for $a=\omega b$ and $a=\omega^2 b$.
The second factorisation contains a term in $\sqrt{ab}$, and there is no such simple expression to find the zeroes. In fact finding a value for $\frac{a}{b}$ to give a zero for either factor, would effectively involve going back to the original expression.
There are certainly situations where factorisations like the second one would be useful, but there are more places where the first is more helpful.

Trouble on Factorizing


How to instantiate an Object in a class which extends HttpServlet?

Question: I have a class which extends the HttpServlet class. I know that Java it's multithreaded and different threads (read: HTTP requests) can make use of the same instance. I want to instantiate an Object on the first request and use it until the end of session.
How should I proceed?
For example : I want to open a file on the first request and close it at the end of session.
Comment: When you say session, do you mean a user's http session visiting your site or do you mean a single request to the servlet?
Comment: when I say session I mean a user's http session visiting my site.
Answer: You could either just instantiate it yourself in one of the servlet's doXxx() methods depending on its presence in the session
SomeObject someObject = (SomeObject) request.getSession().getAttribute("someObject");

if (someObject == null) {
    someObject = new SomeObject();
    request.getSession().setAttribute("someObject", someObject);
}

// Use someObject.

Or you could instantiate it yourself in a HttpSessionListener
@WebListener
public class SomeObjectInitializer implements HttpSessionListener {

    @Override
    public void sessionCreated(HttpSessionEvent event) {
        event.getSession().setAttribute("someObject", new SomeObject());
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent event) {
        // NOOP.
    }

}

Either way, the SomeObject itself could implement HttpSessionBindingListener so that you can perform some logic during binding and unbinding to the session.
public class SomeObject implements HttpSessionBindingListener {

    @Override
    public void valueBound(HttpSessionBindingEvent event) {
        // Perform job during adding to the session.
    }

    @Override
    public void valueUnbound(HttpSessionBindingEvent event) {
        // Perform job during removal from the session.
    }

}

Comment: Balusc I tried to instantiate it in my doGet() method but it seems that even I save the Object with request.getSession().setAttribute("x",x) method, when I try to get it, the object is always NULL
Comment: Then either the session is not maintained properly (use the webbrowser's developer toolset to track `JSESSIONID` cookie), or you used the wrong attribute name (case sensitive!), or you actually have put `null` in it.
Comment: I checked and it seems that the session is not maintained properly. Do you know how can I keep the session alive? I tried "request.getSession().setMaxInactiveInterval(30*60)" but it doesn't worked
Comment: You need to ensure that your webbrowser has cookies enabled and that you aren't calling session.invalidate() anywhere. The setMaxInactiveInterval() should not be necessary. It defaults to 30 seconds already.
Comment: My webbrowser has cookies enabled. I checked the source code and I don't call the invalidate() method. Do you have another idea?
Comment: Okay. How exactly did you conclude that the session is not maintained properly? Did the `JSESSIONID` cookie change on every response? Or did the client not send it along with every request?
Comment: well,the JSESSIONID cookie changes by every response.
Comment: Okay, does the client send the `JSESSIONID` cookie from last response along with every next request or not? If it does, then the problem is definitely in server side (e.g. `session.invalidate()` **is** been invoked). If it does not, then the problem is definitely in client side (e.g. cookies **are** disabled).
Comment: I checked and the client send the JSESSIONID cookie from last request along with the response of that request. After that the request JSESSIONID cookie changes. I am not sure if I proceeded properly : I printout the request.getSession.getId() and I compared it with the JSESSIONID cookie value from the response (captured with Firebug)
Comment: For starters, it'd be easier to implement a `HttpSessionListener` and put a breakpoint in `sessionCreated()` and `sessionDestroyed()` methods so that you can track down in the stack to figure when and why exactly the session has been created and destroyed.
Answer:
I want to instantiate an Object on the first request and use it until the end of session.

Well, that suggests you should put it in the session, not in the servlet.
See this tutorial for some details around using sessions from Java servlets. Note that if you want to scale out to multiple servers, you'll need to think carefully about how that affects sessoins. (You could persist the session information in a database, or attempt to configure your load balancer to send all requests for the same session to the same machine, etc.)


Tomcat/https: I can see compression is enabled, but file sizes are the same as without compression

Question: I have enabled compression on Tomcat running on my machine. The https response header is showing compression is enabled, but the same amount of data is being transferred with and without compression turned on.
Without compression:
Status OK
Code    200
Encoded 218.89 KB
Decoded 218.89 KB
Transfered  219.22 KB
Compressed  No

With compression:
Status  OK
Code    200
Encoded 218.89 KB
Decoded 218.89 KB
Transfered  219.26 KB
Compressed  Yes
Compression 1.00×

I can see Content-Encoding as gzip in response header.
My connector definition in server.xml follows:
<Connector port="443" protocol="org.apache.coyote.http11.Http11NioProtocol"
           maxThreads="150" SSLEnabled="true" scheme="https" secure="true"
           clientAuth="false" sslProtocol="TLS"
           keystoreFile="xxxxx" keystorePass="xxxx"
           useSendfile="false" compression="force" />

I am using Tomcat 8.0.12. Browsers are latest versions of Safari running on MAC OS X Yosemite.
Detailed info with compression ON
Detailed info with compression OFF
Edit: As per Tim's answer, I was misled by the Safari reporting numbers. See stackoverflow.com/a/21943693/3944823.
Comment: what is your compressionMinSize ? also, compression + https = danger
Comment: It is the default "2048" bytes. I tried explicitly setting it to "2048" and also a very low value "3" with no changes in results. Thanks for the heads up on the vulnerability this opens, but I am willing to explore the benefits of compression.
Comment: Are you sure that it's Tomcat that's not working? It could be that the web browser is incorrectly reporting content size rather than transfer size. Check it with another web browser, or check the web server access logs.
Comment: @Tim: You're right! Checking in Chrome clearly shows the content is being compressed (Network->Size column). For each applicable file, it shows the "size" (what's transferred on the wire) is much smaller than the "content".
Comment: Knowing now it is a Safari thing, I see this is probably a duplicate of http://stackoverflow.com/a/21943693/3944823. The second answer nails the reason why I was on a wrong path.
Comment: I'll write it up as an answer so you can accept it, so others don't have to spend time on it.
Answer: Are you sure that it's Tomcat that's not working? It could be that the web browser is incorrectly reporting content size rather than transfer size. Check it with another web browser, or check the web server access logs.
Note - confirmed as per comments above.


Problemas com Request utilizando superagent

Question: Estou tentando realizar um request utilizando a biblioteca superagent no meu servidor nodejs, estou seguindo a documentação, porém, não está funcionando. Segue meu código nodejs:
var express = require('express');
var app = express();
var request = require('superagent');

app.set('port', (process.env.PORT || 5006));

request
   .get('http://www.google.com.br')
   .end(function(err, res){

   });

app.listen(app.get('port'), function() {
  console.log('Node app is running on port', app.get('port'));
});

Segue o link da documentação do superagent:
http://visionmedia.github.io/superagent/#request-basics
Alguém poderia me ajudar no que estou errando neste request ?
Comment: Qual é o problema? testei e funciona bem. Coloca `console.log(err, res.text);` dentro desse `.end(function(err, res){`
Comment: @Sergio, minha dúvida é, após receber o conteúdo `res.text`, ao invés de exibir no `console.log`, é possível exibir no browser a página html requisitada? Exemplo, nesse trecho, eu requisitei  a página do google através do meu servidor `nodejs` e gostaria de exibi-la no browser e não no console.
Comment: @Sergio, consegui, acrescentei esse trecho de código `app.get('/', function(req, resp) {
 request
   .get('http://www.google.com.br')
   .end(function(err, res){
  //console.log(err, res.text);
  enviar = res.text;
  console.log(enviar);
  resp.writeHead(200, { 'Content-Type': 'text/html, application/json; charset=utf-8' });
  resp.end(res.text);
   });
});`
Answer: Podes usar assim:
app.get('/', function(req, resp) {
    request("http://www.google.com.br", function(err, res){
        resp.send(res.body);
    });
});

Quando usas o resp.send(res.body); o Express adiciona automaticamente os HTTP headers e não precisas de fazer isso separado.
Comment: @Duds acho que depende se estás a usar sintaxe `request().get().end()` ou passando argumentos como eu fiz.
Comment: com o `body` o meu não funcionou, com ele aparece `{ }`. Quando uso o `text` aparece certo.


Solve "Cron run failed" without Watchdog

Question: Some years ago i wanted to turn off watchdog because it's memory and db consumption, but today i need info about why my cron isn't running because need to use Search module from now?
Trying to run cron manually (admin/reports/status/run-cron) return

Cron run failed.

calling /cron.php and running from server's command line has no return,
How can i debug this?
or
There is any other way to turn on logging?

admin/settings/logging/dblog

has no return
SELECT * FROM `watchdog`

MySQL returned an empty result set
function watchdog()

still there in bootstrap.inc
settings.php and .htaccess free from any relevant "error", "watch", "dog", "bdlog", "repor" keywords (have no php.ini)

/modules/dblog/dblog.module

still untouched. XML sitemap and Search is disabled
No logging, no cron, i am puzzled. Thanks for any help.
Answer: To enable the recording of the watchdog() messages, you just need to enable the Database logging module (short name: dblog). Once you enable it, on admin/reports/dblog you will start reading the recent log entries.
As for the possible error that could return cron, they are the following ones:

Cron has been running for more than an hour and is most likely stuck
Cron is already running and you try to re-run it

This is evident from Drupal code. The function that is executed when you go to admin/reports/status/run-cron is system_cron_run(), which returns the error you are seeing when drupal_cron_run() doesn't return TRUE. This is that function code.
  // Try to allocate enough time to run all the hook_cron implementations.
  if (function_exists('set_time_limit')) {
    @set_time_limit(240);
  }

  // Fetch the cron semaphore
  $semaphore = variable_get('cron_semaphore', FALSE);

  if ($semaphore) {
    if (time() - $semaphore > 3600) {
      // Either cron has been running for more than an hour or the semaphore
      // was not reset due to a database error.
      watchdog('cron', 'Cron has been running for more than an hour and is most likely stuck.', array(), WATCHDOG_ERROR);

      // Release cron semaphore
      variable_del('cron_semaphore');
    }
    else {
      // Cron is still running normally.
      watchdog('cron', 'Attempting to re-run cron while it is already running.', array(), WATCHDOG_WARNING);
    }
  }
  else {
    // Register shutdown callback
    register_shutdown_function('drupal_cron_cleanup');

    // Lock cron semaphore
    variable_set('cron_semaphore', time());

    // Iterate through the modules calling their cron handlers (if any):
    module_invoke_all('cron');

    // Record cron time
    variable_set('cron_last', time());
    watchdog('cron', 'Cron run completed.', array(), WATCHDOG_NOTICE);

    // Release cron semaphore
    variable_del('cron_semaphore');

    // Return TRUE so other functions can check if it did run successfully
    return TRUE;
  }

As for why Drupal thinks cron is still running, that happens when an error in the code (generally one of the hook_cron() implementations) doesn't permit drupal_cron_run() to execute the following line:
    // Release cron semaphore
    variable_del('cron_semaphore');

This means that to debug why cron doesn't work properly, you need to check any hook_cron() implementation, and see what is wrong with them. The problem could also be an implementation of hook_node_view() which is wrongly calling drupal_goto().
Comment: Thank you, enabling the *Database logging* was the first solution. But the dump result of `drupal_goto()` return only the defaults except the `$path`: *"string(20) "admin/reports/status" NULL NULL int(302)"*. And  *PHP filter* is disabled and there is no any hook in *template.php*, and in any other *template file*. And yes, you are right "Attempting to re-run cron while it is already running."
Answer: If you have Drush available on the site, you can run this from the document root for that Drupal site:
drush cron

It should output errors so you can further troubleshoot. Also, if you have drush, you can enable dblog like so:
drush en -y dblog

Answer: Enabling the Database logging was the solution to enable watchdog (thank you @kiamlaluno), then this is the message after running cron:

Message Attempting to re-run cron while it is already running.

Manually deleting cron_semaphore cause

Cron ran successfully

but with Search module enabled cause

Internal Server Error - 500

Then just changing this in search.module resolved the problem:
 function search_cron() {
  // Update word index
--  foreach (module_list() as $module) {
++  foreach (module_list(true, true, false) as $module) {