Como forçar uma Exception ao tentar excluir um registro Master que já contenha relacionamento em um Registro Child?

Question: Criei a seguinte estrutura no SQL Server:

Usando o EntityFramework com Code-First as classes ficaram dessa forma:
[Table("Master")]
public class Master
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Id { get; set; }
}

[Table("Child")]
public class Child
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public string Description { get; set; }

    [ForeignKey("Master")]
    public int? MasterId { get; set; }
    public virtual Master Master { get; set; }
}

Veja que MasterId por ser nulo (int?).
Ainda assim, setando a Foreign key criada em Child para não deletar em cascata (setando No Action) esperava que ao tentar excluir um registro em Master, que já tenha sido relacionado na Child, gerasse uma Exception.
Atentando para o fato de eu ter removido as convenções de deleção em cascata:
public class DataContext : DbContext
{
    public DataContext()
        : base("Data Source=(local); Initial Catalog=TestFK; Integrated Security=True")
    {
        this.Configuration.LazyLoadingEnabled = false;
        this.Configuration.ProxyCreationEnabled = false;
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
        modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
        base.OnModelCreating(modelBuilder);
    }

    public DbSet<Master> Masters { get; set; }
    public DbSet<Child> Childs { get; set; }
}

Então testei isso esperando receber uma Exception, mas não ocorreu:
class Program
{
    static void Main(string[] args)
    {
        using (var ctx = new DataContext())
        {
            ctx.Masters.Add(new Master { Id = 22 });
            ctx.Childs.Add(new Child { Description = "Teste 1", MasterId = 22 });
            ctx.SaveChanges();

            var versao = ctx.Masters.SingleOrDefault(x => x.Id == 22);
            if (versao != null)
            {
                ctx.Masters.Remove(versao); // <-- esperava que isso geraria uma exception
                ctx.SaveChanges();
            }
        }
    }
}

Do contrário, o registro foi excluído e o valor em Child foi setado como null.

Como forçar essa Exception?
Faltou alguma configuração? É um comportamento padrão?

Para concluir, a operação sendo feita diretamente no banco de dados retorna uma Exception, como esperado.
Comment: Porque é que quer que o MasterId possa ser null?
Comment: Olá @ramaral! Bom, claro que esse é apenas um pequeno exemplo em relação ao meu real problema. E **`MasterId`** em **`Child`** pode ficar um bom tempo ou até nunca receber uma referência de **`Master`**,
Comment: Aí está a resposta à sua pergunta. O EntityFramework comporta-se assim porque, quando indica que MasterId pode ser nulo, você está indicando que quer filhos sem pais. O EntityFramework não tem como adivinhar que você só quer isso em algumas situações.
Comment: @ramaral, entendi. Mas isso deve ter alguma forma de se contornar, já que não é o comportamento padrão do SQL Server. Conforme acabei de atualizar a pergunta mostrando que manualmente é gerado uma exceção.
Comment: Estranho! Não vejo porque o comportamento seja diferente.
Answer: É um comportamento padrão?
É. Repare que seu Master (o registro pai) pode ser nulo no filho (é chamado de "registro órfão"), portanto não haveria motivo para gerar exceção já que seu banco permite esta exclusão. O que o Entity Framework faz é arrumar os registros pra você de forma a assegurar consistência relacional.
Neste caso, levantar exceção seria uma regra de negócio:
class Program
{
    static void Main(string[] args)
    {
        using (var ctx = new DataContext())
        {
            ctx.Masters.Add(new Master { Id = 22 });
            ctx.Childs.Add(new Child { Description = "Teste 1", MasterId = 22 });
            ctx.SaveChanges();

            var versao = ctx.Masters.SingleOrDefault(x => x.Id == 22);

            if (ctx.Childs.Any(c => c.MasterId == versao.Id)) {
                throw new Exception("Não é possível excluir registro pai que tenha filhos.");
            }

            // Comentei porque SingleOrDefault dá exceção quando o registro vem nulo,
            // então esse condicional não faz muito sentido.
            // if (versao != null)
            // {
                ctx.Masters.Remove(versao); // <-- esperava que isso geraria uma exception
                ctx.SaveChanges();
            // }
        }
    }
}

Sobre a exceção
O Entity Framework primeiro define MasterId em Child como null antes de excluir Master porque conhece o relacionamento e sabe que tem ali uma chave estrangeira.
Comment: Ok! Obrigado pela ajuda!
Comment: Pelo o que entendi, apesar do "***No Action***", o EntityFramework ignora e assume um "***Set Null***". Não existe uma forma de contornar isso no Banco? Pergunto, apesar de você já ter dito que a solução é na aplicação. Preciso assegurar isso pelo banco de dados também.
Comment: No banco dá pra fazer por *trigger*, mas fica dependente de tecnologia. O ideal é resolver via regra de negócio. Tem gente que não vai gostar do que eu vou dizer, mas a regra poderia ser resolvida num *Controller* ou num *Helper*.
Comment: Cigano, viu a alteração à pergunta? Consegue dar uma explicação para isso?
Comment: @ramaral, setar null é do próprio EntityFramework.
Comment: @ramaral Atualizei a resposta.


Can you have a matrix with no zero rows that has an eigenvalue equal to zero

Question: Can you have a matrix with no zero rows that has an eigenvalue equal to zero?
So for $A \in \mathbb{R}^{n \times n}$ with $0$ as an eigenvalue, is the $\text{rank}(A)$ always smaller than $n$?
Comment: Yes.${}{}{}{}{}{}{}{}$
Comment: If a matrix is singular, then one of its eigenvalues is zero, and it is no trouble to build a singular matrix with none of its entries being zero.
Answer: $$\pmatrix{1&1\\1&1}\binom1{-1}=\;?$$
The answer to your second question, however, is yes, because the nullity of $A$ is positive; use the rank-nullity theorem.
Answer: Consider the matrix $A \in \mathbb{R}^{n \times n}$ obtained as $uv^T$, where $u,v \in \mathbb{R}^{n \times 1}$ and none of the entries of $u$ and $v$ are zero.
$\color{blue}{\text{This matrix $A = uv^T$ has no zero entries since $A(i,j) = u(i)v(j)$, where both $u(i)$ and $v(j)$ }}$ $\color{blue}{\text{are non-zero for all $i,j \in \{1,2,\ldots,n\}$}}$.
However, $\color{red}{\text{the matrix $A$ has $n-1$ eigenvalues as zero}}$.
One of the many equivalent definitions of rank of a matrix is the number of non-zero eigenvalues of the matrix. Hence, if $r$ eigenvalues of a matrix are non-zero, then the matrix has rank $r$.


Translation of BlockBase (ConfigurablePluginInterface)

