Causal Markov condition simple explanation

Question: I am trying to explain in simple words the Causal Markov condition to establish probabilistic causation.  The definition from Hausman and Woodward (1999) is the following:

Let G be a causal graph with vertex set V and P be a probability distribution
over the vertices in V generated by the causal structure represented by G. G
and P satisfy the Causal Markov Condition if and only if for every X in V, X
is independent of V\(Descendants(X) ∪ Parents(X)) given Parents(X)

My explanation is that a Causal Markov condition is satisfied if the set of  variables in a causal relationship with given probability distributions are independent of all the other variables unless they are their parents or their descendants.  This is slightly different than other definitions around so, is my explanation first, correct?, second clear?
Any advice will be appreciated.
Comment: Note also that Hausman and Woodward (1999) did not originally define the Causal Markov Condition. They clearly cited Spirtes, Glymour and Scheines' book _Causation, Prediction and Search_, and note that the CMC was "apparently first described by Kiiveri and Speed (1982)".
Comment: Y doesn't seem to be quantified anywhere in the definition.
Comment: Just got both the Kiiveri paper and the Spirtes, Scheines and Glymour book.  References corrected.  Also added the last missing clause.  Fortunately it was included in my original Ms.  Thanks for noticing.
Comment: You have omitted the last clause from Hausman and Woodward's definition: "given Parents(X)". Without that clause, both the definition and your restatement of it are incorrect.
Answer: One way to think about the Causal Markov Condition (CMC) is giving a rule for "screening off": once you know the values of $X$'s parents, all other variables in $V$ become irrelevant for predicting $X$, except for $X$'s descendants.
I find examples make the CMC easiest to understand. I did a quick google image search for "mechanism of cardiovascular disease" so I can give you a medical example. Take this graph (let's call it $G$):

Say you have a probability distribution $P$ over the variables in $G$. If the CMC holds in $P$ (relative to $G$), then you can infer that:

If I know the patient's amount of Oxidative stress and inflammation, then learning the patient's degree of Plaque progression won't give me any extra information about the patient's Platelets.
If I know the patient's amount of Atheroma, then learning the amount of Oxidative stress and inflammation won't help me predict Plaque progression.

However, the CMC allows the following possibilities:

If I know the patient's amount of Atheroma, then learning the patient's degree of Plaque rupture might still tell me something more about Plaque progression. (I'm learning from a descendant variable.)
If I don't know the patient's amount of Oxidative stress and inflammation, then learning the patient's degree of Plaque progression might well give me some extra information that helps me predict the patient's Platelets. (I'm not conditioning on the parents.)
Comment: Another even simpler example: say the graph is just $A \to C \leftarrow B$. Then the parent sets of $A$ and $B$ are the empty set, so you're always conditioning on their parents (trivially). Because neither $A$ nor $B$ is a descendant of the other, they are independent by the CMC, even though they have a common child $C$.
Comment: Thanks for the helpful example.  The First three points are clear.  However, if I don't know _Oxidative stress and inflammation_, but I know about _Plaque progression_ but I am not conditioning on the parent _Atheroma_ do I learn about _Platelets_  form the common descendant _Myocardial ischemia and infarction _ ?  And if that is the case, would I also learn about  _Endothjelium_  ?
Comment: You're asking whether information can be transmitted between _Atheroma_ and _Platelets_ through the common child, _Myocardial ischemia and infarction_. But you're giving an example where information will be transmitted through the common parent, _Oxidative stress and inflammation_, because you aren't conditioning on it. Say we condition on _Oxidative stress and inflammation_ so we block that "back-door" flow of information. Then by the CMC, _Atheroma_ and _Platelets_ will be independent. So you see how the CMC rules out transmitting information through a common child.
Comment: Now clear.  "Conditioning" blocks the flow of new information because you already know about it.  Thanks for your help.


Create infinite loop with css

Question: I have an image of waves that takes about the bottom third of the screen(not the background image) that I want to run on an infinite loop from right to the left but using css. I have tried different things but so far have been unable to make it work.
I have defined the img src on the HTML, but if needed i can do it on the css file.
Any help or suggestions on how to do it are appreciated.
CSS
body {
    border: 2px solid black;
    width: 700px;
    background-image: url("./cave.jpg");
    background-size: 700px 505px;
    background-repeat: no-repeat;
    background-position: 10px 10px;
}

.waves {
    height: 380px;
    width: 700px;
    position: relative;
    top: -300px;
    background-repeat: repeat-x;
    animation: animatedImage 20s linear infinite;
}

    @keyframes animatedImage {
    from {background-position: 0 0;}
    to {background-position: 100% 0;}
}

HTML
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <title>Escape the Cave</title>
    <link rel="stylesheet" href="./jogo.css">

Comment: An `` element's image is not the same thing as a `background-image` and you cannot animate an `` element the same way you can with CSS properties.
Answer: I moved class "waves" on div in which image is putted, because it's easier to operate.
Here's CSS
body {
border: 2px solid black;
width: 700px;
background-image: url("./cave.jpg");
background-size: 700px 505px;
background-repeat: no-repeat;
background-position: 10px 10px;
}

.waves {
height: 380px;
width: 700px;
position: relative;
top: -300px;
background-repeat: repeat-x;
animation: animatedImage 5s linear infinite;
}

@keyframes animatedImage {
    0% { left: 0;}
    50%{ left : 100%;}
    100%{ left: 0;}
}

HTML

Create infinite loop with css


Does the probability that at least one statistic will exhibit a "statistically significant" fluctuation converge to 1 as $N\rightarrow\infty$?

Question: In the study and usage of statistics the idea that particular statistics will converge "almost certainly" to some value as the sample size $N$ diverges plays a key role (e.g. the central limit theorem, the law of large numbers). Thinking about the phenomenon of $p$-hacking has lead me to wonder: what are the limits of these theorems? Particularly, can this statement be proven:

Considering the family of all statistics that converge almost certainly to some "true" value if the sample size $N\rightarrow\infty$ while the number of statistics $n$ are are fixed, if we let $n=f(N)\rightarrow\infty$ and maintain a fixed criterion for the significance of a statistic then the probability of a type I error tends to 1.

What I mean by "family of statistics that converge almost certainly" is I'm only interested in the statistics where each statistic will converge to some "true" value almost certainly, when considered in isolation. And by "significant" I mean by any metric by which distance from the null hypothesis can be measured for a particular statistic considered in isolation (e.g. $p$-value [the probability that the null hypothesis would produce the observed result or greater]) that we use to test the hypothesis.
Basically, what I'm wondering is if it has been proven that the act of letting the number of hypotheses tested increase with sample size in some fashion (e.g. $n=N/2$ or $n=\sqrt{N}$) inevitably produces false positives.
Comment: If an event has a fixed positive probability in every try, then the probability that it will eventually happen, is $1$
Comment: Might you be mixing the Law of Large Numbers (convergence to a point) with the Central Limit Theorem (convergence to normal distribution)? Sorry, but your highlighted statement seems to me  imprecise or wrong.
Comment: Do you mean that according to CLT, when you'll take infinitely many samples then with strictly positive probability you will have a statistic that is far away from $\mu$ as you like?
Comment: @V.Vancak yes to the 'statistic as far from its true value as you like', no to "according to the CLT." CLT/LLN are only included because I'm not interested in statistics that trivially diverge (e.g. $X$ Gaussian distributed, $\sum_{i=1}^N x_i$ diverges).
Comment: https://en.wikipedia.org/wiki/Multiple_comparisons_problem
Answer: Let $p>0$ the probability of type $I$ error in one test and assume that $X$ counts the number of false-positives. Assume independence for mathematical inconvenience, then for $n$ tests, $X_n \sim Bin(n,p)$, so
$$
\lim_{n\to\infty}\mathbb{P}(X_n \ge 1) = 1 - \lim_{n\to\infty}\mathbb{P}(X_n = 0)=1-\lim_{n\to\infty}(1-p)^n = 1.
$$


Sprite Kit test in xcode6 simulator

Question: my problem is when I want to use "SKPhysicsBody" to detect which spritenode I'm touching, it returns "nil" in xcode6 simulator, the code is below.
init
    SKLabelNode *startLabel = [SKLabelNode labelNodeWithFontNamed:@"Chalkduster"];
    startLabel.text = @"Start";
    startLabel.name=@"start";
    startLabel.fontSize = 30;
    startLabel.position = CGPointMake(CGRectGetMidX(self.frame),
                                   CGRectGetMidY(self.frame)-100);
    startLabel.fontColor=[SKColor blackColor];
    [self addChild:startLabel];
    startLabel.physicsBody=[SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake(80, 50)];

touch detection
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
/* Called when a touch begins */
for (UITouch *touch in touches) {
    CGPoint touchLocation = [touch locationInNode:self];
    NSLog(@"%f",touchLocation.x);
    SKPhysicsBody* body = [self.physicsWorld bodyAtPoint:touchLocation];
    NSLog(@"%@",body.node.name);
    if ([body.node.name isEqualToString:@"start"]){
        NSLog(@"go");
        [audioPlayer stop];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"nameHide"object:@"Hide"];

        SKScene *spaceshipScene=[[SpaceshipScene alloc]initWithSize:self.size];
        SKTransition *doors=[SKTransition doorsOpenVerticalWithDuration:0.5];
        [self.view presentScene:spaceshipScene transition:doors];

    }
}

}
The NSLog(@"%@",body.node.name); returns nil.
what's wrong there, thanks in advance.
Answer: Try to cycle through the nodes. In the last Xcode 6 GM this is different from Xcode 5.
I had the same problem and i resolve in this way.
In your case change your code to this:
    NSArray *nodes = [self nodesAtPoint:touchLocation];
        for (SKNode *n in nodes){

 if ([n.name isEqualToString:@"start"]){
        NSLog(@"go");
        [audioPlayer stop];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"nameHide"object:@"Hide"];

        SKScene *spaceshipScene=[[SpaceshipScene alloc]initWithSize:self.size];
        SKTransition *doors=[SKTransition doorsOpenVerticalWithDuration:0.5];
        [self.view presentScene:spaceshipScene transition:doors];

    }
}

Comment: I have test it on my device(ios7.1), both methods can work, maybe in ios8 can only cycle through the nodes?
Comment: Yes, i think in iOS 8 you must cycle to be sure to pick the correct node.

Sprite Kit test in xcode6 simulator


Running logistic regression on survey data

Question: I have a survey data which has one dependent variable ("Overall experience") and several independent variables(Quality of food, creativity of menu etc.). The response scorecard for both dependent and independent variables are as follows:
Excellent   5
Very Good   4
Good        3
Fair        2
Poor        1
As per my understanding and from what I have read, I cannot run a simple linear regression and thus I have opted for logistic regression.
Can anyone guide me in the right direction regarding logistic regression using R.
Answer: Logistic regression would be a fine start. The basic function to do binary logistic regression in R is glm. See here for how to use it.
If performance seems unacceptably poor you can fit a logistic regression using functions of the original features in order to create a more flexible decision boundary (e.g. glm(formula = y ~ x + I(x^2), ...)). Make sure to evaluate performance on either a holdout set or via cross-validation so as to prevent overfitting if you take this route.
If you are not comfortable making this a binary response then you could try ordinal logistic regression. I believe that the ordinal package in R would be helpful.
As a final note, it is not impossible to use OLS linear regression to predict ordinal variables although other things like logistic regression will probably work far better.
Comment: There's also the polr() function, in the MASS package.
Answer: In the social sciences and market research, linear regression is used for this exact problem / scale all the time. There are problems associated with linear regression, but it works quite well on such data.
As I understand logistic regression, you would have to divide your dependent variable into a dichotome 0/1 variable. Which is problematic for your scale because code 3 could be either category.
Comment: You can use ordinal logistic regression instead of dichotomizing the scale.


Serviço não está sendo chamado para fazer update no banco

