Forms alter submit button callback not working

Question: I have managed to override a profile2 form using hook form alter. After adding a second submit button to the form successful an issue arose. I can not get the call back function to work. Below is the hook and the call function. Can anyone see a issue with the code?
function multi_step_form_form_profile2_form_alter(&$form, &$form_state){
          $form['profile_x']['field_personal_info']['submit']['und'][0] = array(
            '#name' => 'personal_info_alt',
            '#type' => 'submit',
            '#value' => t('Info Save'),
            '#attributes' => array('alt' => t('get data')),
            '#submit' => array('testing_to_see'),
          );
}

function testing_to_see() {
  print'I am in call back ';
  exit;

}

Thanks for the responses. The reason I am trying to add another submit button is that the current profile page is using JQuery to hide and display some field collections that have been added to the profile page.
Currently when the user fills out the inputs in a fieldset and clicks next it only hides that fieldset and then displays the next fieldset.
Now each fieldset needs to save the data on the server each time you press next. So I found a way to add a submit button using the above code and to display the next fieldset by unsetting the array.
What I can't get the submit button to do when pressed is go to a call back function so I can manipulate the process to achieve this goal.
To answer the current questions below.

field_personal_info is adding the submit button inside the fieldset
multi_step_form is the name of the module
Comment: The form ID doesn't look right to me. In my case the form ID for the profile edit form is:  profile2_edit_main_form. Also usually a new action button should be defined as ['actions']['new_button'] = array (); to avoid overwriting the existing submit button.  See https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#actions
Comment: What's the short name of the module? multi_step_form?
Comment: You should also explain what field_personal_info is and why you are trying to add a submission button to it. If it is a field created with the field API, then that code is completely wrong, to answer about issues in the code.
Answer: Expanding on my comment, be sure you have the correct form ID in the hook_form_FORM_ID_alter. This is an example of how I made this work. You'll need to modify the name of the hook and the FORM_ID
function tempo_form_profile2_edit_pet_ownder_form_alter(&$form, &$form_state){

    $form['actions']['new_button'] =  array(
            '#type' => 'submit',
            '#name' => 'personal_info_alt',
            '#value' => t('Info Save'),
            '#attributes' => array('alt' => t('get data')),
            '#submit' => array('testing_to_see'),
        );
}

function testing_to_see(&$form, &$form_state) {
  drupal_set_message('I am in call back');
}

Comment: @kiamlaluno I have narrowed the question can you please re-open it. thanks


JavaScript: How do use instance variables

Question: why doesn't this work as expected. (see expected comment)
var Module = function () {
    var public_instance_var;

    function doStuff () {
        Module.doOtherStuff();
        console.log(public_instance_var); // expected: true, but logs undefined
    };

    function doOtherStuff() {
        public_instance_var = true;
    };

    return {
        public_instance_var: instance_var,
        doStuff: doStuff,
        doOtherStuff: doOtherStuff
    }
}();

Module.doStuff();

Update: Fixed accordingly to a few of jAndy suggestions
Comment: `Module.doStuff();` should throw the error that `Module` does not have a callable property `doStuff` (or similar). The line with your comment is never executed. Also, this really does not have anything to do with OOP.
Comment: seems like you missed instance_var
Comment: Is there a typo in the return? where is instance_var defined?
Answer: Multiple errors here:

You don't return DoStuff as module interface
instance_var is not declared, probably meant public_instance_var
doOtherStuff is never assigned to Module, just call it like doOtherStuff();

Fixed code:
var Module = function () {
    var public_instance_var;

    function doStuff() {
        doOtherStuff();
        console.log(public_instance_var); // expected: true, but logs undefined
    };

    function doOtherStuff() {
        public_instance_var = true;
    };

    return {
        doStuff: doStuff,
        public_instance_var: public_instance_var
    }
}();

Module.doStuff();

Comment: public_instance_var : instance_var reveals a public pointer to the private property public_instance_var and is thus correct in my code. The rest of your observation seem correct.
Answer: change your code like so
var Module = function () {
    var public_instance_var;

    function doStuff () {
        doOtherStuff();
        console.log("var is ", public_instance_var); // expected: true, but logs undefined
    };

    function doOtherStuff() {
        public_instance_var = true;
    };

    return {
        public_instance_var: public_instance_var,
        doStuff : doStuff
    }
}();

Module.doStuff();

you have to return doStuff() function (otherwise outside it will be undefined) and public_instance_var instead of instance_var
you need to execute doOtherStuff() without prefixing Module.
Answer: What this code does is, simply put: create and run a function and assign its return value to a variable: Module. The return value is an object with 1 property: public_instance_var, that points to the variable instance_var, or (after correcting the typo: public_instance_var). This variable was declared, but not instantiated. Therefore the return value looks like this:
Module.public_instance_var = undefined

The very last line Module.doStuff(); won't work one bit: Module is an object that has no methods. The functions you declared are garbage collected when the anonymous function returns. If you want access to those functions, you'll need to include them in the return statement. Read up on closures, Object constructors and design patterns in general, but I'd say the code you're after will look something like this:
var Module = (function()
    var public_instance_var;
    function doStuff () {
        this.doOtherStuff();
        console.log(public_instance_var); // expected: true, but logs undefined
    };
    function doOtherStuff() {
        public_instance_var = true;
    };
    return {
        public_instance_var: public_instance_var,
        doStuff: doStuff,
        doOtherStuff: doOtherStuff
    };
})();

Of course, this way your variable public_instance_var is a public property, so my guess would be what you're really trying to do is simulate a private properties and methods. In which case you might end up with code similar to this:
var Module = (function()
{
    var public_instance_var;
    return {
        //public_instance_var: public_instance_var, remove this line
        //the closure will preserve access to the variable
        doStuff: function ()
        {
            this.doOtherStuff();//this, you're referencing the object's property
            console.log('here I am');
        },
        doOtherStuff: function ()
        {
            public_instance_var = true;
            //this won't work anymore:
            //this.public_instance_var = true;
        };
    }
})();

Module.doStuff() now logs here I am, but the doOtherStuff is now a public method, too. Here's how you might choose to solve the issue:
var Module = (function()
{
    var public_instance_var;
    function doOtherStuff ()
    {
        public_instance_var = true;
    };
    return {
        //public_instance_var: public_instance_var, remove this line
        //the closure will preserve access to the variable
        doStuff: function ()
        {
            doOtherStuff();//don't use this here, but the reference to the function exists thanks to closure
            console.log('here I am');
            console.log(public_instance_var);//logs true
        }
    };
})();

These are just a few of the very powerful things you can do with closures and functions returning objects. Just read a couple of articles, like this one, there are better ones out there. Google the term power constructors


Generic return types and lambda function arguments

Question: I'm currently working on abstract code that can handle operations on any grid-like structure.  In lieu of concrete methods, I've been trying to develop a framework that accepts lambda expressions and provides functionality based on directional relationships between grid elements, and I've run into trouble when attempting to return a generic type into these methods.
I have a working methods like the one below, that accept a lambda Function that finds the grid element in a particular direction and a Consumer that executes some method on each of the elements.
public static <E> void forEachClockwise(Direction d, Function<Direction, ? extends E> f, Consumer<? super E> c){
    /*For each of the orthogonal directions, in order:*/
        c.accept(f.apply(d));
    /*end For*/

}

Instead of having to pass an element-finding Function every time this method is called, I decided it would be good to have an interface 'Orthogonal' that has such a function declared, and overload the forEachClockwise method to accept elements of this interface.
public static <O extends Orthogonal> void forEachClockwise(Direction d, O center, Consumer<O> c){
    forEachClockwise(d, center::findNextByDirection, c);
}

I used generics here and declared  so that the Consumer method would be able to access fields of the grid elements without casting.  I'm concerned this was a poor design choice, as the Orthogonal interface and the test class I created haven't compiled without warnings and without casts, despite trying a few different things.
public interface Orthogonal {
    public <E extends Orthogonal> E findNextByDirection(Direction a);
}

The two 'valid' implementations of findNextByDirection I've tried are:
/* in Coordinate implements Orthogonal: */
@Override
public <E extends Orthogonal> E findNextByDirection(Direction a) {
    return (E) (/*The proper Coordinate*/);
}

And
@Override
public Coordinate findNextByDirection(Direction a) {
    return /*The proper Coordinate*/;
}
//Warning on return type declaration:
/*Type safety: The return type Element for findNextByDirection(Direction) from the type Element needs unchecked conversion to conform to E from the type Orthogonal*/

Optimally, I would like to have a method that the forEachClockwise (and other methods) can accept, which returns an element of the same class that calls it, without casting.  Coordinate's findNextByDirection should return a Coordinate, Address should return an Address, Cell should return Cell, etc.  Other questions and answers I've looked at discuss how to get away with making a method with a generic return type, but I haven't found any hints on how to use this kind of method as a lambda parameter.
A couple things I haven't yet tried are making a new findByDirection method that accepts some kind of Orthogonal and a Direction as arguments, or calling the forEachClockwise method with some method defined in Orthogonal, though those approaches sound about as reasonable as what I've attempted.  The other approach I've seen that works is to give the interface its own generic type, but it feels distinctly wrong and purpose-defeating to declare every Orthogonal class as "MyClass implements Orthogonal"
Have I been designing this interface entirely wrong from the beginning, and expecting generics to do something they weren't designed for?  Or is there a simpler way of getting a class to call the right method and return elements of its own type generically?
Full code:
package test;

import java.util.function.Consumer;
import java.util.function.Function;

public enum Direction {
    NORTH, EAST, SOUTH, WEST;

    public static <O extends Orthogonal> void forEachClockwise(Direction d, O center, Consumer<O> c){
        forEachClockwise(d, center::findNextByDirection, c);
    }

    public static <X> void forEachClockwise(Direction d, Function<Direction, ? extends X> f, Consumer<? super X> c){
        c.accept(f.apply(d));
        forEachExcept(d, f, c);
    }

    public static <X> void forEachExcept(Direction d, Function<Direction, ? extends X> f, Consumer<? super X> c){
        for(int i=0; i<3; i++){
            d = Direction.getClockwise(d);
            c.accept(f.apply(d));
        }
    }

    public static Direction getClockwise(Direction d){
        switch(d){
        case EAST:
            return SOUTH;
        case NORTH:
            return EAST;
        case SOUTH:
            return WEST;
        case WEST:
            return NORTH;
        default:
            return null;
        }
    }

}

interface Orthogonal {
    public <E extends Orthogonal> E findNextByDirection(Direction a);
}

class Coordinate implements Orthogonal{

    int x;
    int y;

    public Coordinate(int x, int y){
        this.x = x;
        this.y = y;
    }

    public int getX(){
        return x;
    }

    public int getY() {
        return y;
    }

    @Override //Warning on "Coordinate" below.  Compiler suggests writing
              //entire <E extends Orthogonal> method signature
    public Coordinate findNextByDirection(Direction a) {
        switch(a){
            case NORTH:
                return new Coordinate(x+1, y);
            case SOUTH:
                return new Coordinate(x-1, y);
            case EAST:
                return new Coordinate(x, y+1);
            case WEST:
                return new Coordinate(x, y-1);
            default:
                return null;
        }
    }
}

Comment: It would help if you could produce a full example that compiles (with warnings). For example, this implementation of Orthogonal compiles without warning: `public class Element implements Orthogonal {
    @Override public Element findNextByDirection(Direction a) {
      return this;
    }
  }`
Comment: That snippet does compile with a warning for me, on the return type declaration Element:

"Type safety: The return type Element for findNextByDirection(Direction) from the type Element needs unchecked conversion to conform to E from the type Orthagonal"
Comment: did you copy the method signature (returning an Element, not an Orthogonal)?
Comment: Yes.  I'm using Eclipse to compile.  Judging from other questions, using Eclipse vs. javac can throw different compiler warnings and errors when using passing generics.
Answer: Let's assume for a moment there are two classes implementing Orthogonal - Coordinate and Area.
public <E extends Orthogonal> E findNextByDirection(Direction a);