Question: <code>  public function blockForm($form, FormStateInterface $form_state) {
    $form = parent::blockForm($form, $form_state);

    // Retrieve existing configuration for this block.
    $config = $this->getConfiguration();

    // Add a form field to the existing block configuration form.
    $form['Heading'] = array(
      '#type' => 'textfield',
      '#title' => t('Heading'),
      '#default_value' => isset($config['heading']) ? $config['heading'] : '',
    );
</code>
'#default_value' => isset($config['heading']) ? $config['heading'] : '',
can this thing be translated? And how?
I use it to display a text to site users
Answer: The key was in creating mymodule.schema.yml in mymodule/config/schema/mymodule.schema.yml
with content of a kind
<code>block.settings.myblock:
  type: block_settings
  mapping:
    Heading:
      type: text
      label: 'Heading'
      translatable: true
</code>
also
<code>$config = $this->getConfiguration();
</code>
is not needed
using
<code>$this->configuration['heading']
</code>
insted
\core\modules\system\src\Plugin\Block\SystemBrandingBlock.php -- is a good example


Exibir valores monetários de forma simples

Question: bom dia!
Qual seria a forma mais simples de se exibir valores monetários com o Javascript? Eu consegui limitar as casas decimais usando o .toFixed(2). Só que a parte inteira fica mais ou menos assim 10510.20 eu queria que fosse 10.520,20. Alguma sugestão?
Comment: Da uma olhada nessa função: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat
Comment: Mas esse resultado desejado seria retorno de que?
Answer: Usa esta função sempre me deu um jeito enorme para este problema:
function format_num(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

Comment: Não seria x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");  Ponto ao invés de virgula em g, ",") .Se possível coloque um executar na sua resposta para testar
Comment: não porque o autor queria em virgulas
Comment: não, ele diz "eu queria que fosse 10.520,20" separador de milhar ponto e decimal virgula


Why does Path.Combine produce this result with a relative path?

Question: To my surprise, this code does not produce expected results:
var basePath = @"\\server\BaseFolder";
var relativePath = @"\My\Relative\Folder";

var combinedPath = Path.Combine(basePath, relativePath);

The result is \My\Relative\Folder instead of the expected \\server\BaseFolder\My\Relative\Folder.
Why is this? What's the best way to combine relative paths that may or may not have a slash in them?
EDIT: I'm aware that I can just do string manipulation on relativePath to detect and remove a starting slash. Is there a safer way of doing this (I thought Path.Combine was supposed to be the safe way) that will account for backslashes and frontslashes?
Comment: That's not a _relative_ path.
Comment: Yes; seriously.  `\a\b` is an **absolute** path.   (although it's relative to the drive)
Comment: I would understand that if there were 2 backslashes at the front, making it a UNC path, but one slash? Seriously?
Answer: Drop the leading slash on relativePath and it should work.
The reason why this happens is that Path.Combine is interpreting relativePath as a rooted (absolute) path because, in this case, it begins with a \.  You can check if a path is relative or rooted by using Path.IsRooted().
From the doc:

If the one of the subsequent paths is
  an absolute path, then the combine
  operation resets starting with that
  absolute path, discarding all previous
  combined paths.
Comment: What a stupid thing.. If I need to trim start/end of the string etc. why would I use Path.Combine in the first place?
Comment: Is there a single use case in history where this is how anybody would want this to work??
Answer: Paths that start with a slash are interpreted as being absolute rather than relative. Simply trim the slash off if you want to guarantee that relativePath will be treated as relative.
var basePath = @"\\server\BaseFolder";
var relativePath = @"\My\Relative\Folder";

var combinedPath = Path.Combine(basePath, relativePath.TrimStart('/', '\\'));

Answer: According to this doc on Path.Combine the remark states it's best to use Path.Join() for this scenario where the user may have entered values. Looks like it was introduced with .NET Core 3.0
Path.Join(basePath, relativePath);

Seems like the only difference is this explicit scenario where we don't want to regard any of the paths we are combining as potential root paths.

Unlike the Combine method, the Join method does not attempt to root the returned path. (That is, if path2 or path2 or path3 is an absolute path, the Join method does not discard the previous paths as the Combine method does.
Comment: Just to point out that this is not available in .net framework
Comment: This doesn't work, it adds another slash to the root folder. For example,
``path1 = \\files\,
path2 = \filename.txt,
result = \\files\\filename.txt``
Comment: It is true that it doesn't remove the extra slashes, but on Windows and Unix (read: essentially everywhere) that's fine: https://unix.stackexchange.com/a/1919


Correctly configure a test svn/apache server

Question: I'm testing subversion, the base svnserve works, but I'm interested in testing the Apache/Httpd server.
I appear to be running into something, because regardless of what I type on the cmdline "svn list http://192.168.1.45/foo" I get something like
svn co http://192.168.1.45/Cool
svn: OPTIONS of 'http://192.168.1.45/Cool': 200 OK (http://192.168.1.45)

here's ny filestructure
ls /apps/CollegeDir/CollegeRepository
conf  db  format  hooks  locks  README.txt

ls /apps/CollegeDir/
atmp  baseCollegeSvn  CollegeRepository  CollegeRepositoryRoot

ls /apps/CollegeDir/CollegeRepositoryRoot/
cat    dog   car

I created the repository by using:
svnadmin create /apps/CollegeDir/CollegeRepository

I can access the repos for the svnserve by:
svn list svn://192.168.1.45/apps/CollegeDir/CollegeRepository/trunk/apps/CollegeRoot

as well as by the file by:
svn list file:///apps/CollegeDir/CollegeRepository/apps
CollegeDir/

But I can't seem to figure out how to get the svn list, using the http process. My issue is either in using the wrong http url path, or I've setup the svn portion of the apache http.conf/subversion.conf file incorrectly.
Here's what I have as a test in the subversion.conf file
<Location /trunk/apps/CollegeRoot>
   DAV svn
   SVNPath /apps/CollegeDir/CollegeRepository/
</Location>

The goal of the test, is to simply get a basic read/write for anyone with no auth process..
By the way, all of the folders/files are fully open (766) and "apache.apache" for the chown. This is to ensure the testing should work.
I've looked at various sites/threads but can't seem to pin down the issue.
Thoughts/comments are appreciated.
Thanks
Answer: I think:
<Location CollegeDir>
   DAV svn
   SVNParentPath /apps/CollegeDir/
   SVNListParentPath On
</Location>

should be accessible by
svn ls http://192.168.1.45/CollegeDir/CollegeRepository

You can get a list of all repositories available by pointing your browser to (note that this list is not supported by svnclients!)
http://192.168.1.45/CollegeDir/

Alternative:
<Location CollegeRepository>
   DAV svn
   SVNPath /apps/CollegeDir/CollegeRepository
</Location>

will be accessible under
should be accessible by
svn ls http://192.168.1.45/CollegeRepository

Comment: hey... tried your suggestions.. still not getting data back.. all i get back is 192.168.1.45 - - [11/Mar/2011:17:21:12 -0800] "OPTIONS /College HTTP/1.1" 200 - "-" "SVN/1.6.13 (r1002816) neon/0.29.3"
192.168.1.45 - - [11/Mar/2011:17:21:16 -0800] "OPTIONS /cc HTTP/1.1" 200 - "-" "SVN/1.6.13 (r1002816) neon/0.29.3"
[root@dell-1 /]#
Comment: aha.... turns out it was a permission issue regarding the repository/working copy files.   as a base test, simply set everything to 766, and to apache.apache for the chown.


Looking for name of a piano music style

Question: There is some piano music, of which the melody is consisted of short, equal duration notes and the accompaniment is also equal duration notes from chord breakdown. There are quite some repetition in the texture and chord progression, but there is not much variation in the rhythm, nor is there much use of heavy chords. As a result, the music sounds fluid and intangible.
Some of the examples include: music from the movie The Hours composed by Philip Glass and music from the movie Effroyables Jardins by composer Zbigniew Preisner.
My question is: in professional musicians' eyes, is music with these properties considered the same style, or style categorization is based on some other properties? If it is, what is the name of this style?
(I don't know if this question is considered to be off-topic genre identification question, but I give it a shot anyway because I can't think of another way to effectively get an answer. If it is off-topic, I'll close or delete it. Thanks for you time and sorry for the missing/inaccurate terminologies due to my still-improving English.)
Answer: I believe the style you're looking for is known as Minimalism. It was a style conceived in the late 20th century by composers such as Philip Glass, Steve Reich, Terry Riley, and others. The underlying philosophy is "less is more." The typical pattern in minimalist music is to construct simple motifs and repeat them (similar to Alberti or ostinato patterns from classical theory). The minimalist concept involves layering these simple, repeating motifs in set intervals to create the same style of tension & release as found in other styles of music. By adding/removing/changing one layer at a time at set intervals, the music is said to have a mechanical fluidity exclusive to this style of musical design. It's worth mentioning that the limiting constructs of minimalist music are not solely set to harmony -- minimalist music can take any aspect of music (rhythm, pitch, note length, etc...), limit it to only a small scope, and attempt to work within those limitations to create something magnificent.
For further listening, I might recommend some of the following:

Koyaanisqatsi - A beautiful film by Francis Ford Coppala with music by Philip Glass.
Short Ride In A Fast Machine - An iconic piece of literature for modern wind orchestras. Written by John Adams.
In C - A really cool piece by minimalist Terry Riley. I had the pleasure of performing this with some friends from college - you should read up on the construction of this from a musical standpoint.
Music for 18 Musicians - An amazing piece of music by Steve Reich. He is well known in the percussion world for his compositions.

I hope this helps out, and good luck!
Comment: @NS.X. - Listening again, I will say the 2nd piece you listed sounds more like a hybrid between Impressionism & French cabaret music (Moulin Rouge, etc...). The improvisational quality of the melody is not minimalist in nature. The 1st one would definitely fall under the minimalism umbrella. Bear in mind that minimalism doesn't have to be mechanical - it can be deeply emotional and melodic. It's only the process that has a mechanical structure. If you have the time, check out Koyaanisqatsi (above) from beginning to end and you'll see what I mean.
Comment: Hi, thanks for the answer! I think the music pieces I've mentioned may fall into minimalist category on technical aspects, but seems far more melodic and emotional than the examples in the answer. Do you think they're of the same style or might be a different one?

Looking for name of a piano music style


How to score a psychological scale with three factors

Question: I have helped to validate a new psychological scale and after conducting exploratory and confirmatory factor analyses, we have found the best fit for the scale is a 3-factor structure. The factor loadings between factors range from 0.28-0.56 and when a second order factor is added to create an overall factor, one of the factor loadings is 0.94 and the remaining two are 0.59 and 0.47.
My question relates to how we can explain to potential users of the scale how it should be scored - should we use a total score or do we need to score the three factors/dimensions separately? Any references or insight into this would be very appreciated as I am new to the field and unsure how to justify appropriate scoring based on 3-factor scale structure. Thanks in advance (:
Answer: I don't think this is completely statistically answerable. It depends on your purposes, on the three factors, and, to an extent, on your audience.  And it might vary by participant as well.
Lots of psychological measures have both an overall score and factor scores. Maybe the best known is the WISC and WAIS (Wechsler IQ tests). They give an overall IQ, index scores, and subtest scores. Often, the overall IQ is reasonable, but for some people (like me, for example) any sensible report would have to be on the subtests, because my scores vary a LOT.  But lots of other examples exist
Never mind the numbers, think about these things:

Do your three factors make sense together?
Who are the users? If the test will be used by psychologists, social workers, and other professionals, then you can explain more than if it is going to be used by the general public.
For each individual person, how much do scores vary?
Comment: Thanks for your insight Peter, I do think the factors make sense together but could also be measured separately depending on the focus of a psychological intervention, for example. I just wanted to ascertain whether there was a recommended cut off when comparing the strength of factor loadings or other goodness of fit statistics when considering all the factors together versus separately
Comment: In my experience, this is a 2-stage process. First you do the factor analysis (or other data structure investigation) and based on that you decide what is the best factor structure of your measure (preferably with more than one sample). Then, you stick with that structure and build your user manual specifying this structure. OR you realize after phase 1 that your measure does not have a clear structure --> back to the drawing board to revise the items, create more items etc.


Address of an object in c++ and its members

Question: I am working on one of my application issue.
Here the problem i am facing is there are some bunch of function which i need to call using the pointer of a class object.
But the main problem is i donot have a class pointer with me,instead i have a member variable value(lets say its a list of values). following this i did a small test with the below code.
using namespace std;

class Person {
public:
      Person(string name, int age) {
            this->name = name;
            this->age = age;
      }
      string getName() {
            return name;
      }
      int getAge() {
            return age;
      }
      void Print()
      {
      printf("This address is %x\n",this);
      printf("age adress is %x\n",&age);

      }
private:
      int age;
      string name;

};

int main() {
      cout << "Creating a person..." << endl;

Person *johnDoe=new Person("John Doe", 25);
      cout << "Person's name: " << johnDoe->getName() << endl;
      cout << "Person's age: " << johnDoe->getAge() << endl;
      johnDoe->Print();
      delete johnDoe;
      return 0;
}

The coutput of the execution is :
> ./a.out
Creating a person...
Person's name: John Doe
Person's age: 25
This address is 72918
age adress is 72918

Now my doubt is :
Is it guaranteed that the address of the class member variable always points to the address of the object?
Can i use this address in case i need to use the pointer for calling other core api functions?
I saw this when i googled?
(C1x §220.127.116.11.13: "A pointer to a structure object, suitably converted, points to its initial member ... and vice versa. There may be unnamed padding within as structure object, but not at its beginning.")
is this true even in case of c++ and classes?
Comment: See offsetof macro. Only for POD types!
Comment: may be related: http://stackoverflow.com/questions/8240273/a-portable-way-to-calculate-pointer-to-the-whole-structure-using-pointer-to-a-fi
Comment: For each class type, every data member will be at fixed offset value. This is not the starting address of the object as compiler puts some stuff at the top. But this will be different when you have virtual functions as compiler needs to put the vptr* in the object as well. So I don't its generally good practice to do this way.
Answer:
Is it guaranteed that the address of the class member variable always points to the address of the object?

No. In C++, there is potentially stuff before the first member (in particular for derived classes and polymorphic classes). What exactly there is is implementation defined.

Can i use this address in case i need to use the pointer for calling other core api functions?

No, and you don't need to: whenever you have access to members, you also have access to this, no?
Comment: Unfortunately No.i have a pointer to the last leaf of the tree i only have parent key and using the parent key i can get the list of children that it has which is a list and which is a meber of the class.This can be said as a tree but it is not an actual tree implementation.
Comment: @peter That's unclear. But the answer remains the same. You *cannot* use a pointer-to-member as a pointer to class. Doing so leads to invalid C++ code that will break.
Answer: This is true also for classes unless they have any virtual functions. Also you should take care if you have inheritance (not sure how exactly the rules are there).
In general, this is a bad idea though. Why do you want to do that? You rely on the structure of the class (i.e. your code will break if you by accident add a member before age) and you give away encapsulation (no other class should have a pointer to age anyway, since it is private - you would leak you object representation).
Btw: Are you a Java programmer? Your constructor looks like you are, since you do not initialize your object correctly. You should do it like this:
Person(String n, int a) : age(a), name(s) {}

(otherwise the compiler will first call the default contstructors of int and string and then call operator= on them - this is not efficient).


Why routerLink and router.navigate() act differently?

Question: When using this code in HTML:
 <button [routerLink]="[{ outlets: { flow: ['step1'] } }]">click me to show step1</button>

it navigates correctly to '/child/(flow:step1)'!!!
When trying to use this code in Typescript:
this.router.navigate([{ outlets: { flow: ['step1'] } }]);

it trying to navigate to wrong path '/child(flow:step1)'!!!
It just missing the slash.
Service:
import { Injectable } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { EventBusService } from '../../../services/eventBus/eventBus.service';
import { RouterService } from '../../../services/router.service';

@Injectable()
export class FlowManagerService {
  constructor(private router: Router, private r: ActivatedRoute, private     eventBus: EventBusService, private routerService: RouterService) {
  }

  initValidStep() {
    return     (parseInt(this.routerService.currentUrlName.substr(this.routerService.currentUrlName.indexOf('step'), 5).replace('step', ''), 10) === 1);
  }

  goToFirstStep() {
    this.router.navigate([{ outlets: { flow: ['step1'] } }], {relativeTo: this.r});

    this.eventBus.off(this.eventBus.globalEvents.FLOW.FLOW_STEP_NEXT);
    this.eventBus.off(this.eventBus.globalEvents.FLOW.FLOW_STEP_BACK);
  }

  next(params) {
    const currentStep = this.routerService.currentUrlName.substr(this.routerService.currentUrlName.indexOf('step'), 5).replace('step', '');

    this.eventBus.emit(this.eventBus.globalEvents.FLOW.FLOW_STEP_CHANGE, ({
      type: 'NEXT'
    }));
    this.router.navigate([{ outlets: { flow: [`step${parseInt(currentStep, 10) + 1}`, params] } }], {relativeTo: this.r});

    this.eventBus.off(this.eventBus.globalEvents.FLOW.FLOW_STEP_NEXT);
    this.eventBus.off(this.eventBus.globalEvents.FLOW.FLOW_STEP_BACK);

  }

  back(params) {
    const currentStep = this.routerService.currentUrlName.substr(this.routerService.currentUrlName.indexOf('step'), 5).replace('step', '');

    this.eventBus.emit(this.eventBus.globalEvents.FLOW.FLOW_STEP_CHANGE, ({
      type: 'NEXT'
    }));
    this.router.navigate([{ outlets: { flow: [`step${parseInt(currentStep, 10) - 1}`, params] } }], {relativeTo: this.r});

    this.eventBus.off(this.eventBus.globalEvents.FLOW.FLOW_STEP_NEXT);
    this.eventBus.off(this.eventBus.globalEvents.FLOW.FLOW_STEP_BACK);
  }

}

Here is the Module using the Service above:
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { FlowManagerService } from './service/flowManager.service';
import { CommonModule } from '@angular/common';

@NgModule({
  providers: [FlowManagerService],
  imports: [
    RouterModule,
    CommonModule
  ]
})
export class FlowManagerModule {

}

Answer: Because routerLink uses relativeTo option implicitly:
export class RouterLink {
  ...
  get urlTree(): UrlTree {
    return this.router.createUrlTree(this.commands, {
      relativeTo: this.route, <----

You need to provide it explicitly in router.navigate:
constructor(private route: ActivatedRoute)

this.router.navigate([{ outlets: { flow: ['step1'] } }], {relativeTo: this.route});

Here is plunker and the complete working code:
import { Component, NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { RouterModule, Routes, Resolve, Router, ActivatedRoute } from '@angular/router';
import { APP_BASE_HREF } from '@angular/common';

@Component({
  selector: 'my-app',
  template: `

          <router-outlet></router-outlet>

  `,
})
export class App {
  constructor() {
  }
}

@Component({
  selector: 'master-page',
  template: `

Master Component

          <button (click)='clickFirst()'>Inner Section 1</button>
          <button (click)='clickSecond()'>Inner Section 2</button>
          <router-outlet name='child'></router-outlet>

  `
})
export class Master {
  constructor(private router: Router, private activeRouter: ActivatedRoute) {
  }

  clickFirst() {
    this.router.navigate([{outlets: {child: 'details1'}}], {relativeTo: this.activeRouter});
  }

  clickSecond() {
    this.router.navigate([{outlets: {child: 'details2'}}], {relativeTo: this.activeRouter});
  }
}

@Component({
  template: `

          This content is in the "Inner" page (1)

  `
})
export class Details1 {
  constructor() {
  }
}

@Component({
  template: `

          This content is in the "Inner" page (2)

  `
})
export class Details2 {
  constructor() {
  }
}

const routes: Routes = [
  {
    path: 'master',
    component: Master,
    children: [
      {
        path: 'details1',
        component: Details1,
        outlet: 'child'
      },
      {
        path: 'details2',
        component: Details2,
        outlet: 'child'
      }
    ]
  },
  {
    path: '',
    pathMatch: 'prefix',
    redirectTo: 'master'
  }
];

@NgModule({
  imports: [BrowserModule, RouterModule.forRoot(routes)],
  declarations: [App, Master, Details1, Details2],
  providers: [{
    provide: APP_BASE_HREF,
    useValue: '/'
  }],
  bootstrap: [App]
})
export class AppModule {
}

Comment: can you setup a plunker?
Comment: [link](https://plnkr.co/edit/2HbHcjjKyg0KmEGGpT22?p=preview) here...

there is a base outlet and child outlet... every click should insert component to a child outlet...
Comment: @VladiIsakov, it's working fine for me. In your plunker there's a typo, you should use `outletS`, not `outlet`. I posted the working `app.ts` code in the question.
Comment: sorry about the typo, working for me too... in my code its still not working... it says "Error: Cannot match any routes. URL Segment: 'step1'"
Comment: I don't see your code. The answer to your question is correct as demonstrated by the example
Comment: I think that I finally got it... I'm trying to navigate in service and its not working, but when I navigate in component it works... how is that possible?
Comment: you're most likely injecting wrong `ActivatedRoute` into a service, where is this service defined? see [this answer](https://stackoverflow.com/a/39980190/2545680)
Comment: How can I perfect it?
Comment: where it's registered?
Comment: Added the module using the service
Comment: Fixed by giving the component that using the service "providers: [FlowManagerService]"... thank you for your help :)
Comment: yeah, if you define a service on the root module it will be injected root level activatedroute. you're welcome, good luck


Is possible use HoG features to train a Neural Network?

Question: I was wondering if it is possible use HoG features to train a Neural Network, I know that in the original paper by Dalal and Triggs they used the data generated to train a SVM.
If not is possible or suitable do you know a descriptor to get features in order to train a neural network.
Answer: Neural networks work on any data with consistent dimenionality.
If your images all have the same size, than the HOG features will also have consistent dimensionality over all images.
Indeed it is quite standard to train NNs on complexer features like HOG or SIFT instead of on the raw pixel data.
As a deeper point, HOG can be computed using NNs. In fact, the HOG computation can be seen as a specific instance of convolutional neural networks, albeit with some obscure connectivity restrictions and obscure kernel functions (like atan, and normalization functions).
This is a purely theoretical point, however - I would not recommend implementing HOG using NNs!


Problems with emmeans if RE-adjustment and backtransformation from logit

Question: In an experiment (4 sessions, 2 groups), subjects try to remember words.
We want to test

H1: the overall (marginal) main effect of group
H2: the specific interaction contrast of group and sesson1 _ 2

library(lme4)
library(lmerTest)
library(emmeans)
set.seed(123)

imgdat_final_shortterm[20:25, c("VP", "GROUP", "session", "items", "maxitems")]
#> # A tibble: 6 x 5
#>      VP GROUP     session items maxitems
#>   <dbl> <fct>     <fct>   <dbl>    <dbl>
#> 1     2 Imagery   3           6        8
#> 2     2 Imagery   3           6        8
#> 3     2 Imagery   4           6        8
#> 4     2 Imagery   4           6        8
#> 5     2 Imagery   4           7        8
#> 6     3 Rehearsal 4           5        8

fit <- glmer(cbind(items, maxitems - items) ~ session + GROUP + session:GROUP +
                                  (1 | VP),
                                data = imgdat_final_shortterm, family = binomial())

H1: Marginal group effect

After regrid due to the RE-adjustment, the z- and p-values change (see following). Am I doing something wrong?

emm_1_version2 <- emmeans(fit, specs = pairwise ~ GROUP, infer = c(T,T)
)
#> NOTE: Results may be misleading due to involvement in interactions

emm_1_version2[[2]]
#>  contrast            estimate    SE  df asymp.LCL asymp.UCL z.ratio p.value
#>  Imagery - Rehearsal  -0.0568 0.262 Inf     -0.57     0.456  -0.217  0.8281
#>
#> Results are averaged over the levels of: session
#> Results are given on the log odds ratio (not the response) scale.
#> Confidence level used: 0.95

regrid(emm_1_version2[[2]], bias.adjust = TRUE,
       sigma = as.numeric(attributes(lme4::VarCorr(fit)$VP)$stddev))
#>  contrast          odds.ratio    SE  df asymp.LCL asymp.UCL z.ratio p.value
#>  Imagery/Rehearsal       1.31 0.342 Inf     0.636      1.97   3.820  0.0001
#>
#> Results are averaged over the levels of: session
#> Confidence level used: 0.95

H2: group x session1_2
emm_2 <- emmeans(fit, specs = ~ session * GROUP, adjust = "none")

emm_2_contrasts <- contrast(emm_2, interaction = c("revpairwise", "pairwise"),
              bias.adjust = TRUE,
              sigma = as.numeric(attributes(lme4::VarCorr(fit_shortterm_assigned)$VP)$stddev)
              ,infer = c(T, T)
              , adjust = "none"
)
emm_2_contrasts
#>  session_revpairwise GROUP_pairwise      estimate    SE  df asymp.LCL asymp.UCL
#>  2 - 1               Imagery - Rehearsal   0.3025 0.191 Inf   -0.0714     0.676
#>  3 - 1               Imagery - Rehearsal   0.1586 0.193 Inf   -0.2196     0.537
#>  3 - 2               Imagery - Rehearsal  -0.1438 0.188 Inf   -0.5120     0.224
#>  4 - 1               Imagery - Rehearsal   0.0578 0.196 Inf   -0.3254     0.441
#>  4 - 2               Imagery - Rehearsal  -0.2447 0.190 Inf   -0.6177     0.128
#>  4 - 3               Imagery - Rehearsal  -0.1008 0.192 Inf   -0.4770     0.275
#>  z.ratio p.value
#>    1.586  0.1128
#>    0.822  0.4110
#>   -0.766  0.4438
#>    0.296  0.7675
#>   -1.286  0.1986
#>   -0.525  0.5994
#>
#> Results are given on the log odds ratio (not the response) scale.
#> Confidence level used: 0.95

Is this correct? Again, tests and p-values change:
regrid(emm_2_contrasts
       , transform = "response"
       , adjust = "none"
)
#>  session_revpairwise GROUP_pairwise    odds.ratio    SE  df asymp.LCL asymp.UCL
#>  2/1                 Imagery/Rehearsal      1.353 0.258 Inf     0.847      1.86
#>  3/1                 Imagery/Rehearsal      1.172 0.226 Inf     0.729      1.62
#>  3/2                 Imagery/Rehearsal      0.866 0.163 Inf     0.547      1.18
#>  4/1                 Imagery/Rehearsal      1.060 0.207 Inf     0.654      1.47
#>  4/2                 Imagery/Rehearsal      0.783 0.149 Inf     0.491      1.08
#>  4/3                 Imagery/Rehearsal      0.904 0.174 Inf     0.564      1.24
#>  z.ratio p.value
#>    5.243  <.0001
#>    5.182  <.0001
#>    5.324  <.0001
#>    5.115  <.0001
#>    5.254  <.0001
#>    5.210  <.0001
#>
#> Confidence level used: 0.95

Created on 2022-08-03 by the reprex package (v2.0.1)
Comment: Regrid puts everything on the response scale, AND forgets the previous structure altogether. If instead you do `summary(..., type = "response")`, it does the tests on the logit scale and then back-transforms the results. Read the vignette on transformations and note what it says under "timing is everything."
Comment: Then, the null column in the results is 1.38 insted of 1.00 which makes CI's very difficult to interpret:

I used: `summary(emm_2_contrasts , type = "response" , adjust = "none")`
Comment: Apparently because a RE-adjustment is involved. I came up with using regrid because of a similar case in https://github.com/easystats/modelbased/issues/57 (bottom). Do I need to take test- and p-values manually from the not regridded objects? And are the CI's still correct in the regridded one? They appear face-valid
Answer: Following up on some comments... I had said

Regrid puts everything on the response scale, AND forgets the previous structure altogether. If instead you do summary(..., type = "response"), it does the tests on the logit scale and then back-transforms the results. Read the vignette on transformations and note what it says under "timing is everything."

... and @Swarley responded

Then, the null column in the results is 1.38 insted of 1.00 which makes CI's very difficult to interpret: I used: summary(emm_2_contrasts , type = "response" , adjust = "none")

Yes, but...
The bias adjustment requested in the OP is manifested in a change to the inverse transformation that is used. That change, among other things, causes

Increases in the estimated odds ratios
Increases in the confidence limits for them
A shift in the null value from 1.0 to 1.38 (in your case)

It does seem surprising to have a null value of 1.38; however, by (1) we have made all the estimates larger as well; we moved the estimates, and we moved the target. That 1.38 is the value that corresponds to a null of 0 before back-transformation (with the bias adjustment included). So if you want the P values to be the same as what you had on the link scale, the corresponding null on the response scale is 1.38.
But you can't have it both ways. If you want to test against a null of 1.0 on the response scale, then I guess the regrid strategy is what you need; but obviously, that gives you different P values.
What parameter do you want to make inferences about?
Another way to think about this is to ask whether you want to make inferences about the mean, or the median? The situation we have here is that, due to subject variations, the distribution of the odds ratios is log-normal. The log-normal distribution has two parameters $\mu$ and $\sigma$. It is a skewed distribution. The mean of that distribution is $e^{\mu + \frac12\sigma^2}$, and the median is $e^\mu$. The greater is $\sigma$, the bigger the discrepancy between the mean and the median.
In your case, your subject variations are enough to make the mean odds ratio 38% greater than the median, as demonstrated by the null value of 1.38. But note the median does not depend on $\sigma$. So if you want to think in terms of the median odds ratio, just remove the bias adjustment from all of this and you are making inferences about the median odds ratio, which on the link scale is assumed to be normal so that the median and the mean are the same. Doing that and using type = "response" will put the null median odds ratio back at 1.0, your confidence intervals will be for the median odds ratio, and everything will have a simpler interpretation in that context because tests on the link scale go hand-in-hand with the back-transformed versions of those.
Comment: Great explanations, I really appreciate that!

I wonder whether the approach using the median and not RE-adjusting at all does not have its problems. In that case, I would still use the un-adjusted confidence intervals which are still conditional on the random effects of this particular study. The median point estimate would be alright, but its CI not.

I assume there is no simple way to calculate new z-values and p-values for the regrid object (e.g. based on a RE-adjusted SE)?

I would really like to see how this is done properly as this is a standard modeling case in psychology...
Comment: It's not conditional on the random effects, it is averaged over them. This is important, because the idea of random effects is that you can *expand* the scope of inference beyond the current study, in that the random subjects, etc. were sampled from the population of all subjects, etc. I don't see a problem with interpreting a CI of the mean of a normal population being interpreted as a CI for the median of some transformed version of that variable.
Comment: I am aware of what REs are, but I have difficulties to see why CIs of medians are not conditional on REs but averaged over them even if I did not do any RE-adjustment.
Comment: Well, in a simple design with 10 random subjects and 4 observations per subject, the variance of each treatment mean (on the link scale) is Var(subj)/10 + Var(error)/40. I'd call that the variance of an average with two random components. And our CI for the mean (which is equal to the median) on the link scale is the estimate +/- (about 2) * sqrt(above). And the median gets transformed directly when we transform to the response scale; so when we transform the CI endpoints to the response scale, we obtain a CI for the median. Maybe you can discuss this with a colleague?


Does there exist $N \in \mathbb N$ such that $\inf\{a_N , a_{N+1}, \cdots\}= \liminf a_n$?

Question:
If $\liminf a_n=m\in \mathbb R$, does there exists $N \in \mathbb N$ such that $\inf\{a_N, a_{N+1},\cdots\}= m$?

This is an intriguing question I encounter when I am learning the limit superiors and limit inferiors.
I think we can find such an $N$. But I'm struggling in proving it.
I guess it has something to do with the limit inferior being an increasing sequence.
Can anyone share their opinions/insights on this, and share some techniques dealing with limit superiors/inferiors?
Comment: Hint: If $a_n$ is increasing the $\mbox{inf} \{a_N, a_{N+1},...\}=a_{N}$.
Comment: You appear to be using $N$ to stand for a couple of different things, no?  Also, it';s hard to guess which of your numbers are meant to be subscripts.  Is aN+1  meant to be $a_{N+1}$ for example?
Comment: It would be easier to understand if you would repeat the headline-question inside of the question, with all the possibilities of better readability, such as distinguishing mathbord font N from simple N.
Answer: Take : $a_n=\frac{-1}{n}$, the limit inferior of this sequence is 0, but there is no $N\in\mathbb{N}$ such that $0=inf\{a_N,a_{N+1}.....\}$ .
Answer: No it is not true. Just consider the sequence $-1/n$.


How can I compile Boost 1.54.0 (1.54) for the iOS simulator (6.1) on OS X 10.8.4?

Question: I have successfully managed to compile several of the Boost libraries and create a framework for use with OS X, iOS, and the iOS simulator using this script: https://github.com/wuhao5/boost/blob/188e905626dbd522f65950102ed0c8ce77cb28e8/boost.sh based on Peter Goodliffe's work here: http://goodliffe.blogspot.com/2010/09/building-boost-framework-for-ios-iphone.html with Boost 1.53.0 using clang and linking against libc++.
The script fails when compiling for the iOS simulator with Boost 1.54.0 with the following error:/bin/sh: line 1: -ftemplate-depth-128: command not found.
I did quite a bit of digging and here is what I know:

In boost.sh, the iOS simulator bjam and compiler options include "-arch i386"
The release notes for Boost 1.54.0 state that "Boost no longer supports the 80386 target CPU"
Boost 1.53.0 appears to compile fine for OS X, iOS, and the iOS simulator using the same script
Boost 1.54.0 appears to compile fine for OS X and iOS itself using the same script

Here is what I think I know:

When passing "-d13" to bjam (to generate debug information), it appears that the variable "CONFIG_COMMAND" is not being set when building for the iOS simulator.  For the other configurations, this variable is set to the path to clang and includes the compiler options.  For the simulator, it is empty which I believe leads to the error above as when bjam attempts to run the compiler using this variable, it instead runs some appended options which begin with the template depth.  Therefore, the CONFIG_COMMAND variable does not appear to be being set properly causing the failure.

I have no idea why it's not being set as I don't know enough about the Boost build system to sift through the rest of the 100+MB output it generated with the "-d13" flag.  I suspect an incompatibility with the "-arch i386" option was introduced with 1.54.0.  I've tried changing this to "-arch i486" and "-arch x86_32" but the same problem occurs.
Has anyone else had success with this?  I'd like to use Boost.Log which is why I'm even attempting this.
Comment: I'm in the same boat as you, and I would like to know whether you or someone had finally solved this.

From what I know, "-ftemplate-depth-128: command not found" is probably the result of a blank substitution of a compiler, as in the following:

    ${COMPILER} -ftemplate-depth-128

Which is why the error makes it sound like ftemplate-depth-128 is intended as a command.
Comment: I haven't yet found a solution unfortunately.  I believe the compiler command is supposed to be set in ${CONFIG_COMMAND}.  For the iOS builds for the actual device lines like this appear in the debug output:
`toolset.handle-flag-value /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang++` shortly after a line that says:
`get .darwin.variable.295 = CONFIG_COMMAND`.
Comment: Which version of XCode are you using?
Comment: I'm using Xcode 4.6.3
Answer: I got it building with the boost.sh given here by changing the line in buildBoostForiPhoneOS()
./bjam -j16 --build-dir=iphonesim-build --stagedir=iphonesim-build/stage --toolset=darwin architecture=x86 target-os=iphone macosx-version=iphonesim-${IPHONE_SDKVERSION} link=static stage

to
./bjam -j16 --build-dir=iphonesim-build --stagedir=iphonesim-build/stage --toolset=darwin-${IPHONE_SDKVERSION}~iphonesim architecture=x86 target-os=iphone macosx-version=iphonesim-${IPHONE_SDKVERSION} link=static stage

Modified boost.sh with Boost pkg download and unpacking. Just need to run and all done!
Boost 1.54
MacOSx 10.8.4
Xcode 4.6.3

Comment: Great work. I extended @matthias's script to build for arm64 and x86_64 too. Here's the gist: https://gist.github.com/rsobik/7513324
Comment: OK, just trying to help with question: http://stackoverflow.com/questions/18888327/using-boost-on-xcode-5-apple-llvm-5-0 but I'm getting the following error using Xcode 5 DP6 under OSX 10.8: `boost.sh: line 252: /Users/andy/Applications/Xcode5-DP6.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin//ar: No such file or directory`.  Any idea how to fix this?
Comment: @trojanfoe I was having the same issue after running boost.sh the first time. The following seemed to help me (in that my machine is now busily building code instead of hanging on a lipo call):
`cd` to `{generated src dir}/boost_1_54_0/`
Run `./bootstrap.sh toolset=clang`
Rerun `boost.sh`
Comment: Here's a gist with the changes. Seems to work for me. https://gist.github.com/payco/6880661

I'm now running into Semantic Issues all over the standard library, but I think that's something deciding not to compile libc++ headers with c++11.
Comment: Actually, it looks like the script expects to find a version of `ar` in the bin folders for iphoneos and iphonesimulator. That's not necessarily the case. That assumption should be replaceable with an invocation to xcrun --sdk={iphoneos | iphonesimulator }
Answer: I figured this out a while ago by reading through diffs of every single jam file between boost 1.53.0 and 1.54.0, which was a serious undertaking.  I meant to post a patch, but just finding the cause took time I didn't have, and now I don't remember what it was.
At any rate, I DO remember the quick fix I used to move along and meet a deadline.  It is, for boost 1.54.0, to supply bjam with the "toolset=darwin-[version]~iphonesim" argument.  You can also give arm builds toolset=darwin-[version]~iphone, though it doesn't need it.
For example, using the iOS 6.1 SDK:
./b2 toolset=darwin-6.1~iphonesim architecture=x86 target-os=iphone macosx-version=iphonesim-6.1 link=static variant=debug  define=BOOST_TEST_NO_MAIN define=BOOST_TEST_ALTERNATIVE_INIT_API linkflags="-stdlib=libc++" -j2 -d+2 -sICU_PATH=/usr/local/icu --without-python --layout=tagged --build-dir="/Users/wix/Desktop/boost_1_54_0/_build/simd_build" --stagedir="/Users/wix/Desktop/boost_1_54_0/_build/simd_stage" --debug-configuration stage

If this doesn't work for you, let me know and if I have a moment I'll get the old build dir off backup to see if there's anything else I did.  The command above is from my histfile.
Also, FYI, to make the ICU check pass for arm builds targeting only v7 and v7s with ICU libs built likewise, apply the following patch to tools/build/v2/tools/darwin.jam:
460,464c460,465
<             if $(instruction-set) {
<                 options = -arch$(_)$(instruction-set) ;
<             } else {
<                 options = -arch arm ;
<             }
---
>             #if $(instruction-set) {
>             #    options = -arch$(_)$(instruction-set) ;
>             #} else {
>             #    options = -arch arm ;
>             #}
>       options = -arch armv7 ;

Also, more generally, you may need something like the following in your ~/user-config.jam:
using clang : : : <cxxflags>"-std=c++11 -stdlib=libc++" <linkflags>"-stdlib=libc++" ;

using darwin : 6.1~iphone
   : /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang++ -arch armv7 -arch armv7s -fvisibility=hidden -fvisibility-inlines-hidden -std=c++11 -stdlib=libc++ -miphoneos-version-min=5.1 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS6.1.sdk
   : <striper> <root>/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer
   : <architecture>arm <target-os>iphone
   ;

using darwin : 6.1~iphonesim
   : /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang++ -arch i386 -fvisibility=hidden -fvisibility-inlines-hidden -std=c++11 -stdlib=libc++ -miphoneos-version-min=5.1 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator6.1.sdk
   : <striper> <root>/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer
   : <architecture>x86 <target-os>iphone
   ;

Also, for boost::context to build correctly for the simulator, I needed to add the following to libs/context/build/Jamfile.v2:
alias asm_context_sources
   : asm/make_i386_sysv_macho_gas.S
     asm/jump_i386_sysv_macho_gas.S
   : <address-model>32
     <architecture>x86
     <binary-format>mach-o
     <target-os>iphone
     <toolset>darwin
   ;

Comment: Aldrich Co, my arguments don't make a framework.  I think making a framework is mostly a matter of putting all the boost headers and libs in the right places in a directory structure and merging libs.  Merging the libs is a bit tricky due to some of the individual .a files b2 creates containing object files with the same name; duplicates need to be renamed as you merge...  Note that the .sh file posted above does not do this and will have issues if you need codecvt.  I ended up writing a python script to work around this.  If you need it, I'll check if I can share it (I wrote it at work).
Comment: I'm interested to know more. The change to the b2 arguments you posted, does that create a .framework file like the script mentioned?
Comment: Erik, with your b2 arguments I am not able to build for architecture i386, just tested today with boost 1.54.
Comment: tetuje, I suggest trying it with the following in your ~/user-config.jam: (not enough space here, look at my edits above)
Answer: Based on responses in this post and scripts created by other people I put together a bash script that builds boost framework for iOS and OSX with Xcode 5, that means for armv7, armv7s, arm64, i386 and x86_64.
Check it out here https://github.com/mgrebenets/boost-xcode5-iosx.
I know for sure it builds boost starting with 1.49.0
Comment: Thanks for this! But it seems I am having some issues (commands extracted from bjam output):

g++ -x assembler-with-cpp -arch armv7 -o make_arm_aapcs_macho_gas.o -c make_arm_aapcs_macho_gas.S

The above seems working, but

g++ -x assembler-with-cpp -arch arm64 -o make_arm_aapcs_macho_gas.o -c make_arm_aapcs_macho_gas.S

just doesn't compile:

make_arm_aapcs_macho_gas.S:52:18: error: invalid variant 'save'
    mov a4, a1 @ save address of context stack (base) A4

Any insights?
Answer: For those interested in keeping up to date:
You can use the BOOST 1.57.0 with ofxiOSBoost static libraries and headers:
https://github.com/danoli3/ofxiOSBoost
Releases for libc++ (c++11), libstdc++.
All build scripts are in the /scripts folder (updated Peter Goodliffe script)
Comment: I am interested in keeping up to date with the framework.


O que é a tecnologia JNDI?

Question: Estou iniciando estudos sobre aplicações corporativas, e  segundo o meu professor vou  precisar dessa tecnologia java e gostaria  saber o que exatamente é o JNDI.Se possível queria um exemplo de seu uso.
Answer: O que é?
JNDI é uma API utilizada em aplicações que acessam recursos externos, ela permite obter esses recursos através do nome. Ela especifica a interface de serviço SPI e esse mecanismo permite que o suporte de vários serviços de diretório, como : LDAP, DNS, NIS, RMI, CORBA, entre outros. A aplicação que utiliza JNDI busca os recursos através de um método chamado lookup.Esta API possui um ambiente de configuração, e através dele podemos passar várias informações, estas devem ser informadas na criação de um contexto, podendo ser por um arquivo.properties ou um HashTable.
Caso um HashTable seja utilizado podemos inserir os seguintes paramentros:
Context.INITIAL_CONTEXT_FACTORY  → Utilizado para informar a classe responsável pela criação do InitialContext. Geralmente ela depende do servidor de aplicação utilizado na aplicação;
Context.PROVIDER_URL → Utilizado para informar a URL do provider. Também depende do servidor de aplicação utilizado;
Caso seja um serviço com autenticação, utilizamos os parâmestros abaixo para informa-las ao ambiente de configuração:
Context.SECURITY_PRINCIPAL → Para informar usuário;
Context.SECURITY_CREDENTIALS → Para informar a senha;
Caso um arquivo properties seja utilizado devemos definir os nomes :
java.naming.factory.initial → Utilizado para informar a classe responsável pela criação do InitialContext. Geralmente ela depende do servidor de aplicação utilizado na aplicação;
java.naming.provider.url → Utilizado para informar a URL do provider;
java.naming.security.principal → Para informar usuário;
java.naming.security.credentials →  Para informar a senha;
Os nomes colocados no arquivo properties são os mesmos representados pelos atributos da classe context ou InitialContext.
Os parametros mostrados anteriormente são os mais utilizados, mas temos diversos outros que podem ser encontrados na documentação da classe  javax.naming.Context;
É possível definir uma classe que faz a criação do InitialContext ao invés de utilizar uma classe fornecida por um servidor de aplicação, para isto deve-se estender a classe InitialDirContext  e também ter uma interface que implementa a interface DirContext.
Os recursos ficam armazenados em uma área que pode ser chamada de namespace, e nela podemos buscar tais recursos para a utilização em nossa aplicação, atravé do lookup.
Existem 3 tipos de namespace:
java:global
É a maneira portatil de busca remota de um EJB usando JNDI lookup.
Ela segue o seguinte padrão:
java:global[/application name]/module name/enterprise bean name[/interface name]
java:module
É a maneira de busca do EJB dentro do mesmo módulo.
java:module/enterprise bean name/[interface name]
java:app
É a maneira de busca do EJB dentro da mesma aplicação.
java:app[/module name]/enterprise bean name[/interface name]
Exemplo utilização:
Por exemplo, se um EJB , mybean, é empacotado dentro de um WAR  myApp.war, o nome do módulo é myApp. O nome JNDI portátil é java:module/mybean Um nome JNDI equivalente usando o java: namespace global é java:global/myApp/mybean.
Agora é hora de entender o funcionamento do lookup, como já sabemos ele é usado para fazer chamadas de recursos externos como EntityManager, EJBs, entre outros.
Para acessar qualquer um dos namespaces citados acima temos que utilizar o lookup e este método pode ser direto, ou seja, ele pode acessar diretamente o endereço do recurso no namespace global da aplicação ou portatil, ou seja, um endereço lógico é definido na aplicação para a chamada dos recursos, para isto deve-se usar o endenreço da seguinte forma "java:comp/env/nome_lógico."
Agora com um entendimento sobre o lookup vamos discutir sobre a diferença entre usar um lookup portatil ou direto.
Lookup Direto e Portátil respectivamente:

Através das imagens podemos ter uma ideia do problema de usar um lookup direto, caso existam vários servidores ou vários containers EJB em um ambiente corporativo pode ser necessário a redefinição dos nomes JNDI, o que pode levar a um grande trabalho no momento de implantação e principalmente de integração da aplicação desenvolvida com sistemas que já estão em funcionamento.
OBS: Encontrei uma explanação muito simples e objetiva. Por isso fiz um copy & past. Retirei o conteúdo do site: http://www.pognao.com.br/2012/05/entendo-o-funcionamento-do-metodo.html

O que é a tecnologia JNDI?


On the number of possible solutions for a quadratic equation.

Question: Solving a quadratic equation will yield two roots:
$$\frac{-\sqrt{b^2-4 a c}-b} {2 a}$$
and:
$$\frac{\sqrt{b^2-4a c}-b}{2 a}$$
And I've been taught to answer it like:
$$\frac{\pm\sqrt{b^2-4a c}- b}{2 a}$$
Why does it yields only two solutions? Aren't there infinite solutions for that? Is there a proof on the number of possible solutions for a quadratic equation?
Comment: [As Gauss said...](http://en.wikipedia.org/wiki/Fundamental_theorem_of_algebra)
Comment: There are two solutions because $a,b,c$ are all *given* to you. You aren't choosing them: by the time you're applying this formula you should know what they are. So the only thing you have to choose is the $\pm$, giving you two solutions.
Comment: Ah, I see. In which case, as others have shown, it's because there are two values of $x$ for a given $x^2$ (say, $2$ and $-2$ for $4$), and so when you're solving the equation you have to consider both. You get two for the price of one.
Comment: Uhhhh...no. For constant (real number) values of $a$, $b$, and $c$, the polynomial equation $ax^2 + bx + c = 0$ has at most two real roots--and has exactly two complex roots.
Comment: Your general solution is wrong. It must be $$\frac{-b\pm\sqrt {b^2-4ac}}{2a}=\frac{\pm\sqrt{b^2-4ac}-b}{2a}$$
Comment: @DonAntonio Fixed, thanks.
Comment: @RobertMastragostino Why there's a $\pm$ instead of $+$ or $-$?
Comment: That's what I meant by that, sorry if that wasn't clear. The $\pm$ gives you two choices, $+$ and $-$.
Comment: @RobertMastragostino No, it's not that: What I tried to ask was something like this: "Someday, someone solved a quadratic equation with, say, with $\frac{\sqrt{b^2-4a c}-b}{2 a}$. How did one had the idea of doing $\frac{-\sqrt{b^2-4a c}-b}{2 a}$ to get the second root? Was it a [combinatorial technique](http://en.wikipedia.org/wiki/Rule_of_product) based on *"let's try all possible operators here"* or there's another kind of heuristic behind it?
Comment: @RobertMastragostino +200! (If I could) you answered a parallel question that was bugging me. Thank you so much!
Answer: Think about the graph of $y = ax^2 + bx + c$ (where $a \ne 0$). It's a parabola. It may be concave or convex, depending on whether $a>0$ or $a<0$, but it's still a parabola. The roots of $ax^2 + bx + c = 0$ are the places where $y=0$; in other words, the places where this parabola crosses the $x$-axis. Usually, there will be either two crossings, or none. There's a special case when the parabola just touches the axis. In this case, the quadratic has two equal roots.
This isn't a "proof", but it may help your intuition.
Answer: One can see that there are only two solutions from the way it is solved. If $ax^2+bx+c=0$ with $a\neq 0$, it follows that $ax^2+bx=-c$, so that $x^2+\frac{b}{a}x=-\frac{c}{a}$. Trying to complete the square, one obtains $(x+\frac{b}{2a})^2=x^2+\frac{b}{a}x+(\frac{b}{2a})^2=(\frac{b}{2a})^2-\frac{c}{a}=\frac{b^2-4ac}{4a^2}$. Taking square roots, the result follows.
Answer: Any polynomial equation of the form
$$a_nx^n+a_{n-1}x^{n-1}+...+a_1x+a_0=0\,\,,\,\,a_i\in\Bbb C$$
has exactly n solutions, counting multiplicities (this much is true over more general fields, of course)
Thus, a quadratic over any field has two roots over any algebraically closed field. If you're working over the reals though, then sometimes there are no real roots (solutions) to a quadratic, but there always be two solutions on the complex field.
Answer: This is to do with the fact that every polynomial over the complex numbers has a "unique factorization". The proof is based on Euclidean algorithm for polynomials.
It is not the case anymore when you allow solutions outside the domain of complex numbers. For example, there are infinitely many quaternions that satisfy $x^2 = -1$.
Answer: A more important question: Why should there be infinitely many solutions?
The roots/solutions of a quadratic equation $ax^2 + bx + c = 0$ are given by looking at when the graphs $y = ax^2 + bx + c$ cuts the $x$-axis. Remember that $a$, $b$ and $c$ are all fixed numbers, e.g. $y = x^2 + 2x + 1.$  Ask yourself this: Why should there be infinity many values of $x$ for which $x^2 + 2x + 1 = 0$? In fact, there is only one single value of $x$ for which $x^2 + 2x + 1 = 0$. This is because $x^2 + 2x + 1 = (x+1)^2$ and so $x = -1$ is the only solution. Find me another value of $x$ for which $x^2 + 2x + 1 = 0$ and I will give you US$1,000,000.
Draw yourself some sketches. Draw the one-parameter family of parabolae given by $y = x^2 - k$ where $k$ is a number we're going to play with. When $k > 0$, the parabola cuts the $x$-axis at two distinct points: $x = \pm \sqrt{k}$. When $k = 0$, the parabola cuts the $x$-axis at one point: $x = 0$. When $k < 0$, the parabola misses the $x$-axis altogether.
Comment: "Find another value to $x$..." Sorry, TD4I.


ERRO: Object of class mysqli_result could not be converted to int

Question: Olá! Estou desenvolvendo um site de compra de um jogo que possui uma página para registrar as informações de cada compra, entre elas, a quantidade de jogos comprados.
Eu queria que, durante o salvamento das informações, a quantidade de jogos comprados fosse subtraída do estoque.
Minha tentativa:
<code><?php

    $nome               = $_POST['NOME'];
    $cpf                = $_POST['CPF'];
    $email              = $_POST['EMAIL'];
    $quantidade         = $_POST['QUANTIDADE'];
    $pagamento          = $_POST['PAGAMENTO'];

    $strcon = mysqli_connect('localhost','root','', 'ecoventura') or die('Erro ao conectar ao banco de dados');
    $jogos = mysqli_query($strcon, "select JOGOS from estoque");
    $novaquan = $jogos - $quantidade; //ESSA É A LINHA DO ERRO

    $sql = "INSERT INTO compra (NOME, CPF, EMAIL, QUANTIDADE, PAGAMENTO) VALUES ('$nome','$cpf', '$email', '$quantidade', '$pagamento')";
    $modifica = "UPDATE  `ecoventura`.`estoque` SET `JOGOS` = '$novaquan'";

    mysqli_query($strcon,$sql) or die("Erro ao tentar cadastrar registro" . mysqli_error($strcon));
    mysqli_query($strcon,$modifica) or die("Erro ao tentar modificar estoque" . mysqli_error($strcon));
    mysqli_close($strcon);
    /*echo '<script type="text/javascript">
            alert("Salvo com Sucesso !");
            window.history.go(-1);
        </script>';*/

?>
</code>
O formulário até salva as informações, mas a coluna jogos tem um registro e aparentemente $jogos contem a quantidade de registros e não o conteúdo dele.
O erro apresentado é esse:

Notice: Object of class mysqli_result could not be converted to int
  in C:\EasyPHP5.2.10\www\ecoventura\salva-form.php on line 13

Como posso pegar o conteúdo do registro e não sua quantidade?
Comment: Errado. Você não está pegando a quantidade, está pegando o conteúdo, só está utilizando o retorno de forma errada. Vide documentação, o retorno da função `mysqli_query` é uma instância de `mysqli_result`, então estude a [documentação](https://www.php.net/manual/pt_BR/class.mysqli-result.php) para verificar como trabalhar com esse objeto.
Comment: Também não. Como o próprio nome da função diz, `num rows` retorna a quantidade de registros retornado na consulta. *Returns **number of rows** in the result set*. O que você precisa são as funções *fetch*.
Comment: O retorno da função `mysqli_query` não é um número, então não faz sentido fazer uma operação algébrica com `$jogos`, como fez. Você selecionou a coluna jogos de todos os registros da tabela estoque, qual seria o resultado esperado para `$jogos - $quantidade`?
Comment: Ah, então é por isso que tá dando -4. Jogos tá recebendo 1 porque só tem um registro. Como eu faço pra pegar o conteúdo desse registro e não a quantidade de registros?
Comment: Então, eu não sei se eu entendi direito mas lendo a documentação parece que aquele mysqli_num_rows ( mysqli_result $result ) : int pega o conteúdo do registro, mas tentei usar e não funcionou. Por que?
Answer: O problema está na verdade entre as linhas 10 e 11 do teu código.
<code>    (linha 10) $jogos = mysqli_query($strcon, "select JOGOS from estoque");
    (linha 11) $novaquan = $jogos - $quantidade; //ESSA É A LINHA DO ERRO
</code>
Na linha 10, $jogos retornará FALSE caso não encontre nenhum dado para a consulta ou um array de objetos, logo o ideal seria primeiro tratar esse resultado para então rodar a função do PHP mysqli_num_rows() para retornar o número de linhas para o resultado da consulta:
<code>   if ($result = mysqli_query($link, "select JOGOS from estoque")) {

        /* determine final result */
        $TotalDeJogosEncontrados = mysqli_num_rows($result);
        $novaquan = $TotalDeJogosEncontrados - $quantidade;

        /* return a row from result */
        $row = mysqli_fetch_assoc($result);

        /* close result set */
        mysqli_free_result($result);
    }
</code>
Comment: Uai para pegar o conteúdo de um mysqli_result, retornar uma linha e tal é só usar o mysql_fetch_assoc.

$row = mysqli_fetch_assoc($result);
$JogoData = $row["JOGOS"];
Comment: O retorno não é falso quando não encontra dados, nem array quando encontra. Em ambas as situações o retorno é uma instância de `mysqli_result`. Falso só é retornado em casos de falha durante a execução da SQL.
Comment: Está na documentação do PHP que mysqli_result Returns FALSE em caso de falha, tanto que se não tiver resultado não entra no if. Agora com relação ao retorno, realmente me expressei mal retornará uma instância do mysqli_result.
Comment: Nesse caso não encontrar registros é considerado falha? Não lembro deste detalhe.
Comment: Eu tentei usar seu código e adicionei mais um registro na coluna jogos, que agora possui dois registros. Dei um var_dump() e percebi que o $TotalDeJogosEncontrados tá retornando a quantidade de registros da coluna. Como essa coluna sempre terá somente um registro eu gostaria de pegar o conteúdo dele. Como faço isso?


gamblers fortune expectation[ith game winnings] = 0. Why?

Question: I couldn't understand the expression below for the problem,
consider a gambler who plays a sequence of fair games. Let $X_i$ be the amount the gambler wins on the $i^{th}$ game ($X_i$ is negative if the gambler loses), and let $Z_i$ be the gambler's total winnings at the end of the $i^{th}$ game. Because each game is fair,

$\mathbb{E}[X_i] = 0$

and $\mathbb{E}[Z_{i+1}|X_1, X_2, ..., X_i] = Z_i + \mathbb{E}[X_{i+1}] =Z_i$
Why is $\mathbb{E}[X_i] = 0$. Even with fair/unbiased coin tosses the expectation of heads is 1/2?
Comment: $\mathbb E[X_i]=0$ by assumption...the fact that there is some other variable that has a non-zero expectation doesn't seem relevant.  If you want to use the coin toss as an example, make a fair game out of it by saying you win $1$ if it comes up $H$ and you lose $1$ if it comes up $T$.  The expectation of that is $0$.
Comment: To your other question, knowing $X_1,\cdots, X_{i}$ tells us $Z_i$ but, assuming that all the games are independent, they tell us nothing about the outcome of $X_{i+1}$.  Thus, starting from $Z_i$ you expect the next round to return $0$, so the expected value stays the same.
Comment: You mixed the amount of money the player wins ( a loss is considered as a negative win) with the fraction of the number of heads to the total number of tosses. If the coin shows head in exactly the half of the tosses, the player won exactly amount $0$.
Comment: Somewhat sloppy formulated does $E(X)=0$ mean that the average outcome is that the player does not win or lose anything.
Answer: Since in gamble we win (+1) or lose(-1) the expectation  = 1(1/2) + (-1)(1/2) = 0 wheras
in coin toss we lose(0) and win(1), the expectation = 1(1/2) + 0(1/2) = (1/2).


Magento Store URLS don't use the info to show in FB

Question: I've develop an online store, and created a FB app, and integrated with a social share module.
As you can see in this page ( http://www.citromen.com/en/c/c3-ii/travagem/discos-de-trav-o-frente-ebc-ultimate-sloted-rotor.html ) I've the xml namespaces in html tag, the og:xpto tags in head...
I've I try to share, don't show the title, description or image.
What I'm missing? :(
Thanks in advance
Answer: One possible cause is that the result is cache by facebook.
Did you try clearing facebook cache using https://developers.facebook.com/tools/debug
Also see Facebook object debugger: Could not retrieve data from URL. (200)
Comment: Yes, I try to use the tool, the code is 200, but the tool don't fetch the data...
Because I fail all my ideas, I need the community to help in this matter... :(
Edit: Thanks for the second link!
Comment: Did you take a look @ http://stackoverflow.com/questions/10786209/facebook-object-debugger-could-not-retrieve-data-from-url-200
Answer: In FB Open Graph page https://developers.facebook.com/docs/opengraphprotocol/ they some the xml namespaces to opengraph and facebook in html tag.
I've that in my page and do not work...
In the test suggested by @R.S. I remove these two namespaces... Started to work...
Thanks for the guide...


Share feedback review option - adding link to homework FAQ

Question: In the new "First questions" review queue there is an option to "Share feedback". The current choices are the "unclear" and "too broad" close reasons, but you can share these here without initiating the vote to close.
Is it possible the add the "problematic homework" explanation with a link to the FAQ?

Edit: This question incorrectly stated that the "opinion-based" share feedback option was already implemented, but it isn't. Is it possible to add that as well?
Comment: I tried to research way to edit it and unless I missed something we mods cannot edit those messages so I added status-review tag to your Q, some CM's can either help or explain why it can't be at the moment implemented
Answer: It's currently not possible customize changes here on an individual site. Currently changes in the review queue are network wide which is why I updated the tag to status-declined. Customizing close reasons isn't on the current roadmap. If it's something that is prioritized in the future we can revisit this request.


How to print an entity bundle field from one with multiple values

Question: Struggling to find the answer to this. I have an entity called "school objects" which has a bundle called "homepage". One of the fields attached to this is called "Hero banners" and it allows multiple text values.

All I want to do is print each value. I don't need to check for conditions, I don't need NIDs, I just want each value. I am not really a php developer but understand the basics of what it is doing. I was looking into the EntityFieldQuery code, but cannot get anything to print on a tpl file I am using.
The output I need, based on image attached, is simply:

images/symbol.png

Let's make a difference

Start today

All I can find after a lot of searching is complex bits of code checking for conditions and stuff that I do not need. I need some kind of array I think so that my template looks like:

Value[0]

Value[1]

Value[2]

All I got so far is this:
query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'school_objects')
  ->entityCondition('bundle', 'homepage')
  ->range(0, 14);
$result = $query->execute();

I have read the link to this on the Drupal site but cannot understand it or how to print what I need.
Answer: Try the following and load the actual entity to get its field values.
The code assumes you have drupals entityTypeManager injected via dependency injection. Otherwise use \Drupal::entityTypeManager() isntead of $this->entityTypeManager()
// Get the entity ids.
$entityIds = $this->entityTypeManager()->getStorage('school_objects')->getQuery()
  ->condition('type', 'homepage')
  // Add more conditions if you need.
  ->execute();
// I assume only one id is returned and reset the array. Otherwise go over
// each Id with a foreach() and do this in a loop.
$entityId = reset($entityIds);
$schoolObject = $this->entityTypeManager()->getStorage('school_objects')->load($entityId);
// Now get the values of your field. I assume the fields machine_name is 'field_hero_banners'. Adjust if needed.
$values = $schoolObject->get('field_hero_banners')->getValue()
// Loop over all values.
foreach ($values as $item) {
  $value = $item['value'];
}

Comment: This just breaks the page. Also this bit "\Drupal::entityTypeManager()" I tried instead of the other line and that also breaks the page. Do I add most of this code to the top of the page, then the loop bit between my html tags? I am total novice with php.
Comment: well, this code should be part of a Controller class or something similar. In a drupal way I'd add this code to a controller, prepare the array of values for a twig template, add a custom twig template with a loop to print those values between your html tags. You can't just put this code in a html file. That means this is part of a custom module. I could help you with that, but I doubt this would help you, given your little knowledge of php/drupal?
Comment: No idea what a controller class or a twig is. Was trying to adapt some existing php that is on a tpl file. But seems I am years away from that at the moment. Thanks for your help, this might help someone on a higher level than me.
Comment: I think the sample of code in the question for drupal 7, and your code snippet for drupal 8, @Rich Stevens which version of drupal you use ?
Comment: Drupal 7.I also made it this far now: `entityCondition('entity_type', 'school_objects')
->entityCondition('bundle', 'homepage');
$result=$query->execute();
if (!empty($result['school_objects'])) {
$nids=array_keys($result['school_objects']);
$entity_testimonails=entity_load('school_objects', $nids);
foreach($entity_testimonails as $testimonails) {
$wrapper=entity_metadata_wrapper('school_objects', $testimonails->id, array('bundle' => 'homepage'));}}?>

field_hero_banners->value());?>` .
Comment: ok where did you put that come, which hook , which file ?
Answer: <?php
$wrapper = entity_metadata_wrapper('school_objects', '353', array('bundle' => 'homepage'));
$homepage_hero_banners = $wrapper->field_hero_banners->value();
?>

<?php echo $homepage_hero_banners[1]; ?>

<?php echo $homepage_hero_banners[2]; ?>

It has taken 4 days for me to get this code. I truly hope this helps someone else!


Memory level for Ceph logs. What's this for?

Question: I want to increase the logging level of some OSDs, but I don't understand what the memory level is for. I didn't find an exact explanation in the documentation. Is there a need to increase this level? OSD logs are written in rsyslog.
Answer: After some research, I understand that this is the level of logs directly stored in memory and they can be read in the log file after the command is executed:
<code>ceph daemon osd.X log dump
</code>


Renice: How to change all threads?

Question: When I renice a multithreaded process in Ubuntu 10.04, then view the results in top, it seems that only the main thread actually gets reniced.  All the other threads retain their old nice value.  What's the easiest way to renice all threads in a process instead of just the main thread?
Answer: renice +/-n -g gid

Where gid is the process group id which you can find with
ps -Aj
Answer: Inspired by zhihui's answer, what I actually used:
renice -n <niceness> -p `ps --no-heading -Lo tid <PID>`

Answer: The following command can set the nice value to +15 for all threads in process "procid":
ps --no-heading -Lj <procid> | awk '{system("renice +15 "$4)}'

Renice: How to change all threads?


Home runs on back to back pitches

Question: Related to this question, I'm wondering how many times in MLB history a team has hit home runs on consecutive pitches. That is 2, 3, or 4 home runs in as many pitches.
Please provide the team, date and players hitting the homers.
Answer: On September 18th, 2006, J.D. Drew, Russell Martin, and Marlon Anderson hit home runs on 3 consecutive pitches. Drew hit a home run off Jon Adkins. Martin and Anderson hit home runs off Trevor Hoffman.
I checked all of the instances of teams hitting 4 consecutive home runs, and this was the only one I found in which 3 were hit on consecutive pitches. However, there were 3 instances in the 1960's that didn't have pitch count available.
It's very likely that 3 is the record.
Comment: Tied by the Yankees in the 4th inning against the Blue Jays on September 17, 2020 by Brett Gardner (5th of the season), DJ LeMahieu (10th) and Luke Voit (20th) on consecutive pitches. In addition, Giancarlo Stanton (4th) and Gleyber Torres (3rd) also hit dingers for a total of 5 home runs (7 total runs) in the inning. The 5 home runs in an inning also ties a major league record.
Answer: Tied by the Los Angeles Angels, against the Colorado Rockies, on June 24, 2023.
In the third inning, Mike Trout homered on a 1-0 count, followed by Brandon Drury and Matt Thais both homering on the first pitch.
Chase Anderson was the pitcher.  He was also the pitcher who allowed three home runs on consecutive pitches by the New York Yankees, when pitching for the Blue Jays, on September 17, 2020.
Answer: Tied by the Yankees in the 4th inning against the Blue Jays on September 17, 2020 by Brett Gardner (5th of the season), DJ LeMahieu (10th) and Luke Voit (20th) on consecutive pitches. In addition, Giancarlo Stanton (4th) and Gleyber Torres (3rd) also hit dingers for a total of 5 home runs (7 total runs) in the inning. The 5 home runs in an inning also ties a major league record.
Answer: Tied by the Cincinnati Reds, on May 5, 2019.
In the first inning, Eugenio Suarez, Jesse Winker, and Derek Dietrich all homered off Jeff Samardzija, of the San Francisco Giants.

Home runs on back to back pitches


How to resolve the SSL error with local copy of site on Dev Desktop?

Question: I am running a local copy of my site on Acquia Dev Desktop and everything is working fine.
The site is set to enforce SSL connection when logging in to the sitename.com/admin page. However, since it is now installed on my localhost, it does not have an SSL certificate and throws the error like so:
SSL connection error
Unable to make a secure connection to the server. This may be a problem with the server,
or it may be requiring a client authentication certificate that you don't have.
Error code: ERR_SSL_PROTOCOL_ERROR

What can I do in order to get around this, and log in to my page administratively?
Comment: How are you going about forcing the ssl on login?  Module or .htaccess etc?
Answer: DevDestop now supports this.
https://docs.acquia.com/dev-desktop2/sites
Acquia Dev Desktop now provides simulated HTTPS support using a self-signed SSL certificate, which supports local testing and development of websites that rely on SSL. Learn more.
Just download a new version of DevDesktop. I'm currently on Version 2, Control panel rev: 032976b and have it working with sites that use SSL.
Answer: On the Config settings from Acquia Dev Desktop >> Preference >> Config:
Now Select Apache Module (mod_php) and hit OK Button. That's All the SSL Connection Error has Fixed.
Answer: DevDesktop doesn't have mod_ssl included in its version of Apache.
The only way to go about it is to disable the site configuration that enforces SSL. If it's .htacess, you can edit the root .htaccess file to remove the HTTPS redirect rules. If it's a module like securepages, you can disable it directly in the system database ("UPDATE system SET status = 0 WHERE name = 'securepages' AND type = 'module' ), or better, use Drush to disable it from the console (e.g. "drush dis securepages").


Assigning tasks to specific machines with airflow

Question: I'm new to Airflow.
I have a DAG which contains a task that should run on a specific machine (EMR cluster in my case). How can I tell airflow where to run specific tasks so that every time it will run it will do so on that machine only?
Answer: Run your worker on that machine with a queue name. In the airflow cli you could do something like:
airflow worker -q my_queue

Then define that task to use that queue:
task = PythonOperator(
    task_id='task',
    python_callable=my_callable,
    queue='my_queue',
    dag=dag)

Comment: Please ask questions as actual questions, and not in comments. The questions and answers here in a comment chain will not easily be found by someone with the same issue.
Comment: suppose I add another `airflow worker` to the mix, do I need to edit `celeryd_concurrency` in the airflow.cfg if I add a worker with more than the previously defined concurrency value?  Or could I simply override it with `airflow worker -c 12` (if I load up a box with 12 concurrent threads)
Comment: additionally -- suppose I have 5 independent tasks that lead to another task (i.e., 5 independent chains of A->B).  if I run them with `CeleryExecutor` with `concurrency = 4`, none of tasks B will start until all of tasks A finish.  That means that 4 threads will work on task A; when they're done, three threads will sit idle while another thread will work on task A. once all finish, they get to task B. any ideas about this?
Comment: would running `airflow worker -q my_queue` take advantage of all processors on that cluster? or do you need to run multiple `airflow worker` commands
Comment: is it possible to have dynamic queue name like queue='{{ ti.xcom_pull("provide_queue_name") }}' ?
Comment: I think you would need to start a worker on each individual box, at least if using Celery. If using Mesos I'm not sure.
Comment: @jhnclvr, I can see below line in documentation.
queue (str) – which queue to target when running this job. Not all executors implement queue management, the CeleryExecutor does support targeting specific queues.
Why is that there?


Installation Profile: $install_state['task_not_complete'] = TRUE doesn't seem to work

Question: I need to set up multiple user in the last step of my install profile. My idea was to create a form like  form_example_tutorial_9
But every time I click on the add_teammember button my form is submit and go to the last task which display the link "Visit your site". Although the user as been created I'm unable to display the form again in order to add other team members
So here is my code in the .profile file:
<code>/**
 * Implements hook_install_tasks().
 */
function drupal_base_install_tasks() {
  $tasks = array(
    'team_members_form' => array(
      'display_name' => st('Team members'),
      'type' => 'form',
    ),
  );
  return $tasks;
}

function team_members_form($form, &$form_state) {
  $form['#tree'] = TRUE;

  $form['description'] = array(
    '#type' => 'item',
    '#title' => st('Setup team members accounts'),
  );

  if (empty($form_state['num_members'])) {
    $form_state['num_members'] = 1;
  }

  // Build the number of member fieldsets indicated by $form_state['num_members']
  for ($i = 1; $i <= $form_state['num_members']; $i++) {
    $form['member'][$i] = array(
      '#type' => 'fieldset',
      '#title' => st('Member #@num', array('@num' => $i)),
      '#collapsible' => TRUE,
      '#collapsed' => FALSE,
    );

    $form['member'][$i]['name'] = array(
      '#type' => 'textfield',
      '#title' => st('Name'),
      '#description' => st("Enter member's name."),
      '#size' => 20,
      '#maxlength' => 20,
      '#required' => TRUE,
    );

    $form['member'][$i]['email'] = array(
      '#type' => 'textfield',
      '#title' => st("Enter member's email"),
      '#required' => TRUE,
    );

    $form['member'][$i]['password'] = array(
      '#type' => 'textfield',
      '#title' => "Enter member's password",
      '#required' => TRUE,
    );
  }

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Save and continue',
  );

  // Adds "Add another member" button
  $form['add_members'] = array(
    '#type' => 'submit',
    '#value' => st('Add another member'),
    '#submit' => array('add_another_team_member'),
  );

  // If we have more than one member, this button allows removal of the
  // last member.
  if ($form_state['num_members'] > 1) {
    $form['remove_member'] = array(
      '#type' => 'submit',
      '#value' => st('Remove latest member'),
      '#submit' => array('remove_latest_team_member'),
      // Since we are removing a member, don't validate until later.
      '#limit_validation_errors' => array(),
    );
  }

  return $form;
}

function team_members_form_validate(&$form, &$form_state) {
  for ($i = 1; $i <= $form_state['num_members']; $i++) {
    if (!valid_email_address($form_state['values']['member'][$i]['email'])) {
      form_set_error('email', t('Please enter a valid email address'));
    }
  }
}

function team_members_form_submit($form, &$form_state) {
  $values = $form_state['values'];

  for ($i = 1; $i <= $form_state['num_members']; $i++) {
    $account = array(
      'name' => $values['member'][$i]['name'],
      'pass' => !empty($values['member'][$i]['password']) ? $values['member'][$i]['password'] : user_password(),
      'mail' => $values['member'][$i]['email'], 'status' => 1,
      'init' => $values['member'][$i]['email'],
    );
    $account = user_save(null, $account);

    // Assign the member of the team to the "administrator" role.
    $role = user_role_load_by_name('administrator');
    db_insert('users_roles')
      ->fields(array('uid' => $account->uid, 'rid' => $role->rid))
      ->execute();
  }
}

function add_another_team_member($form, &$form_state) {
  //reload the same step
  //$install_state['task_not_complete'] = TRUE;
  $form_state['num_members']++;
  $install_state['task_not_complete'] = TRUE;
  return drupal_render($form);
}

function remove_latest_team_member($form, &$form_state) {
  if ($form_state['num_members'] > 1) {
    $form_state['num_members']--;
  }
  $form_state['rebuild'] = TRUE;
}
</code>
My question:
Inside the function add_another_team_member, I don't want the installation to go to the next step but I want it to display the form again. That's the reason I used $install_state['task_not_complete'] = TRUE. But the installation continue to the next and final step anyway.
Thanks.
Comment: Can you post the code for your entire form? It's impossible to debug with just two lines of code. The example you've linked to contains no reference to a variable called `$install_state`, please also make it clear how that's involved.
Comment: Thanks, I've added the code. I hope it will help to explain my question.
Comment: Certainly does :) Not sure if it will fix the problem completely, but you need to add `global $install_state;` to the `add_another_team_member()` function to access the global var
Comment: Thanks again for your help but unfortunately that doesn't solve the issue. It makes an infinite loop and inevitably finish with a Fatal error:  Maximum execution time of 300 seconds exceeded in D:\Developpement\Websites\profile27\includes\common.inc on line 2379
Comment: I decided to try to add new field using #ajax. I though it will not have any page submit and should not go to the next step... Well... Ajax doesn't seems to work inside the installation profile... (I've created a module of my code first so I know that the code should run correctly... Any other idea ?
Answer: This patch allows Ajax in install profiles
https://drupal.org/node/1334818


Merge dataframe with another dataframe while groupby on the fly

Question: I have a dataframe (df1) with a column that is corresponds to being melted from another dataframe (df0). So in df1 I have a "feature" column which can be "Material", "Customer" etc. from df0 and then a "value" column in df1, which would be the same value in df0 in the corresponding "feature" column. For instance in df1 I have df1.feature = 'Material' and df1.value = 'Car'. In df0 I would have a column df1.Material which would contain a valua called 'Car'.
I need to get the total "Revenue" from df0, for each value in df1. My problem is that I can't use a merge as the df1.feature is not present as one column in df0, but would be either df0.Material, df0.Customer etc. I can pivot df1 so the df1.feature would be multiple columns and then make some groupby's for df0 and merge them to df1, but that seems very inefficient.
Can I somehow make a function or similar, where df1 gets the grouped value of df0 depending of what column name and value is in df1.feature and df1.value?
df0 = pd.DataFrame({'feature': ['Material', 'Material', 'Customer'],
                    'value': ['Car', 'Bike', 'Trump'],
                    'Coefficient1': [1, 2, 3],
                    'Coefficient2': [5,6,7]})

   df1 = pd.DataFrame({'Material': ['Car', 'Car','Watch'],
                    'Customer': ['Clinton', 'Obama', 'Trump'],
                    'Revenue': [100, 200, 300],
                    'Margin': [10, 20, 3]})

df0
   feature    value  Coefficient1      Coefficient2
0   Material    Car     1                 5
1   Material    Bike    2                 6
2   Customer    Trump   3                 7

df1
       Material     Customer    Revenue    Margin
0   Car             Clinton      100       10
1   Car             Obama        200       20
2   Watch           Trump        300        3

What I would like is then in df0 to have:
feature       value coefficient1 coefficient2 Revenue    Margin
Material      Car   1             5            300       15
Material      Bike  2             6            NaN       NaN
Customer      Trump 3             7            300       3

Comment: Add some example data and expected output based on that example data. It's easier to understand your problem if we can visually see what you want to do, then to read through lot of text.
Comment: I have updated with the dataframes and output - hope that helps :-)
Comment: How did you get the value `300` at `Revenue` and `15` at `Margin` in your expected output in the first row? Is that the `sum` and `average`? What is the logic behind it.
Answer: Here is one way including melt , groupby.agg and merge:
m=(df1.melt(['Revenue','Margin'],var_name='feature')
   .groupby(['feature','value'],as_index=False).agg({'Revenue':'sum','Margin':'mean'}))
final=df0.merge(m,on=['feature','value'],how='left')

    feature  value  Coefficient1  Coefficient2  Revenue  Margin
0  Material    Car             1             5    300.0    15.0
1  Material   Bike             2             6      NaN     NaN
2  Customer  Trump             3             7    300.0     3.0

Where the result of print(m) is:
    feature    value  Revenue  Margin
0  Customer  Clinton      100      10
1  Customer    Obama      200      20
2  Customer    Trump      300       3
3  Material      Car      300      15
4  Material    Watch      300       3


css3 animation, change property after animation starts?

Question: please see below:
    @-webkit-keyframes myfirst /* Safari and Chrome */
{

0% { height:200px;     }

50% {opacity:1}

50% {height:300px; opacity: 0; }

}

I would like to start fading the object away only 50% thorugh the animation. not at the beginning. This currently doesn't do any opacity animation.
Answer: Not getting your question quiet well but I assume you want to delay the start of your animation, if it's that so.. than you can use animation-delay property... This will help you in delay your animation by few seconds
Demo (Modified demo of my answer here)
.blink_me {
    animation-name: blinker;
    animation-duration: 1s;
    animation-timing-function: linear;
    animation-iteration-count: infinite;

    -webkit-animation-name: blinker;
    -webkit-animation-duration: 1s;
    -webkit-animation-timing-function: linear;
    -webkit-animation-iteration-count: infinite;

    -moz-animation-delay: 5s;
    -webkit-animation-delay: 5s;
    animation-delay: 5s;
}

@-moz-keyframes blinker {
    0% { opacity: 1.0; }
    50% { opacity: 0.0; }
    100% { opacity: 1.0; }
}

@-webkit-keyframes blinker {
    0% { opacity: 1.0; }
    50% { opacity: 0.0; }
    100% { opacity: 1.0; }
}

@keyframes blinker {
    0% { opacity: 1.0; }
    50% { opacity: 0.0; }
    100% { opacity: 1.0; }
}

As commented by jCuber, if you want to start animation at 50% than try this
Demo
Comment: I believe he wants the opacity to start changing only after 50% through the animation
Comment: @Mr.Alien right that works. but what happens if you have different properties in the mix, not just opacity. e.g. http://jsfiddle.net/umz8t/291/
Comment: @dgamma3 I was using `span` so as its `inline` element it wont take `width` so here you go http://jsfiddle.net/umz8t/294/
Answer: try this i made  some changes in your fiddle it's work  and also link of new fiddle

 Blink

  .blink_me {
     animation-name: blinker;
     animation-duration: 5s;
     animation-iteration-count: infinite;

    -webkit-animation-name: blinker;
    -webkit-animation-duration: 5s;
    -webkit-animation-iteration-count: infinite;
    background:#ff0000;
    border:1px solid #00ff00;
 }

 @-webkit-keyframes blinker {
   0% {width:20px; opacity: 0;}
   50% {width:20px; opacity: 1; }
   100% {width:50px; opacity: 0; }
 }

http://jsfiddle.net/umz8t/293/
Comment: 2 upvotes and a tick? what was wrong with my answer? also, this is just a copy of my answer..
Comment: @Mr.Alien your answer is also right but not as dgamma3 want he like add height property with opacity.
Answer: it looks like you just made a simple mistake the last line should read 100% not 50%. It could actually read anything between 51% to 100%. You also were missing a semi-colon, added it in.
   @-webkit-keyframes myfirst /* Safari and Chrome */
{

0% { height:200px; }

50% {opacity:1; }

100% {height:300px; opacity: 0; }

}


Locally Euclidian, Hausdorff and Second Countable are independent conditions

Question: When defining a smooth manifold $M$, one usually requires $M$ to be a topological space satisfying these $3$ conditions:
1) Locally euclidean
2) Hausdorff
3) Second countable
I want to verify that these are independent conditions, i.e., that one can find a topological space for each combination:
a) Locally Euclidean + not Hausdorff + not second countable
b) Not locally Euclidean + Hausdorff + not second countable (Ex.: $\mathbb{R}$ with coarse topology)
c) Not locally Euclidean + not Hausdorff + second countable
d) Locally Euclidean + Hausdorff + not second countable (Ex.: the long line $\omega_1\times[0,1)\setminus\{(0,0)\}$)
e) Locally Euclidean + not Hausdorff + second countable
f) Not locally Euclidean + Hausdorff + second countable (Ex.: union of two concurrent lines in $\mathbb{R}^2$)
I'm still stuggling with a), c) and e), since non-Hausdorff spaces are always so hard to think about... Any ideas?
Answer: For (e), take the real line with the doubled origin. (That is, it has two origins, and an open set around either origin must contain that origin and an interval around the origin, but not necessarily the other origin.)
For (a), take an example like the previous one, but use the long line instead.
For (c), you could do "basically anything", because locally Euclidean is easily the "strongest" of the conditions. E.g., take the indiscrete space on 2 points.
Comment: @AguirreK, a two-point space $X$ with topology $\{\emptyset,X\}$.
Comment: what do you mean by indiscrete space on 2 points?


How to use custom converter org.eclipse.persistence.mappings.converters.Converter with EclipseList?

Question: I am trying to implement org.eclipse.persistence.mappings.converters.Converter use it in my orm.xml. Most examples show me how to do it with annotations. Like use @TypeConverter in entity class. But I can't use annotations. How do I am trying to create orm.xml using java  (based on java classes generated based on orm_2_1.xsd using xjc tool). For some reason type-converters are missing in xsd definition.
So my question is how do I use custom converter without using annotations. How to get it to orm.xml?
This link says:

"...Each TypeConverter must be uniquely named and can be defined at the class, field and property level and can be specified within an Entity, MappedSuperclass and Embeddable class. A TypeConverter is always specified by using an @Convert annotation"

So does it mean we can't mention the convert in orm.xml? Is there any reason it was designed (typeconvert are skipped in orm_2_1.XSD?)
Answer: this is described at eclipselink docs:
in the eclipselink-orm.xml
<entity class="Employee">
...
  <attributes>
  ...
    <basic name="gender">
      <convert>genderConverter</convert>
      <converter name="genderConverter" class="org.myorg.converters.GenderConverter"/>
    </basic>
  ...
  </attributes>
</entity>