Question: Fiz um serviço e quando eu chamo na URL, passando os devido parâmetros, não funciona:
Chamada na URL:
http://localhost:9078/api/atualiza/1000012120/teste

Meu serviço:
public class AtualizaController : ApiController
    {
        AutorizadorContext contexto = new AutorizadorContext();
        PedidoLiberacao liberacao = new PedidoLiberacao();

        [AcceptVerbs("Put")]
        public void putItensLiberacao(int id, [FromBody]string value)
        {
            liberacao.AtualizaLiberacao(id, value);
        }
    }

Esse é o método que o serviço chama e faz a atualização no BD:
[Route("atualiza/{id}/{value}")]
        public void AtualizaLiberacao(int id, string value)
        {
            var lista = contexto.Liberacoes
                        .Where(l => l.IdOrcamento == id).ToList();

            lista.ForEach(f =>
            {
                f.FlagLiberacao = 0;
                f.AutorizouReceberAtrazado = value;
            });

            contexto.SaveChanges();

        }

Tá dando ERRO:

page not found(404)

EDIT2
O erro acima já não tem mais, mais dá esse erro(Postman):

{
      "Message": "O recurso solicitado não suporta o método http 'GET'." }

Assim ficou meu serviço e método
[RoutePrefix("api/Atualiza")]
    public class AtualizaController : ApiController
    {
        AutorizadorContext contexto = new AutorizadorContext();
        PedidoLiberacao liberacao = new PedidoLiberacao();

        [Route("{id}/{value}")]
        [AcceptVerbs("Put")]
        public void putItensLiberacao(int id, [FromBody]string value)
        {
            liberacao.AtualizaLiberacao(id, value);
        }
    }

e o método
[Route("atualiza/{id}/{value}")]
        public void AtualizaLiberacao(int id, string value)
        {
            var lista = contexto.Liberacoes
                        .Where(l => l.IdOrcamento == id).ToList();

            lista.ForEach(f =>
            {
                f.FlagLiberacao = 0;
                f.AutorizouReceberAtrazado = value;
            });
            contexto.SaveChanges();
        }

No método eu comentei o atributo, mas o erro persiste. Coloquei um break point no serviço e nem sequer entrou.
Comment: Coloque na sua classe Controller (encima da definição) `[RoutePrefix("api/")]` fazendo um favor.
Answer: Acontece que você está usando a definição de rotas por atributos e, desta forma, você precisa definir a rota completa do serviço (isso inclui o api/).
Você pode usar o atributo RoutePrefix pra não precisar repetir a parte padrão das rotas
[RoutePrefix("api/Atualiza")]
public class AtualizaController : ApiController
{
    [Route("{id}/{value}")]
    public void AtualizaLiberacao(int id, string value) { }
}

Comment: A lambda está dando pau, o mesmo problema que eu não consegui resolver há tempos, no começo de tudo. Na lambda me dá esse erro:`The 'DataLib' property on 'Liberacao' could not be set to a 'System.Double' value. You must set this property to a non-null value of type 'System.Single'.`
Comment: @pnet Mas isso não ta ver com o problema da pergunta, né?
Comment: É, tá certo. Vou fazer outro post, caso eu não encontre uma solução. É o hábito.


AD and Exchange Migration - 2003 to 2008 R2

Question: I am working on a project where we need to migrate a 2003 AD domain to a 2008 R2, they also have exchange 2003 in place, and all users account would need to be migrated to exchange 2010.
So, what I know, is that we are going to create a trust between 2003 domain and 2008 R2 domain, after the trust has established I am planning to run the ADMT 3.2 so that I can migrate all users,groups etc, but how about exchange???? I know that I can dump the mailboxes to a pst file and then do the import... but what happened with the user mailbox after the migration??? it will still point to exchange 2003? if so, i will need to brake that in order to create the mail on exchange 2010, or not??? How can I a accomplish this task???
We only have 150 users, and the exchange DB is around 40GB, also any advise on the AD migration would be really appreciated.
Thanks!
Comment: Exactly this type of work is well documented by Microsoft, just try searching for it.
Answer: You have to do a cross-forest migration of Exchange after doing ADMT. Or use a 3rd-party tool to do the same thing. Or export to PST and import on the new server.
ADMT doesn't do Exchange, and in fact specifically strips out the MSExch attributes on groups and users, so you have to re-apply email addresses on DLs, and then mail-enable them, etc.


Need help in matrix dimension while converting from fortran to matlab

Question: I have been working on a fortran code to convert it into the matlab. I am facing some issues with dimensioning! Following is the code which is giving me error
   do 10 p = 1,m

    d(p) = 0.d0
    d(p) = x - x1(i,p) - x2(i,p) -
 &      double_sum(i,p,n,m,str,mot)

10      continue

double_sum = 0.d0

    do 10 j = 1,m
      do 20 k = 1,n
        if (k .eq. i) then
        else
          double_sum = double_sum + mot(k,j,i,p)*str(k,j)
        endif

20      continue
10    continue

to which I converted it into matlab as:
for p=1:m
                d(p)=0;
                double_sum = 0;
                for j=1:m
                    for k=1:n
                        if k==i
                        else
                          double_sum = double_sum + mot(k,j,i,p)*str(k,j);
                        end
                    end
                end
                d(p)=x - x1(i,p) - x2(i,p)-double_sum(i,p,n,m,str,mot);
            end

I am getting error of "index exceeding matrix".
The error line is for this part of my code:
d(p)=x - x1(i,p) - x2(i,p)-double_sum(i,p,n,m,str,mot);

So if I ignore double_sum(i,p,n,m,str,mot); this part, code runs perfectly.
I know the double_sum matrix is of 6D which looks suspicious to me, but I would like to have your support to successfully port this piece of fortran code.
Note:Asked the same question on matlab forum. But stackoverflow have more chances of people worked on fortran 77. Hence asking it here.
Comment: That Fortran lump is not valid.  It contains (part of) one scoping unit, but there are two statements with the label `10`.  Please look carefully at the original source.
Comment: As you define it before in your code, `double_sum` is only a scalar. What are you trying to accomplish with your call to `double_sum(i,p,n,m,str,mot)`?
Comment: After 1st initialization

double_sum = double_sum + mot(k,j,i,p)*str(k,j)

is also there. So from this I can say it's a 6D in fortran. Same I want to "translate" in matlab
Comment: Actually I am too struggling to understand the code. What I got is this code and I need to translate it with matlab. I have really low knowledge of fortran. Hence your reply matters a lot.
Comment: @roygvib agree, double_sum looks like a function doing a sum on the first two indexes. Therefore, the output is scalar (matrix element (i,p)). A similar function can be defined in matlab...
Comment: This is not fortran77. you can not do a scalar assignment to an array in f77, and obviously you can not assign to a function in any fortran version.
Answer: If the Fortran code in the Question is really everything, it may be a very rough snippet that explains how to calculate array d(:)
do 10 p = 1, m
    d( p ) = x - x1( i, p ) - x2( i, p ) - double_sum( i, p, n, m, str, mot )
10 continue

with a function double_sum() defined by
double precision function double_sum( i, p, n, m, str, mot )
implicit none
integer,          intent(in) :: i, p, n, m
double precision, intent(in) :: str( n, m ), mot( n, m, ?, ? )
integer j, k

    double_sum = 0.d0

    do 10 j = 1, m
    do 20 k = 1, n
        if (k .eq. i) then
        else
            double_sum = double_sum + mot( k, j, i, p ) * str( k, j )
        endif
20  continue
10  continue
end

though it is definitely better to find the original Fortran source to check the context...(including how i and d(:) are used outside this code). Nevertheless, if we use the above interpretation, the corresponding Matlab code may look like this:
for p = 1:m

    double_sum = 0;
    for j = 1:m
    for k = 1:n
        if k == i
        else
            double_sum = double_sum + mot( k, j, i, p ) * str( k, j );
        end
    end
    end

    d( p ) = x - x1( i, p ) - x2( i, p ) - double_sum;    % <--- no indices for double_sum
end

There is also a possibility that double_sum() is a recursive function, but because we cannot use the function name as the result variable (e.g. this page), it may be OK to exclude that possibility (so the Fortran code has two scopes, as suggested by redundant labels 10).
Answer: There is an error in your loops. The fortran code runs one loop over p=1:m, whose end is marked by the continue statement. Then, two nested loops over j and k follow.
Assuming, you know the size of all your arrays beforehand and have initialized them to the correct size (which may not be the case given your error  statement) this is more along the lines of the fortran example you posted.
 d = zeros(size(d));
 for p=1:m
     d(p)=x - x1(i,p) - x2(i,p)-double_sum(i,p,n,m,str,mot);
 end

% add a statement here  to set all entries of double sum to zero
double_sum = zeros(size(double_sum))

for j=1:m
    for k=1:n
        if k==i
        else
            double_sum = double_sum + mot(k,j,i,p)*str(k,j);
        end
    end
end

It is a little hard to give advice without knowledge of more parts of the code. are mot and str and double_sum functions? Arrays? The ambiguous choice of brackets in those two languages are hardly OPs fault, but make it necessary to provide further input.
Comment: Thank you for the reply. I tried the suggested code but now it gives "Undefined function or variable 'double_sum'." error on "double_sum = zeros(size(double_sum))" line.
Comment: Is double_sum a function or an array? If double_sum is a function, this means, you posted a recursive function, which would change quite a bit in the advice you would be receiving.


Attribute "ng-click" not allowed on element in netbeans

Question: I just love AngularJs. I write all my projects in netbeans and I would like to stick with netbeans. I searched over the net for a plugin that supports AngularJs in netbeans, with no luck.
There is a plugin, but it seems not to work, or I can not get it to work.
I am not looking for a full fledged plugin, if I could get rid of the warnings in the editor I would be satisfied.
My questions:

Does anyone know a working plugin for netbeans that supports AngularJs?
If not, a link to instructions how to make netbeans understand a custom attribute would also help/
Comment: just FYI, directives can be prefixed with `data` so `ng-click` can be expressed as `data-ng-click`
Answer: you can prefix them with data- or x- ...


Add user location marker to existing gmap

Question: I am using Drupal 7 - Location, GMap module. I have a view that renders the result in a gmap. Everything works fine here and I get all the markers. Now I need a Find My location button which shows the users current location and adds a marker to the existing map.
Google Map Api V3 always works on a newly created map and I couldn't find a function which returns an existing map in the current page.
Gmap module provides a JS function - Drupal.gmap.getMap('ur-map-id') which is supposed to return a pointer to the map whose id is given. But this did not work.
Could someone please guide me as to how I should go about this? Can I get it work with Google Maps API? I need to retain the original map with all its markers.
Answer: Here's something for reference.
if (typeof(navigator.geolocation) !== 'undefined') {
  var showUserOnMap = function(position) {
    var map = Drupal.gmap.getMap('gmap-auto1map-gmap0');
    if (typeof(map) !== 'undefined' && map !== false) {
      latitude = position.coords.latitude;
      longitude = position.coords.longitude;
      var marker = {
        latitude: latitude,
        longitude: longitude,
        markername: Drupal.t('You'),
        opts: {
          title: Drupal.t('You')
        }
      }
      marker.opts.position = new google.maps.LatLng(latitude, longitude);
      marker.opts.map = map.map;
      Drupal.gmap.factory.marker(marker.opts);
    }
  };

  // Get the current location
  navigator.geolocation.getCurrentPosition(showUserOnMap);
}

Answer: I am having this issue as well, you can put this jquery code in for it to actually centre around your current location - but no marker is added. Just add it anywhere in your theme,
jQuery(document).ready(function() {

jQuery(function($) {
$.extend({
initialize: function () {
var m = Drupal.gmap.getMap('auto1map');
if (m.map && m.markersready) {
$.setCoords();
}
else {
m.bind('markersready', function(data) {
$.setCoords();
});
}
},
setCoords: function () {
navigator.geolocation.getCurrentPosition(function (position) {
var gmap = Drupal.gmap.getMap('auto1map').map;
var lat = position.coords.latitude;
var lng = position.coords.longitude;
gmap.setCenter(new google.maps.LatLng(lat, lng));
gmap.setZoom(13);
});
}
});
$.initialize();
});

});