What you declared here is a templated method. The declaration basically says: "given a particular context, this method will always return the expected type - if the result is to be assigned to a Coordinate variable, the method will return a Coordinate, if to an Area - it will return an Area and so on - as long as what is expected is a type that implements Orthogonal"
However, when you try to implement it in Coordinate as public Coordinate findNextByDirection(Direction a), you no longer promise to return whatever is expected in a given context - you now only ever return Coordinate, thus breaking the contract declared in the interface. Worse still, if you think of it, there was no way of actually satisfying that contract in the first place.
What you should do is declare your interface generic (Orthogonal<E>) and drop the <E extends Orthogonal> from the method declaration.
If it is the declaration class Coordinate implements Orthogonal<Coordinate> that feels "distinctly wrong", it shouldn't. This is common practice, used extensively in the SDK itself (see Comparable for instance).
If you find it necessary for findNextByDirection to return an Orthogonal, you can declare the return type as Orthogonal<E>. You should even be able to implement your method in Coordinate as public Coordinate findNextByDirection(Direction a) without any warnings due to Java's type covariance.
Comment: "Worse still, if you think of it, there was no way of actually satisfying that contract in the first place." Unless it always returned `null` :)
Answer: My understanding is that from your findNextByDirection method, you need to return the same type as the enclosing class. So in your Coordinate example, you need to return a Coordinate.
If that's the case, you can go one step further with the generics:
interface Orthogonal<E extends Orthogonal<E>> {
    public E findNextByDirection(Direction a);
}
class Coordinate implements Orthogonal<Coordinate> {
  //rest is the same
  //you should not have any warnings left
}

public static <O extends Orthogonal<O>> void forEachClockwise2(Direction d, O center, Consumer<O> c){
    forEachClockwise(d, center::findNextByDirection, c);
}

Note: the two forEachClockwise methods have a conflict (same raw signature) so I have renamed one of them to forEachClockwise2.


No front Page Content Error

Question: While creating a new view and after added the specific content to it.It's not showing the content which I've created instead it's showing
"no front page content has been created "
Comment: what kind of view did you created? if it is a block, you need to set it first to show in front page. if it is a page, then your on the wrong page.
Comment: It's a page actually.but i've created only one page as of now.then what should i do now?
Answer: Go to "admin/config/system/site-information" to set front page.
Bottom section of this page there is a option for set "Default front page".
Give the view link in "Default front page" textbox. You will not able to see that message.
Answer: create a basic page or article and promote to front. or

create view
go to " configuration>site information"
input path of the view I just created as a default front page.

you can see the PATH on View list ( structure > views)

I am using drupal 7.
" Welcome to YOUR SITE NAME " and " No front page content has been created yet." message are gone !
or in D7, I personally have used and like two edits in my theme's 'page.tpl.php' template:
1.) To remove the default message, anywhere within the page is added
<?php if(drupal_is_front_page()) {unset($page['content']['system_main']['default_message']);} ?>

2.) To remove the default page title,
<?php if ($title): ?> is changed to
<?php if ($title && !drupal_is_front_page()): ?>

Alternatively, one could use a template override ('page--front.tpl.php') and specify this output to be omitted.
or refer this module https://www.drupal.org/project/empty_front_page
or You don't need to add modules for small changes: you can override your template file and add the followning code :
function MYTHEME_preprocess_page(&$vars) {
if (drupal_is_front_page()) {
unset($vars['page']['content']['system_main']['default_message']); //will remove message "no front page content is created"
}

refer this link for more
https://www.drupal.org/node/1049290
Comment: Right now i've deleted all the content related to the view and also the view.Still it's showing the same error.and more over i've created a new view and added my custom content to it.in view's preview it's showing all the contents i've added but in actual it's showing no content shows only the title.

No front Page Content Error


usar ViewPager para incrementar variavel

Question: bom o que eu queria era que meu ViewPager incrementasse uma variável dentro da Activity em que ele foi executado.
isso é possível?
só acho documentação para diferentes layouts
minha aplicação tem 1 página que eu simulo outras, para não carregar muito e por precisar de 60 páginas, eu criei um único layout, que quando o usuário manda mudar de página eu incremento uma variável global que altera todos meus textviews e os textos dos botões de acordo com as informações contidas no banco de dados. entao queria usar esse ViewPager para incrementar essa variavel e assim "mudar a pagina"
Comment: Acredito que se refira ao [ViewPager](http://developer.android.com/training/animation/screen-slide.html), certo? Você tem algo para implementar nele como várias páginas ou simplesmente quer incrementar essa variável?
Comment: assim, minha aplicação tem 1 página que eu simulo outras,
para não carregar muito e por precisar de 60 páginas,
eu criei um único layout, que quando o usuário manda mudar de página eu incremento uma variável global que altera todos meus textviews e os textos dos botões de acordo com as informações contidas no banco de dados.

entao queria usar esse ViewPager para incrementar essa variavel e assim "mudar a pagina"
Comment: @Joannis, coloca essa informação em sua pergunta, para deixar mais claro.
Answer: Pois bem, o que fiz bem rápido aqui, foi totalmente baseado no exemplo que indiquei pra você no comentário. Então, para simplificar sugiro seguir o inicio do exemplo em que ele monta o ViewPager.
Feito isso, como você terá apenas um Fragment mas com dados diferentes, na classe ScreenSlidePageFragment acrescente um parâmetro e o construtor passando o número da página:
private int position;

public ScreenSlidePageFragment(int position) {
    this.position = position;
}

Nesta mesma classe, no onCreateView você já tem o número da página e faz o que precisa ser feito, utilizando o banco de dados e etc.
Voltando agora no ScreenSlidePagerAdapter, você precisa passar o número da página no seu novo construtor, fica assim agora o seu adapter:
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
    public ScreenSlidePagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        return new ScreenSlidePageFragment(position);
    }

    @Override
    public int getCount() {
        return NUM_PAGES;
    }
}

Se quiser pode fazer o download deste projeto que fiz e testar você mesmo (ignore o nome do projeto).
Comment: cara vlw..
entao minha duvida agora que tenho um
public class MainActivity extends ActionBarActivity
e vc criou um
public class MainActivity extends FragmentActivity
Comment: `ActionBarActivity` estende `FragmentActivity`, então você pode usar o primeiro sem problema. Usei o `FragmentActivity` porque era o que estava no exemplo.


Radical of an ideal - prove every prime ideal that contains $I$ also contains $\sqrt{I}$

Question: Let $R$ be a commutative ring with a unit and $I$ an ideal.
Please prove that every prime ideal that contains $I$ also contains $\sqrt{I}$.
I easily conclud that $I \subseteq \sqrt I$ but I couldn't find how to go on.
Answer: Suppose $\mathfrak a\subseteq \mathfrak p$. If $x^n\in\mathfrak a$ for some $n$; then $x^n\in\mathfrak p$, and since $\mathfrak p$ is prime...
Comment: Can you please explain more?  Notice that the prime ideal $P$ contains the ideal $I$, which means that $x^n \in I \subseteq P$ and we need to prove that $x \in P$
Comment: @RanKashtan Use the definition of "prime ideal".
Comment: I'm not sure what do you mean by that. We don't know if $R$ is a final ring or not. Therefore, I can't tell the the prime ideal is the maximal ideal.
Comment: @RanKashtan What is the definition of "prime ideal"?
Comment: If $a$ and $b$ are two elements of $R$ such that their product ab is an element of $P$, then $a$ is in $P$ or $b$ is in $P$.
Comment: @RanKashtan Good. Now use that to deduce that $x^n\in\mathfrak p\implies x\in\mathfrak p$.


What is the motivation for DNS64?