Now you can centre your map around your location and now I need to figure out a way to place a marker down at this location.
Comment: Thanks. However, the map is also available as m['map'], where m is as you've mentioned Drupal.gmap.getMap(map-id).


How can I avoid synthetic access compiler warning with inline-anonymous class declaration and what does it mean?

Question: I have the following code:
public class SomeClass {
   //InterfaceUpdateListener is an interface
   private InterfaceUpdateListener listener = new InterfaceUpdateListener(){
        public void onUpdate() {
           SomeClass.this.someMethod();  //complier complains on this line of code
        }
   };

   private void someMethod() {
     //do something in here on an update event occuring
   }

   //other code to register the listener with another class...
}

My compiler in Eclipse complains that

Access to enclosing method 'someMethod' from type SomeClass is emulated by a synthetic accessor method.

Can anyone explain exactly

what this means,
what the possible ramifications might mean if I leave it as is (since its only a warning), and
how I might fix it?

Thanks
Comment: Duplicate of http://stackoverflow.com/questions/921025/eclipse-warning-about-synthetic-accessor-for-private-static-nested-classes-in-jav
Comment: @JB Nizet, not exactly.  I saw that question which deals with concrete inner classes rather than anonymous ones.  I can't (AFAIK) add a constructor to my declaration to the error go away.
Answer: I would just deactivate the rule (i.e. make the compiler not generate warning for this). If the construction is legal, and if an additional method is added by the compiler to support it, then it's the way it must be done.
I doubt there is a significant loss of performance caused by this synthetic method. The JIT must inline it anyway if necessary.
Comment: Synthetic methods can cause serious hassles when debugging code. The hot code replacement doesn't support adding/removing methods, but it's not transparent to users when a synthetic method will be added/removed behind your back.
Comment: Thanks.  I'm not worried about performance but this is new territory for me so want to make sure I design the code correctly in the first place since its critical to the rest of my application.
Comment: Security implications ? see : http://stackoverflow.com/a/5559064/281545. I mean the method is not private anymore - it is package private - so why not declare it as such (related to my question in http://stackoverflow.com/questions/17772622/is-it-needed-to-declare-innards-of-private-inner-classes-private - I finally found a concrete reason for *not* declaring private members of Nested I access from Enclosing)
Answer: How about this?
There's only one class declaration that has to be keept by your JVM (PermGen), implementing class is still not available outside SomeClass (I think this is the only legal intention to write an nested class anyway) and last but not least you might also provide a second constructor with InterfaceUpdateListener as argument (if needed for mor flexibility and testability). And ther's no need to change warnings.
expect
public interface InterfaceUpdateListener {
    public void onUpdate();
}

is provided, SomeClass might be implemented like this
public class SomeClass {
   //InterfaceUpdateListener is an interface
   private final InterfaceUpdateListener listener;
   private static class SomeClassInterfaceUpdateListener implements InterfaceUpdateListener {
       private final SomeClass internal;
       public SomeClassInterfaceUpdateListener(final SomeClass aSomeClass) {
           internal = aSomeClass;
       }
       @Override
       public void onUpdate() {
           internal.someMethod();  //complier complains on this line of code
       }
   }
   public SomeClass() {
       listener =  new SomeClassInterfaceUpdateListener(this);
   }
   private void someMethod() {
     //do something in here on an update event occuring
   }
}


Como selecionar a partir do fim de um textBox

Question: Boa tarde galera!
Minha pergunta é simples e um pouco boba, mas esta me fazendo quebrar a cabeça.
Meu programa tem um textBox onde é gravado um log, a todo tempo novos dados (caracteres) são adicionados a este textBox.
O que eu realmente me interessa neste log são seus últimos 7 caracteres. Eu estava pensando em usar o controle "textBox.selection" para seleciona-los, o problema é que não existe (até onde eu sei) um "SelectionEnd". O comando SelectionStart seta a partir de onde a seleção começa e o Length quantos caracteres essa seleção compreende, o que eu preciso é setar onde a seleção deve terminar (como eu disse, algo do tipo "SelectionEnd") e usar o "SelectionLength" para setar que é deste ponto até 7 caracteres atrás que a seleção deve compreender. Como posso fazer isso da maneira mais simples possível? Esses últimos 7 caracteres serão usados como nome do arquivo log no salvamento automático do mesmo.
Segue código referente ao salvamento automático. (onde meu problema está)
{
            CaptureInfo.CaptureFrame();

            textBox1.SelectionStart = 99999;
            textBox1.SelectionLength = -7;

            Thread.Sleep(1000);

            caminhoImagemSalva = @"\\172.21.xxx.xxx\Impresa tal\Arquivo Digital\Arquivo de imagem atendimento\Guichê 04\"
                 + "Atendente 04"
                 + " "
                 + textBox1.SelectedText
                 + " "
                 + DateTime.Now.Day.ToString()
                 + "."
                 + DateTime.Now.Month.ToString()
                 + "."
                 + DateTime.Now.Year.ToString()
                 + " as "
                 + DateTime.Now.Hour.ToString()
                 + "h"
                 + DateTime.Now.Minute.ToString()
                 + "min"
                 + ".jpg";
            picWebCam.Image.Save(caminhoImagemSalva, ImageFormat.Jpeg);

        }

Agradeço desde já!
Comment: Se sabe o tamanho do texto no TextBox e quantos quer pegar é fácil saber qual é o start.
Comment: No caso em questão o textbox não tem um tamanho pré-definido.
Comment: Não entendi... o que você pretende com isso? Capturar esse conteúdo ou disponibilizar no clip board?
Answer: A forma de selecionar os últimos 7 caracteres é simples, e você pode recuperar essa informação de forma simples através do atributo SelectedText, como no exemplo abaixo.
var numeroDeCaracteres = 7;
var startIndex = textBox1.Text.Length - numeroDeCaracteres;

textBox1.SelectionStart = startIndex;
textBox1.SelectionLength = numeroDeCaracteres;

Mas esse tipo de operação é mais comum para manipulação de interface ou se você quiser por exemplo lançar esse conteúdo no clipbard, recortar e ou colar em algum outro controle... se o que lhe interessa o conteúdo, faz mais sentido apenas um Substring do Text...
var numeroDeCaracteres = 7;
var startIndex = textBox1.Text.Length - numeroDeCaracteres;
var conteudo = textBox1.Text.Substring(startIndex);

Comment: Perfeito! A ideia é usar parte do conteúdo do textBox (no caso os ultimos 7 caracteres) como variável de nome para um arquivo de imagem. Acho que o primeiro método funciona melhor no meu código pois uso "textBox1.SelecectedText" como output. Irei fazer o teste das duas e depois digo qual funcionou melhor. Muito obrigado Leandro!
Comment: Testado e aprovado! Ambos os métodos funcionaram perfeitamente, mas preferi usar o primeiro pois não precisou de nenhuma outra modificação no meu código. Mais uma vez meus sinceros agradecimentos ao Leandro! Valeuu!
Comment: Recomendo a segunda opção, você não vai precisar mudar tanta coisa e o que mudar vai ser pra melhor. Ela faz muito mais sentido...


The package org.w3c.dom is accessible from more than one module: , java.xml ~ Find and exclude dependency

Question: I know there's already some topics on issues like these, but the case I've come across is somehow different.
It starts with this error message:
import org.w3c.dom.Element;
The package org.w3c.dom is accessible from more than one module: <unnamed>, java.xml

I know that the following dependency "causes" this, because if I remove it, this error disapperas (and many others pop up):
compile "org.eclipse.lyo.clients:oslc-java-client:2.4.0"

I have already tried this:
    compile ("org.eclipse.lyo.clients:oslc-java-client:2.4.0") {
        exclude group: "org.w3c.dom", module: "org.w3c.dom"
    }

However, that did not change anything about the issue.
I have tried listing the transitive dependencies using gradle dependencies, which returned me this dependency tree for the OSLC Java Client:
+--- org.eclipse.lyo.clients:oslc-java-client:2.4.0
|    +--- org.slf4j:slf4j-api:1.7.25
|    +--- org.apache.jena:apache-jena-libs:3.6.0
|    |    +--- org.apache.jena:jena-tdb:3.6.0
|    |    |    +--- org.apache.jena:jena-arq:3.6.0
|    |    |    |    +--- org.apache.jena:jena-core:3.6.0
|    |    |    |    |    +--- org.slf4j:slf4j-api:1.7.25
|    |    |    |    |    +--- org.apache.jena:jena-iri:3.6.0
|    |    |    |    |    |    \--- org.slf4j:slf4j-api:1.7.25
|    |    |    |    |    +--- xerces:xercesImpl:2.11.0
|    |    |    |    |    |    \--- xml-apis:xml-apis:1.4.01
|    |    |    |    |    +--- commons-cli:commons-cli:1.4
|    |    |    |    |    \--- org.apache.jena:jena-base:3.6.0
|    |    |    |    |         +--- org.apache.jena:jena-shaded-guava:3.6.0
|    |    |    |    |         |    \--- org.slf4j:slf4j-api:1.7.25
|    |    |    |    |         +--- org.apache.commons:commons-csv:1.5
|    |    |    |    |         +--- commons-io:commons-io:2.6
|    |    |    |    |         +--- org.apache.commons:commons-lang3:3.4
|    |    |    |    |         +--- com.github.andrewoma.dexx:collection:0.7
|    |    |    |    |         \--- org.slf4j:slf4j-api:1.7.25
|    |    |    |    +--- org.apache.jena:jena-shaded-guava:3.6.0 (*)
|    |    |    |    +--- org.apache.httpcomponents:httpclient:4.5.3
|    |    |    |    |    +--- org.apache.httpcomponents:httpcore:4.4.6
|    |    |    |    |    +--- commons-logging:commons-logging:1.2
|    |    |    |    |    \--- commons-codec:commons-codec:1.9
|    |    |    |    +--- com.github.jsonld-java:jsonld-java:0.11.1
|    |    |    |    |    +--- com.fasterxml.jackson.core:jackson-core:2.9.0
|    |    |    |    |    +--- com.fasterxml.jackson.core:jackson-databind:2.9.0
|    |    |    |    |    |    +--- com.fasterxml.jackson.core:jackson-annotations:2.9.0
|    |    |    |    |    |    \--- com.fasterxml.jackson.core:jackson-core:2.9.0
|    |    |    |    |    +--- org.slf4j:jcl-over-slf4j:1.7.25
|    |    |    |    |    |    \--- org.slf4j:slf4j-api:1.7.25
|    |    |    |    |    \--- commons-io:commons-io:2.5 -> 2.6
|    |    |    |    +--- org.apache.httpcomponents:httpclient-cache:4.5.3
|    |    |    |    |    \--- org.apache.httpcomponents:httpclient:4.5.3 (*)
|    |    |    |    +--- org.apache.thrift:libthrift:0.10.0
|    |    |    |    |    +--- org.slf4j:slf4j-api:1.7.12 -> 1.7.25
|    |    |    |    |    \--- org.apache.httpcomponents:httpclient:4.4.1 -> 4.5.3 (*)
|    |    |    |    +--- org.slf4j:jcl-over-slf4j:1.7.25 (*)
|    |    |    |    +--- org.apache.commons:commons-lang3:3.4
|    |    |    |    \--- org.slf4j:slf4j-api:1.7.25
|    |    |    \--- org.slf4j:slf4j-api:1.7.25
|    |    +--- org.apache.jena:jena-tdb2:3.6.0
|    |    |    +--- org.apache.jena:jena-dboe-trans-data:3.6.0
|    |    |    |    +--- org.apache.jena:jena-dboe-transaction:3.6.0
|    |    |    |    |    +--- org.apache.jena:jena-dboe-base:3.6.0
|    |    |    |    |    |    +--- org.apache.jena:jena-arq:3.6.0 (*)
|    |    |    |    |    |    \--- org.slf4j:slf4j-api:1.7.25
|    |    |    |    |    \--- org.slf4j:slf4j-api:1.7.25
|    |    |    |    +--- org.apache.jena:jena-dboe-index:3.6.0
|    |    |    |    |    +--- org.apache.jena:jena-dboe-base:3.6.0 (*)
|    |    |    |    |    \--- org.slf4j:slf4j-api:1.7.25
|    |    |    |    \--- org.slf4j:slf4j-api:1.7.25
|    |    |    \--- org.slf4j:slf4j-api:1.7.25
|    |    +--- org.apache.jena:jena-rdfconnection:3.6.0
|    |    |    +--- org.apache.jena:jena-arq:3.6.0 (*)
|    |    |    \--- org.slf4j:slf4j-api:1.7.25
|    |    \--- org.slf4j:slf4j-api:1.7.25
|    +--- net.oauth.core:oauth:20100527
|    +--- net.oauth.core:oauth-consumer:20100527
|    |    \--- net.oauth.core:oauth:20100527
|    +--- net.oauth.core:oauth-httpclient4:20090913
|    |    +--- net.oauth.core:oauth-consumer:20090617 -> 20100527 (*)
|    |    \--- org.apache.httpcomponents:httpclient:4.0 -> 4.5.3 (*)
|    +--- org.apache.wink:wink-client:1.4 (*)
|    +--- org.apache.wink:wink-client-apache-httpclient:1.4
|    |    +--- org.apache.wink:wink-client:1.4 (*)
|    |    \--- org.apache.httpcomponents:httpclient:4.1.3 -> 4.5.3 (*)
|    +--- org.eclipse.lyo.oslc4j.core:oslc4j-core:2.4.0
|    |    +--- javax.ws.rs:jsr311-api:1.1.1
|    |    +--- org.apache.jena:apache-jena-libs:3.6.0 (*)
|    |    +--- org.slf4j:slf4j-api:1.7.25
|    |    \--- org.assertj:assertj-core:3.8.0
|    +--- org.eclipse.lyo.oslc4j.core:oslc4j-jena-provider:2.4.0
|    |    +--- org.eclipse.lyo.oslc4j.core:oslc4j-core:2.4.0 (*)
|    |    +--- xml-apis:xml-apis:1.3.04 -> 1.4.01
|    |    +--- xerces:xercesImpl:2.8.0 -> 2.11.0 (*)
|    |    +--- org.slf4j:slf4j-api:1.7.25
|    |    \--- org.apache.jena:apache-jena-libs:3.6.0 (*)
|    +--- org.eclipse.lyo.oslc4j.core:oslc4j-json4j-provider:2.4.0
|    |    +--- org.eclipse.lyo.oslc4j.core:oslc4j-core:2.4.0 (*)
|    |    \--- org.apache.wink:wink-json4j:1.2.1-incubating
|    +--- org.apache.httpcomponents:httpcore:4.4.5 -> 4.4.6
|    +--- org.apache.httpcomponents:httpclient:4.5.2 -> 4.5.3 (*)
|    +--- xerces:xercesImpl:2.8.0 -> 2.11.0 (*)
|    +--- xml-apis:xml-apis:1.3.04 -> 1.4.01
|    +--- javax.servlet:javax.servlet-api:3.1.0
|    \--- javax.ws.rs:jsr311-api:1.1.1

Now, what baffles me is that w3c does not seem to exist anywhere in that tree. How is that possible? I know for a fact that removing this dependencies resolves the w3c conflict, so logically it has to be in there somewhere, or am I missing something?
Does anyone have any idea how this can be and what can be done about it?
Answer: I now managed to figure out how to fix it, even though I don't have a perfect understanding how the fix relates to the problem.
The bottom line is that the transitive dependency on xml-apis somehow caused this, even though xml-apis does not seem to have any dependencies on its own. So writing the dependency like this fixed the issue for me:
    compile ("org.eclipse.lyo.clients:oslc-java-client:2.4.0"){
        exclude module: "xml-apis"
    }

Does anyone have a more satisfying explanation for this? Thus far, all I know is that xml-apis (https://mvnrepository.com/artifact/xml-apis/xml-apis/1.4.01) does not seem to have any dependencies, however, it does for some reason use the W3C License.


Colocar uma barra no final da url (ou antes da interrogação)

Question: Implementei este script, de troca de idiomas (ou troca de unidades, neste caso):

<code>   /*Aqui ele coleta a seleção*/
      $('#unidade').on('change', function() {
    document.getElementById('form_unidade').submit();
   });
   </code>
<code>     <!-- Aqui se seleciona a unidade -->
          <form method='get' action='' id='form_unidade' >
      <select name='unidade' id="unidade" >
       <option value='cidade-1' <?php if(isset($_SESSION['unidade']) && $_SESSION['unidade'] == 'cidade-1'){ echo "selected"; } ?> >São José do Rio Pardo</option>
       <option value='cidade-2' <?php if(isset($_SESSION['unidade']) && $_SESSION['unidade'] == 'cidade-2'){ echo "selected"; } ?> >Mococa</option>
      </select>
     </form>

          <!-- Ele aqui ele grava na sessão a unidade selecionada -->
          <?php

 if(isset($_GET['unidade']) && !empty($_GET['unidade'])){
  $_SESSION['unidade'] = $_GET['unidade'];

  if(isset($_SESSION['unidade']) && $_SESSION['unidade'] != $_GET['unidade']){
   echo "<script type='text/javascript'> location.reload(); </script>";
  }
 }

 if(isset($_SESSION['unidade'])){
  include "php/multi-unidades/unidade_".$_SESSION['unidade'].".php";
 }else{
  include "php/multi-unidades/cidade-1.php";
 }

 if(!isset($_SESSION['unidade'])){
  $unidade = "sao-jose-do-rio-pardo";
 }else{
  $unidade = $_SESSION['unidade'];
 }
          ?>          </code>

Funciona perfeitamente para a ocasião.
Se pudesse melhorar um detalhe, o link que ele gera fica assim:
http://localhost/site/contato?unidade=cidade-1
Há algumas páginas que isso causa problemas.
Nessa estrutura, seria possível que o link gerado tivesse uma barra antes da interrogação?
http://localhost/site/contato/?unidade=cidade-1
Answer: Você tentou utilizar o window.location.href = "url_aqui", em vez de usar o location.reload?
Qual a finalidade disso que você está fazendo? A URL muda assim que você seleciona a unidade? Isso é salvo em banco de dados ou é um formulário de envio de e-mails?
Tem como fornecer mais informações a respeito caso o window.location.href não sirva?
Comment: Isto não responde à pergunta. Quando você tiver [reputação](https://pt.stackoverflow.com/help/whats-reputation) suficiente, você vai poder deixar [comentários em qualquer post](https://pt.stackoverflow.com/help/privileges/comment) mas, até lá, escreva apenas resposta que não [dependam de mais informações de quem perguntou](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [Da Revisão](/review/low-quality-posts/264149)
Comment: Então responda à pergunta do rapaz por favor, ele tá precisando de ajuda. Se a minha ajuda não é o suficiente, então ajude ele, seria mais útil do que me repreender por tentar ajudar.
Comment: Jean, ninguém está de repreendendo, apenas você não entendeu o propósito do SOpt. Recomendo a leitura:  [Tour](https://pt.stackoverflow.com/tour) , [Como criar um exemplo Mínimo, Completo e Verificável](https://pt.stackoverflow.com/help/minimal-reproducible-example) , [Guia de sobrevivência do Stack Overflow em Português](https://pt.meta.stackoverflow.com/questions/8045/guia-de-sobreviv%c3%aancia-do-stack-overflow-em-portugu%c3%aas).
Comment: Tentei usar o window.location.href, mas ficou do mesmo jeito. Acho que o problema está na linha "document.getElementById('form_unidade').submit();". Uma opção que tinha tentado, sem sucesso e ajustar o .htaccess para colocar uma barra no final de todas as url.


Is a monoid $M \in \bf{\text{Mon}}$ equivalent to the same monoid $M \in \bf{\text{Cat}}$?

Question: We usually say that a monoid is just a category with only one object. Thus, for every monoid $M$, viewed in as a category, there corresponds a monoid $M$ in the category of monoids and vice-versa. But this a little bit vague, isn't? What machinery do we need to make this more elegant?
Is there a way to I establish that $M \in \bf{\text{Mon}}$ and $M \in \bf{\text{Cat}}$ are equivalent? My guesses:
($\Rightarrow$) I think we can define a functor $F : \bf{\text{Mon}} \to \bf{\text{Cat}}$ that takes objects to themselves and each monoid homomorphisms to a functor between those monoids viewed as categories.
($\Leftarrow$) Really have no idea. What domain would this functor have?
Also, since $\bf{\text{Mon}}$ and $\bf{\text{Cat}}$ are different categories, is an isomorphism even possible?
Thanks!
Comment: Your functor $F : \mathbf{Mon} \to \mathbf{Cat}$ has a left adjoint. This is a natural candidate.
Comment: @ZhenLin So, my functor $F$ is well-defined? Sorry, I am a beginner in Category Theory, I am not very familiar with the concept of an adjoint yet. Would you please elaborate it a little bit more?
Comment: @StudentType Yes, $F$ is well-defined.
Comment: I'll lift this out to a comment, because my answer was so very wrong: Mon and Cat are not isomorphic. Indeed, the initial object is the same as the terminal object, in Mon: they're both the trivial monoid. However, in Cat, the initial and terminal objects are the empty category and the one-object one-arrow category respectively, and they're not isomorphic.
Answer: The more precise and invariant statement is that the category of monoids is equivalent to the category of pointed connected categories; "connected" means there is a single isomorphism class of object (as opposed to just a single object; that's an evil condition), and "pointed" means you've distinguished such an object.
If you remove "pointed," then connected categories naturally form a 2-category, not a category, and this 2-category is a bit more complicated than the 1-category of monoids.
Comment: The point (no pun) being that choosing a point trivialises the 2-dimensional structure in this case.
Answer: You want to establish something like an equivalence of categories between monoids and the full subcategory of categories on the categories with a single object. Given a monoid $M$, there is a category $FM$, but you shouldn't say this is "the object $M$ itself" before you've proved your proposition! $FM$ is instead simply defined to be the single-object category whose morphisms $FM(*,*)$ are given by $M$. Then $F$ is a functor-just check explicitly that the monoid homomorphism axioms are the same as the axioms for a functor between one-object categories.
The inverse is similarly simple: send a one-object category to the endomorphisms of its single object. This is a monoid, and you'll check that these two functors are inverse to each other.
Comment: I should note, that what you describe provides an _equivalence_ between the category of monoids and the category of one-object categories, not an isomorphism of categories.
Comment: @TasiWalde Yes, that's right, thanks, although it's an isomorphism with the one-object categories whose only object is $*$.
Comment: @KevinCarlson: There are other fine details about how these categories are defined that would make them not obviously isomorphic. For example, the category of monoids defined as sets with a binary function and chosen element is not (obviously) isomorphic to the category of monoids defined to be the models of a finite limit sketch; e.g. because each model gets to pick its own singleton set to use in the definition of the identity element, or its own product diagram to use in the definition of multiplication. Because of things like this, I like to avoid ever mentioning isomorphisms of categories


SQL Server Profiler discrepancy

Question: I am struggling with a strange problem using Sql Profiler. While running some performance testing scripts, I run profiler to find bottlenecks. One particular statement seems to be taking a lot of time - with CPU 1407, Reads 75668 and Duration of 175.
However when I run the same statement in Management Studio, SQL Profiler returns CPU 16, Reads 4 & Duration 55.
Can anyone point me towards what I am doing wrong, as I am completely baffled by this.
Thanks, Susan.
Comment: Perhaps you are not doing anything wrong and are seeing the results of caching. If you profile again, does the time taken shrink?
Comment: Thanks for the tip but I cleared the cache first.
Answer: You may have a scalar user defined function that has table access.
The resources used are only picked up by profiler: SSMS won't show the internal IO or CPU of the scalar udf.
Example:
<code>CREATE FUNCTION dbo.MyUdf (
    @param int
)
AS
RETURNS int
BEGIN
    RETURN (SELECT MAX(foo) FROM dbo.MyOtherTable WHERE Key = @param)
END
GO

SELECT
    col1, col2, dbo.MyUdf(col3)
FROM
    dbo.MyFirstTable
</code>
However, this may not explain duration...
Comment: Thanks. It's a common gotcha and is effectively a CURSOR if you think about it...
Comment: I think it may be using a cursor as I'm seeing this in the sql traced sometimes
exec sp_prepexec
Comment: @Susan: can you post the offending statement please?
Comment: We got a little more information, we found that the statement is called from a Java/Hibernate combination and something about the way the call is being made is returning 50,000 rows instead of the 2 rows returned when the statement is executed directly
Comment: @Susan: Interesting. Do you have more for us?
Answer: Was a java/hibernate issue.
Answer: If you run the query in enterprise manager directly after the profiling, all pages it needs will be cached in memory. This can lead to drastic improvements.
If you right-click the server in Enterprise Manager and select Properties, you can change the amount of memory available to the server. If you change this number even one step, SQL server will flush its cache.

SQL Server Profiler discrepancy


Find a sequence of whole numbers $n _ { 1 } , n _ { 2 } , \ldots$ such that $n _ { i - 1 } | n _ { i }$ for all $i \geq 2$

Question:
Problem : Find a sequence of whole numbers $n _ { 1 } , n _ { 2 } , \ldots$ such that $n _ { i - 1 } | n _ { i }$ for all $i \geq 2$ and for every $k \in \mathbb{N}$ there exists $i$ such that $k | n _ { i }$.

The subject of the exercice is "the splitting field of $\mathbb{F}_p$", with $p$ a prime. But this first question doesn't seem to relate (yet) to rings and fields theory.
This question makes me think of the proof of the the fundamental theorem of finite abelian groups with invariant factors.
Comment: They will work wonderfully. You do have to check this yourself, though. You shouldn't trust strangers on the internet, after all :)
Comment: What have you tried? For instance, one famous sequence in particular stands out to me as almost _made_ for this purpose. Try constructing such a sequence yourself, and maybe you can figure out which one I'm talking about.
Comment: @arthur the Fibonacci sequence?
Comment: The Fibonacci sequence has, somewhere close to the beginning, a $2$ and then a $3$. Do we have $2\mid 3$?
Comment: @Arthur Sorry that was a dumb and quick answer, you said "famous sequence" and I directly thought about this. I'm gonna look into that.
Comment: De **facto**... you can just multiply by increasing sequence of numbers.
Comment: @Arthur Got it, is it the factorial numbers?
Comment: @Arthur Sure, thank you for your help. I should have thought a little bit more about this before posting on StackExchange. Have a nice day!
Comment: I dare guess it is about the algebraic closure of $\Bbb{F}_p$. The condition $n_{i-1}\mid n_i$ tells us that $\Bbb{F}_{p^{n_{i-1}}}\subset\Bbb{F}_{p^{n_{i}}}$ when we can form the nested union $K=\bigcup_i\Bbb{F}_{p^{n_{i}}}$. The condition $k\mid n_i$ tells us that $\Bbb{F}_{p^k}\subset K$. So $K$ contains all the finite fields of characteristic $p$ and is thus algebraically closed.
Comment: @JyrkiLahtonen You're exactly right. The goal of the exercise was to show that $\overline { \mathbb { F } } _ { p }= \bigcup _ { i } \mathbb { F } _ { p ^ { n _ { i } } }$ as you said.
Answer: What about
$n_i = i!$?
(Is this enough characters?)


Menu (Picture) does not fill width of my Joomla site

Question: I have set up my picture menu and it is working correctly but I notice it does not fill the width of the website.
I have set all pictures to max-width: 100%; and height: auto; within the actual component but it doesn't want to fill the width of the website.
My Protostar template was set to Fluid already.
I'd like the picture menu to be responsive relative to the width of my website and when the screen size is reduce I'd like the same.
This is currently not the case.
Any help would be appreciated.
This is the link to my site:

.image-title {
display: flex;
font-size: 30px;
color: white;
justify-content: center;
position: relative;
top: -70px;
line-height: normal;
}
.item-241 {
vertical-align: bottom;
padding: 0px;
display: table-cell;
}
.item-242 {
vertical-align: bottom;
padding: 0px;
display: table-cell;
}
.item-244 {
vertical-align: bottom;
padding: 0px;
display: table-cell;
}
.nav > li > a > img {
max-width: 100%;
height: auto;
}
Comment: do you want so? - https://ibb.co/3kpRMNp
Comment: I actually only want the images to auto-resize and maximize on the browser.
Comment: this link does not work for me (((
Comment: I understood how. I'll do it now.
Comment: Please ask your Joomla questions at [joomla.se] Stack Exchange.  While there can be general purpose solutions which can be offered on SO, the audience at JSE has more intimate knowledge of the CMS, its features, as well as 3rd party extensions and they can advise you on best practices and common pitfalls.
Answer: If you do everything right, you will get the desired result. Use the following css rules for the solution:
.nav:ntd-child(2) {
    display: flex;
    justify-content: space-between;
}

In this rule, delete these lines that I pointed to.
.nav-tabs:before,
.nav-tabs:after,
.nav-pills:before, <--- delete
.nav-pills:after <--- delete {
    display: table;
    content: "";
    line-height: 0;
}

here I replaced max-width with width
.nav > li > a > img {
    width: 100%;
    height: auto;
}

.item-241, .item-242, .item-244   {
    width: 33%; /*add this it*/
    vertical-align: bottom;
    padding: 0px;
    display: table-cell;
}

.nav-pills > li > a {
    padding-top: 8px;
    padding-bottom: 8px;
    margin-top: 2px;
    margin-bottom: 2px;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    border-radius: 5px;
    height: 90%; /*add this it*/
}

I warn you that the native size of all pictures is different, which means that if you set one height for everyone (fixed), it will not be beautiful. In order to be beautiful, the pictures need to be hooked through the background-image, in the div.
Comment: did you succeed?
Comment: Thank you! I did all the changes you suggested but it is not displaying correctly on the two computers I tried: https://ibb.co/K9PWTdr
https://ibb.co/hLhVMrL
Comment: have you set the index for the child class? `.nav:ntd-child(2) {
    display: flex;
    justify-content: space-between;
}`
Comment: yes I added it under custom.css along with the .nav, .items and .nav-pills that you provided. Should I add those under template.css in the Protostar template of Joomla?
Comment: I have tested this on different screens too. Everything shows well. https://ibb.co/cwc4W15
Comment: yes add in template.css. And try adding `!important` - .nav:ntd-child(2) { display: flex!important;     justify-content: space-between; }
Comment: How are you doing with the layout?
Comment: It is working properly on 2 computers but another 2 computer it overlaps with the top menu beside COVID-19 https://ibb.co/K9PWTdr. Thank you for all the help. By the way, how can I fix the height of the images? Should all of the images have the same ratio?
Comment: for this section of the site, yes, it will be correct if all the pictures are of the same ratio. And the best thing will be if you upload images not through the `img` tag, into the `div`, using the `background-image` rule.
Comment: after playing around the code you gave me. Everything is working flawlessly now on 4 different computer and phone. I added back the .nav-pills:before, .nav-pills:after { that I have deleted and that solved the problem of it overlapping on the top menu. Format is perfect now. Thanks alot for the help! My website is beautiful now
Comment: Sometimes it's hard to give the right solution when you don't have the complete code at hand :) I was glad to help you!


Use LAN with Cloud

Question: I have a scenario in my new office that I have only client PC's which i have to setup a server to manage these PC's. So of the high cost of server, can i use any of the cloud computing services to do so, so that all my PC's will b managed by the cloud service(i think it is active directory). Please help me in how can i do this?
I thought of having an internal server that will manage the client PC's. But the cost of server is a big problem. Also we will need to expand the server config when requirement increases.
Answer: Taking a brief look, Microsoft offers Azure Active Directory(http://azure.microsoft.com/en-us/services/active-directory/), which has a free trial. If the server is cost prohibitive, I would consider looking into the long term cost of the cloud service to see if it really outweighs the purchase of on-campus equipment. The problem with cloud services is that you are now dependent on your internet connection for people to log into their systems and interact with the directory. What happens if the connection goes down?
Another option, depending on the size of the business and it's needs, are to purchase a couple of lower end server options and host active directory and other services in appropriate VMs. This will be a bigger up front cost but MAY be a more robust solution depending on your needs.
Furthermore, security is always a consideration when using cloud services - make sure you read up on the docs and have a good idea of how to keep thing secure (you'll be passing user credentials back and forth to AD).
Comment: I need up to 20 clients only. And in this need to connect laptops to this AD from remote locations. So what option will be good for me as should be cost effective on long term (since there may chance of increasing the number of clients, and thereby upgrade server config which may tends to make the current server config unusable).
Comment: As Jeff Muzzy mentions, you can get server equipment cheaply. And a little bit of hardware goes a long way with user numbers as low as you are talking about. If you choose a cloud service, you are paying for convenience. The question you need to ask yourself is if you want to save money or if you want a convenient externally managed service. What is best for the business? if the latter, explore the cloud route.  Another option to consider is if the Microsoft stack is even right for the business. There are other options depending on the environment and technical levels of the employees.
Answer: I'm not so sure this belongs here but I'll try and answer.
Going to the cloud only saves you the capex costs of doing something or getting something going quickly.  You still will have to account for the OpEx costs of having stuff in the cloud.  The monthly, VM cost, networking traffic.  You get free into cloud but every outbound traffic is going cost you something.  Read that all the traffic pushed to your clients in your office will keep th
I have a local recycler (Seattle) here that sells HP DL180 (Dual Quad Core Rack mounted servers for 69$ that use SAS or SATA drives Raid controller and 4GB of ram) for 69$.
I have work on a few startups where OpEx over ran the Cap in less than 7 months.

Use LAN with Cloud


Running php script as cron job - timeout issues?

Question: I am coding a php script that does some back end stuff and needs to run every 8 hours or so. The script takes a while to execute. For the hell of it, I tried it from my browser and the connection to the server gets reset well before the script terminates. My question is - if I run it directly, ie. php -a file.php as a cron job, are there any internal time constraints on execution? This script may take 2-5 minutes to complete and cannot be interrupted. I've never done this before so I am not sure if php has quirks when running heavy scripts.
Comment: cli called php scripts have no time limit. a shared host however may stop process that take more than X seconds - how is this going to be hosted?
Comment: Check [set_time_limit](http://php.net/manual/en/function.set-time-limit.php)
Comment: See: http://www.php.net/manual/en/info.configuration.php#ini.max-execution-time, there is no time limit in CLI
Comment: It's not that there is no limit in CLI it's that there's no limit in the the default setting. I don't see anything that says this can't be overridden though.
Comment: fyi- its not unheard of for hosting providers to kill user processes that have run too long. I've personally come across one that killed my php processes after 2 minutes. Regardless, if it cannot be interrupted, you better think long and hard about what happens when the inevitable server reset/crash happens.
Answer: As said before, CLI scripts by default have no time limit.
But I would also like to mention an alternative to your cron job approach:
You can fork a CLI PHP script from a PHP script under webserver control. I have done this many times. It is especially useful if you have a script with long execution time which must be triggered by some website user action (e.g. building a very large archive file and send a download link by email when the file is complete).
I usually fork a CLI script from a webserver PHP script using the popen() function. This allows to nicely transfer parameters to the new script instance like this:
$bgproc = popen('php "/my/path/my-bckgrnd-proc.php"', 'w');
if($bgproc===false){
  die('Could not open bgrnd process');
}else{
  // send params through stdin pipe to bgrnd process:
  $p1 = serialize($param1);
  $p2 = serialize($param2);
  $p3 = serialize($param3);
  fwrite($bgproc, $p1 . "\n" . $p2 . "\n" . $p3 . "\n");
  pclose($bgproc);
}

In the CLI script you would receive these params like this...
$fp = fopen('php://stdin', 'r');
$param1 = unserialize(fgets($fp));
$param2 = unserialize(fgets($fp));
$param3 = unserialize(fgets($fp));
fclose($fp);

...and do anything with them that would take to long under webserver control.
This technique works equally well in *nix and Windows environments.
Answer: No there are no time limits in php itself when executing php from the command line.
But there can be other timeouts, like connections to mysql. So if you have a mysql connection in your code, make sure to keep it alive or set your mysql timeout to something high enough to run your code.
Another thing: I've seen some webhosting providers killing php apps running more then a few minutes. So make sure your provider does not do that.
Answer: As default, PHP scripts timesout after 30 seconds which can be overridden by editing the PHP.ini or by adding this at the top of your script.
set_time_limit(0);

This sets unlimited execution time to your script, that is, it never ends unless the scripts finish execution, or the server goes down, or the file is deleted or any fatal error comes.
Additionally,
You can add this to your script and open it in your browser to initiate the script, and it will run as if you are opening it in a browser and keeping the browser open.
ignore_user_abort();

It simply runs the script in background. These both would be useful for you.
ADD : When the scripts are run from the commandline,Cli, the default timeout is 0.(No Timeout)
Comment: wrong, cli scripts have a default of 0,. http://www.php.net/manual/en/features.commandline.differences.php
Comment: "not the command line" has a default of 30. "This sets the maximum time in seconds a script is allowed to run before it is terminated by the parser. This helps prevent poorly written scripts from tying up the server. The default setting is 30. When running PHP from the command line the default setting is 0. " http://www.php.net/manual/en/info.configuration.php#ini.max-input-time
Comment: set_time_limit(0);  on most shared hosts will either be ignored, or will restart the 30-second limit.
Comment: Ok, point taken. To add to my knowledge, what has 30 seconds as default timeout then?
Comment: Thanks, adding it to the answer.


how to push a view from a ToolBar, BarButtonItem

Question: I have a toolbar with 4 UIBarButtonItem's, on click of one of the buttons, i would like to change the current view controller to another view controller.
Could please tell me how i could achieve this??
Thanks,
BR,
Suppi
Answer: Do you use UINavigationBar along with UIBarButtonItem?
If so, then just casual
<code>[self.navigationController pushViewController:theViewCntrlrYouWant animated:NO];
</code>
should fit to your wish.
(Edited according to Suppi's observation)
If there's no navigation bar, then smth like:
<code>YourViewController * first = [[YourViewController alloc] init];
[self presentModalViewController:first animated:NO];
[first release];
</code>
Comment: i don't have a UINavigationBar, i use a UIToolBar along with UIBarButtonItem. I used the above code, i get [MapScreen presentViewController:animated:]: unrecognized selector sent to instance
Comment: Hi, i got it working, you need to use,self presentModalViewController:first animated:NO]; instead.


What do you call the reversal point of a logarithm?

Question: I am looking for the correct terminology to describe the region of greatest "curve", or "bend" in a logarithmic function. Because of the nature of logarithmic functions I don't think this meets the definition of a "reversal point" or "curve reversal". Specifically, due to the system that I'm describing, I'd like to draw a differentiation between the "stable" portion of the function (in the context I'm describing) that primarily runs across the X axis, and the period of steep decay that runs across the y-axis. I hope to do this by describing the rapidity of the transition between these two states in terms of the "curve" between. Is there an existing nomenclature here?
Comment: The logarithm function that I know is monotonically increasing, there is nothing that seems to be a "reversal point".  Its increases slows but gradually, there is no sudden transition from fast to slow.
Comment: I don't think there is such a term.  You want something like "inflection point" but that already means something else.
Comment: $x=1$ would be natural for your purposes.
Comment: Do you mean a "logistic" function?
Comment: I don't, I think, but it's worth discussion: I mean exponential, and bounded exponential, but not the amalgam, which I would term logistic.  There is an interesting side question as to whether the term 'logarithmic' subsumes the term 'bounded logarithmic'.  Do you think my terms are in order?
Comment: MathStudent, can you elaborate? Badjohn, in applied questions steep is the correct word, I think. Consider log spending, population growth, drops in blood pressure, etc...
Answer: For a function $y$ of a variable $x$, the curvature of the graph of $y$ is
$$
\kappa = \frac{y''}{(1 + y'^2)^\frac{3}{2}}
$$
which, when you apply it to $y = \ln x$, gives
$$
\kappa = \frac{\frac{-1}{x^2}}{(1 + (1/x)^2)^\frac{3}{2}}
$$
Multiplying top and bottom by $x^3$ gives
\begin{align}
\kappa
&= \frac{-x}{x^3(1 + (1/x)^2)^\frac{3}{2}}\\
&= \frac{-x}{(x^2)^\frac{3}{2}(1 + (1/x)^2)^\frac{3}{2}}\\
&= \frac{-x}{(x^2 + 1)^\frac{3}{2}}
\end{align}
As $x$ gets large, this goes to zero. As $x$ goes to $0$, it approaches $0$ as well. So it has a critical point somewhere in between.
Graphing suggests that the critical point occurs at $x = \frac{\sqrt{2}}{2}$, but you can use some calculus to determine that directly.
To answer the second question: I don't think that there's an accepted term for this, although sometimes folks talk about the "knee" of a curve, and maybe that captures what you're thinking of.
Comment: Curvature = 1/radius of curvature, I think I recall, so maybe *turning point* or *pivot point* would be appropriate things to call it.  With an explanation for this nonce term, of course.
Comment: The name is actually the only question. "Knee" is interesting, but on some log functions is not a great descriptor... "Pivot point" is interesting. Possibly most interesting is that there is indeed no accepted term. Everyone in my lab was sure there must be, and that we had simply forgotten it...
Comment: Sorry for wasting your time; I thought it might be useful to check that in a log function there actually WAS a point of greatest curvature, so that we weren't searching for a name for a thing that didn't exist.
Comment: You in no way wasted my time, and your response is interesting and relevant. Thank you for it.


Display an Array as a List inside a Table

Question: I have an array that have a created with items in it that I want to populate a cell in a table.  In my case this is a table of Orders in Ubercart and have created an array, called $models that is populated with the Model numbers of the line items in that order.  What would be the best way to display this array in my table?
Currently,
$rows[] = array(
  ...
  array('data' => $models),
  ...

display's nothing in the Model column.
Answer: There's theme_item_list() which

Returns HTML for a list or nested list of items.

e.g.
$rows[] = array(
  ...
  array('data' => theme('item_list', array('items' => $models))),
  ...

Comment: thats working but it's only displaying the first item in the array and not looping through the whole array.


Combine subject and observer in a single subscribe RxJs

Question: I have an Behavior Subject
private usersSubject: BehaviorSubject<ActionedUser[]> = new BehaviorSubject([]);
public usersChange: Observable<ActionedUser[]> = this.usersSubject.asObservable();

constructor() { }

set updatedUsers(users: ActionedUser[]) {
    this.usersSubject.next(users);
}

and an Observable
getCurrentUser(): Observable<WebAuthUser> {
    if (environment.production) {
        return this.http.get<WebAuthUser>(`${this.webAuthURL}/wauth/api/user`, { withCredentials: true });
    }
    const devUser: WebAuthUser = {
        userName: 'local_dev_user',
    };

    return of(devUser);
}

i want to join them into a single subscribe but for some reason when i use forkJoin() and subscribe to it nothing is being emitted
 forkJoin([
        this.saveUsersSubject.usersChange,
        this.api.getCurrentUser(),
    ]);
    this.getUsersDataAndLoggedUserSubscription.subscribe(([ userData, loggedUser]) => {

        this.actionedUsers = userData;
        this.currentUser = loggedUser;
    });

i think that it is due to the Subject but what can be the best way to join them and provide value once both are done?
Answer: Option 1: reactive method (IMO elegant)
forkJoin would only emit when both observables complete. The quickest way would be to tack in a take(1) to the BehaviorSubject observable. But this assumes you do not need the future emissions from the BehaviorSubject. If you wish to react to each emission of the BehaviorSubject, then you could use combineLatest or zip (note: they aren't synonymous) instead of forkJoin.
import { take } from 'rxjs/operators';

forkJoin([
  this.saveUsersSubject.usersChange.pipe(take(1)),
  this.api.getCurrentUser()
]);

Option 2: synchronous method (IMO inelegant)
As opposed to Subject and ReplaySubject, BehaviourSubject contains a special trait that it "holds" the last value pushed to it. You could access it anytime synchronously using the the value getter or the getValue() method (both essentially serve the same purpose).
private usersSubject: BehaviorSubject<ActionedUser[]> = new BehaviorSubject([]);
public usersChange: Observable<ActionedUser[]> = this.usersSubject.asObservable();

constructor() { }

set updatedUsers(users: ActionedUser[]) {
  this.usersSubject.next(users);
}

public actionedUsers(): ActionedUser[] {
  return this.usersSubject.value;
}

this.api.getCurrentUser().subscribe({
  next: (currentUser: any) => {
    this.actionedUsers = this.saveUsersSubject.actionedUsers();
    this.currentUser = loggedUser;
  },
  error: (error: any) => {
    // handle errors
  }
});

Comment: Thank you so much i used combineLatest as such and it solved my problem:

combineLatest([this.saveUsersSubject.usersChange, this.api.getCurrentUser()])
   .subscribe(([userData, loggedUser]) => {
    this.userDetails = userData;
    this.currentUser = loggedUser; },
   );


Cannot import name, error from python-telegram-bot

Question: I am trying to push my app with practically zero changes, just added a file that isn't involved in the app for now. Yesterday the app worked fine but now when I try to push the new version I get this error:
2020-02-29T15:26:39.875071+00:00 heroku[web.1]: State changed from crashed to starting
2020-02-29T15:26:43.028851+00:00 heroku[web.1]: Starting process with command `python costanti.py`
2020-02-29T15:26:44.744355+00:00 heroku[web.1]: State changed from starting to crashed
2020-02-29T15:26:44.729594+00:00 heroku[web.1]: Process exited with status 1
2020-02-29T15:26:44.668773+00:00 app[web.1]: Traceback (most recent call last):
2020-02-29T15:26:44.668795+00:00 app[web.1]: File "costanti.py", line 1, in <module>
2020-02-29T15:26:44.668918+00:00 app[web.1]: from telegram.ext import Filters,CommandHandler,MessageHandler
2020-02-29T15:26:44.668921+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site- packages/telegram/ext/__init__.py", line 25, in <module>
2020-02-29T15:26:44.669051+00:00 app[web.1]: from .callbackcontext import CallbackContext
2020-02-29T15:26:44.669054+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/telegram/ext/callbackcontext.py", line 21, in <module>
2020-02-29T15:26:44.669186+00:00 app[web.1]: from telegram import Update
2020-02-29T15:26:44.669189+00:00 app[web.1]: ImportError: cannot import name 'Update'

The app should be a telegram bot, and it worked for months until now, and I just can't understand why it isn't working on Heroku, but it works for me. I can think about PyCharm adding libraries to my requirements.txt. In fact when I use:
from telegram.ext import something

PyCharm underlines telegram telling me to add it to the requirements, but the actual library name is python-telegram-bot, not telegram. So maybe PyCharm added the name to the requirements and Heroku installed it, so when it says ImportError: cannot import name 'Update' it's actually looking for it in the telegram library, not in python-telegram-bot. Now I removed the library telegram from requirements but it still doesn't work.
It sounds strange to me, but this is the only reason I could find to this problem since the program runs on my pc, and the code in File "costanti.py", line 1 didn't change, and also because the problem comes from the library files.
Comment: Please don't add SOLVED and solutions to the question itself. You are free to post answers to your question (and even accept)
Answer: In my requirements.txt I removed the telegram dependency.
I removed telegram==0.0.1
e.g I now have only 3 dependencies left, which are
python-telegram-bot==12.4.2
requests==2.22.0
urllib3==1.25.7

Comment: Already tried this but didn't work. I'll try pushing with an empty requirements file and then re-push the right one, without telegram dependency. Thank you
Comment: Can I see your requirements.txt and also the top part of your python code where you import your modules?


Importance of (category of) injective objects

Question: I understand that injective objects play a central role for doing homological algebra in an abelian category, for example having enough injectives allows one to form injective resolutions which can be used to compute derived functors.
Somehow I can't shake the feeling that I'm still missing some central observation about injectives. For example, it feels like the category $\operatorname{Inj} \mathcal A$ of injectives in an abelian category $\mathcal A$ "knows a lot about" $\mathcal A$.
Somewhat relatedly, the Gabriel's spectrum of a Grothendieck category has as underlying set the isomorphism classes of indecomposable injective objects. This strikes me as a strange choice, if one views injectives merely as a technical device to compute derived functors. Could someone explain what is going on here and what I am missing?
Comment: I think that's not so surprising if you think about it in the dual form: an abelian category with enough projectives is determined by its subcategory of projective objects. This is especially clear for categories of modules over a ring, since projective modules are precisely the direct summands of free modules.
Comment: Have you looked at [this question](https://math.stackexchange.com/q/126107/5191)?
Comment: @ZhenLin Thank you for the link. That is a satisfying answer from the homological algebra perspective, but I think it might be something else I'm looking for. I just found that an abelian category $\mathcal A$ with enough injectives is equivalent to the opposite category of the finitely presented functors $\operatorname{Inj} \mathcal A \to \mathbf{Ab}$ (Lemma 18.1.13 in Prest "Purity, Spectra and Localisation"). I guess in this sense one can "recover" $\mathcal A$ from $\operatorname{Inj} \mathcal A$, but I don't yet fully understand this yet.
Comment: @ZhenLin I see, thanks. So I guess the reason why one often ends up working with $\operatorname{Inj} \mathcal A$ is that there are enough injectives, for example in categories of sheaves of $\mathcal O_X$-modules on a ringed space $(X, \mathcal O_X)$.
Answer: Let $\mathcal{A}$ be an abelian category, let $\mathcal{B}$ be the full subcategory of injective objects in $\mathcal{A}$, and let $[\mathcal{B}, \textbf{Ab}]$ be the category of additive functors $\mathcal{B} \to \textbf{Ab}$.
As you say, we have the following representation theorem:
Theorem.
If $\mathcal{A}$ has enough injectives, then $\mathcal{A}^\textrm{op}$ is equivalent to the full subcategory of finitely presentable objects in $[\mathcal{B}, \textbf{Ab}]$.
In other words, $\mathcal{A}$ is (equivalent to) the additive category obtained by freely adding kernels to $\mathcal{B}$.
In some sense, this is the 0-dimensional version of the fact that the derived category $\mathbf{D} (\mathcal{A})$ is equivalent to the chain homotopy category $\mathbf{K} (\mathcal{B})$.
(In fact, $\mathcal{A}$ embeds fully faithfully in $\mathbf{D} (\mathcal{A})$, hence also in $\mathbf{K} (\mathcal{B})$.)

The theorem is an immediate consequence of the following three propositions.
Proposition 1.
If $\mathcal{A}$ has enough injectives, then the evident functor $\mathcal{A}^\textrm{op} \to [\mathcal{B}, \textbf{Ab}]$ defined by $A \mapsto \textrm{Hom} (A, -)$ is fully faithful.
Given a commutative diagram in $\mathcal{A}$ of the form below,
$$\require{AMScd}
\begin{CD}
0 @>>> A_0 @>>> I_0 @>>> J_0 \\
&&& @VVV @VVV \\
0 @>>> A_1 @>>> I_1 @>>> J_1
\end{CD}$$
where the rows are exact, there is a unique morphism $A_0 \to A_1$ compatible with this diagram.
Conversely, given
$$\require{AMScd}
\begin{CD}
0 @>>> A_0 @>>> I_0 @>>> J_0 \\
& @VVV \\
0 @>>> A_1 @>>> I_1 @>>> J_1
\end{CD}$$
where the rows are exact and $I_0$ and $J_0$ are injective, there are morphisms $I_0 \to I_1$ and $J_0 \to J_1$ compatible with this diagram.
Hence, the full subcategory of $\mathcal{A}$ spanned by the objects that occur as kernels of morphisms between injective objects embeds contravariantly and fully faithfully in $[\mathcal{B}, \mathbf{Ab}]$ (by the functor in question).
But $\mathcal{A}$ has enough injectives, so we are done. ◼
Proposition 2.
Let $A$ be an object in $\mathcal{A}$.
If $\mathcal{A}$ has enough injectives, then $\textrm{Hom} (A, -)$ is a finitely presentable object in $[\mathcal{B}, \textbf{Ab}]$.
Proof.
This is clear if $A$ is injective, since representable functors are finitely presentable.
But the class of finitely presentable objects is closed under cokernels, and every object in $\mathcal{A}$ is a kernel of a morphism between injective objects, and $\mathcal{A}^\textrm{op} \to [\mathcal{B}, \textbf{Ab}]$ is exact, so its image is contained in the class of finitely presentable objects. ◼
Proposition 3.
If $\mathcal{A}^\textrm{op} \to [\mathcal{B}, \textbf{Ab}]$ is fully faithful, then every finitely presentable object in $[\mathcal{B}, \textbf{Ab}]$ is (up to isomorphism) in the image of $\mathcal{A}^\textrm{op} \to [\mathcal{B}, \textbf{Ab}]$.
Proof.
The class of finitely presentable objects in $[\mathcal{B}, \textbf{Ab}]$ is the smallest class of objects containing the representable functors and closed under isomorphisms, finite direct sums, and cokernels.
But the image of $\mathcal{A}^\textrm{op} \to [\mathcal{B}, \textbf{Ab}]$ contains the representable functors, and it is closed under finite direct sums and cokernels (because $\mathcal{A}^\textrm{op} \to [\mathcal{B}, \textbf{Ab}]$ is exact by construction and fully faithful by hypothesis), so we are done. ◼
Comment: Thank you for providing all the details! It's very clear now.


Python monkeypatch.setattr() with pytest fixture at module scope

Question: First of all, the relevant portion of my project directory looks like:
└── my_package
    ├── my_subpackage
    │   ├── my_module.py
    |   └── other_module.py
    └── tests
        └── my_subpackage
            └── unit_test.py

I am writing some tests in unit_test.py that require mocking of an external resource at the module level. I would like to use a pytest fixture with module level scope and pytest monkeypatch to acomplish this. Here is a snippet of what I have tried in unit_test.py:
import unittest.mock as mock
import pytest
from my_package.my_subpackage.my_module import MyClass

@pytest.fixture(scope='function')
def external_access(monkeypatch):
    external_access = mock.MagicMock()
    external_access.get_something = mock.MagicMock(
        return_value='Mock was used.')
    monkeypatch.setattr(
        'my_package.my_subpackage.my_module.ExternalAccess.get_something',
        external_access.get_something)

def test_get_something(external_access):
    instance = MyClass()
    instance.get_something()
    assert instance.data == 'Mock was used.'

Everything works just fine. But when I try to change line 8 from @pytest.fixture(scope='function') to @pytest.fixture(scope='module'), I get the following error.
ScopeMismatch: You tried to access the 'function' scoped fixture 'monkeypatch' with a 'module' scoped request object, involved factories
my_package\tests\unit_test.py:7:  def external_access(monkeypatch)
..\..\Anaconda3\envs\py37\lib\site-packages\_pytest\monkeypatch.py:20:  def monkeypatch()

Does anyone know how to monkeypatch with module level scope?
In case anyone wants to know, this is what the two modules look like as well.
my_module.py
from my_package.my_subpackage.other_module import ExternalAccess

class MyClass(object):
    def __init__(self):
        self.external_access = ExternalAccess()
        self.data = None

    def get_something(self):
        self.data = self.external_access.get_something()

other_module.py
class ExternalAccess(object):
    def get_something(self):
        return 'Call to external resource.'

Answer: I found this issue which guided the way. I needed to make a few changes to the solution for module level scope. unit_test.py now looks like this:
import unittest.mock as mock

import pytest

from my_package.my_subpackage.my_module import MyClass

@pytest.fixture(scope='module')
def monkeymodule():
    from _pytest.monkeypatch import MonkeyPatch
    mpatch = MonkeyPatch()
    yield mpatch
    mpatch.undo()

@pytest.fixture(scope='module')
def external_access(monkeymodule):
    external_access = mock.MagicMock()
    external_access.get_something = mock.MagicMock(
        return_value='Mock was used.')
    monkeymodule.setattr(
        'my_package.my_subpackage.my_module.ExternalAccess.get_something',
        external_access.get_something)

def test_get_something(external_access):
    instance = MyClass()
    instance.get_something()
    assert instance.data == 'Mock was used.'

Answer: This has gotten simpler as of pytest 6.2, thanks to the pytest.MonkeyPatch class and context-manager (https://docs.pytest.org/en/6.2.x/reference.html#pytest.MonkeyPatch). Building off Rich's answer, the monkeymodule fixture can now be written as follows:
@pytest.fixture(scope='module')
def monkeymodule():
    with pytest.MonkeyPatch.context() as mp:
        yield mp

@pytest.fixture(scope='function')
def external_access(monkeymodule):
    external_access = mock.MagicMock()
    external_access.get_something = mock.MagicMock(
        return_value='Mock was used.')
    monkeymodule.setattr(
        'my_package.my_subpackage.my_module.ExternalAccess.get_something',
        external_access.get_something)


Hierarchical Taxonomy Term View

Question: I have a Taxonomy which looks like this:
<code>Parent1
-Child1
--SubChild2
--SubChild3
-Child4
--SubChild5
--SubChild6
-Child7
Parent2
-Child8
-Child9
--SubChild10
-Child11
</code>
I have created a view to display all terms under a specified Parent by setting a context tid . Here you can find the exported view: http://pastebin.com/us7KnKsD
The Problem is that the view only shows the terms which have sub-children.
How can I also display the terms which doesn't have sub-children?
Is it possible with views? In php I would just create some recursive function...
Comment: Isn't that that you set `Require this relationship` in the relationship setup dialog?
Comment: Changing this setting have no effect concerning to the problem
Answer: Start your query from the Taxonomy table. Meaning select Taxonomy as your base table when creating your view. Then establish a relationship to your content from there. This will ensure your results contain all taxonomy names and then their subsequent children.
Answer: You can use the module Views tree

Hierarchical Taxonomy Term View


Does the idempotent law for union of a set imply that the measure of a set is zero?!!!

Question: Sorry in advance for this question!!!
The idempotent law for union of a set is :
A= A $\cup$ A
But it seems to imply that for the measure we get:
m(A)=m(A)+m(A)=2$\cdot$m(A),
which, then would imply that
m(A)=$0$
And so,the measure of every set would be zero!!!!
What I am doing wrong????
Answer: You would have that ${\frak m}A = 2\,{\frak m}A$ if the union $A = A \cup A$ were disjoint. This is not the case, unless $A = \varnothing$ (and here $0 = 2 \cdot 0$ is ok).
Comment: Paaah... Thank you very much, I saw that Kolmogorov used this argument to show that the measure of the empty set was zero, and it seemed to generalized for an arbitrary set, but your argument is completely valid and clear... Thanks
Answer: We don't assume that $ m( A \cup B ) = m(A) + m(B) $ for every pair of sets $A, B$, but only for when they're disjoint. Refer to a simple example of a measure like Lebesgue measure on the real line, i.e. "length". We expect to be able to add the lengths of two segments when they don't touch (or only touch in small ways), but if I have two segments that overlap significantly, I won't add their lengths together because I'll be "double-counting" some of it.


Google Now-like asymmetrical grid on tablet

Question: Does anybody have an idea how was a gridview with items of uneven height implemented?
Answer: It could be a StaggeredGridView.
See the answer to this question.
You can find an implementation at github.com/maurycyw/StaggeredGridView
Comment: yea it is, I bet you that it will get announced now at IO.


Delimiting transactions in a text file with bash

Question: I've got a text file with the following pattern:
06:52:25 -> TRANSACTION START
06:52:26 - line1
06:52:27 - line2
06:52:29 -> TRANSACTION END*
06:53:24 -> TRANSACTION START
06:53:25 - line3
06:53:40 - line4
06:53:52 -> TRANSACTION END

I would like to separate every occurrence of starting transactions and ends into separate files
Comment: @Tushar it'as totally fine here.
Comment: @AvinashRaj `I would like to seperate every occurence of starting transactions and ends INTO SEPARATE FILES` bothers me
Comment: I think this should belongs to http://superuser.com/ if you need complete code, if you need only `regex` then it's fine here
Comment: what are the output names ( of the split files )
Comment: output file names could be trans_1.txt, trans_2.txt
Answer: Try:
awk '/TRANSACTION START/{file="trans_"cont++".txt"}{print $0 >> file}' inputfile

Explanation:
/TRANSACTION START/{file="trans_"cont++".txt"}: When the START pattern is matched the target file name is updated.
{print $0 >> file}: Print every line in the current file with >> to avoid overwrite.
Comment: And if the OP has 10k transaction, the last line will be `print $0 > "FILE10000"` ?
Comment: Yeah thanks, but what I really need is the content between every  'code' TRANSACTION START and TRANSACTION END, included, thanks
Comment: Yeah Thomas, in my script I intend to use these files as temporary files, so they will be deleted later !
Comment: If the OP want a bash/regex combo, I seriously doubt (but I might be wrong) that he just have two files to compute
Comment: Thanks @klashxx, can I have a detailed explanation please ?


Como recuperar o último pagamento?

Question: Tenho a seguinte tabela no meu banco:
"financeiro
    financeiro_id INT AUTO_INCREMENT,
    financeiro_pagamento DATE,
    financeiro_pid INT,
    financeiro_valor INT,
";

Nessa tabela eu registro os pagamentos que o meu sistema recebe, depois uso a seguinte Query para me retornar os valores:
"SELECT *FROM login lo
  inner join financeiro fi on lo.login_id = fi.financeiro_pid
  Order by financeiro_pagamento";

Essa Query pega o financeiro_pid e faz as junção com a tabela login para saber quem pagou, só que eu preciso que cada registro igual dessa tabela me retorne apenas o último pagamento da pessoa. Com essa Query estou pegando todos os pagamentos, mas eu queria apenas o último pagamento do usuário.
Obs.: financeiro_pid é onde eu registro a chave do usuário.
Answer: A query abaixo deve fazer o que desejas. Irá pegar apenas os pagamentos mais recentes de cada cliente (MAX()):
SELECT * FROM financeiro fi
   inner join login lo on lo.login_id = fi.financeiro_pid
WHERE
   fi.financeiro_pagamento = (SELECT MAX(fi2.financeiro_pagamento) FROM financeiro fi2 where fi2.financeiro_pid = fi.financeiro_pid)
ORDER BY
   financeiro_pagamento

Comment: Top resolveu valeu pelo salve
Answer: Não uses max()
Utiliza o last_insert_id() :
Razão:
https://stackoverflow.com/questions/8345399/is-it-conceptually-right-to-do-a-select-maxid-etc-for-finding-the-last-insert
Yes, there is some relationship between max id and most recent insert, but consider the following:
what if the most recently inserted row was deleted?

Como recuperar o último pagamento?


Autocompeletextview & customtable

Question: HI i have a autocompletextview ,when am typing in autocomplete textview i need to directely query the custom table ,insted put it in array, My custom table contain list of names, how can i do this?
Comment: you want to retrieve and show each row from database while user typing text or want to get all rows from database and show data from query result without put result in array and use array adapter?
Comment: I'm sorry, but I can't still understand: query database WHILE user types text OR show data without putting data into array ? (if second you should use method which is @Sunil Pandey already posted)
Comment: when am types in autocompletextview it will directley query the table instead of reading the array
Answer: You should use SimpleCursorAdapter
SQLiteDatabase db // reference to database
// note that your query result should have an id field with name "_id"
Cursor cursor = db.rawQuery("select name_id as _id, name from table_names", new String[]{});
// create adapter over cursor, returned from database
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,android.R.layout.simple_dropdown_item_1line, cursor, new String[]{"name"}, new int[]{android.R.id.text1});
AutoCompleteTextView autocomplete = (AutoCompleteTextView)findViewById(R.id.autocomplete_id);
autocomplete.setAdapter(adapter);

Also you should look at SimpleCursorAdapter.CursorToStringConverter to convert data from cursor to String, which will be displayed. Maybe this link helps you with SimpleCursorAdapter.CursorToStringConverter

Autocompeletextview & customtable


Matrix exponential of a particular block matrix

Question: Can anyone compute the following matrix exponential
$$\Phi = \exp\begin{pmatrix} -\alpha I_3 & \alpha A \\ I_3 & O_3 \\
\end{pmatrix}$$
where $A$ is an arbitrary $3 \times 3$ matrix, $I_3$ is the $3 \times 3$ identity and $O_3$ is the $3 \times 3$ zero matrix?
Thanks in advance!

Edit: This comes about as the solution to a linear ODE. I tried evaluating it in MAPLE for the 2D case and it gives a result, but MAPLE can only do calculations component-wise so it's difficult to extract a concise expression in terms of the matrix A. For the 2D case, the answer seems to be in the form
$$\Phi=M_1e^{\omega_1}+M_2e^{-\omega_1}+M_3e^{\omega_2}+M_4e^{-\omega_2}$$
where $$\omega_{1}=\alpha/2+1/2\,\sqrt {\alpha\, \left( \alpha+2\,\sqrt { \left( {\it
Tr} \left( A \right)  \right) ^{2}-4\,{\it \det} \left( A
 \right) }+2\,{\it Tr} \left( A \right)  \right) }
$$
$$\omega_{2}=-\alpha/2+1/2\,\sqrt {\alpha\, \left( \alpha-2\,\sqrt { \left( {\it
Tr} \left( A \right)  \right) ^{2}-4\,{\it \det} \left( A
 \right) }+2\,{\it Tr} \left( A \right)  \right) }
$$
and all the $M_i$ are 4 by 4 matrices. It is not clear to me if $\Phi$ will have this structure in 3 dimensions, however.
Comment: How did you come across this problem? What are your thoughts on the problem? What have you tried so far?
Answer: Write out the eigenvector equation
$$
Mx = \lambda x \implies \pmatrix{-\alpha I & \alpha A\\ I & 0} \pmatrix{x_1\\x_2} = \lambda \pmatrix{x_1\\x_2}.
$$
That is, we have the system
$$
\begin{cases}
- \alpha x_1 + \alpha Ax_2 = \lambda x_1\\
x_1 = \lambda x_2.
\end{cases}
$$
Substituting the second equation into the first yields
$$
- \alpha \lambda x_2 + \alpha Ax_2 = \lambda^2 x_2 \implies\\
Ax_2 = \frac{\lambda(\lambda + \alpha)}{\alpha}x_2.
$$
So: if $\alpha$ is non-zero, then for every eigenvector $v$ of $A$ associated with $\mu$ and the solutions to $\lambda(\lambda+ \alpha)/\alpha = \mu$, the vector $x = (x_1,x_2)$ with $x_1 = \lambda v$ and $x_2 = v$ is an eigenvector of $M$.
If $\alpha \neq 0$ and $A$ is diagonalizable, this allows us to compute the exponential of $M$ directly.

Yet another approach: suppose that $J = S^{-1}AS$ is the Jordan form of $A$. It follows that
$$
M_2 = \pmatrix{S & 0\\0 & S}
\pmatrix{-\alpha I & \alpha A\\ I & 0}
\pmatrix{S & 0\\0 & S}^{-1} =
\pmatrix{-\alpha I  & \alpha J \\ I & 0}.
$$
If $J = \operatorname{diag}(\lambda_1,\lambda_2,\lambda_3)$, then we can see that $M_2$ is permutation similar to the block-diagonal matrix
$$
\operatorname{diag}\left[\pmatrix{-\alpha  & \alpha \lambda_1\\ 1 & 0},
\pmatrix{-\alpha  & \alpha \lambda_2\\ 1 & 0},
\pmatrix{-\alpha & \alpha \lambda_3\\ 1 & 0}\right].
$$
The blocks can be exponentiated separately.

(My previous answer below)
One approach is to simply use eigenvalues to calculate the Jordan form and proceed in the standard fashion. The key here, however, is that it is easy to find the eigenvalues of $M$ using only the eigenvalues of $A$. Denote
$$
M = \pmatrix{-\alpha I & \alpha A\\ I & 0}.
$$
Because the blocks of $M$ commute, we find that
$$
\det(M - \lambda I) = \det((-\alpha - \lambda I)(-\lambda I) - (\alpha A) (I))
\\
= \det(\lambda(\alpha + \lambda)I - \alpha A).
$$
So, if $p$ is the characteristic polynomial of $A$ (i.e. $p(\lambda) = \det(A - \lambda I)$), then the characteristic polynomial of $M$ is $p(\frac{\lambda(a + \lambda)}{\alpha})$. So, for each eigenvalue $\lambda$ of $A$, both $\lambda$ and $\lambda - \alpha$ are eigenvalues of $M$.

In fact, we could say a bit more. Suppose that $\lambda$ is an eigenvalue of $A$. We find that
$$
\operatorname{rank}(\lambda I - M) =
\operatorname{rank} \pmatrix{-\alpha I - \lambda I & \alpha A\\ I & -\lambda I}.
$$
If it holds that $\alpha$ is not an eigenvalue of $A$, then the nullity of $M - \lambda I$ is equal to the nullity of the Schur complement
$$
(M - \lambda I)/(-\alpha I - \lambda) = -\lambda I + \frac{\alpha}{\lambda + \alpha}A \\
\to \frac{\lambda(\lambda + \alpha)}{\alpha} I - A
$$
Comment: I found a much nicer approach, see my latest edit
Comment: Ah yes, this seems to fit very will with the edit that I made. I guess the $\omega_i$ actually involve the explicit solution to $det(A-\lambda I)$. Should be straight forward to get the answer from here.
Comment: Finally got around to the full problem... (you work very fast!). Your recent update is very straight forward and lead to the correct answer! Thank you
Answer: That follows is valid for every dimension $n$.
We consider $U=\begin{pmatrix}-aI_n&au\\I_n&0_n\end{pmatrix}$ where $u\in M_n(\mathbb{C}),a\in\mathbb{C}^*$; we use the notation $a+u$ for $aI_n+u$.
If we put $w=\sqrt{a(aI_n+4u)}$, and if $-a/4\notin spectrum(A)$ then $e^U=$

It remains to correctly choose the square root $w$; there are several square roots and, moreover, we must choose one which commutes with $u$.
We assume that, for every $\lambda\in spectrum(u), a(a+4\lambda)\notin (-\infty,0]$. Then $a(a+4u)$ admits a unique square root whose spectrum lies in the open right half plane; moreover, this square root is a polynomial in $u$ (cf. Functions of matrices, Higham). Note that, in these conditions, to divide by $w$ has a (obvious) mathematical meaning.