Question: I'm wondering why NAT64 needs something like DNS64 at all.
Couldn't an IPv6-only host, when trying to reach an IPv4-only host, just embed the IPv4 address of the target host in an IPv6 packet (by prefixing and/or padding it with zeroes) and leave the rest to "the network"?
The 0000::/something subnet could then be routed to an appropriate NAT gateway, which would take care of changing the IPv6 header to an IPv4 one, as well as doing the reverse for incoming responses.
Isn't that possible?
Comment: Duplicated in [this SuperUser question](http://superuser.com/questions/384097/).
Answer: The idea is that the IPv6-only host which is behind NAT64 doesn't know or care that it is behind NAT64. You need the DNS64 to fool it into thinking that the IPv4-only hosts it wishes to talk to actually have AAAA records so they can accept IPv6 connections. Without DNS64 the hosts behind NAT64 would receive regular A records. They would do what hosts always do with A records: attempt an IPv4 connection. Either it would work (if the host actually has IPv4 connectivity, but then why do you need NAT64?) or it would fail (if the host has no IPv4 connectivity).
Comment: No, why would the IPv6-only host think that it could contact a remote peer using one address family when it was told (A record) to use a different address family? You are more or less proposing to implement DNS64 functionality IN THE HOST instead of IN THE NETWORK. Sure, if you do that then you don't need to duplicate DNS64 out there in the network, but obviously the problem with that is that you have to do it in every host, which is never going to happen.
Comment: That's correct.
Comment: So when an IPv6-only host receives an A reply, it doesn't try to contact the IPv4 address over IPv6 (by encapsulating it into an IPv6 packet, like 0::de:ad:be:ef:0...:0? The gateway could then change the header to IPv4 and do the NAT translation. Wouldn't that be an easy way to implement IPv6 to IPv4 connectivity?
Comment: I see, so a host will always try to contact a remote host by the address family that has been returned by the DNS lookup, but fail if there is no corresponding interface available? Does that also mean that an IPv4-only application (e.g. one with hard-coded IP literals) will _never_ be able to work on an IPv6-only host (at least not without any modifications to the network stack)?

What is the motivation for DNS64?


What is value of $\prod_{x\geq 2} \frac{x^2+1}{x^2-1}\;?$

Question: For $x \in \mathbb{Z^+}$ what is:
$$
\prod_{x\geq 2} \frac{x^2+1}{x^2-1}\;?
$$
Numerically it seems to be approximately $3.676$.
Comment: Maple says it's $(\sinh \pi)/\pi.$  I have no idea how.
Comment: Do you mean $p^2-1$ in the denominator ? Moreover, what is $p$ ? Any number, or prime number ?
Comment: @TheSilverDoe Thank you. Typos fixed.
Comment: What is the upper bound of $p$?
Comment: @NoChance It's an infinite product.
Comment: Maybe taking logarithm may help.
Comment: This may be remotely related: http://mathworld.wolfram.com/MertensTheorem.html
Comment: Maybe rewriting it as follows and using Taylor series for the logarithm expression might help:

$$\exp\ln\prod_{x\ge2}\dfrac{x^2+1}{x^2-1}=\exp\sum_{x\ge2}\ln\left(1+\dfrac{2}{x^2-1}\right)$$
Answer: You will find it here.
What is amazing is that the partial products
$$P_n=\prod_{x=2}^n \frac{x^2+1}{x^2-1}=\frac{\sinh (\pi )}\pi\, \frac{ \Gamma (n+1-i) \,\Gamma (n+1+i)}{  \Gamma (n)\, \Gamma (n+2)}$$ Using Stirling approximation of the gamma function, the asymptotics
$$P_n=\frac{\sinh (\pi )}\pi\,\left(1-\frac{2}{n}+\frac{3}{n^2}+O\left(\frac{1}{p^3}\right)\right)$$
Comment: It would be great if you could add an explanation for the first line of equations.
Answer: Very partial answer:
$$\prod_{x\geq2} \frac{x^2+1}{x^2-1} =
\prod_{x\geq2} \frac{1+\frac{1}{x^2}}{1-\frac{1}{x^2}}.$$
Then Maple says that both the numerator and denominator converge.  It gives
$$\prod_{x\geq2} 1-\frac{1}{x^2}  = \frac{1}{2}$$
and
$$\prod_{x\geq2} 1+\frac{1}{x^2}  = \frac{\sinh \pi}{2\pi}.$$
So your product is apparently equal to $(\sinh \pi)/\pi.$
Comment: This is discussed in [Borwein's book](https://books.google.com/books?hl=en&id=10BZDwAAQBAJ&pg=PA6).


How to get Views Criteria Filter arguments inside Views API hook?

Question: My question is related to:
https://drupal.stackexchange.com/questions/70551/how-to-sort-view-by-taxonomy-multiple-value-field-with-a-range-of-only-selected
I have an idea, but I didn't manage to find a way to get arguments passed to Views Filter Criteria.
I would like to get them inside hook_views_pre_render
Could someone give me any advice?
Answer: Ok, I found it.
In $view->filter property is an array of views filter handler objects. In selected object inside $hander->value array are arguments passed to this filter.


Cruzando listas em python

Question: Boa noite, estou quebrando a cabeça para achar o erro, é o seguinte estou cruzando está lista de números binários, o primeiro cruzamento está dando certo porém o segundo está ficando com o final do primeiro, para exemplificar está é minha minha lista de entrada:
POPULAÇÃO SELECIONADA
['1', '0', '1', '0', '1', '0']
['1', '0', '1', '1', '1', '1']
['1', '1', '0', '0', '0', '1']
['0', '0', '0', '0', '1', '1']
['1', '0', '1', '0', '1', '0']
['1', '0', '1', '0', '1', '0']
['1', '0', '1', '0', '1', '0']
['0', '0', '1', '0', '0', '1']
['1', '0', '1', '0', '1', '0']
['1', '0', '1', '0', '1', '0']

Estes são os que vão cruzar em pares (pai e mãe):
CROSSOVER
 INDICES: [0, 1, 2, 3, 4, 6, 7, 8]
 Corte em: 6
 Pai: ['1', '0', '1', '0', '1', '0']
 Mae: ['1', '0', '1', '1', '1', '1']
 Corte em: 2
 Pai: ['1', '1', '0', '0', '0', '1']
 Mae: ['0', '0', '0', '0', '1', '1']
 Corte em: 1
 Pai: ['1', '0', '1', '0', '1', '0']
 Mae: ['1', '0', '1', '0', '1', '0']
 Corte em: 2
 Pai: ['0', '0', '1', '0', '0', '1']
 Mae: ['1', '0', '1', '0', '1', '0']

E está é minha saida que está errada:
POPULAÇÃO CROSSOVER
['1', '0', '1', '0', '1', '0']
['1', '0', '1', '1', '1', '1']
['1', '1', '0', '0', '1', '1']
['0', '0', '0', '0', '1', '1']
['1', '0', '1', '0', '1', '0']
['1', '0', '1', '0', '1', '0']
['1', '0', '1', '0', '1', '0']
['0', '0', '1', '0', '1', '0']
['1', '0', '1', '0', '1', '0']
['1', '0', '1', '0', '1', '0']

CÓDIGO
def crossover(probCrossover):
    indices = []
    randoms = []

    print('\nCROSSOVER')
    print('-----'*6)
    for i in range(len(populacao)):
        randoms.append(random())

    for i , r in enumerate(randoms):
        if r <= probCrossover:
            indices.append(i)

    if len(indices)%2!=0:
        indices.pop()
    print('\nINDICES: {}'.format(indices))
    for ind in range(0, len(indices), 2):

        pontoCorte = randint(1, precind)
        print('Corte em: {}'.format(pontoCorte))
        print('Pai: {}\nMae: {}'.format(populacao[indices[ind]], populacao[indices[ind+1]]))

        populacao.__setitem__(indices[ind], populacao[indices[ind]][0:pontoCorte]+populacao[indices[ind+1]][pontoCorte:])
        populacao.__setitem__(indices[ind+1], populacao[indices[ind+1]][0:pontoCorte]+populacao[indices[ind]][pontoCorte:])

Comment: O que significa "cruzar" a lista? Pode dar um exemplo da entrada e saída desejadas, e postar todo o código necessário pra tornar o problema reproduzível?
Comment: Bom a entrada é ah 'população selecionada' que mostrei logo acima. Cruzara é assim tenho essa linha por exemplo linha[1,2,3,4,5] e linha2[5,6,7,8,9] e ponto de corte por exemplo corte=2, ele resulta em 2 linhas novas linha[1,2,7,8,9] e linha2[5,6,3,4,5] @PedrovonHertwig
Answer: Consegui resolver meu problema, na verdade era muito simples, eu estava utilizando o setitem no list, então como o código para modificar estavam juntos e quando se alterava o primeiro o segundo iria utiliza-lo ja modificado e isso causava o erro na saida. Como solução criei duas variavel filho1 e filho2 que recebem o item alterado e depois foi alterado na lista.
SOLUÇÃO:
def crossover(probCrossover):
     indices = []
     randoms = []

     print('\nCROSSOVER')
     print('-----'*6)
     for i in range(len(populacao)):
        randoms.append(random())

     for i , r in enumerate(randoms):
         if r <= probCrossover:
             indices.append(i)

     if len(indices)%2!=0:
         indices.pop()
     print('\nINDICES: {}'.format(indices))
     for ind in range(0, len(indices), 2):

         pontoCorte = randint(1, precind)
         print('Corte em: {}'.format(pontoCorte))
         print('Pai: {}\nMae: {}'.format(populacao[indices[ind]], populacao[indices[ind+1]]))
         filho1 = populacao[indices[ind]][0:pontoCorte]+populacao[indices[ind+1]][pontoCorte:]
         filho2 = populacao[indices[ind+1]][0:pontoCorte]+populacao[indices[ind]][pontoCorte:]

         populacao.__setitem__(indices[ind], filho1)
         populacao.__setitem__(indices[ind+1], filho2)

Cruzando listas em python


Where Debian Lenny stores initial ifconfig values?

Question: With upgrade of VMWare Player I suddenly found my Debian Lenny VM not getting IP address. Some DHCP issue maybe, I don't know. So I have to set it manually every boot in Player window, via:
ifconfig eth0 down
ifconfig eth0 192.168.175.128 netmask 255.255.255.0 up

I usually start up VM and then connect to it via SSH, so this procedure bothers me. Sure I can add it to startup script, but is there some special place to enter these values? Like, some config file or so?
Answer: I think the values you're looking for are configured in the /etc/network/interfaces file.
See this resource regarding static networking configuration.
Comment: Okay, will try now.


Multiple clickable icons to PrimeNG TreeNode in Angular2 application

Question: I am developing an angular2 application using PrimeNG. I have a tree view and in certain scenarios I need to add more than one icon to specific tree node. Any help on this is appreciated.
Example:

Icon TreeNode1
     Icon1 Icon2 TreeNode2

I want the icons to be clickable so that I can perform actions like showing tooltips or show popup dialog etc...
Open on suggestions regarding any other technology that can be used to achieve above funtionality
Answer: I was looking for something related and found your question right now.
To add multiple icons to a branch (or leaf) of the tree you need to make your own templates for each type of TreeNode.`
<ng-template let-node  pTemplate="group">

        {{node.label}}
</ng-template>
<ng-template let-node  pTemplate="node">

        {{node.label}}
</ng-template>

`
Check here the TreeNode interface https://github.com/primefaces/primeng/blob/master/src/app/components/common/treenode.ts


Certain VMware guests run slowly unless I feed them extra I/O interrupts

Question: Running ESX server 3 on four identical 4-CPU hosts, guests on Fibre SAN VMFS.
Guest OS is Fedora 10. Cloned it to create web, jboss, mysql, and memcached templates.
Cloned each template into four guests, one for each server.
Out of these 16 guests, one jboss and one mysql guest run so slowly as to be unusable. By "slowly", I mean that no matter how CPU-intensive the process launched, they never utilize more than ~200Mhz CPU. Moving them between hosts has no effect--it appears to have something to do with those guests themselves.
BUT! Today I found that they will run at nearly full speed if I either:

Hold down the spacebar in the console
Open an SSH session and, hold down some repeating key
Flood them with ICMP packets

In other words, any kind of I/O activity seems to "wake them up", and all processes run at perfectly normal speeds during this time. Stop that I/O activity, and they again slow to a crawl.  So apparently, their processes aren't being scheduled unless there is some sort of interrupt activity.
Any ideas why?
All guests are fully patched as of today. openvm-tools is installed, guest time sync enabled, kernel parameters are "notsc" (but changing that doesn't affect this issue).
Have used rsync in --dry-run mode to verify that /bin, /usr/bin, /var/jboss and /var/lib/mysql are identical to the normally-behaving guests, and that /etc only varies in hostname, IP address, and other instance-specific settings.
Have tried setting their resource utilization to "high" with no effect. (All guest resource utilizations are "normal", except for memory reservations on all JBoss and MySQL guests. The total memory reservations per server are about half of the host memory, and all guest memory sizes added together only use about 70% of the host memory.
The *.vmx, *.vmxf, and *.vmdk files vary only in uuid, displayName, MAC address and disk/swap filenames.
Comment: What is the VM Config (#vCPU, RAM, #drives, #nics)? Are the VM's all located on the different FC LUNs? What's the host config (CPU Model in particular), #of NICs and HBA's? What FC SAN is behind all this and is it properly setup (dual independent fabrics?, properly zoned)?  Is this really ESX 3 or 3.5? Have you set any CPU affinity rules on the VMs? Anything unusual in the Service Console (3rd party agents?).
Comment: Helvick, you pointed me right at it, thanks!!

One of the other guests on the same host had all four cores checked for CPU affinity. This wasn't part of the planned config, somebody was experimenting, forgot to reset it, and moved that machine with the others when we were experimenting with different hosts because it looked nice to keep all of the "xxxxx1" servers on the same host.

Would upvote your answer but it's a comment.  :-)
Answer: One of the other guests on the same host improperly had the CPU affinity bits checked for all cores on the host. Removing the affinity settings restored normal operation.
There's five of us working on those hosts, I should have checked the configs myself before posting.
EDIT: I can't accept my answer and close the question for 2 days?
Answer: Have you looked as esxtop from the service console?  It might give you some clues as to what is going on.


Drush cache clear corrupting database?

Question: I just moved to a new computer: Windows 10 with XAMPP. As far as I know I set everything up the same as it was on my old Windows 7 computer. But now, for some reason, much of the time when I run drush cc all or run update.php, the database gets corrupted. Most frequently, some cache tables' *.idb files (tablespaces) are deleted from my mysql directory, which makes those tables appear as "in use" in phpMyAdmin and prevents them from being edited or emptied. They are always cache tables and never tables that actually get modified by my update hooks. Restoring the database is the only way to fix it then. This is a mature site that I've been working on for a long time, and have never seen this until the new computer. What's happening here?
A sample error message when using update.php, caused by a missing *.idb file:
PDOException: SQLSTATE[HY000]: General error: 1812 Tablespace is missing
for table '(null)': DELETE FROM {cache_field} WHERE
(cid = :db_condition_placeholder_0) ; Array (
[:db_condition_placeholder_0] => field:message_type:6 )
in cache_clear_all() (line 168 of
C:\<path>\includes\cache.inc).

My most recent drush cc all error message, which Google has never even heard of, was:
exception 'PDOException' with message 'SQLSTATE[HY000]: General      [error]
error: 1030 Got error -1 "Internal error < 0 (Not system error)" from
storage engine InnoDB'

Comment: increase your local server max_execution time
Comment: My max_execution_time in php.ini is already set to 60000. That's over 16 hours. More than that? Or somewhere else?
Answer: In general Drush can't corrupt your database, as it's a software which just sends the SQL queries.
However this error can be related to newer version of MySQL, as of 5.5.7, InnoDB always uses the fast truncation technique (which is equivalent to DROP TABLE and CREATE TABLE). So it no longer performs a row-by-row delete for tables with parent-child foreign key relationships, therefore TRUNCATE TABLE returns an error for such tables.
See: 18.104.22.168 Changes Affecting Upgrades to 5.5
This already has been reported in #2229013 for Drupal core.
So you should either:

consider using different data structures:

non-InnoDB,
use redis/memcached for your cache management (so this won't happen),

try clearing your caches in different way, e.g.
echo "SHOW TABLES LIKE 'cache%'" | drush sqlc --extra=--skip-column-names | xargs -L1 -I% echo "DELETE FROM %;" | drush sqlc --extra=-v

upgrade your Drupal to 8 and see if the same happens (drush cr),
use different database (maybe will work in MariaDB?),
downgrade your MySQL to <5.5.7,
patch the Drupal core by replacing TRUNCATE with DELETE statement,
You may also consider the condition like if ($mysqlversion > 5.57 AND $cache_table_type = 'innodb') { // DELETE } else { // TRUNCATE }.
or wait until the fix is provided for Drupal core (#2229013).
Comment: Thanks for the advice! This is a large company project and I don't really have the option of changing data structures, using a different DB, or upgrading Drupal. Wasn't able to successfully downgrade my local MySQL. So I guess I'm stuck for now.
Comment: @JohnAlexander You can do some core patching and change all `DELETE * FROM {table}` into `TRUNCATE TABLE {table}`.
Comment: Same error happens on MariaDB 10.1.13.

Drush cache clear corrupting database?


Changing from database mirroring to transaction log shipping

Question: I'm considering dumping database mirroring and go with transaction log shipping on our SQL Server 2008 Standard server instead, because there's a noticeable performance hit due to the principal being a beefier machine.
Is it non-trivial to do?
I am guessing I just need to break the synchronization, bring them offline and then configure for log shipping, or will I have to perform a new RESTORE WITH NORECOVERY? Is this correct?
Other things I should keep in mind?
Preferably I'd like asynchronous mirroring but the Enterprise license is a bit much.
Answer: this is pretty straight forward in setting up, you shouldnt have to offline the databases either.  you can actually begin setting up the transaction log shipping before even needing to break the mirror.
for more info here is the SQL dev center link;
http://msdn.microsoft.com/en-us/library/bb895393.aspx
best,
Nick
Comment: That's reassuring, thanks. I'll also have to stop the transaction log backups I'm guessing, or the log chain will be broken?
Comment: yes for sure otherwise the shipping will be inconsistent.


Pass function parameters to API response in React

Question: I have an API call I am making:
function createReferral(referralData: { actionTypeId: number }) {
  referralAxios.post(`/api/ReferralMasters`, {
    appTypeID: referralData.appTypeId,
  }).then(function (response) {
    console.log(actionTypeId)
  })
}

I am getting an error message saying that actionTypeId is not defined.
How do I go about passing my function parameter to the .then part of the API call?
Comment: @jonrsharpe not sure what you mean. `number` refers to the type.
Answer: Your parameter description does not desctructure actionTypeId from parameters.
If you would like to destructure, this is the way to do it.
 function createReferral({ actionTypeId, appTypeId }: {actionTypeId: number, appTypeId: number}) {
    referralAxios.post(`/api/ReferralMasters`, {
      appTypeID: appTypeId,

    })
      .then(function (response) {
        console.log(actionTypeId)
      })
  }

However, if you would like to simplify, it's best not to destructure, and use interfaces/types for type definition.
interface ReferralInterface {
  actionTypeId: number;
  appTypeId: number;
}

function createReferral(referralData: ReferralInterface) {
   referralAxios.post(`/api/ReferralMasters`, {
     appTypeID: referralData.appTypeId,

   })
     .then(function (response) {
       console.log(referralData.actionTypeId)
     })
 }

Answer: The attribute actionTypeId is a part of the referralData object and therefore not visible to the then function. Try to print it the following way instead:
.then(function (response) {
  console.log(response.data.actionTypeId);
})

Answer: You have to get that value from referralData:
function createReferral(referralData: { appTypeId: number, actionTypeId: number }) {
  referralAxios.post(`/api/ReferralMasters`, {
    appTypeID: referralData.appTypeId,
  }).then(function (response) {
    console.log(referralData.actionTypeId)
  })
}

createReferral({ appTypeId: 10, actionTypeId: 20 })


How could I add Eventlisteners for each div so it's not undefined? (javascript, more below)

Question: I don't understand why it says it's undefined.
error message:

dom.js:51 Uncaught TypeError: Cannot set property 'backGroundcolor' of undefined
at HTMLDivElement. (dom.js:51)

The problematic line: pixels.style.backGroundcolor = 'black';

let drawBtn = document.querySelector('#letsDraw')
drawBtn.onclick = clearAndDraw

function clearAndDraw() {
  clear()
  draw()
}

function draw() {
  screenSize = textbox.value
  for (i = 0; i < screenSize ** 2; i++) {
    pixel = document.createElement('div');
    pixel.classList.add('pixel');
    pixel.style.border = '1px solid black';
    pixel.style.backgroundColor = 'white';
    screen.appendChild(pixel);
  }
  screen.style.gridTemplateColumns = `repeat(${screenSize}, auto) `;
  screen.style.gridTemplateRows = `repeat(${screenSize}, auto) `;

  const pixels = document.querySelectorAll('.pixel')
  pixels.forEach(pxl => {
    pxl.addEventListener('mouseenter', function() {
      pixels.style.backGroundcolor = 'black';
    })
  })
}

Comment: `pxl.style.backgroundColor` instead of `pixels.style.backGroundcolor` in the second loop
Comment: Also `backGroundcolor` -> `backgroundColor`
Comment: side bit: do you need to quote your class name in the HTML?
Comment: @silversunhunter not in HTML5 if you use only *one* className. Only if you're going to add two: `class="screen foo"` - otherwise `class=screen` is **absolutely valid**
Comment: Why are you not adding the event handler when you create the div? Seems weird you create all the divs and look them all back up to add an vent handler.
Comment: @RokoC.Buljan oh wow.. Learned something new!
Answer: You are targeting pixels list and not the element itself. So if your forEach is using 'pxl' as a variable for each element, you must change this line.
Edit: Another thing is a typo on your style attribute. Change 'backGroundcolor' to 'backgroundColor'
pixels.style.backGroundcolor = 'black';

To this
pxl.style.backgroundColor = 'black';

Comment: Thank you very much, I already tried this before but maybe for some other reason it didn't worked, now it's good to go
Comment: Yeh @RokoC.Buljan. Totally agree. I mistyped during my edition. Now it's correct.


How to prove that $n\sum\limits_{d\mid n}\frac{|\mu(d)|}{d}=\sum\limits_{d^2\mid n}\mu(d)\sigma\left(\frac{n}{d^2}\right)$?

Question: This is problem 11 part b in chapter 3 of Tom M. Apostol's "Introduction to Analytic Number Theory". A variation on Euler's totient function is defined as
$$\varphi_1(n) = n \sum_{d \mid n} \frac{|\mu(d)|}{d}$$
The question asks to show that
$$\varphi_1(n) = \sum_{d^2 \mid n} \mu(d) \sigma\left( \frac{n}{d^2} \right)$$
My attempt so far: I have proved in part (a) of the same question that
$$\varphi_1(n) = n \prod_{p \mid n}\left(1 + \frac{1}{p} \right)$$
And so in an attempt to equate these two expressions I write
\begin{eqnarray}
\varphi_1(n) &=& n \prod_{p \mid n}\frac{p + 1}{p} \\
&=& n \left(\prod_{\substack{p \mid n \\ p^2 \mid n}}\frac{p + 1}{p}\right)\left(\prod_{\substack{p \mid n \\ p^2 \nmid n}}\frac{p + 1}{p}\right)
\end{eqnarray}
Let $s = \prod_{\substack{p \mid n \\ p^2 \mid n}} p$ and $r = \prod_{\substack{p \mid n \\ p^2 \nmid n}} p$. Then
\begin{eqnarray}
\varphi_1(n) &=& n \frac{\sigma(s)}{s} \frac{\sigma(r)}{r} \\
&=& \sigma(s) \sigma(r) \frac{n}{sr}
\end{eqnarray}
Using $N = \mu * \sigma$ where $*$ is the Dirichlet convolution and $N(n) = n$ we obtain
\begin{eqnarray}
\varphi_1(n) &=& \sigma(s) \sigma(r) \sum_{d \mid \frac{n}{sr}}\mu(d) \sigma\left( \frac{n}{srd} \right)
\end{eqnarray}
Because $(r, \frac{n}{srd}) = 1$ we can simplify the expression:
\begin{eqnarray}
\varphi_1(n) &=& \sigma(s) \sum_{d \mid \frac{n}{sr}}\mu(d) \sigma\left( \frac{n}{sd} \right)
\end{eqnarray}
We know that $\frac{n}{r}$ is square, and that all $d$ that contribute (a non zero value) to the above sum are squarefree, because otherwise $\mu(d) = 0$, and so the sum over $d$ such that $d \mid \frac{n}{sr}$ is the same as the sum over $d$ such that $d^2 \mid n$. This brings us to where I am stuck:
\begin{eqnarray}
\varphi_1(n) &=& \sigma(s) \sum_{d^2 \mid n}\mu(d) \sigma\left( \frac{n}{sd} \right)
\end{eqnarray}
I cannot see how to proceed from here. Hints or answers for how to proceed from where I currently am, or how to show what is required using a different approach would be appreciated.
Answer: Since $\varphi_1$ is multiplicative it suffices to show this for prime powers
$p^k$. The product definition in part (a) yields
$$\varphi_1(p^k)=p^k\prod_{p|n}(1+p^{-1})=p^k+p^{k-1}$$
The formula in part (b) yields
$$\sum_{d^2|n}\mu(d)\sigma(\frac{n}{d^2})=\sigma(p^k)-\sigma(p^{k-2})=\frac{(p^{k+1}-1)-(p^{k-1}-1)}{p-1}=p^k+p^{k-1}.$$
so that the two definitions are the same.
Comment: Thank you. I knew I was over complicating it!
Comment: For a proof that $\sum\limits_{d^2\mid n}\mu(d)\sigma\left(\frac{n}{d^2}\right)$
is multiplicative, see this question: https://math.stackexchange.com/q/1837522


Sometimes SQL Server trigger is not firing

Question: I created a trigger on my recharge table. It updates the balance of onaccountregistry table.
But sometimes when inserting rows into my recharge table it is not firing the trigger. Then values are mismatch. This recharge table insert rows every time.
I created the trigger as follows. This is not a replicated table. I'm using SQL Server 2008 Enterprise edition.
Please help me solve this matter
CREATE TRIGGER [dbo].[RechargeRefund]
   ON [dbo].[ISRecharge]
   FOR INSERT
AS
   declare @tin char(9)
   declare @depocd char(1)
   declare @oldvalue money
   declare @newvalue money
begin
    select @tin = inserted.tin_subtin from inserted
    select @depocd = inserted.updatetype from inserted
    select @newvalue = inserted.DepositAmt from inserted
    select @oldvalue = Totdeposit from ISOnAcctRegistry where tin_subtin = @tin
end

if @depocd ='1'
begin
  update ISOnAcctRegistry
  set Totdeposit = @oldvalue + @newvalue
  where tin_subtin = @tin
end

if @depocd ='2'
begin
  update ISOnAcctRegistry
  set Totdeposit = @oldvalue - @newvalue
  where tin_subtin = @tin
end
GO

Answer: As @marc points out, writing assuming a single row in inserted is bad - it can even be possible for your 3 selects from inserted to assign values to your 3 variables from 3 different (arbitrary) rows from inserted.
What you probably want is:
update i1
set Totdeposit = Totdesposit + t2.Total
from ISOnAcctRegistry i1
        inner join
     (select
         tin_subtin,
         SUM(CASE updatetype
              WHEN 1 THEN DepositAmt
              WHEN 2 THEN -DepositAmt
         ELSE 0 END) as Total
      from inserted
      group by tin_subtin) t2
        on
            i1.tin_subtin = t2.tin_subtin

But you might be able to replace this work (and this column in ISOnAcctRegistry) with an indexed view built on ISRecharge - with some limitations, you can build a view that automatically performs a SUM across the rows in ISRecharge, and SQL Server would take responsibility for maintaining the value in the background for you.
Obviously, at present, your trigger doesn't account for any UPDATE or DELETE activity on ISRecharge. An indexed view would.
Answer: Well, of course it won't work - you're assuming that the trigger fires once per row inserted.
But that's NOT the case.
The trigger fires once per INSERT batch, and the pseudo-table Inserted might contain multiple rows!
If you did get an INSERT with more than one row - which row did your statements here select ?
select @tin = inserted.tin_subtin from inserted
select @depocd = inserted.updatetype from inserted
select @newvalue = inserted.DepositAmt from inserted
select @oldvalue = Totdeposit from ISOnAcctRegistry where tin_subtin = @tin

You need to rewrite your trigger so that it will handle multiple rows in Inserted - then it'll work every time.
Comment: @user1811342 - If you'd care to look at my answer, provided yesterday, it shows how the trigger ought to be written.
Comment: How can I handle multiple row inserted please change my triger dear.please help me to do this


Installation error with Composer

Question: I'm trying to install Drupal 8 with Composer. Drupal Console is already installed (in case that's relevant), so I go to my localhost folder (working locally) and type:
composer create-project drupal-composer/drupal-project:8.x-dev cmpsprjct --stability dev --no-interaction

Everything runs well with the composer installation in the terminal. When I try to proceed with the installation in the browser I get following error:
Additional uncaught exception thrown while handling exception.
Original

TypeError: Return value of Doctrine\Common\Annotations\AnnotationRegistry::reset() must be an instance of Doctrine\Common\Annotations\void, none returned in Doctrine\Common\Annotations\AnnotationRegistry::reset() (line 55 of /var/www/html/cmpsprjct/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationRegistry.php).

Doctrine\Common\Annotations\AnnotationRegistry::reset() (Line: 113)
Drupal\Component\Annotation\Plugin\Discovery\AnnotatedClassDiscovery->getDefinitions() (Line: 86)
Drupal\Component\Plugin\Discovery\DerivativeDiscoveryDecorator->getDefinitions() (Line: 283)
Drupal\Core\Plugin\DefaultPluginManager->findDefinitions() (Line: 174)
Drupal\Core\Plugin\DefaultPluginManager->getDefinitions() (Line: 109)
Drupal\Core\Render\ElementInfoManager->buildInfo('seven') (Line: 76)
Drupal\Core\Render\ElementInfoManager->getInfo('form') (Line: 806)
Drupal\Core\Form\FormBuilder->prepareForm('install_select_language_form', Array, Object) (Line: 272)
Drupal\Core\Form\FormBuilder->buildForm('install_select_language_form', Object) (Line: 898)
install_get_form('Drupal\Core\Installer\Form\SelectLanguageForm', Array) (Line: 1324)
install_select_language(Array) (Line: 670)
install_run_task(Array, Array) (Line: 548)
install_run_tasks(Array) (Line: 117)
install_drupal(Object) (Line: 44)

Additional

TypeError: Return value of Doctrine\Common\Annotations\AnnotationRegistry::reset() must be an instance of Doctrine\Common\Annotations\void, none returned in Doctrine\Common\Annotations\AnnotationRegistry::reset() (line 55 of /var/www/html/cmpsprjct/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationRegistry.php).

Doctrine\Common\Annotations\AnnotationRegistry::reset() (Line: 113)
Drupal\Component\Annotation\Plugin\Discovery\AnnotatedClassDiscovery->getDefinitions() (Line: 86)
Drupal\Component\Plugin\Discovery\DerivativeDiscoveryDecorator->getDefinitions() (Line: 283)
Drupal\Core\Plugin\DefaultPluginManager->findDefinitions() (Line: 174)
Drupal\Core\Plugin\DefaultPluginManager->getDefinitions() (Line: 109)
Drupal\Core\Render\ElementInfoManager->buildInfo('seven') (Line: 76)
Drupal\Core\Render\ElementInfoManager->getInfo('html') (Line: 298)
Drupal\Core\Render\Renderer->doRender(Array, 1) (Line: 195)
Drupal\Core\Render\Renderer->render(Array, 1) (Line: 139)
Drupal\Core\Render\Renderer->Drupal\Core\Render\{closure}() (Line: 576)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 140)
Drupal\Core\Render\Renderer->renderRoot(Array) (Line: 66)
Drupal\Core\Render\BareHtmlPageRenderer->renderBarePage(Array, 'Error', 'install_page', Array) (Line: 76)
Drupal\Core\ProxyClass\Render\BareHtmlPageRenderer->renderBarePage(Array, 'Error', 'install_page', Array) (Line: 1004)
install_display_output(Array, Array, Array) (Line: 264)
_drupal_log_error(Array, 1) (Line: 584)
_drupal_exception_handler(Object)

I have searched in Google and found that a composer update could solve the problem, but it didn't.
Any hints about how to proceed?
Working with Ubuntu 17.04 and php 7.1
Answer: Please make sure your webserver (nginx/apache) is using the same PHP version as your cli one. For example, you may encounter this issue if your cli PHP version is PHP 7.1 and your webserver is using PHP 7.0.
Comment: This helped me. To clarify -- after I made sure my php cli version was correct I ran `composer update` again and the problem was fixed.
Comment: Perfect. When upgrading from Ubuntu 16.04 to 18.04, the CLI version of PHP updated to 7.2.15, but the version on the webserver was stuck at 7.0.33, the latest version I had installed on 16.04. Because Composer figures dependencies differently depending on the PHP version, when you run "composer update" with a CLI version incompatible with your server version you get this problem
Answer: For Ubuntu 16.04 I had to run the following commands to adjust the PHP version used by Apache:
sudo a2dismod php7.0
sudo a2enmod php7.2
sudo service apache2 restart

Answer: I removed all php dependencies:
sudo apt-get remove php*

I installed php again:
sudo apt-get install php7.1 php7.1-cli php7.1-common libapache2-mod-php7.1 php7.1-mysql php7.1-fpm php7.1-curl php7.1-gd php7.1-bz2 php7.1-mcrypt php7.1-json php7.1-tidy php7.1-mbstring php-redis php-memcached

Restarted Apache
sudo service apache2 restart

There is the installation screen!
Comment: php7.1-xml is missing. ihere. by adding this drush will work fine, too

Installation error with Composer


Is the set $[-1,1]\times[-1,1]\subset \Bbb R^2$ compact with respect to this metric?

Question: Is $[-1,1] \times[-1,1]\subset\Bbb R^2$ a compact subset with regards to the distance function
$$d\bigl((x,y),(a,b)\bigr):=\begin{cases}|x-a| & \text{if }y=b\\|x|+|y-b|+|a| & \text{if }y\neq b\end{cases}$$.
Well the first thing I would note is that the subset is closed and then maybe try to show that for both cases the distance is bounded above
$|-1-1|=2$ furthest distance if  $y=b$
$1+2+1=4$ furthest distance if  $y\neq b$
So it's bounded above by four, and so closed and bounded and then by the Heine-Borel Theorem also compact? Is this close to being correct?
Answer: Hint: If you want to use the Heine-Borel characterisation: this space is not totally bounded. You cannot cover it with finitely many balls of diameter less than $1$, for instance.
Answer: Hint
For each $a \in [-1,1]$ the set $(-1,-1) \times \{ a\}$ is open.
Show that for some small $r >0$
$$
\left( [-1,1] \times [-1, -1+r)  \cup  [-1,1] \times (1-r, 1]  \right)\cup \left(\bigcup_{a  \in [-1,1]} I_a \right)
$$
is an open cover which doesn't have a finite subcover.


Cauchy–Riemann differentiable

Question: Hi I'm stuck on this problem, given the following and I have to find the derivatives using cauchy riemann and state the points where it is analytic:
$$ f(z) = (z^2-iz+6)^8$$
This is what I have so far:
$$ f(z) = ((x^2 - y^2 +y +6)+i(2xy-x)^8$$
From this I would say:
$$ u(x,y) = (x^2 - y^2 +y +6)^8$$
$$ v(x,y) = (2xy-x)^8$$
Im confused about this power to 8? I dont think I'm expected to expand this, any thoughts? Thanks.
Answer: Note that $z^2, -iz$ and $8$ are holomorphic, then the sum too, and the product too.
Comment: ie, is a polynomial
Comment: I dont know what means
Comment: Does this seem right? $$ f(z) = 8(z^2 -iz+6)^7(2z-i) $$ There for it is analytical everywhere?
Answer: I'm not sure exactly how it is expected of you to do this, but I'll offer some possibilities.
First, one can show using the definition of the derivative that any polynomial with complex coefficients is holomorphic everywhere in $\mathbb{C}$, and that the multiplication of holomorphic functions is again holomorphic. So, since $f(z)$ is just a power of a polynomial, it is holomorphic everywhere.
Furthermore, you can prove again with the definition of the derivative that both the power rule and chain rule for differentiation hold for complex variables. Thus, you can find $f'(z)$ just like you would normally find it if $z$ and all the coefficients where real.
That being said, if you are asked to use the Cauchy-Riemann equations it's not as straightforward. The problem is that
$$f(z) = \left[(x^2-y^2+y+6) + i(2xy-x)\right]^8 \neq (x^2-y^2+y+6)^8 + i(2xy-x)^8$$
so you can't conclude that the functions $u$ and $v$ that you have written are indeed the real and imaginary parts of $f$. What you could do is use the following alternate form of the Cauchy-Riemann equations
$$ \frac{\partial f}{\partial x} = -i \frac{\partial f}{\partial y}$$
This is what the Cauchy-Riemann equations look like before you plug in $f = u + iv$ and obtain the familiar formulas. If you use this, however, you don't have to determine the real and imaginary parts of your function. You can just use it as it is after plunging in $z=x+iy$. If the above equality holds (and if the derivatives are continuous, which they are), then $f$ is holomorphic and
$$ f'(z) = \frac{\partial f}{\partial x} = -i \frac{\partial f}{\partial y} $$

Cauchy–Riemann differentiable


Unable to get my ContentEntity base field definition to appear as checkboxes

Question: I am trying to implement a base field with multiple selections as checkboxes I have had a go at implementing it but it stills appears as a select even after clearing the cache. I'm sure I'm doing this wrong but this is what I have:
$fields['content_display'] = BaseFieldDefinition::create('list_integer')
  ->setDisplayOptions('form', array(
    'type' => 'checkboxes',
    'weight' => -4,
  ))
  ->setSetting('allowed_values', $values)
  ->setDisplayConfigurable('form', TRUE);

Answer: Try with options_buttons because this is the ID if the OptionsButtonsWidget widget.
$fields['content_display'] = BaseFieldDefinition::create('list_integer')
  ->setDisplayOptions('form', array(
    'type' => 'options_buttons',
    'weight' => -4,
  ))
  ->setSetting('allowed_values', $values)
  ->setDisplayConfigurable('form', TRUE);

Comment: Great that worked just had to set my cardinality to unlimited


Como transformar um IPath em Path

Question: Estou com dúvidas em como conseguir um Path através do IPath,
Tenho uma variável do tipo IPath mas tenho um método que requer um Path, tentei fazer um cast mas não tive sucesso, alguém conhece alguma solução ?
Answer: Assim:
<code>Path path = Paths.get(iPath.toFile().toURI());
</code>
Comment: Muito Obrigado Daniel, funcionou perfeitamente

Como transformar um IPath em Path


Display Time in Label 1 and Display Date in Label 2

Question: How can I Display time in military clock format to label 1  and Display date in Longdate format to label 2 regards guys.
<code>    Label6.Text = DateTime.Now.ToLongDateString()
    Label3.Text = Now.ToLongTimeString.ToString()
</code>
Comment: Label6.Text = DateTime.Now.ToLongDateString()
Comment: And what is the error? Please edit your post and add info there.
Comment: theres no error @lucio the time cant display
Answer: Try the following:
<code>Me.Label1.Text = DateTime.Now.ToString("HH:mm:ss")
Me.Label2.Text = DateTime.Now.ToLongDateString
</code>
Comment: Don't forget about the '()' at the end :)
Comment: Label6.Text = Format(Now, "Long Date")
        Label7.Text = Format(Now, "HH:mm:ss")
this codes .. got it..


Determine the values of a for which the following system of linear equations has no solutions, a unique solution, or infinitely many solutions

Question: I am not quite sure if I am doing this equation right. I am still a bit stumped how to solve for a. If I could have some guide towards the right direction that would be greatly appreciated. enter image description here
$$2_x1+2x_2+4x_3  =  −6$$
$$3x_1+5x_2+6x_3  =  −3$$
$$3x_1+4x_2+ax_3  =  −5$$
Comment: You should type at least the initial system.
Comment: I guess you made a mistake while copying the 5 below. You wrote it as a 3
Answer: $$\det\left|
\begin{array}{ccc}
 2 & 2 & 4 \\
 3 & 5 & 6 \\
 3 & 4 & a \\
\end{array}
\right|=4a-24$$
if $\det\ne 0$ then for Cramer's Theorem there is one and only one solution.
If $\det=0\to a = 6$ then the matrix becomes
$$A=\left(
\begin{array}{ccc}
 2 & 2 & 4 \\
 3 & 5 & 6 \\
 3 & 4 & 6 \\
\end{array}
\right)$$
and its range is $2$.
While the completed matrix
$$\left(
\begin{array}{ccc|c}
 2 & 2 & 4 & -6 \\
 3 & 5 & 6 & -3 \\
 3 & 4 & 6 & -5 \\
\end{array}
\right)$$
has rank $3$. Thus the system is impossible for this theorem.


Condition of Statistical Independence

Question: I have this question:
P(A | B)P(B) = P(B | A)P(A) if A and B are independent events.
My reasoning:
If A & B are independent, P(A|B) = P(A) and P(B|A) = P(B)
and the above expression reduces to P(A)*P(B) = P(B)*P(A), which proves that the statement is true.
However the answer indicates that it is not true. Any mistakes in my argument?
Thanks.
Comment: This holds true whenever A and B are independent or not. Hint: recall the definition of P(A|B).
Answer: $\Pr(A|B)\Pr(B)=\Pr(A \cap B)$ whether A and B are independent or not.
Similarly $\Pr(B|A)\Pr(A)=\Pr(B \cap A)$.
And $A \cap B = B \cap A$ since intersection is a commutative function.
So  $\Pr(A|B)\Pr(B)=\Pr(B|A)\Pr(A)$.

Condition of Statistical Independence


How to display custom fields of taxonomy in field twig

Question: In my content type for Event, I have an entity reference called Speakers which refers to a taxonomy called Team Members.   It's set to multiple so I can say which speakers belong to my event.    On the event detail page, I want to list the speakers out with all of their fields.
I have a field hook called field-field-speakers.html which lists all of the speakers.   I can't seem to get any of the fields within the taxonomy.  (ex: item.content.field_job_title ).   It doesn't display any content.
  {% for item in items %}

                 {{ item.content }}

{{ item.content.field_job_title }}

  {% endfor %}

How do I do this?   I think the answer might be in a View but not sure how to map it dynamically based on which event I am in.
Comment: Taxonomy is an entity, so you should have a custom View Mode for that, and change the field formatter setting on the Event (in the View Mode its using) to point to that view mode for rendering the term. Then they all become normal twig templates. Note, View Mode != Views.
Answer: You can use item.content['#options'].entity.field_job_title.value to get the value of the job_titlefield value, I don't know if this is the best way to do it.
So your code will be something like:
{% for item in items %}

        {{ item.content }}

{{ item.content['#options'].entity.field_job_title.value }}

{% endfor %}


How to convert an array of mixed sized integers in swift

Question: Swift 5, iOS 14
I have playing around with generics in Swift trying to understand them and made up a problem that seems unsolvable. Imagine I have an array of mixed sized integers.
var dindex = [Int8(1),Int16(2),Int32(3),Int64(4)] as [Any]

And I want to convert them to as array of Doubles for processing for example. Now map does not work nor am I able it seems to simply step through the array and I having no luck with generics at this point...
// does not work
func convertMap(qindexIn qindexOut:[Int]) -> [Double] {
  return(qindexOut.map({ Double($0) }))
}

// does not work
func convertMap22(qindexIn qindexOut:[Any]) -> [Double] {
  let foo:[Double] = []
  for i in qindexOut {
    foo.append(Double(i))
  }
  return(foo)
}

// does not work
func convertMap2<T: BinaryInteger>(qindexIn qindexOut:[T]) -> [Double] {
  return(qindexOut.map({ Double($0) }))
}

// this doesn't work either
func convertMap22(qindexIn qindexOut:[Any]) -> [Int] {
  return(qindexOut.compactMap { $0 as? Int })
}

Indeed the code doesn't even compile for the most part. What is the trick here? It is surely possible?
Answer: Any in Swift is really a hard thing to work with.
Please try this:
func convertMap(qindexIn qindexOut:[Any]) -> [Double] {
    return(qindexOut.map{ ($0 as? NSNumber ?? NSNumber(0.0)).doubleValue })
}

Hope there may be some better ways.
Answer: This will work. I casted Any to Int type
 func convertMap22(qindexIn qindexOut:[Any]) -> [Double] {
     var foo:[Double] = []
     for i in qindexOut {
     if let intValue = i as? Int{
         let doubleValue = Double(intValue)
         foo.append(doubleValue)
     }else if let intValue = i as? Int8{
         let doubleValue = Double(intValue)
         foo.append(doubleValue)
     }else if let intValue = i as? Int16{
         let doubleValue = Double(intValue)
         foo.append(doubleValue)
     }else if let intValue = i as? Int32{
         let doubleValue = Double(intValue)
         foo.append(doubleValue)
     }else if let intValue = i as? Int64{
        let doubleValue = Double(intValue)
        foo.append(doubleValue)
    }
  }
  return(foo)
}

Comment: I have updated the answer. It will work but I guess Ooper solution is better
Comment: Babar it is nice try as they say, OOPer solution looks very objective C 'isn. Would like to do it without resorting to NSNumber in an ideal world.
Comment: @user3069232, I do agree. If some more Swifty answer would be posted, please do not hesitate to approve it. I'm also curious about it.
Comment: @OOPer, followed your lead and posted an answer :)
Answer: Looking at OOPer answer gave me an idea, this works too and although isn't more Swifty perhaps is less Objective C'ish.
func convertMap26(qindexIn qindexOut:[Any]) -> [Double] {
    return(qindexOut.map{ Double("\($0)") ?? 0.0 })
}

Comment: As I said it depends if OP wants to convert "a" to zero or just skip it. In this case where they are all numbers it wont make a difference and map it is probably faster
Comment: or simply `compactMap { Double("\($0)") }` it will depend if a non number should be converted to zero or skipped
Comment: What is the difference Leo? Is compactMap faster perhaps?


Python - Criar variavel dinamica para o firebase

Question: Tenho um código que recebe de uma planilha o CodProduto, Descrição e Quantidade e, em seguida, os insere no banco de dados. Só que ele faz esse looping 1000x.
Como posso criar variáveis com esse db.child e fazer tudo de uma vez só ou em uma quantidade menor de vezes?
Código:
while contador2 < npedido2.count():

  while logica1 == logica2:

  db.child("Pedidos").child(str(npedido2[contador2])).child("CodProduto").update({contador2:
codpedido[contador2]})

  db.child("Pedidos").child(str(npedido2[contador2])).child("Descrição").update({contador2: descricao[contador2]})

  db.child("Pedidos").child(str(npedido2[contador2])).child("Quantidade").update({contador2: str(quantidade[contador2])})

  contador2 = contador2 + + 1

Comment: Vai ficar mais fácil alguém te responder se o código acima for identado corretamente. Tente usar apóstrofo invertido triplo, em vez de identar pra frente (\`\`\` ) para demarcar o trecho de código. Lembre-se que em Python identação nao é um "acessório estético", e sim, define a estrutura do seu programa.
Answer: @Giovane,
Se a biblioteca que você estiver usando for a firebase. Use algo como abaixo:
from firebase import firebase

firebase = firebase.FirebaseApplication('URL of Database', None)
data =  { 'Name': 'John Doe',
          'RollNo': 3,
          'Percentage': 70.02
          }
result = firebase.post('/python-example-f6d0b/Students/',data)
print(result)

Retirado daqui
No seu caso, contrua a variável data com o CodProduto, Descrição e Quantidade.
Vc também teria que acertar a URL of Database e a url do post
Espero ter ajudado.
Answer: não conheço muito como funciona a api para python e não sei se é o realtime database ou o firestore.
no firestore, quando for realizar uma quantidade muito grande de registros e recomendado realizar gravações em lote no banco de dados. tem um limite de 500 gravações por lote.
leia mais em: https://www.google.com/url?sa=t&source=web&rct=j&url=https://firebase.google.com/docs/firestore/manage-data/transactions%23batched-writes


Eclips output display language is symbols instead of english words

Question: I have a problem with the output display of both Eclips Luna and Netbeans. Everytime I run my application my output comes out with symbols that I do not understand instead of plain English. My machines locale language is set to English and I made sure that when i downloaded these programs it was the english version.
Any help would be appreciated.
Thank you.
Comment: It may help to see your code
Comment: I am still new to all this, but even on a basic code like this my output comes out with symbols or a different language. import javax.swing.JOptionPane;
public class HelloDialog
{

 public static void main(String[] args)
 {
  JOptionPane.showMessageDialog(null, "Hello World!");

 }

}
Answer: add the -Duser.language=en parameter in the eclipse.ini file
Comment: I have done that but It still displays in a different language. My whole IDE is in English, it is just when I run my program that it displays incorrectly.
Comment: I would like to see your code and the output if it is possible in a screen shot
Comment: Unfortunatley I cannot post screen shots yet. This is happening on both Netbeans and Eclips so I wonder if it could possibly be my JDK. version 1.
Comment: I don't think so. it has to be something related to your eclipse and NetBeans. I would suggest try installing the software again.


$\mathcal{L}$ is very ample, $\mathcal{U}$ is generated by global sections $\Rightarrow$ $\mathcal{L} \otimes \mathcal{U}$ is very ample

Question: Let $\mathcal{L},\mathcal{U}$ be invertible sheaves over a
noetherian scheme $X$, where $X$ is of finite type over a noetherian
ring $A$. If $\mathcal{L}$ is very ample, and $\mathcal{U}$ is
generated by global sections, then $\mathcal{L} \otimes \mathcal{U}$
is very ample.
Since $\mathcal{L}$ is very ample, there exists $n$, s.t. $i:
X\mapsto \mathbb{P}^n$ is an immersion with $\mathcal{L}=
i^*\mathcal{O}(1)$, and since $\mathcal{U}$ is generated by global
sections, one can construct $j:X \to \mathbb{P}^m$ with
$j^*\mathcal{O}(1) = \mathcal{U}$. From this I can construct the
following morphism:
$$
h: X \xrightarrow{\Delta} X\times X \xrightarrow{i\times j}
\mathbb{P}^n \times \mathbb{P}^m \xrightarrow{ \operatorname{segre \
embedding}} \mathbb{P}^N $$
I can prove $\mathcal{L}\otimes \mathcal{U } \cong
h^*\mathcal{O}(1)$, and the segre embedding is a closed immersion.
But I don't know whether the map $(i\times j) \circ \Delta$ is an
immersion, which is suspicious to be such, especially for the
$\Delta$.
Comment: Oh, Liu has the proof (more or less): Let $\pi$ be the projection $\mathbb P^m\to \mathrm{Spec}A$. Then, $\left(\mathrm{id}\times \pi\right)\circ \left(i\times j\right)\circ \Delta = i$ is an immersion, while $\mathrm{id}\times \pi$ is separated (by Hartshorne's Corollary II.4.6 (c)), so that Hartshorne's Exercise II.4.8 (applied to $\mathcal P = \text{"being an immersion"}$) yields that $\left(i\times j\right)\circ \Delta$ is an immersion. Let's hope this isn't wrong again...
Comment: Now I am wondering: Isn't your proof symmetric in $\mathcal L$ and $\mathcal U$? Aren't you proving that the tensor product of two very ample sheaves is very ample?
Comment: This is Hartshorne's Exercise II.7.5 (d), and his Exercise II.7.4 (a) shows that $\Delta$ is a closed immersion.
Comment: Yes, you are right. But is $i \times j$ also an immersion? I can prove $X \times \mathbb{P}^m \to \mathbb{P}^n \times \mathbb{P}^m$ is an immersion, but not for the whole morphism.
Comment: $i\times j=\left(i\times \mathrm{id}\right)\circ \left(\mathrm{id}\times j\right)$, and the composition of two immersions is an immersion (this follows from the fact that a closed subscheme of an open subscheme is always an open subscheme of a closed subscheme if everything is Noetherian; this is Exercise 9.3.C in Vakil's notes http://math.stanford.edu/~vakil/216blog/ ).
Comment: Note that Vakil comments that calling these things "immersion" here is a bad idea.
Comment: Ah, I see! $j$ needs not be an immersion.
Comment: Yeah, that works! By the way, can you point out where is the Liu's result as you quoted above. Is that from Liu Qing 's book Algebraic geometry and arithemetic geometry?
Comment: Yeah, it's from that book. Chapter 5, Exercise 1.28.
Answer: From the comments, to clear this from the unanswered queue:

Let $\pi:\Bbb P^m\to \operatorname{Spec} A$ be the projection. Then, $(\text{id}\times\pi)\circ (i\times j) \circ \Delta = i$ is an immersion, while $\text{id}\times \pi$ is separated (by Hartshorne's Corollary II.4.6(c)), so that Hartshorne's Exercise II.4.8 (applied to $\mathcal{P} = \text{"being an immersion"}$) yields that $(i\times j)\circ \Delta$ is an immersion.

This argument is sourced to Liu's Algebraic Geometry and Arithmetic Curves, Chapter 5, Excercise 1.28. This comment was originally written by darij grinberg (2011-11-29), and at the time of this posting was comment-upvoted at +7 as well as confirmed by the original asker in a subsequent comment.
Answer: It is true that if $i: X \to Y$ is an immersion, and $j:X \to Z$ is any morphism (all over $S$), then $(i, j): X \to Y \times_S Z$ is an immersion. See this answer for a proof.


Detect Cell Modified or Update in Web Browser Excel

Question: I have an Excel located in SharePoint Online Library.
I tried using Intersect to detect any change or update in Column A, Column B will be updated to the month value of the change or update made in respective Column A.
It works well in Microsoft Excel Desktop App, but if I open the Excel in Web browser, the function not firing.
Comment: The Excel web application cannot be automated with VBA. As far as I know, there is a Java Script API for this. However, I do not know any more details about this. https://learn.microsoft.com/en-us/office/dev/add-ins/reference/overview/excel-add-ins-reference-overview
Answer: Check the function and/or formula/VBA. Things like "color" for cells are not available in the Online Excel, nor will VBA and macros work.


Understanding marginalizing over many variables using joint probabilities.

Question: If we have a joint probabiliy $p(x, y)$, where each are binary variables having $K$ values, we can compute the marginal probability $p(y)$ as:
$$p(x, y) = p(y|x)p(x) \tag 1$$
$$p(y) = \sum_{x^{*}}p(y|x^{*})p(x^*) \tag 2$$
now say I have many random variables: $x_1, x_2, ... , x_N$, and I want to compute a particular marginal $p(x_a)$. How does one go about doing this naively? Would it be an iterative application of (1) and (2) ?
So, say I have three discrete random variables: $x_1, x_2, x_3$ and I want to get the marginal of $x_2$
$$p(x_1, x_2, x_3) = p(x_2|x_1, x_3)p(x_1, x_3) \tag 3$$
$$p(x_2) = \sum_{x_1}\sum_{x_3}p(x_2|x_1, x_3)p(x_1, x_3) \tag 4$$
if the above is correct, I have to admit that the "meaning" of it is a bit fuzzy. By meaning I mean the steps it is telling me to carry out. My initial thought is to apply (1) and (2) to the second term in (4). Picking which variable I want to marginalize first:
$$p(x_2) = \sum_{x_3}\sum_{x_1}p(x_2 | x_1, x_3)p(x_3|x_1)p(x_1)$$
$$=\sum_{x_3}p(x_2|x_1, x_3)p(x_3) \tag 5$$
the last term in (5) should sum to 1 now leaving $\sum_{x_3}p(x_2|x_1, x_3)$, but now I am confused as I still have of $x_1, x_3$ being conditioned on.
Perhaps the crux of the problem is I am unsure as to what happens with $x_3$ in something like $p(x_2|x_1, x_3)$ as I sum over all $x_3$, does it just drop out and become $p(x_2|x_1)$ ? If so, why?
EDIT:
New insight ... maybe. Say I write (4) as:
$$p(x_2) = \sum_{x_1}\sum_{x_3}p(x_2|x_3, x_1)p(x_1, x_3) \tag 4$$
now I can set $z = x_2|x_3$ and rewrite this as:
$$p(x_2) = \sum_{x_1}\sum_{x_3}p(z, x_1)p(x_1, x_3) \tag 4$$
now I apply (1) and (2) to the second term:
$$p(x_2) = \sum_{x_3}\sum_{x_1}p(z, x_3)p(x_3|x_1)p(x_1)$$
as I sum over $x_1$ I am left with:
$$p(x_2) = \sum_{x_3}p(z, x_1)p(x_3)$$
and I can now substitute $x_2|x_3$ back in place of $z$:
$$p(x_2) = \sum_{x_3}p(x_2|x_3, x_1)p(x_3)$$
oh ... never mind this leaves me with my same issue. So then, is the answer that summing over $x_1$, removes it from $p(x_2|x_3, x_1)$? In which case the result follows pretty straight forwardly
Answer: That last equation should be: $$\begin{align}p(x_2) &= \sum_{x_3}\sum_{x_1}p(x_2 \mid x_1, x_3)p(x_3\mid x_1)p(x_1) \\[1ex]&= \sum_{x_3}\sum_{x_1}p(x_2,x_3\mid x_1)p(x_1)\\[1ex] &=\sum_{x_3}p(x_2,x_3)\\[1ex]&=\sum_{x_3}p(x_2\mid x_3)p(x_3) \tag 5\end{align}$$
Basically, you are marginalising over $x_1$ so it won't appear in the equation.


MC dropout deep learning

Question: I would like to compute the uncertainty of my deep learning model using MC dropout. My original model contains already one dropout and I am satisfied with its performance. To compute the uncertainty, should I place other dropouts in my model? If it is yes, where should I place these dropouts? Will these additional dropouts decrease the performance of my model (in training and testing parts)?
Answer:
I would like to compute the uncertainty of my deep learning model using MC dropout.

To use MC dropout to compute the uncertainty of a model, you are calculating the posterior.
The posterior is proportional to the likelihood times the prior P(θ|D) ∝ P(D|θ) ⋅ P(θ).

My original model contains already one dropout and I am satisfied with its performance.

I think you mean that you have applied dropout to your model in your training. To apply the MC dropout you only need to apply it in test mode as we can see from the original paper:

In practice this is equivalent to performing T stochastic forward passes through the network and averaging the results.

You pass the same data through the neural network several times and take the average of the corresponding results.

MC dropout deep learning


Shortest iptables command allowing only ssh access

Question: When building a new system I do not turn on the network until I have configured iptables to prevent all inbound traffic except on port 22 (ssh). Later, I open up ports and configure allowed address ranges.
What is the shortest iptables command I can type to disallow all inbound traffic except connections to port 22 from a (given) single IP address?
Answer: I'm not great on the actual commands, but my iptables file would look like this:
#Filter all previous rules
*filter
# Loopback address
-A INPUT -i lo -j ACCEPT
# Established inbound rule for eth+  connections
-A INPUT -i eth+ -m state --state RELATED,ESTABLISHED -j ACCEPT
# Allow ssh access
-A INPUT -i eth+ -s X.X.X.X/Y -p tcp --dport 22 -j ACCEPT
# Explicit rules at the end
:INPUT DROP [0:0]
:FORWARD DROP [0:0]
:OUTPUT ACCEPT [0:0]
COMMIT
Answer: # flush rules
iptables -F INPUT
iptables -P INPUT DROP
# allow loopback traffic
iptables -A INPUT -s lo -j ACCEPT
# allow established connections
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# allow ssh
iptables -A INPUT -s 10.15.10.0/24 -p tcp --dport 22 -j ACCEPT

Answer: iptables -F
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -p tcp -j DROP
Very similar to @pQd (vote him up not me), but I hate DROP policies - I think they're bad practice.


QT Creator does not recognize STL types for new projects

Question: I have an existing project where the STL types are recognized. However, when creating a new project none of the STL types are not recognized. For example in
#include <string>
string s;

the colour of stringwill not change and compilation will generate errors.
Strangly enough when on the include line "Follow symbol under cursor" is executed the include file is opened. So the include file is there, Qt Creator knows how to open it and still class string is not recognized.
Did a reinstall of Qt5.5 but no avail.
What's happening?
Comment: The STL type is called `std::string`, not `string`.
Answer: you should use:
std::string

or:
using namespace std

at the beggining and you will not have to add the namespace every time
Comment: Or, better yet, `using std::string`, unless it's a header file in which case `std::string` is the way.


Can eclipse notify me when a task has finished running?

Question: I am often stuck twiddling my thumbs for a couple minutes while eclipse cleans, builds, or loads my projects.  It would be nice if eclipse could notify me with a beep when the last task in the Progress view has finished running, so I can stop reading the internet and get back to work.  Is there a setting or plugin that does this?
Edit: I tried adapting the plugin template that nonty provided below, which adds a listener to the JobManager.  I tried implementing done() to beep only when the job change event's name contains "Building workspace," as that is the task that usually takes the longest in my setup.  Exasperatingly, the task that builds the workspace never sends a done() call, just scheduled() and aboutToRun() calls.  Any other ideas?
Answer: There are no preference for this - yet.
The JobManager have the needed API to support this functionality...
EDIT: I have constructed and attached a very simple plug-in that will beep for every job that terminates. That turns out to be rather often :-) . You can modify it to filter out all the false positives, e.g. by  getPriority() and getName(). Also you can make the listener play a tune, popup a message (don't!) or whatever...
See jobnotifier.zip.
UPDATED the link above again
Comment: Thanks for making this plugin!  I'm having some trouble getting it to run, though.  I unzipped the folder, dropped it into my plugins directory, and restarted eclipse.  The plugin shows up under Help->About->Plugins, but I don't hear any beeps. :( (Eclipse 3.5.2)
Comment: Hmm... In the Console view, try to select the "Host OSGi Console". Then issue the commands `ss` ("short status") - this will list the plug-ins of the Eclipse installation along with their state. Check the jobnotifier plugin - likely the last. It should be state `STARTED`but can be `RESOLVED`- in the later case you can start it with the command `start _id_`...
Comment: @nonty The plugin's state was `RESOLVED`.  When I tried to start it, I got this stack trace: http://pastebin.com/Xiqj2kQr (Thanks so much for your help, by the way!)
Comment: Ahh... You wrote "I unzipped the folder, dropped it into my plugins directory, and restarted eclipse." If that is really the case, then it explains it :-) The zip contained the source code for you to modify - it did not contain the compiled ready-to-use bundle. Sorry for the confusion. You must first import the zip as a new project ("Existing Projects into WS"), then export it... and now you can put it into the `dropins` folder. Though I would recommend creating a feature and a update site as well..
Comment: Gotcha!  Thanks, got it working now.  You're right, it does beep a lot. :o)
Comment: This is a really good idea, and it really should work, but it turns out that eclipse sends the most ridiculous hodgepodge of `done()` calls, most of them useless.  See edit to my question.
Comment: It is vacation time, so a new version depends on the weather... So I don't hope you will get it the next couple of weeks..
Comment: This link isn't working for me. Not sure if it's just me. Please fix if possible. Thanks.


Prove that $\sum_{n=1}^{\infty}\exp\left(-n^{\varepsilon}\right)$ converges.

Question: I have the problem to prove, that the following series converges:
\begin{equation}
\sum_{n=1}^{\infty}\exp\left(-n^{\varepsilon}\right),
\end{equation}
where $\varepsilon > 0$.
I tried everything. I tried the ratio and root test, but I don't come to a solution. Can someone help me?
Thanks!
Answer: Because $\lim_{n\to\infty}\frac{n^2}{\exp(n^{\epsilon})}=0$ for any $\epsilon>0$ by twice L'Hospitals rule, you can infer that for a certain $N$ we have $n^2<\exp(n^{\epsilon})$ for all $n>N$, and from there the comparison test gives convergence.
Comment: This answer is not quite correct as stated. You need something like limit superior or a positivity condition here. For example, the limit of $\frac{1}{(-1)^n n} $ is obviously $0$ but we cannot say there exists $N$ such that $1 < (-1)^n n$ for all $n > N$. Obviously the exponential function is positive on a real domain, so your argument will still hold.
Answer: For $\epsilon>0$, find an $N$ such that $N\epsilon>1$. Now use Taylor formula to obtain that $e^{u}>Cu^{N}$, $u>0$ for some constant $C>0$ that depending only on $N$. Then $e^{-n^{\epsilon}}<c\dfrac{1}{n^{N\epsilon}}$ and we have $\displaystyle\sum\dfrac{1}{n^{N\epsilon}}<\infty$ by $p$-series.
Answer: Observe that $$\lim_{n \to \infty} \frac{2 \log n}{n^\epsilon} = 0$$ for every $\epsilon > 0$.  In particular, there exists an $N$ with the property that
$$n \ge N \implies 2 \log n < n^\epsilon \implies e^{-n^\epsilon} < e^{-2 \log n} \implies e^{-n^\epsilon} < \frac 1{n^2}.$$
Now use the comparison test.
Answer: Using the Cauchy condensation test $\sum_{n=1}^{\infty}\exp\left(-n^{\varepsilon}\right)$ is convergent iff
$$
\sum_{n=1}^\infty\frac{2^n}{e^{2^{n\epsilon}}} =
\sum_{n=1}^\infty\frac1{e^{2^{n\epsilon} - n\log 2}}
$$
is convergent, but as $2^{n\epsilon} - n\log 2 > n$ for n large enough,
$$\frac1{e^{2^{n\epsilon} - n\log 2}}< \frac1{e^n}$$
for $n$ large enough.


Is there any operator which I can use to attach 2 calculations?

Question: I'm doing some homework where I use only elementary operations. I need to code a function which given a positive number, calculates the whole half of that number.
My problem is at:
int half(int x, int y)
{
    return x == 0 ? y : half(x-1-1, y+1) , x == 1 ? y : half(x-1-1, y+1);
}

I don't know what if exists any operator or something that connects these calculations. On that line of code i tried to use ( , ).
I tried to replace ( , ) by using ( | ) and ( & ). But i had many errors.

#include <stdio.h>

int sum(int x, int y)
{
    return y == 0 ? x : sum(x+1, y-1);
}

int half(int x, int y)
{
    return x == 0 ? y : half(x-1-1, y+1) , x == 1 ? y : half(x-1-1, y+1);
}

int main(void)
{
    int x;
    int y=0;
    scanf("%d", &x);
    int z = half(x, y);
    printf("%d\n", z);
    return 0;
}

On this code i expect the output of 6/2 to be 3 and 5/2 to be 2.
Note: The function sum although is not doing nothing i cannot remove since the homework says not to remove from the code, perhaps i need to use it.
Comment: If you know about `? :`, then you probably have learned about `if` statements already as well, right? They would be much easier to read and write.
Comment: They're teaching recursion and ternary operator but haven't covered `if`???
Comment: @uneven_mark Ye i know about `if` but i still didn't learned yet in class so we can't use it.
Comment: What's the point of the second argument to `half`? This homework seems convoluted.
Comment: @JL2210 The second argument is to calculate odd number like 1, 3, 5, etc...
Comment: @vunax Usually only one number is involved in calculating a half of a number.
Comment: the function: `sum()` is never called!  Please explain why it is even there.
Comment: the initial value of `x` is determined via the input of a value from the user.  What if the user enters -1 (or any other number less than 0)
Comment: regarding: `return x == 0 ? y : half(x-1-1, y+1) , x == 1 ? y : half(x-1-1, y+1);`  The comma ',' operator will result in the results of the first part of line being evaluated and discarded, so the actual return value will only depend on the last part of the line
Comment: if you really want to find the 1/2 value of an integer, you can simply use: `return x>>1;`
Answer: You can just use || to put these together:
int half(int x, int y)
{
    return x == 0 || x == 1 ? y : half(x-1-1, y+1);
}


Spring Boot JDBC-Test DB Connection Leak When running all the tests

Question: I have structured my test in the following way.
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {BizServiceTestContextConfig.class})
@JdbcTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@TestPropertySource( {
    "file:${apps.config.root}/test_config/bizservice.test.properties",
    "file:${apps.config.root}/test_config/dcs.test.properties"
})
@PropertySource(name = PropSourceKey.SCHEDULER_PROPERTIES, value = "file:${apps.config.root}/config/scheduler.properties")
@PropertySource(name = PropSourceKey.MESSAGING_PROPERTIES, value = "file:${apps.config.root}/config/messaging.properties")
public abstract class BizServiceTest {

}

For each test class I have extended this class to avoid code duplication.So a typical test class would look like this.
public class SystemParameterServiceImplTest extends BizServiceTest {

    @Autowired
    private SystemParameterService systemParameterService;

    @Test
    public void testA() throws Exception {

    }

    @Test
    public void testB() throws Exception {

    }

    @Test
    public void testC() throws Exception {

    }

}

I have currently 66 test cases running, all which connect to a pre-initialized the MySQL Db Schema, and run the tests accessing this database. All run on transactions which are rollbacked at the end. The problem I am facing is that, all my tests run and do not release the DB connections. So the more tests I write the higher number of db connections it holds on to. This creates kind of a DB connection leak.

I know the db connections can be increased in an instance like this. But it makes testing highly unscalable. I tried using @DirtiesContext(classMode = ClassMode.AFTER_CLASS) which did not solve the problem. Is there anyway to release the db connections after the class.
Comment: Each `@ContextConfiguration`, `@TestPropertySource` and some other things lead to loading another Spring context. apparently most of your tests require a different configuration each time loading a new context, creating a new datasource and thus eventually flooding your DB. I would say the issue is not so much in Spring but in the way you are doing your tests.
Comment: Use a single configuration for all your tests it will automatically be reused. As soon as you start adding `@TestPropertySource`, `@PropertySource` or start using `@MockBean` etc. you are basically creating a new instance of your application. As Spring Test will cache 32 of those you might end up with a lot of test instances.
Comment: The only weird thing I think we may have done is foregoing embedded DB support and wiring the actual DB instance to run the tests, which is vital since our Data model is too complex to be mocked or included in Embedded dbs. Looks like for each test class context it creates a connection pool but doesn't release it once the class is over. So I used a concrete Data Source[Hikari] implementation and got rid of the pool @ AfterClass. Also since spring caches service implementations across test had to kill off the context afterclass  with @DirtiestContext. Connections are released properly now.
Comment: @DirtiestContext saved our day, Thanks!
Comment: what do you have in this class `BizServiceTestContextConfig` ?
Comment: @pvpkiran the component scans.
Comment: @M.Deinum so what would be the ideal way to do these tests? Any pointers to a proper approach resource. None of the help there teaches you how to do beyond a single test class.
Comment: Having a super class with all the configuration and extending that class, can this be a problem? @M.Deinum
Comment: If that is the only thing you have and you don't use `@MockBean` and/or `@SpyBean` that shouldn't be a problem. Which could actually indicate you have an issue in your code and not so much in your tests.
Comment: But other than the tests, I cant find any problem. The more tests are introduced the higher the connections that are made. I was constantly running show process-list on mariadb and it shows that as each test class starts, it adds new processes add up to the processlist. @M.Deinum
Comment: Then you aren't only extending the test class but also have additional configurations or are doing weird things in your test or application code. However the code you have posted here is too small to give you an answer.
Answer: The only weird thing I think we may have done is foregoing embedded DB support and wiring the actual DB instance to run the tests, which is vital since our Data model is too complex to be mocked or included in Embedded dbs.
ooks like for each test class context it creates a connection pool but doesn't release it once the class is over.

So I used a concrete Data Source[Hikari] implementation and explicitly
  got rid of the pool @ AfterClass.

Also since spring caches service implementations across test had to kill off the context afterclass with @DirtiestContext. Connections are released properly now.


PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number

Question: Boa noite, Pessoal.
Estou recebendo o erro a seguir: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in C:\xampp\htdocs\ZENVIA\php-rest-api\model\ConnectMysql.php on line 43.
já revisei 200x e não consigo identificar... o numero de parâmetros x bind está ok..Segue abaixo, parte do código:
    <?php

class ConnectMysql extends PDO {

    private $conn;

    public function __construct(){

        $this->conn = new PDO(....);

    }

    private function setParams($statement, $parameters = array()){

        foreach ($parameters as $key => $value) {

            $this->setParam($statement, $key, $value);

        }

    }

    private function setParam($statement, $key, $value){

        $statement->bindParam($key, $value);

    }

    public function query($rawQuery, $params = array()){

        $stmt = $this->conn->prepare($rawQuery);

        $this->setParams($stmt, $params);

        $stmt->execute();

        return $stmt;

    }

    public function select($rawQuery, $params = array()):array{

        $stmt = $this->query($rawQuery, $params);

        return $stmt->fetchAll(PDO::FETCH_ASSOC);

    }

    public function insert ($data, $params = array()){

            $stmt = $this->select("CALL sp_base_insert(:MTID, :OPERACAO, :STATUS_TRATAMENTO, :ID_MSG, :ESTAGIO_ENVIO, :OS, :PDV, :CLIENTE, :TELEFONE_1, TELEFONE_2, TELEFONE_3, :SERVICE_TYPE);",
                array(
                ':MTID'=> $data["mtid"],
                ':OPERACAO'=> $data["operacao"],
                ':STATUS_TRATAMENTO'=> $data["status_tratamento"],
                ':ID_MSG'=> $data["id_msg"],
                ':ESTAGIO_ENVIO'=> $data["estagio_envio"],
                ':OS'=> $data["os"],
                ':PDV'=> $data["pdv"],
                ':CLIENTE'=> $data["cliente"],
                ':TELEFONE_1'=> $data["telefone_1"],
                ':TELEFONE_2'=> $data["telefone_2"],
                ':TELEFONE_3'=> $data["telefone_3"],
                ':SERVICE_TYPE' => $data["service_type"]
                )
            );
    }
}

?>

a procedure é a seguinte:
    DELIMITER $$
CREATE PROCEDURE sp_base_insert(
pmtid varchar(30),
poperacao enum('AUD','AGF','DEV'),
pstatus_tratamento varchar(15),
pid_msg char(2),
pestagio_envio enum('1','2','3'),
pos int(9),
ppdv varchar(8),
pcliente int(15),
ptelefone_1 varchar(13),
ptelefone_2 varchar(13),
ptelefone_3 varchar(13),
pservice_type varchar(30)
)
BEGIN

    insert into sms (mtid, operacao, status_tratamento, id_msg, estagio_envio, os, pdv, cliente, telefone_1, telefone_2, telefone_3, service_type)
    values (pmtid, poperacao, pstatus_tratamento, pid_msg, pestagio_envio, pos, ppdv, pcliente, ptelefone_1, ptelefone_2, ptelefone_3, pservice_type);

END $$
DELIMITER ;

Alguém consegue me ajudar?
Answer: É erro de digitação, quando a mensagem aparece:

number of bound variables does not match number of tokens

É sempre relacionado aos seus "binds" da query
Tem dois TOKENS com erro no CALL:
:TELEFONE_1, TELEFONE_2, TELEFONE_3, :SERVICE_TYPE

Deveria ser:
:TELEFONE_1, :TELEFONE_2, :TELEFONE_3, :SERVICE_TYPE

Corrija isto e vai funcionar.
Comment: Guilherme, muito obrigado!!

Não acredito que não vi isso kkk... Deu certo agora!