Getting updated values from Observable's subscription

Question: I have noticed something about Observables in Angular 2 that I cannot explain and hope a good sould sheds light on me.
My understanding was that when subscribing to an Observable you have basically two strategies to consume the value it emits:
stream combined with async pipe, as in:
myTextSubscription$ = SomeObservable.subscribe();

{{ myTextSubscription$ | async }}

or extract the value and bind it from within the subscribe handler:
myTextSubscription$ = SomeObservable.subscribe(text => this.text = text);

{{ text }}

Well, the problem is that I have already tried a couple of times to use the latter approach and I never managed to get the text value updated, unless I invoke this.cdRef.markForCheck() within the handler. I guess invoking the changeDetection manually should not be required for such a basic scenario - at least I haven't seen that used in any of screencasts or tutorials.
Does this sound familiar to anyone? Is it my wrong understanding of the method, or is it perhaps a bug in Angular 2?

Edit:
The code above has been abstracted as I believed the problem could be explained on a more abstract level.
I cannot recall the first case when it bit me, but now the Observable comes from ngrx store, so it's basically something along these lines:
this.text$ = store.let((state$: Observable<State>) => {
  return state$.select(state => state.text);
});

Comment: Can you post more code? Like how is `SomeObservable` created? And what change detection strategy have you put on your component?
Comment: No you HAVE to run changedetection yourself. See http://stackoverflow.com/questions/38445670/angular-2-view-will-not-update-after-variable-change-in-subscribe/40707669#40707669
Answer: This usually happens if SomeObservable is somehow initialized outside Angulars zone or uses some API that is not coverted by zone.js.
We would need to see how SomeObservable is exactly constructed to know for sure.
Comment: Now we need to see how and where `store` is initialized and where it comes from (what package, GitHub repo).
Comment: The app has been scaffolded following the [ngrx example app](https://github.com/ngrx/example-app), so `store` comes from the StoreModule
Comment: That should work. Sorry, no idea why it doesn't for you. Is this in Chrome or some other browser?
Answer: In fact, you shouldn't subscribe to the observable when using async.
It's why async is that awesome. It handles both subscribe AND unsubscribe when your component is initialized/destroyed.
So instead of :
JS
myTextSubscription$ = SomeObservable.subscribe();

HTML
{{ myTextSubscription$ | async }}

You should rather have :
JS
myTextSubscription$ = SomeObservable;

HTML
{{ myTextSubscription$ | async }}

I'd like to clarify the use of $ in your variable name :
 - an observable should be suffixed with '$'
 - when you use subscribe, you do not get an observable
With respect of convention :
JS
let someObservable$ = ...;

HTML
{{ someObservable$ | async }}

Remember that :
- you need to unsubscribe manually from an observable when you use subscribe to it, except from the router and http)
- when you have a .subscribe, the value returned is of type Subscription (which means you can unsubscribe from it)
So here's an overview of a cleaner structure (without using async pipe) :
@Component({
  selector: '...',
  templateUrl: '...html',
  styleUrls: ['...css']
})
export class AppComponent implements OnInit, OnDestroy {
    private myText: string;
    private myTextSubscription: Subscription;

    constructor() { }

    ngOnInit() {
        // I assume here that you declared an observable called "someObservable"

        this.myTextSubscription = someObservable$.subscribe(text => this.myText = text);
    }

    ngOnDestroy() {
        // as our observable is not coming from router or http, we need to manually
        // unsubscribe in order to avoid memory leaks

        this.myTextSubscription.unsubscribe();
    }

}

EDIT 1:
With your updated example, here's how you should use it with @ngrx :
@Component({
  selector: '...',
  templateUrl: '...html',
  styleUrls: ['...css']
})
export class AppComponent implements OnInit, OnDestroy {
  private text: string;
  private textSub: Subscription;

  constructor(private store$: Store<State>) {
    this.textSub =
        store$.select('yourState')
            .subscribe((state: State) => this.text = state);
  }

  ngOnDestroy() {
    this.textSub.unsubscribe();
  }
}

Comment: If you want more info on ngrx/store or even ngrx/effects, here's what helped me a lot : This [tutorial](http://bodiddlie.github.io/ng-2-toh-with-ngrx-suite/) and once you feel comfortable enough, read the *awesome* code of this [repo](https://github.com/teropa/harmonics-explorer) (from Teropa).


Amazon SQS long polling returning 0 messages when messages are in the Queue

Question: Amazon SQS long polling is returning 0 messages when there are still messages in my queue. I've been able to reproduce this effect multiple times.
I'm aware that it's possible for SQS long polling to yield fewer messages than the max requested even if there are more messages on the queue.
I'm also aware that short polling can yield zero messages even when there are more than zero messages on the queue.
But I did not know that long polling could yield zero messages when there are more than zero messages on the queue. And from what I can tell after reading the docs, this isn't supposed to happen.
Question:
Is it possible for SQS long polling to return 0 messages even when there are messages on the queue? If so, are their specific conditions that make this likely to occur? If not, has anyone else experienced this behavior?
Comment: Your assertions are correct -- that should not be possible -- but the messages do have to be *visible* -- not already *in flight*.  Do you have messages showing in the console as in flight? Or as visible?  Is this a standard queue or a fifo?
Comment: @Michael-sqlbot Sorry for the slow response here and thanks for the comment. No messages showing as in flight, everything is visible. And it's a fifo queue.
Comment: @PeterBerg I've just faced the same (I guess) problem - did you manage to solve yours?
Comment: @Pijotrek no unfortunately. I've resorted just polling once every 20 seconds all day long to make sure I eventually get all of my messages. I'm not happy about this solution =/
Comment: @PeterBerg thanks, I'll have to think of a work-around too
Comment: Can you post example code?
Answer: Check that the group ID's are unique.
AFAIK, if one message in a group is in-flight, then the entire group is not visible.
Comment: When I add the messages I was using the same group id. It worked after changing group ids to different.
Thank you
Answer: As far as I know this could be related to any of these queue attributes:

Visibility timeout
Delay queues

Please rewiew your queue configuration. Bear in mind that it's possible to set specific visibility timeout on a message level, which could not match the value set for the queue.
Hope this may help.
Best regards,


Add SELECT DISTINCT ORDER BY to SQL Server VIEW

Question: I need to create a SQL VIEW (in Azure SQL Server) of the working statement below. I have tried many variations from Stack Overflow to no avail.
Code that returns exactly what I need:
SELECT DISTINCT
CAST (valueColumn AS INT)
FROM dbo.valueDB
ORDER BY CAST (valueColumn AS INT)

When prefixing this code with...
CREATE VIEW [distinctValues]
AS

I get the following error:
Started executing query at Line 1

Msg 1033, Level 15, State 1, Procedure distinctValues, Line 7
The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.

I've tried inserting TOP (100) PERCENT into the statement and cannot get it to work. I've also read this is a "hack" of sorts and shouldn't be used in production.
So how do I get the statement I want created as a VIEW?
Comment: You can't. A view, like a table, is logically unordered. The rows of a resultset have no specific order if the query creating it does not order the rows. The link you posted tells you EXACTLY THIS - there is no solution and only hacks are not 100 percent reliable.
Comment: @ericOnline, I hope that your question was answered. If so, can you consider to mark it as such one.
Answer: You can use a CTE in the view definition:
CREATE VIEW vwYourView
AS

    WITH AllValues
    AS (
        SELECT DISTINCT
            intValue = CAST (valueColumn AS INT)
            , intRank = ROW_NUMBER() OVER(PARTITION BY CAST (valueColumn AS INT) ORDER BY CAST (valueColumn AS INT))
        FROM dbo.valueDB
        )
    SELECT TOP(100) PERCENT intValue
    FROM AllValues
    WHERE intRank = 1
    ORDER BY intValue

Comment: Although this will not cause an error, it will not guarantee ordering of results. The only way to ensure ordering is with an `ORDER BY` clause in the `SELECT` statement that uses the view.
Comment: @DanGuzman, do you have a working example you can post of an `ORDER BY` clause in the `SELECT` statement?
Comment: @ericOnline, not tested but the view would be `CREATE VIEW distinctValues AS SELECT DISTINCTCAST (valueColumn AS INT) AS valueColumn FROM dbo.valueDB;`. The query from the view would be  `SELECT valueColumn FROM distinctValues ORDER BY valueColumn;`
Answer: No doubts that the most right way is:
SELECT valueColumn FROM vwYourView ORDER BY valueColumn

However, it happens that ETL or BI specific tools allow you only to perform a select of tables/views, but not write SQL and order of the data is important.
At least for now the workaround seems still valid to get a desired result in such cases:
CREATE VIEW vwYourView
AS
SELECT  DISTINCT TOP (9223372036854775807)  CAST (valueColumn AS INT) AS valueColumn
FROM dbo.valueDB
ORDER BY valueColumn

from the article mentioned in OP message:

Of course. There are always going to be ways to get SQL Server to bend
  to your will, even if only temporarily - by using a percentage so
  close to 100 percent that it will round up, or by using the upper
  bound of the BIGINT type:


How do I implement the autocomplete functionality in Webforms?

Question: I have a drop down box with college names that has 9000 options to choose from. I am unable to use the drop-down field in Webforms.
Is there a way to use an autocomplete in a text field for Drupal 6?
Answer:
Autocomplete is implemented in Drupal through AJAX. When users type
  into a textbox, code on the client page dynamically loads new data
  from the server (a Drupal website) and uses this data to update the
  user display (provide a drop-down list of matching options, which the
  user can select from).

Available autocomplete functions (D6):

user_autocomplete() - Use this function to load matching user names.
taxonomy_autocomplete() - Use this function to load matching taxonomy terms.

If you want to have your own autocomplete function it is also possible.
Please see a full article on this subject on drupal.org "Textfield that uses autocomplete"
to see how to build a custom autocomplete function.


load balancing, high availability for webapp setup

Question: We have build a special interest social network and need to setup now the proper server setup for the webapp servers.
We have for the webapp 5 physical server available (2xE5645 CPU, 24 GB Ram, RAID, 4x Gbit NIC), one of the five server need to provide the API for our mobile visitors (iOS, Android). Our webapp need PHP, APC, Memcached and MySQL.
Also we have 4 more physical server inside (2xE5620, 12 GB Ram, RAID, 4x Gbit NIC):

Comet push server (custom server for the chat)
Queue/Mail server (beanstalkd)
static webserver (G-WAN webserver) with 2xDAS with 12x2TB (total 40 TB in Raid 6)
Apache webserver dedicated for HTTPS (this server can also be used for the LB cluster  if the SSL secured page will be put on the LB cluster, is this better?).

For the beginning we only want to have the webapp server in LB/HA, because we don't have more servers available at the moment.
And a last is a low cost server (X3430, 4 GB Ram, RAID, 2x Gbit NIC) that is used for monitoring all Hardware.
We have 2x HP Procurve 2900 managed 48 port Gbit Switch.
All the above equipment stay in our Rack in a network center.
We use RHEL 6 on all servers.
I have much ideas, but I'm not really sure which will be the best way.
My direction is go the way to install HA Proxy and Apache webserver on two boxes, have on two boxes MySQL DB Server and on one both Apache and MySQL for the API/Webservice.
To use one of the switch for private network where all server will be connected and used for internal communication (MySQL, File transfer after upload).
Is it helpful to connect multiple NIC ports per server to the Switch?
Is HA Proxy the best way for our case? Or would it be better to use nginx on 2 or 3 boxes and to use it for load balancing and serving PHP and have LVS or some similar for the HA part?
I'm open for all solutions, and the 5+1 server can be used flexible.
Thanks for any help.
UPDATE:
After more research, I think it would be hard to find a solution to have HA for all Server.
My actual idea for the setup is:
nginx as Proxy for load balancing (I will use one of the mid spec boxes)
3 Apache webserver on private net
2 MySQL Server Master/Slave on private net
In the above solution, the Apache Webserver will also host the SSL site for payout, I'm not sure if nginx can handle the SSL certificate for this different backend servers.
UPDATE 2:
I have do more research, Redhat offers a Add-On for Load balancing based on LVS.
http://docs.redhat.com/docs/en-US/Red_Hat_Enterprise_Linux/6/html/Virtual_Server_Administration/ch-lvs-overview-VSA.html
This Addon looks well, BUT I still don't know which way is the right one? Is it better to go with a nginx in front or with LVS or something other? Someone told me I can use the existing HP Procurve 2900 Switch for simple load balncing too....
Comment: Have a look at a related question http://serverfault.com/questions/272567/setting-up-a-high-speed-load-balancing-server-cluster-web-db-nfs/272649#272649
Answer: LVS is designed for layer 4 load balancing. nginx or ha proxy are only used for layer 7( I mean web traffic) load balancing. Thus, I would like to suggest you use nginx or HA proxy as your load balancer if web traffic is your biggest work load. If max concurrent connections is your bottleneck, then I will recommend that you use HA proxy as your load balancer because HA proxy has better performance(Ref:http://affectioncode.wordpress.com/2008/06/11/comparing-nginx-and-haproxy-for-web-applications/).
Answer: HA for a webapp SHOULD be designed in from the start. Wish I had ever seen that happen :)
But seriously: You are asking for an active/active setup. The most important questions when deciding on such an architecture is how application data needs to or does not need to, can be or cannot be kept synchronous between the app servers. Also, HOW synchronous does it have to be, is there code that expects a change to be globally distributed before returning, are there areas in the application that can deal with a couple seconds state lag but not more (do not forget that mysql replication is of the second type!)? These needs and possibilities will dictate your setup. Scaling hardware comes later. And active/active is always difficult to graft onto anything that wasn't designed with it in mind.


Mobius transformation type and quotient field

Question: I am reviewing materials in polynomial ring and came across this problem from Lang's Algebra.
Let $F$ be a field and $F(X)$ be the quotient field of $F[X]$. Show that every automorphism of $F(X)$ which induces the identity on $F$ is of type $X \mapsto \frac{aX+b}{cX+d}$ where $a,b,c,d \in F$ and the norm of the image is nonzero, i.e $ad-bc \neq 0$.
I don't quite have the intuition for this since I haven't touched this for a long time. Any suggestion or guide is tremendously appreciated.
Answer: I'll use that poles of rational functions behave nicely (of course) under multiplication and inverse, but also under addition.

Note $\text{div}(\frac1x) = [\infty]-[0] \qquad $ ($f(x) =  \frac1x$ has a simple pole at $0$ and a simple zero at $\infty$) and for any $f \in F(x)$, $\#$ poles $= \#$ zeros.
If $\phi \in F(x),f \in F(X)$ and $\phi$ has two poles at $p,q$ then write $$\phi(x) = (x-p)^{-k} (x-q)^{-l} \Phi(x),\qquad  f(\phi(x)) = \frac{\sum_{i=0}^d c_i \phi(x)^i}{\sum_{j=0}^e b_j \phi(x)^j}= (x-p)^{k(e-d)} (x-q)^{l(e-d)} h(x)$$
where $h$ and $\Phi$ have no pole or zero at $p,q$. In particular $f(\phi(x)) \ne \frac1x$ and $x,\frac1x \not \in F(\phi(x))$.
Therefore $x \mapsto \phi(x)$ is an automorphism of $F(x)$ implies $\phi$ has only one simple pole ie. $\text{div}(\phi(x)) = [q]-[p]$ with $p\ne q$ and hence $\phi(x) = C \frac{x-q}{x-p}$ is a Möbius transformation.
Comment: I dont quite understand your second step, why do $\phi$ and $f$ have to be in that form ? Also, what is $\Phi$ in this case ?
Comment: @S_j $\Phi$ has no zeros or poles at $p,q$. Then $\sum_{i=0}^d c_i ((x-p)^{-k} (x-q)^{-l})^i \Phi(x)^i= ((x-p)^{-k} (x-q)^{-l})^d \sum_{i=0}^d c_i ((x-p)^{k} (x-q)^{l})^{d-i} \Phi(x)^i$ where wlog $c_0 \ne 0$ so that $c_0+\sum_{i=1}^d c_i ((x-p)^{k} (x-q)^{l})^{d-i} \Phi(x)^i$ has no poles or zeros at $p,q$.
Comment: @S_j I forgot to mentioned we go into the algebraic closure of $F$ to define the zeros and poles, so possibly $p,q \in \overline{F}$ but $\not\in F$, and then we say $\frac{x-q}{x-p} \in F(x)$ implies $p,q \in F$


Como desabilitar um botão em java sem retirar sua cor

Question: Tenho um botão que, ao clicá-lo ele muda de cor, mas se clicar nele novamente nada deve acontecer. Porém ainda não consigo bloquear essa ação.
Tentei esse codigo:
private void Button1_1ActionPerformed(java.awt.event.ActionEvent evt) {
    if(TextoJogador.getText().equals("Jogador 1")){
        Button1_1.setBackground(Color.CYAN);
        TextoJogador.setText("Jogador 2");
        play(sound);

    }else{
        Button1_1.setBackground(Color.GREEN);
        TextoJogador.setText("Jogador 1");
        play(sound);
    }
    Button1_1.setEnable(false); //essa parte que faz o button perder a cor
}

mas o botão perde a cor que foi selecionada ao ser desativado.
Comment: Qual é a cor inicial do botão (antes de qualquer clique)?
Comment: Nenhuma cor. ele só obtem uma cor apos o primeiro clique, isso é um jogo da velha.
Answer: Pelo que eu entendo o setEnabled(false) muda a aparência do botão mesmo, não tem jeito. Mas experimente assim:
private void Button1_1ActionPerformed(java.awt.event.ActionEvent evt) {
    if (Button1_1.getBackground() != Color.CYAN && Button1_1.getBackground() != Color.GREEN) {
        if(TextoJogador.getText().equals("Jogador 1")){
            Button1_1.setBackground(Color.CYAN);
            TextoJogador.setText("Jogador 2");
            play(sound);

        }else{
            Button1_1.setBackground(Color.GREEN);
            TextoJogador.setText("Jogador 1");
            play(sound);
        }
    }
}

Comment: irei complementar a pergunta
Comment: Veja agora se atende
Comment: Perfeito mano, não havia pensado nisso :) obrigado!
Comment: Beleza, só aceitar a resposta então, clicando no ✓ do lado esquerdo e votando +1. Obrigado.
Answer: Isso ocorre por causa do LookAndFeel(LAF), pois é ele quem define as estilizações de todos os componentes do swing. Se você aplicar o LAF Metal, que é um LAF mais básico, esse problema não irá acontecer.
Porém, imagino que esteja utilizando o Nimbus, que é o LAF padrão de projetos criados pelo netbeans, ainda tem como alterar direto nele, mas a outra resposta acaba sendo mais simples e viável, sem ter que deixar a aparência da aplicação mais básica.
Se quiser se aventurar em alterar o LAF, pode adicionar apenas a linha abaixo dentro do main, antes de iniciar a tela:
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");

Com isso, o setEnabled(false)  não afeta o background que você alterou inicialmente do botão, porém, como consequência de ser um tema básico, sua aplicação fica com uma aparência mais rudimentar, quando comparada ao Nimbus.


Reverting/updating "FILE_DISPLAY" in Features

Question: My site is running Drupal v7.30 and Features v7.x-2.2. I can't revert or update file_display components in features. There are additional definitions under the Default column that appear to be define by the Media (7.x-2.0-alpha3) module in hook_file_default_displays_alter(). How do I go about properly keeping my features not in a perpetual Overridden state?
Comment: This issue from Panopoly might be helpful ['file_display' components are always overridden (update Media / File Entity)](https://www.drupal.org/node/2159149).
Answer: There is a bug with media and the media modules.
There is some patches already that you could try
https://www.drupal.org/node/2104193


D8: Why updated paragraph content does not lead to an updated translation?

Question: I created a content type made up with a long-text field and a multivalue paragraph field. I create some content adding several paragraphs to the same node, then I choose "Translate" and everything is fine the first time I do this: all original paragraphs appear ready to be translated.
However when I update the original language node adding new paragraphs, these new paragraphs do not appear when editing the translation and I'm forced to delete the latter and create a new translation. Why is this happening?
Comment: You should check https://www.drupal.org/node/2735121, this depends on how you've configured the paragraph fields.
Answer: To expand on the comment from @4k4, for most use cases, you want to make the paragraph field untranslatable because it just stores the references to the paragraphs, which are then being translated.
Then you always have the same paragraphs in the same order for all translations.
Translatable paragraph fields are not yet properly supported (this is being worked on in the issue queue) and it should only be done if the paragraph structure must be different for different languages.


Failing getent groups fail but getent passwd works

Question: I have an AD server running on server 2019. I just setup a linux box and configured samba for some reason i can't get getent group "domain admins" to show anything. if i do getent passwd Administrator it does work, and wbinfo -u or wbinfo --domain-groups works fine as well.
SMB.CONF
[global]
        server role = MEMBER SERVER
        security = ADS
        realm = TESTLAB.COM
        workgroup = TESTLAB
        dedicated keytab file = /etc/krb5.keytab
        kerberos method = secrets and keytab
        server string = Samba 4 %h
        log file = /var/log/samba/%m.log
        log level = 5
        idmap config * : backend = tdb
        idmap config * : range = 10000-20000
        idmap config TESTLAB : backend = rid
        idmap config TESTLAB : range = 30000-40000
        idmap config TESTLAB : backend = ad
        password server = adsrv1.testlab.com
        encrypt passwords = yes
        winbind refresh tickets = yes
        winbind offline logon = yes
        winbind enum users = yes
        winbind enum groups = yes
        winbind nested groups = yes
        winbind expand groups = 4
        winbind use default domain = yes
        #winbind normalize name = yes
        os level = 20
        domain master = no
        local master = yes
        preferred master = no
        map to guest = bad user
        host msdfs = no
        netbios name = smbsrv
        client min protocol = SMB2
        client max protocol = SMB3
        client ldap sasl wrapping = plain
        hosts allow = 10.0.0.0/16
        unix extensions = no
        reset on zero vc = yes
        veto files = /.bash_logout/.bash_profile/.bash_history/.bashrc/
        hide unreadable = yes
        acl group control = yes
        acl map full control = true
        ea support = yes
        vfs objects = acl_xattr
        store dos attributes = yes
        #dos flemode = yes
        dos filetimes = yes
        enable privileges = yes
        restrict anonymous = 2
        strict allocate = yes
        guest ok = no
        load printers = no
        printing = bsd
        printcap name = /dev/null
        disable spoolss = yes
        username map = /etc/samba/user.map
        template shell = /bin/bash
        template homedir = /home/TESTLAB/%U
[Data]
        comment = "User Data"
        path = /mnt/data
        create mask = 0770
        browseable = yes
        writable = yes
        valid users = @"Domain Admins" @"Domain Users"
        write list = @"Domain Admins" @"Domain Users"

NSSWITCH.CONF
passwd:         compat files winbind sss
group:          compat files windind sss
shadow:         compat files sss
gshadow:        files

hosts:          files dns mdns4_minimal [NOTFOUND=return] mdns4
networks:       files

protocols:      db files
services:       db files sss
ethers:         db files
rpc:            db files

netgroup:       nis sss
sudoers:        files sss

KRB5.conf
[libdefaults]
        default_realm = testlab.com
        dns_lookup_realm = false
        dns_lookup_kdc = true

# The following krb5.conf variables are only for MIT Kerberos.
        kdc_timesync = 1
        ccache_type = 4
        forwardable = true
        proxiable = true

# The following libdefaults parameters are only for Heimdal Kerberos.
        fcc-mit-ticketflags = true

[realms]
        testlab.com = {
                kdc = adsrv1.testlab.com
                admin_server = adsrv1.testlab.com
        }
        ATHENA.MIT.EDU = {
                kdc = kerberos.mit.edu
                kdc = kerberos-1.mit.edu
                kdc = kerberos-2.mit.edu:88
                admin_server = kerberos.mit.edu
                default_domain = mit.edu
        }
        ZONE.MIT.EDU = {
                kdc = casio.mit.edu
                kdc = seiko.mit.edu
                admin_server = casio.mit.edu
        }
        CSAIL.MIT.EDU = {
                admin_server = kerberos.csail.mit.edu
                default_domain = csail.mit.edu
        }
        IHTFP.ORG = {
                kdc = kerberos.ihtfp.org
                admin_server = kerberos.ihtfp.org
        }
        1TS.ORG = {
                kdc = kerberos.1ts.org
                admin_server = kerberos.1ts.org
        }
        ANDREW.CMU.EDU = {
                admin_server = kerberos.andrew.cmu.edu
                default_domain = andrew.cmu.edu
        }
        CS.CMU.EDU = {
                kdc = kerberos-1.srv.cs.cmu.edu
                kdc = kerberos-2.srv.cs.cmu.edu
                kdc = kerberos-3.srv.cs.cmu.edu
                admin_server = kerberos.cs.cmu.edu
        }
        DEMENTIA.ORG = {
                kdc = kerberos.dementix.org
                kdc = kerberos2.dementix.org
                admin_server = kerberos.dementix.org
        }
        stanford.edu = {
                kdc = krb5auth1.stanford.edu
                kdc = krb5auth2.stanford.edu
                kdc = krb5auth3.stanford.edu
                master_kdc = krb5auth1.stanford.edu
                admin_server = krb5-admin.stanford.edu
                default_domain = stanford.edu
        }
        UTORONTO.CA = {
                kdc = kerberos1.utoronto.ca
                kdc = kerberos2.utoronto.ca
                kdc = kerberos3.utoronto.ca
                admin_server = kerberos1.utoronto.ca
                default_domain = utoronto.ca
        }

[domain_realm]
        .mit.edu = ATHENA.MIT.EDU
        mit.edu = ATHENA.MIT.EDU
        .media.mit.edu = MEDIA-LAB.MIT.EDU
        media.mit.edu = MEDIA-LAB.MIT.EDU
        .csail.mit.edu = CSAIL.MIT.EDU
        csail.mit.edu = CSAIL.MIT.EDU
        .whoi.edu = ATHENA.MIT.EDU
        whoi.edu = ATHENA.MIT.EDU
        .stanford.edu = stanford.edu
        .slac.stanford.edu = SLAC.STANFORD.EDU
        .toronto.edu = UTORONTO.CA
        .utoronto.ca = UTORONTO.CA
        .testlab.com = TESTLAB.COM

SSSD.CONF
[sssd]
config_file_version = 2
services = nss, pam
domains = TESTLAB
# SSSD will not start if you do not configure any domains.
# Add new domain configurations as [domain/<NAME>] sections, and
# then add the list of domains (in the order you want them to be
# queried) to the "domains" attribute below and uncomment it.
; domains = LDAP

[nss]

[pam]

# Example LDAP domain
[TESTLAB.COM/LDAP]
id_provider = ldap
auth_provider = ldap
# ldap_schema can be set to "rfc2307", which stores group member names in the
# "memberuid" attribute, or to "rfc2307bis", which stores group member DNs in
# the "member" attribute. If you do not know this value, ask your LDAP
# administrator.
ldap_schema = rfc2307
ldap_uri = ldap://ldap.testlab.com
ldap_search_base = dc=testlab,dc=com
# Note that enabling enumeration will have a moderate performance impact.
# Consequently, the default value for enumeration is FALSE.
# Refer to the sssd.conf man page for full details.
enumerate = true
# Allow offline logins by locally storing password hashes (default: false).
cache_credentials = true

# An example Active Directory domain. Please note that this configuration
# works for AD 2003R2 and AD 2008, because they use pretty much RFC2307bis
# compliant attribute names. To support UNIX clients with AD 2003 or older,
# you must install Microsoft Services For Unix and map LDAP attributes onto
# msSFU30* attribute names.
[domain/TESTLAB]
id_provider = ldap
auth_provider = krb5
chpass_provider = krb5

ldap_uri = ldap://ldap.testlab.com
ldap_search_base = dc=testlab,dc=com
ldap_schema = rfc2307bis
ldap_sasl_mech = GSSAPI
ldap_user_object_class = user
ldap_group_object_class = group
ldap_user_home_directory = unixHomeDirectory
ldap_user_principal = userPrincipalName
ldap_account_expire_policy = ad
ldap_force_upper_case_realm = true

krb5_server = 10.0.0.10
krb5_realm = TESTLAB.COM

Answer: First thing to try is to correct the typo for group resolution in your nsswitch.conf file.
group:          compat files windind sss

...should be...
group:          compat files winbind sss


Catch the selection of the values in select/drop-down-box prior to the node submission

Question: I have a Drupal 7 custom module with a couple of select/drop-down-boxes.  Is there a hook to catch the selection of the values in those boxes prior to the submission of the content node?  I am looking for a hook before the hook_node_submit occurs.
Thanks,
Derek
Comment: With an ajax callback on your form you can catch whatever, whenever you want prior to submission. The form validate functions fire first, you could always inject another custom form_submit function into the form to handle your own custom processing (and probably adjust your modules weight to come prior to the parent content type as needed).
Comment: Why exactly would you need that?
Comment: I want to call some custom db function to get back values and create a radio-button list dynamically.  This all needs to occur before save/submit.  I am checking out ajax callback as suggested by tenken.
Answer: You might be looking for hook_node_presave()

Act on a node being inserted or updated.
This hook is invoked from node_save() before the node is saved to the
  database.

To attach a custom submit handler, create a custom module and do something like this:
<code>function my_module_form_alter(&$form, $form_state, $form_id)
{
  if($form_id == 'form_abc')
  {
    $form['#submit'][] = "my_module_form_submit_handler";
  }
}

function my_module_form_submit_handler($form, &$form_state)
{
  drupal_set_message("The form is being submitted, do some extra stuff now...");
}
</code>
Comment: Thanks for this advice Geoff. This appears to occur after hook_node_submit().  I think what I am needed is to stop the saving of the node so that I can present the user with some more selections (from the external DB) before they finally save/submit.
Comment: I see - this does occur after submit(), just re-read your question and realised this isn't what you're looking for after all. There is nothing before submit() - you would need to rewrite the submit handler and do whatever processing you want, and then call the core submit() to finalise things
Comment: Not even hook_form_alter then?  I wonder if this was the case in older version of drupal.  I am up for re-writing the submit handler if I can find some documentation on how to do that specific to this node content type.
Comment: hook_form_alter occurs before the form is rendered, not after its filled out - that's where you can make changes to it before the user even sees it
Comment: @geoderek I added some code to get you started on a custom submit handler
Comment: Thanks Geoff.  Stinks to keep being stuck on this.  I created function w/ the name like CUSTMODULE_form_FORM_ID_alter.  I tried putting a set message in there to see if it  even gets there. When I hit save I can't get the code within it to run.
Comment: Be sure to clear the cache or it wont find a new hook
Comment: Brilliant! Thanks for sticking w/ me.  That worked.


On $\eta$-reduction

Question: NB: This is a full reworking of an earlier post of mine (which I have now deleted).  That earlier post was flawed due to a technicality (applying $\eta$-reduction without considering the question of free variables) that clouded issue.  This version sidesteps that technicality altogether (I think).

The $\mathbf{identity}$ function can be represented like this:
$$\lambda f.f\label{a}\tag{1}$$
Now, if I understand $\eta$-reduction correctly, the (atomic!) name that makes up the body of this function, namely $f$, is equivalent to the function $\lambda x.(f\;x)$.
Consider the expression obtained by replacing the body of the identity function above with the equivalent expression $\lambda x.f\;x$ (thus performing an "$\eta$-expansion", if you will):
$$
\lambda f.\lambda x.(f\;x)\label{b}\tag{2}
$$
My question is: are expressions $\ref{a}$ and $\ref{b}$ equivalent?

My naive answer to this question is: "of course!", but I hesitate because

I'm not completely confident on which manipulations produce equivalent $\lambda$-expressions; and, more importantly
My book gives expressions $\ref{a}$ and $\ref{b}$ different names ($\mathbf{identity}$ and $\mathbf{apply}$, respectively), and says nothing about their being equivalent.
Answer: One way to see if they are equivalent is to just see how they treat parameters.
$$Iab = ab$$
$$(\lambda f.f)ab = ab$$
$$(\lambda f. \lambda x . fx)ab = (\lambda x.ax)b = ab$$
All become ab when given arbitrary parameters a then b, so they are equivalent.

On $\eta$-reduction


requirement of root privileges for libpcap functions

Question: The pcap_lookupdev() fills in the errbuf variable when run as non-root user, while the same functions returns the value of the first available network interface when run as root.
Is this access disabled by the OS or the library. I think it is the OS. What is the right answer?
This is not a homework question
Answer: In general, when it comes to accessing files, devices and other services provided by the OS, access models in Unix (and, thus, Linux) are implemented in the OS.
Userspace programs are expected to just try whatever they want to do and gracefully handle any error condition by e.g. informing the user with a message.
This has several advantages:

Maintainability: Access policy enforcement remains with the OS and can be configured uniformly. The administrator that wants to restrict access to a resource does so once, rather than having to configure this library here, than that library there, then...
Configurability: The administrator can configure as simple or complex an access policy they need without being limited by each userspace implementation.
Security: Userspace programs should not in general be trusted with enforcing access policy. It would be like having a wolf guard the sheep.

EDIT:
In your case, pcap needs low-level access to the network interface. Due to the security implications (capturing network traffic, generating arbitrary network packets etc), such access is limited to privileged users only. On Linux, for example, pcap needs the CAP_NET_RAW capability to be available to the user.
Answer: Many of the pcap functions require root privileges in order to work correctly. Might this be the problem?
Comment: Well, that is precisely my question. Why does it require _root_ privileges? Anyway, it has been answered, I must say, quite beautifully, by thkala
Answer: It mostly depends on OS. Not all pcap functions require root privilege on all OS.
Ref to Reference Manual Pages, all special privilege requirements are listed respectively.


Why D sharp not E flat in Turkish March

Question: I'm analyzing Mozart's Turkish March piece for the piano.
As I see in measure 18 the harmony is F7 (fourth) with minor seven.
Assuming it is a minor seven because the harmony is F7 why they thought about the seventh as D sharp but not E flat ?
In other words:
Harmony is F7 --> includes Minor 7 --> should be E flat
See the picture (the measure in the middle)
Comment: What key is it in again? Also note that E is notated in the next measure. While a natural sign wouldn't be strictly necessary in the next measure if Eb were used, it seems a bit clearer as written. Oh and E in the previous measure.
Comment: The key is A minor if anything.
Comment: For context, I believe [this](http://www.mutopiaproject.org/ftp/MozartWA/KV331/KV331_3_RondoAllaTurca/KV331_3_RondoAllaTurca-a4.pdf) is the sheet music.
Answer: It's a D# because it's functioning as a D#. In the three measures you can see the line goes E -> D# -> E. It's acting much more leading tone like than 7th like as if it were truly an F7 the next note would either be the same or resolve down.
The fact the harmony could be interpreted as an F7 is kind of a moot point as the next measure lands squarely on Am which harmonically doesn't make the most sense and could be a more chromatic harmony or exotic in nature which in that case a lot more needs to be looked into in this analysis.
Comment: That makes me think it might really be an augmented 6th instead of a minor 7th.
Comment: It's a French 6th. The B in the descant is a chord tone, the top three notes make a truncated B dominant 7th chord (no fifth), the F in the bass moves to E.
Comment: Yeah, I agree with @Patrx2. This is a fairly clear example of a French augmented sixth (or Italian augmented sixth with a B passing tone, which to me is basically six of one, half a dozen the other). The only thing making it slightly less straightforward is that it doesn't proceed to as clear-cut of a V as it normally tends to. But it's still moving to a cadential 6/4 followed by an (admittedly somewhat mangled) V4/2.
Comment: @PatMuchmore, I'm saying French 6th here because Mozart is being _really_ cute. The first half of the bar is being voiced as if it were F7, but he's treating the high C as an appoggiatura with a cambiata-style resolution.
Comment: ...which is really cute because the C is consonant.
Comment: @ToddWilcox or Augmented 4th to Perfect 5th as the chord before and after seem to be Am and this could be an alteration. Without looking at the whole phrase it could be a lot of different things.
Comment: I agree that the D# functions as a leading tone and is therefore correct. I added the sheetmusic the OP is probably using in the comments section for analysis of the phrase.
Comment: @user16935 is right. The C is part of the chord. The B is merely a passing note between the A and the next bar's C. So the chord is a [German sixth](https://en.wikipedia.org/wiki/Augmented_sixth_chord#German_sixth).
Answer: To amplify Dom's reply, it is indeed a D♯. What is going on here is that Mozart is using an augmented sixth chord (specifically the French sixth) that is being used as dominant preparation. Normally how a French sixth works is that the upper notes form V7 of V (with a missing fifth), while the bass falls a half step from ♭6 to 5. It is a variant of the Phrygian cadence (iv6 - V).
Thus the progression would normally be F6 - V - i, but Mozart is being cute here: instead of holding the high B and heading directly to V, he is taking the chord through the tonic second inversion (which is normally treated as a suspension or appoggiatura leading to V, and is thus also dominant preparation) to the second inversion diminished seventh on G♯, which stands in for V.
Sure enough, in the following bar he ends up on i6 (A minor). The B and A in the descant of the 2nd bar of your example are passing notes, the A being an accented one.

Why D sharp not E flat in Turkish March


Determining the area of a right triangle, perimeter given, hypotenuse value given in terms of one of the legs.

Question: The problem states:
Right Triangle- perimeter of $84$, and the hypotenuse is $2$ greater than the other leg. Find the area of this triangle.
I have tried different methods of solving this problem using Pythagorean Theorem and systems of equations, but cannot find any of the side lengths or the area of the right triangle. I looked for similar problems on StackExchange and around the internet, but could not find anything.
Does anyone know anything that could help find the side lengths of the triangle and the area as well?
Method that I tried:

Made a system with the values given.
\begin{align}
 a+b+c&=84  \\
 c&=b+2
\end{align}
Substituted $c$ with $b+2$.
\begin{align}
 a+b+b+2&=84 \\
 a + 2b &= 82 & \text{subtracted $2$ from both sides}\\
a + a^2 - 4 &= 82
\end{align}
$c^2$ is $(b+2)(b+2)$, so I used Pythagorean Theorem to isolate one of the variables.
\begin{align}
a^2+b^2 &=c^2\\
a^2 + b^2 &=(b+2)(b+2)\\
a^2+b^2 &=b^2+2b+4\\
a^2&=2b+4 & \text{ (Subtracted $b^2$ from both sides)  }
\end{align}
OR
\begin{align}
a^2-4&=2b
\end{align}

I do not know what to do after this point.
Comment: Suppose that we call the length of the hypotenuse $h$ and the other legs $x$ and $y$, and say that $h$ is 2 units longer than the side with length $x$. i. What does the fact that it's a right triangle tell you about $h, x, y$? ii. What does the fact that the hypotenuse is 2 units longer than one leg tell you about $h, x, y$? iii. What does the fact that the perimeter is $84$ tell you about $h, x, y$? You can write these three equations into your question by clicking "edit" just below the question; then you can show us how you tried to solve them, too.
Comment: @amd I edited the question with more information.
Comment: How about showing some of your attempts so that someone might point out where you're going wrong?
Comment: What does "the other leg" mean?
Comment: By other leg, do you mean the "other legs?"
Comment: @JohnHughes I will do such right now.
Comment: @lulu The other leg can be either a or b.
Comment: @MohammadZuhairKhan The other leg can be either a or b.
Comment: I've edited your question to re-format the mathematics, so that you can look at it and see how it's done, in case you need to ask further questions. In doing so, I noticed that in the second set of displayed equations, the third line ($a + a^2 - 4 = 82$) seems to come out of nowhere. [it looks as if perhaps you took the last part of the third set of displayed equations and used it in the second...it's not a good idea to muddle the order like this!]
Comment: @JohnHughes Thank you for the format help and the suggestions.
Answer: Let the sides of the right triangle be $x,y,x+2$.
Given,
$2x+y=82   \tag{1}$
$x^2 + y^2 = (x+2)^2   \tag{2}$
$$\implies x^2 + y^2 = x^2 +4x+4 $$
$$\implies y^2 = 4x+4 $$
Now, substitute the value of $x$ from equation (1) in terms of $y,$ you will get a quadratic equation in $y$ whose roots can be easily found and hence, the sides and area.
Comment: What is the value of x from equation (1)? Is it 2x=82-y or can it be simplified even more?
Comment: It can be simplified to $x = 41 - \frac{y}{2}$. Try that, and further edit your question if you get stuck again. Good work so far!
Answer: $\\ \textbf{Finding triples, given perimeter using Euclid's formula}$ where $P=perimeter$
$$P=(m^2-n^2 )+2mn+(m^2+n^2 )=2m^2+2mn\implies n=\frac{P-2m^2}{2m}\quad where \quad \biggl\lceil\frac{\sqrt{P}}{2}\biggr\rceil\le m \le \biggl\lfloor\sqrt{\frac{P}{2}}\biggr\rfloor$$
Here, the lower limit ensures that  $m>n$ and the upper limit insures that $n>0$.
Example:
$$P=84\Rightarrow \biggl\lceil\frac{\sqrt{84}}{2} \biggr\rceil =5 \le m\le\biggl\lfloor\sqrt{\frac{84}{2}}\biggr\rfloor =6:\quad f(84,5)\notin\mathbb{N}\quad f(84,6)=1\Rightarrow
F(6,1)=(35,12,37)$$
There are no other solutions for $P=84$.


How to give pagination for Rest Service data

Question: I am using Rest Service and pull the data from another non drupal db.
I wrote custom module with two form elements and render that data (rest service call) and display using theme table.
I wrote  <code>$form['pager'] = array('#theme' => 'pager');</code> for pagination.
Pagination is working only for data which rendered using db query. In my condition it's not working.
How can I add pagination for my table.
<code> function myForm($form, &$form_state){
 pager_array_splice($final_data, 10);
foreach($final_data as $key => $value){
     $source=explode('=',$key);
     $options[]=array(
        'Token_Source'=>$source[0],
        'Tokens'=>$value,
     );
}

$form['pagerTop'] = array('#theme' => 'pager');
$form['entities'] = array(
  '#type' => 'tableselect',
  '#header' => $header,
  '#options' => $options,
  '#attributes' => array('class' => array('entity-sort-table viewTable tokensTable')),
  '#empty' => t('There are no Notification ....'),
);
$form['pagerBottom'] = array('#theme' => 'pager');
return $form;
}
function pager_array_splice($data, $limit = 9, $element = 0) {
print_r($data);
global $pager_page_array, $pager_total, $pager_total_items;
$page = isset($_GET['page']) ? $_GET['page'] : '';

// Convert comma-separated $page to an array, used by other functions.
$pager_page_array = explode(',', $page);

// We calculate the total of pages as ceil(items / limit).
 $pager_total_items[$element] = count($data);
$pager_total[$element] = ceil($pager_total_items[$element] / $limit);
 $pager_page_array[$element] = max(0, min((int)$pager_page_array[$element],     ((int)$pager_total[$element]) - 1));
 return array_slice($data, $pager_page_array[$element] * $limit, $limit, TRUE);
}
</code>
Answer: <code>  $row = pager_array_splice($options, 10);

$form['pagerTop'] = array('#theme' => 'pager');
  $form['entities'] = array(
  '#options' => $row,
  );
</code>
please assign $row value in the theme table
Comment: Hey tx for ur reply... Thats great..


How to use flutter geofire to update coordinates in database in realtime

Question: My question is, I want to store the current position of the user (in latitude and longitude) to be stored in the database, and this will change dynamically wherever the user is positioned currently.
All I know from reading the documentation is how to set the location but I'm not sure how to set realtime updates.
I'm building a driver's app and the courses code uses the following:
StreamSubcription<Position> homeTabPageStreamSubscription = Geolocator.getPositionStream().listen(Position position) {
currentPosition = position;
Geofire.setLocation(currentfirebaseUser.uid, position.latitude, position.longitude);

This is I think is outdated, so I would need someone's help with how I can store a user's current location coordinates in realtime database that get's updated when the user's location moves.
Answer: Let flutter set the type for you. Change variable type to final. Doing this worked for me.
final homeTabPageStreamSubscription = Geolocator.getPositionStream().listen(Position position) {
currentPosition = position;
Geofire.setLocation(currentfirebaseUser.uid, position.latitude, position.longitude);


Prove a metric space is totally bounded

Question: Let $X = 2^{\mathbb{Z+}}$ be the space of binary sequences $(x_k)_{k\ge1}$ with each $x_k \in \{0,1\}.$ Define a metric on $X$ by $d(x,y) = \sum^\infty_{k=1} |x_k−y_k|/2^k.$ I am trying to use the definition of a totally bounded space but I haven't found the $\varepsilon$-net of $X.$ My question is how to find the $\varepsilon$-net so that we can prove that $X$ is totally bounded?
Comment: Your space is homeomorphic to $\prod_{n\in\mathbb{Z}_+}\{0,1\}$ with the product topology. The product t of compact spaces is compact.  As for he specifics of your question, notice that $\sum_{n\geq m}\frac{1}{2^n}\xrightarrow{m\rightarrow\infty}0$.
Answer: If I'm understanding the question correctly, what you're looking for is, for each $\varepsilon>0,$ a finite set of points in your space such that every point in the space is within a distance $\varepsilon$ of some point in that finite set.
Find the smallest positive integer $k$ such that $2^{-k}<\varepsilon.$ Then consider the set of all sequences of the following form: $$x_1, x_2, x_3, \ldots,x_k,\,\underbrace{0, 0, 0, 0, 0, \ldots\ldots}$$
There are only $2^k$ of these, a finite number. And every point is within $\varepsilon$ of one of these.
Comment: Yes, this is what I'm looking for. Thank you very much!!
Answer: It is enough to consider the special case of an $\epsilon$ of the shape:
$$
\epsilon = \frac 1{2^{N-1}}\ ,\qquad N\in\Bbb Z_{>0}\ .
$$
So let us fix such an $N$ and a corresponding $\epsilon$. Consider all (finitely many) elements $x(a)=(a_1,a_2,\dots,a_N,0,0,\dots)$ with $a=(a_1,a_2,\dots,a_N)\in\{0,1\}^{\times N}$ that have all possible starts on the first $N$ places, followed by zeros.
Consider now an $x$ in the metric space, select the $x(a)$ with the match with $x$ on the first $N$ places and estimate the distance from $x$ to $x(a)$ by being generous on the places on positions $>N$.
Comment: Both of the answers are very helpful. Thanks a lot!!

Prove a metric space is totally bounded


Writing the dyadic product of two vectors as some product of a matrix and a vector

Question: For a physics problem I have a vector $\mathbf{v}$ which is defined as $$\mathbf{v}=\mathrm{M}\mathbf{u},$$ with $\mathrm{M}$ a matrix and $\mathbf{u}$ a second vector. I am interested in the second-order components of $\mathbf{v}$ ($v_1^2,v_1v_2$ and $v_2^2$) which are conveniently generated by taking the dyadic product $\mathbf{v}\otimes\mathbf{v}$. Now my question is whether it is possible to write this dyadic product $\mathbf{v}\otimes\mathbf{v}$ as the seperated product of $\mathrm{M}$ and $\mathbf{u}$ $$\mathbf{v}\otimes\mathbf{v}=g(\mathrm{M})f(\mathbf{u}),$$
with $f$ and $g$ some function.  I have been trying to work this out by inspecting some algebra properties and taking the tensor product explicitly and seeing if I can work out the pattern, but no luck so far. An erroneous example would be $\mathbf{v}\otimes\mathbf{v}\neq\mathrm{M}\cdot(\mathbf{u}\otimes\mathbf{u})$, which does yield a two-tensor but with the wrong values. My motivation for this construction stems from the physical significance of $\mathrm{M}$ and $\mathbf{u}$.
Comment: $$(v\otimes v)^{ij}=v^iv^j=(M^i{}_k u^k)(M^j{}_lu^l)  =(M\otimes M)^{ij}{}_{kl}(u\otimes u)^{kl}$$
Don't think you can do much better than that.
Comment: In index notation/summation convention, $v\otimes v=v_i v_j$, while $v_i=M_{ia}u_a$ and so $v_i v_j=(M_{ia} M_{jb}) (u_a u_b) $. This is a contraction between a fourth-order tensor formed from $M$, and a second-order tensor $u\otimes u$ formed from $u$. I am not sure how this would be expressed in dyadic notation - can you take a dyadic product of matrices? Would the kroenecker product work?
Comment: I didn't think of the possibility that dyadic notation does not make sense for matrices and index notation may be more natural. The fact that the fourth-order tensor and second-order tensor have different lengths might be a clue that index notation should be used, as dot products don't make sense for tensors with different lengths. Thanks!
Answer: $v \otimes v$ is $(M \otimes M)(u \otimes u)$, as K.defaoite says in the comments. This follows from what is called the exchange law or interchange law relating Kronecker product and matrix multiplication. More generally we have
$$(X_1 \otimes X_2)(Y_1 \otimes Y_2) = X_1 Y_1 \otimes X_2 Y_2$$
where $X_i, Y_i$ are such that the matrix multiplications above make sense.
Comment: Wouldn't you need to specify the indices as per K.defaoite's comment? Or does the order of operations uniquely define the contractions between $X_1\otimes X_2$ and $Y_1\otimes Y_2$? There seem to be 12 separate ways a tensor of rank 4 and 2 can contract, but I guess the matrix multiplication $X_iY_i$ implicitly rules out 8 of these possible contractions?
Comment: There is a unique choice of contraction such that both sides of the interchange law make sense with the weakest possible hypotheses and I'm taking that choice. It's easiest to state in terms of linear map rather than matrices: take $X_i : V_i \to W_i$ to be linear maps and $Y_i : U_i \to V_i$ to be linear maps. So there are six different vector spaces appearing now, which is what disambiguates the intended operations. Your example is confusing because several of these linear maps and vector spaces happen to be identical; things get clearer once you generalize away from this case.
Comment: Thanks, that cleared up my confusion!


Find the control point of a quadratic bezier curve with known maximum curve value

Question: I have a quadratic Bézier curve which starts at $P0(5,10)$ and ends at $P2(7,0)$.
I know that the maximum x-value of the curve is supposed to be at $x = 10$ and that the y-value of the control point $P1$ is at $y_{P1} = \frac{y_{P0}-y_{P2}}{2} = 5$.
How do I find $x_{P1}$ given these information?
The formula for quadratic bezier curves is (according to Wikipedia):
$B(t) = (1-t)^2P0 + 2(1-t)tP1 + t^2P2$
I know that one can calculate $t$ at the maximum x-value of the curve as: $t_{x(max)} = \frac{x_{P0}-x_{P1}}{x_{P0}-2x_{P1}+x_{P2}}$
Also, for a known value of $t$ and the according x-value $x_t$ on the bezier curve the x-value of the control point $x_{P1}$ can be calculated as following:
$x_{P1} = \frac{x_t - (1-t)^2x_{P0}-t^2x_{P2}}{2(1-t)t}$
However, that's where my brain stops working. Is there a way to combine these formulas? Or do I have to approach this problem with an iterative algorithm where I try different values for $x_{P1}$ to find an approximate?
Example image to illustrate the problem
(Move P1 along the x-axis so that the dashed curve has a maximum x-value at x = 10)
Answer: $p(t) = (1 - t)^2 P_0  + 2 t (1 - t) P_1 + t^2 P_2 $
Taking the derivative with respect to $t$ gives us the tangent vector
$p'(t) = - 2 (1 - t) P_0 + 2 (1 - 2 t) P_1 + 2 t P_2 $
At maximum $x$, the $x$ component of $p'(t)$ is zero.  Therefore,
$[p'(t)]_x = - (1 - t) P_{0x} +  (1 - 2 t) P_{1x} +  t P_{2x}  = 0 $
Let $x_0 = P_{0x}, y_0 = P_{0y}, x_2 = P_{2x}, y_2 = P_{2y} $ and $x = P_{1x}, y = P_{1y} $, then the above equation becomes in simpler notation,
$ 0 = (t - 1) x_0 + (1 -2 t) x + t x_2 $
This is a linear equation in $t$, whose solution is
$t = \dfrac{ x_0 - x } { x_0 - 2 x + x_2 } $
Now, we are given that $x_0 =5,  x_2 = 7 $, thus
$t = \dfrac{ 5 - x}{12 - 2 x}$
From which,
$(1 - t) = \dfrac{7 - x}{12 - 2x}$
Plugging this into the equation of $[p(t)]_x$ and equating to $10$ results in
$ 10 (12 - 2 x)^2 = 5 ( 7 - x )^2 + 2 x ( 5-x )( 7 - x ) + 7 (5-x)^2 $
This is a cubic polynomial in $x$ and can be readily solved either in closed form or numerically.
Comment: Yes.  There is a way.  Calculate the value of $t$, it should be between $0$ and $1$.
Comment: Seems right. But there's certainly only one value of $x$ that gives the required shape. So, somehow, the cubic equation must have only one real root. It's easy to see that $x$ must be larger than 10 and less than 50, so the real root can be found efficiently and safely by something like the secant method.
Comment: It feels like there ought to be some approach that avoids the two extraneous roots of the cubic. But I wasn't able to find any such approach.


Display Welcome Message in v4 Bot Framework Bot (C# + .Net Core Web Application)

Question: I had created a bot with v3 (C#) SDK and the welcome message used to work just fine without any sweat. And it still does for me in production. The code is handled in HandleSystemMessage like this -
.. v3 Code additional code removed for clarity...
else if (message.Type == ActivityTypes.ConversationUpdate)
{
// Handle conversation state changes, like members being added and removed
// Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info
// Not available in all channels

//Code to show Welcome Message
if (message.MembersAdded.Any(o => o.Id == message.Recipient.Id))
{
var reply = message.CreateReply();
reply.Attachments = new List<Attachment>();
// Create the attachment.
Attachment attachment = new Attachment()
{
ContentType = AdaptiveCard.ContentType,
Content = AdaptiveCardHelper.GetOptionsCard()
};
reply.Attachments.Add(attachment);
ConnectorClient connector = new ConnectorClient(new Uri(message.ServiceUrl));
await connector.Conversations.ReplyToActivityAsync(reply);
}
}

The Web Chat version that I use is BotFramework-WebChat-0.11.4, I have done certain customizations in it to implement facebook Like/Unlike feature with comment.
Now I am migrating the bots to v4 SDK (C# + .Net Core Web App), and I am intending to use the same old version of webchat. But I am struggling for two days to get a welcome message displayed in the same web chat while it works well on emulator (given to that two ConversationUpdate) events.
I have tried sending a message as well as an event using the solution provided in this article and tried to catch that in Bot on different async methods OnEventAsync, OnEventActivityAsync, OnMessageActivityAsync.
https://blog.botframework.com/2018/07/12/how-to-properly-send-a-greeting-message-and-common-issues-from-customers/
V4 Code looks like below:
 protected override async Task OnConversationUpdateActivityAsync(ITurnContext<IConversationUpdateActivity> turnContext, CancellationToken cancellationToken)
        {
            if (turnContext.Activity.MembersAdded != null)
            {
                if (turnContext.Activity.MembersAdded.Any(m => m.Id != turnContext.Activity.Recipient?.Id))
                {
                    //var welcomeCard = CreateAdaptiveCardAttachment();
                    //var response = CreateResponse(turnContext.Activity, welcomeCard);
                    //await turnContext.SendActivityAsync(response, cancellationToken);

                    await Utility.LogTraceAsync("Inside OnConversationUpdateActivityAsync");

                        var eventActivity = turnContext.Activity.AsConversationUpdateActivity();

                        ConnectorClient connector = new ConnectorClient(new Uri(eventActivity.ServiceUrl), Configuration.MicrosoftAppId, Configuration.MicrosoftAppPassword);

                        await Utility.LogTraceAsync("Service URL OnConversationUpdateActivityAsync" + eventActivity.ServiceUrl);

                        await Utility.LogTraceAsync("Recipient ID OnConversationUpdateActivityAsync" + turnContext.Activity.Recipient?.Id);

                        var welcomeCard = CreateAdaptiveCardAttachment();

                        var reply = ((Activity)eventActivity).CreateReply();
                        reply.Attachments.Add(welcomeCard);

                    //var response = CreateResponse(turnContext.Activity, welcomeCard);
                    await connector.Conversations.ReplyToActivityAsync(reply, cancellationToken);// turnContext.SendActivityAsync(response, cancellationToken);

                        await Utility.LogTraceAsync("OnConversationUpdateActivityAsync Response Returned.");

                    await Utility.LogTraceAsync("Exit OnConversationUpdateActivityAsync");
                }
            }
        }

        protected override async Task OnEventActivityAsync(ITurnContext<IEventActivity> turnContext, CancellationToken cancellationToken)
        {
            await Utility.LogTraceAsync("Inside OnEventActivityAsync");
            if (turnContext.Activity.Type == ActivityTypes.Event)
            {
                var eventActivity = turnContext.Activity.AsEventActivity();

                await Utility.LogTraceAsync("Event Activity from WebChat matched.");

                ConnectorClient connector = new ConnectorClient(new Uri(eventActivity.ServiceUrl), Configuration.MicrosoftAppId, Configuration.MicrosoftAppPassword);

                await Utility.LogTraceAsync("Service URL " + eventActivity.ServiceUrl);

                var welcomeCard = CreateAdaptiveCardAttachment();

                var reply = ((Activity)eventActivity).CreateReply();
                reply.Attachments.Add(welcomeCard);

                var members = await connector.Conversations.GetConversationMembersAsync(eventActivity.Conversation.Id.ToString());
                var membernames = "";
                foreach (var member in members) {
                    membernames += member.Name + ",";
                }

                await Utility.LogTraceAsync(membernames);

                await connector.Conversations.SendToConversationAsync(reply, cancellationToken);

                await connector.Conversations.ReplyToActivityAsync(reply, cancellationToken);// turnContext.SendActivityAsync(response, cancellationToken);

                await Utility.LogTraceAsync("Event Response Returned.");
            }

            await Utility.LogTraceAsync("Exit OnEventActivityAsync");
        }

But it does not seem to work at all. I am pulling my hairs out and there is no clue on how to do for .Net Core App. I will be glad to know if someone has solved this problem.
Update -  I have used the JS code on client-side as provided by @tdurnford and at Bot Side had following two methods -
//Required to Show Welcome Message on Emulator
protected override async Task OnMembersAddedAsync(IList<ChannelAccount> membersAdded, ITurnContext<IConversationUpdateActivity> turnContext, CancellationToken cancellationToken)
        {
            foreach (var member in membersAdded ?? Array.Empty<ChannelAccount>())
            {
                // Greet anyone that was not the target (recipient) of this message.
                // To learn more about Adaptive Cards, see https://aka.ms/msbot-adaptivecards for more details.
                if (member.Id != turnContext.Activity.Recipient.Id)
                {
                    Activity reply = ((Activity)turnContext.Activity).CreateReply();
                    AdaptiveCard card = AdaptiveCardHelper.GetWelcomeCard();
                    Attachment attachment = new Attachment()
                    {
                        ContentType = AdaptiveCard.ContentType,
                        Content = card
                    };
                    reply.Attachments.Add(attachment);
                    await turnContext.SendActivityAsync(reply, cancellationToken);
                }
            }
        }

//Required to Show Welcome Message on Web Chat
        protected override async Task OnEventActivityAsync(ITurnContext<IEventActivity> turnContext, CancellationToken cancellationToken)
        {
            if (turnContext.Activity.Name == "webchat/join")
            {
                Activity reply = ((Activity)turnContext.Activity).CreateReply();
                AdaptiveCard card = AdaptiveCardHelper.GetWelcomeCard();
                Attachment attachment = new Attachment()
                {
                    ContentType = AdaptiveCard.ContentType,
                    Content = card
                };
                reply.Attachments.Add(attachment);
                await turnContext.SendActivityAsync(reply, cancellationToken);
            }
        }

With both methods two welcome messages are shown in the chat window -
Bot Window with two Welcome Messages
Then I've commented the OnEventActivityAsync method in C# and deployed again. Now it shows only one welcome message returned from OnMembersAddedAsync as shown in the window.
Bot Window with only one Welcome Message
If I comment the following code lines in the webchat code i.e. don't send the post-activity -
botConnection.postActivity({
    from: {
        id: 'myUserId',
        name: 'myUserName'
    },
    type: 'event',
    name: 'webchat/join',
    value: {
        locale: 'en-US'
    }
}).subscribe(
    id => console.log("Posted welcome event, assigned ID ", id),
    error => console.log("Error posting activity", error)
);

In this case, no welcome message is displayed. @tdurnford, please check if you are able to replicate this behavior.
Although there is another problem here in this way that when a user types a question in the bot, then a welcome message is displayed again.
Bot window with two welcome messages one on load and another after the first question
Comment: Why are you using Web Chat v0.11.4? The newest version of Web Chat is highly customizable  and there is a [sample](https://github.com/microsoft/BotFramework-WebChat/tree/master/samples/09.customization-reaction-buttons) that shows how to quickly add Reaction Buttons to messages. I would recommend taking a look at v4 since older versions are no longer supported.
Comment: If you do want to continue using your current version, I will need to get some more information from you since I'm unfamiliar with v0.11.4. Does that version still use the DirectLineJs pacakge? If you could add your Web Chat code, that would be helpful.
Comment: @tdurnford, yes it uses the DirectLineJs package. The catch here is that on a v3 bot it works just fine without raising an extra event or something like that. Here is the source link for that version-  https://github.com/microsoft/BotFramework-WebChat/releases/tag/v0.11.4
Comment: @tdurnford, is it possible for you to try this out at your end with a simple Core Bot + Web Chat 0.11.4. I am very much sure you will be able to see the reason for the problem.
Comment: There is a backchannel example in the samples folder of that version @amitc The blog post you referenced is just using the backchannel to send a request to the bot for a welcome message.  How that is handled in the bot has changed from v3 to v4, but the 0.11.4 backchannel client side code is the same.
Comment: @EricDahlvang, Thanks a lot for your response. I checked the samples the folder and found the backchannel example and the client-side code is indeed same. But as you've mentioned handling backchannel in the bot has changed from v3 to v4, thus can you guide me on what code should be written at bot side to handle the incoming event and return the welcome message. And also I have noticed that this additional postActivity request from client side code take a little more time than intial conversations request sent over directline causing subtle delay for the user to see the first message.
Comment: One more thing I found while tracing the code. Following code is being executed inside OnConversationUpdateActivityAsync but nothing sent back from the connectorClient in v4. Can there be something related to this? `ConnectorClient connector = new ConnectorClient(new Uri(eventActivity.ServiceUrl), Configuration.MicrosoftAppId, Configuration.MicrosoftAppPassword);await connector.Conversations.ReplyToActivityAsync(reply, cancellationToken);// turnContext.SendActivityAsync(response, cancellationToken);`
Answer: Typically, the channel sends two conversation update events when the conversation is initialized - one for the bot and another for the user. The second one - the event for the user - is intended to trigger the welcome message. Unlike some other channels, Web Chat waits to send the second conversation update event until after the user messages the bot. Evidently, the welcome message won't be sent until after the first message. To workaround this issue, developers can send a back channel welcome event to the bot when the DirectLine connection is established and send a welcome message from the onEventAsync handler instead of onMembersAdded. For more details, take a look at the code snippets below.
Bot Chat Code
<!DOCTYPE html>

    <link href="https://cdn.botframework.com/botframework-webchat/0.11.4/botchat.css" rel="stylesheet" />

Bot Code - C#
protected override async Task OnEventActivityAsync(ITurnContext<IEventActivity> turnContext, CancellationToken cancellationToken)
{
    if (turnContext.Activity.Name == "webchat/join") {
      await turnContext.SendActivityAsync("Welcome Message!");
    }
}

protected override async Task OnMembersAddedAsync(IList<ChannelAccount> membersAdded, ITurnContext<IConversationUpdateActivity> turnContext, CancellationToken cancellationToken)
{
    if (turnContext.Activity.ChannelId != "webchat" && turnContext.Activity.ChannelId != "directline") {

        foreach (var member in membersAdded)
        {
            if (member.Id != turnContext.Activity.Recipient.Id)
            {
                await turnContext.SendActivityAsync($"Hi there - {member.Name}. {WelcomeMessage}", cancellationToken: cancellationToken);
                await turnContext.SendActivityAsync(InfoMessage, cancellationToken: cancellationToken);
                await turnContext.SendActivityAsync(PatternMessage, cancellationToken: cancellationToken);
            }
        }
    }
}

Screen Capture

Also note, Web Chat v0.11.4 is referred to as either Bot Chat or Web Chat v3. Sorry I got tripped up on that.
Hope this helps!
Comment: @tdrunford, thanks for your response. I used your code above without connection status check as it was returning 0 and not calling post activity. Thus I've used only PostActiity part and verified the webchat/join activity being posted from the client-side and it also reached to OnEventActivityAsync method which I verified from trace logs of code. I also verifed the response of the activity call is returned `{
  "id": "KvCB2ZH26fPII2SQu8lYEK-c|0000000"
}` but unfortunately, the welcome message is not rendered by the webchat. If I post a real question it returns a response and it is rendered.
Comment: Are you sending the welcome message from the `OnEventActivityAsync` handler? This approach should not trigger the `onMembersAddedAsync` handler where welcome messages are usually handled.
Comment: The connection status should switch to online - which I believe is 2 - when the connection to the bot is established. I'm not sure why you would have an issue with that. I'll have to look into that more.
Comment: @turnford, yes, I am sending the message back from OnEventActivityAsync. In fact I have been trying to return an adaptive card with a text message, to mimic how webchat is able to render a normal response after real typed message to bot vs an event activity posted programmatically and a response returned. The main differences I can see after looking into webchat code is that trySendMessageEpic middleware is not invoked from the redux store for programmatic event activity. I am directly looking into js code generated i.e. botchat.js. Instead of connection, I'd request you look at the response.
Comment: @turnford, I tried using the client-side logic from this [link](https://github.com/compulim/BotFramework-WebChat/blob/0cc041356438fddd02c3725ff621eeafbe269663/samples/15.d.backchannel-send-welcome-event/index.html) and with v4 version of Web Chat and the welcome message is still not displayed on the web chat control.
Comment: Can you add your Web Chat code to your question? I updated my answer to include all of my HTML. I don't believe the event should trigger anything on the Web Chat side - it's just a backchannel activity being sent to the bot.
Comment: @turnford, thanks for adding screenshot it motivated me to look my code line by line. Well, I noticed that in my web chat code `BotChat.App({ --- });` was initialized first and then I was calling `botConnection.PostActivity` without connection check. But I removed my existing code and used yours in place and voila it worked but showed two messages on Web Chat Window. The reason was I had bot OnMembersAddedAsync and OnEventActivityAsync in my bot code. I kept OnMembersAddedAsync to view the welcome message in Emulator. I commented OnEventActivityAsync method & redeployed now get only 1 message.
Comment: This means that ideally just a backchannel activity is required to let both user and bot added to the conversation and then OnMembersAddedAsync can be used to display the welcome message. I want you to ascertain this fact at your end as well. I will update my question with C# bot code and with screenshots. Once you've verified it, please update here so that we can conclude this amazing discussion. Thanks a lot man.
Comment: Don't send a welcome message from `onMembersAddedAsyn` if the channel is Web Chat or DirectLine, so that you don't get two welcome messages. I added this to the code snippets in my answer.
Comment: Thanks for your response. I think a better way to seal it off is to use this code check.
`if (turnContext.Activity.ChannelId == "emulator") {
foreach (var member in membersAdded)
    {
        if (member.Id != turnContext.Activity.Recipient.Id)
        {
            await turnContext.SendActivityAsync($"Hi there - {member.Name}. {WelcomeMessage}", cancellationToken: cancellationToken);
...
        }
    }
}`
I think this post will help everyone with clear indications on how to solve this issue.
Comment: The Bot Service Registration supports multiple channels - Teams, Skype, Facebook Messenger, Twillio, Line, etc. Its easier to check for just Web Chat and DirectLine than all of the other channels. I can certainly change the if statement to check if the channel is not Web Chat or Direct Line instead.
Comment: Sure, it sounds okay. Thanks for your shift responses.
Answer: tdurnford's answer didn't work for me. I'm using a new v4 bot (no migration) and embedding iframe into Sharepoint. OnEventActivityAsync just doesn't trigger. I get a conversation update with my bot being a MembersAdded so I did this:
    protected override async Task OnConversationUpdateActivityAsync(ITurnContext<IConversationUpdateActivity> turnContext, CancellationToken cancellationToken)
    {
        await base.OnConversationUpdateActivityAsync(turnContext, cancellationToken);

        if (turnContext.Activity.ChannelId == "webchat" && turnContext.Activity.MembersAdded?.FirstOrDefault(m => m?.Name == Configuration["BotName"]) != null)
        {
            await SendWelcomeMessageAsync(turnContext, cancellationToken);
        }
    }

BotName is "Bot" for local development and the app name for azure deployed apps. SendWelcomeMessage is my own method. Also as above, I added a check in OnMembersAddedAsync:
protected override async Task OnMembersAddedAsync(IList<ChannelAccount> membersAdded, ITurnContext<IConversationUpdateActivity> turnContext, CancellationToken cancellationToken)
    {
        if (turnContext.Activity.ChannelId == "webchat" || turnContext.Activity.ChannelId == "directline")
            return;

        foreach (var member in membersAdded)
        {
            // Greet anyone that was not the target (recipient) of this message.
            // To learn more about Adaptive Cards, see https://aka.ms/msbot-adaptivecards for more details.
            if (member.Id != turnContext.Activity.Recipient.Id)
            {
                await SendWelcomeMessageAsync(turnContext, cancellationToken);
            }
        }
    }

Answer: In v4 of the Bot Framework SDK this functionality is handled by making your bot class inherit from the ActivityHandler class then overriding the OnMembersAddedAsync method.
How this looks in practice is:
...

public class MyBot : ActivityHandler
{
    ...

        protected override async Task OnMembersAddedAsync(IList<ChannelAccount> membersAdded, ITurnContext<IConversationUpdateActivity> turnContext, CancellationToken cancellationToken)
        {
            foreach (var member in membersAdded)
            {
                // Greet anyone that was not the target (recipient) of this message.
                if (member.Id != turnContext.Activity.Recipient.Id)
                {
                    var welcomeMessage = "Hello and welcome!";

                    await turnContext.SendActivityAsync(welcomeMessage, cancellationToken);
                }
            }
        }
    ...
}

There are examples of how to do this here, here, and here.
You may have to update the version of the Microsoft.Bot.Builder package that you are using.
Comment: Matt, Thanks for your response. I have tried this code already and my Bot inherits from ActivityHandler only. The catch is this works only in Emulator but in WebChat control, this code does not work. Have you tried anything that works on WebChat control?
Comment: In webchat the welcome message will not be sent until the user has sent a message, this is a known issue. What you can do is use the back channel functionality to force the bot to send the welcome first. There is an example of how to do this [here](https://github.com/microsoft/BotFramework-WebChat/blob/master/samples/15.d.backchannel-send-welcome-event/index.html) among with others which you will find if you google the issue. :-)
Comment: Thanks for your suggestion Matt, but as I said above I am not using the latest web chat control and instead this version BotFramework-WebChat-0.11.4. And whatever things I have tried haven't worked so far after googling and also putting my brain into the problem.
Comment: Is there some reason that you cannot upgrade to the latest version of webchat? tdurnford provided a link to a sample above. Also posting your webchat code would help.


How to forward an email to external URL

Question: I would like to create a page that will automatically forward to an external site? Similar to what bitly, tinyurl do. So when people type example.com/page in address bar, site will automatically take them to mysite.com? How can I achieve that?
Answer: Sounds like you can just create a URL redirect with Redirect, and send to an external URL. No need to create a node.

How to forward an email to external URL


Adjusting the bridge of a Floyd Rose

Question: Being novice to Floyd Rose guitars, I've been panicking after tuning my guitar for the very first time. After rummaging through a few YouTube videos , I've been able to keep my guitar in tune which required several iterations of adjusting the pitch of the strings in the following order : E (6th) , E(1st) , B (2nd), A(5th), G(3rd), D(4th).
But now, the bridge isn't parallel to the body anymore.

So I tried to loosen and tighten the spring screws for a number of times (considering the screws have a upper limit of tightening)  but the Bridge isn't changing any angle with the body unless I loosen the strings tensions. Simply put, the spring screws aren't altering the bridge position.
Is this normal? I guess there should be some viable solution to this .
Comment: Those two large screws (show vertical in the 2nd pic) should tighten into the wood and start to stretch the 3 springs. There ought to be enough adjustment there to flatten the top side of the bridge. That's what they are there for - to adjust the tension that the springs make, counteracting the tension of the strings on the other side. Fender vibs work in a similar manner. This question is most likely  a dupe. Check answers we have already been given.
Answer: Yeah don't loosen those screws, just tighten them. A lot. You should see the claw (that the screws go through) move like 1/4" towards the wood.
Before you tighten the claw screws, loosen the strings. Then, don't be shy about tightening that claw. If you've loosened the strings then you can tighten the claw until the bridge is to low. Then when you tune the strings back up it should lift the bridge closer to the correct position.
With a Floyd Rose, you will have to iterate through the tuning many times to get it tuned. Once you've got it tuned and locked down, you can usually go for quite a while just making minor adjustments with the fine tuners at the bridge. But the initial setup with the bridge height and so on will take a while. Maybe even hours.
I wonder if what's confusing is that after you tighten the claw screws, you have to retune all the strings or else the bridge won't be in its final position.
Comment: Thanks a lot. I was really afraid since the tightening was taking too much force to deal with. I used a deck of cards to in the spring side to keep the bridges fixed and parallel to the body, did the tuning, and later tightened the claws enough so that the  cards came loose. The claw screws are just so close to the wood after the bridge is parallel to the body so I was wondering whether it's almost impossible to fix this , but I'm glad it worked out.
Comment: Facing another problem if you don't mind to discuss here : I took off the whammy bar during the whole tuning and adjusting process ; now that I've put it back to test the effects, it seems that when I activate the dive bomb, the high E (1st) string isn't coming loose enough as it should be compared to the other strings. Any words on that?

Adjusting the bridge of a Floyd Rose


Proving that the sum of two finite dimensional subspaces is also finite dimensional?

Question: In the textbook that I'm using the sum of two subspaces is defined as
W1 + W2 = {x+y: x is an element of W1 and y is an element of W2}
The information that you're given is that W1 and W2 are finite-dimensional subspaces of vector spaces V and what you're trying to prove is that W1 + W2 must also be finite dimensional.
My thinking was that you can't add two finite things and end up with something infinite but I'm not sure how to go about proving this or even how to start.
Comment: Your intuition about adding finite things is correct, but a finite dimension means that it's spanned by a finite set, so you'd want to show that the sum can be spanned by a finite set, using that fact that the two original spaces are spanned by finite sets.
Comment: What does it mean that a subspace is finite-dimensional? The answer should help you find a proof, since then you know what you need to show.
Comment: Does the definition of being finite-dimensional mean that the dim(V) cannot be infinite?
Answer: Show that every element of the sum can be written as a linear combination of the vectors of the Union of the basis of each subspace. That set is finite and generates the sum space.
Answer: Define the map
$$\Phi: W_1\times W_2\to W_1+W_2,\; (w_1,w_2)\mapsto w_1+w_2$$
then prove that $\Phi$ is a surjective linear transformation hence
$$W_1+W_2=\Phi(W_1\times W_2)$$
is a linear space and using the rank-nullity theorem we get that it's finite dimensional space and
$$\dim(W_1+W_2)\le \dim(W_1\times W_2)=\dim W_1+\dim W_2$$
Notice that in the case of the equality of the dimensions, the sum $W_1+W_2$ is called direct.


UITableView not showing first time, only when scrolling a bit

Question: I have a UITableViewController, which is loading data from a NSURLConnection:
<code>NSURL *url = [NSURL URLWithString:@"http://url.now"];
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30.0];

NSOperationQueue *queue = [[NSOperationQueue alloc] init];

[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
    if ([data length] > 0 && error == nil){
        NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
        [parser setDelegate:self];
        [parser parse];
    }
    else if (error != nil){
        UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"No internet connection" message:@"Content." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alertView performSelectorOnMainThread:@selector(show) withObject:nil waitUntilDone:true];
    }
}];
</code>
When the parsing ends, the reloaddata method is called. But when the app is loaded, the content of the UITableView is not showing. When I scroll a bit, it get's visible immediately. Reloading is no problem.
How can this be fixed?
Comment: In viewDidLoad, you are calling `[tableView reloadData];` correct?
Comment: I'm calling [tableView reloadData]; in the parserDidEndElement when the last element is parsed. I also tried it in the viewDidLoad, but no effect!
Answer: Solved it. Changed the tableView reloadData to this:
<code> dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
 });
</code>
And it worked like a charm. Thanks for all answers and comments.
Answer: What probably happened is that your table loads faster than the time it takes for your commotion to download data.
Add a delegate to the class that manage your data and make your table view controller conform to that delegate protocol.
Than, once data is downloaded and parsed reload the table.
Comment: Actually calling the mainQueue works because the parse was performed on the background asyc of NSURL and according to apple updating the view should be done in the mainThread thats were the mainQueue comes in it runs the the tableview reload on the main thread.
Comment: I don't think so, because the OP says "When the parsing ends, the reloaddata method is called."
Comment: OP? Anyway put some break points out there and see what happened first and if you have data the first time reusable cells deques.
Comment: @MichalShatz The table is indeed loaded first, but when it's loaded, tableView reloadData is called, but nothing happens. Only when the view is scrolled a bit, everything will become visible.
Comment: Reson is that when you call reloadData dat is not available yet. That's why your solution of dispatchingMainQueue "works like a charm" - you are reloading data while using the main queue instead of background and force slow load on the main queue which cause bad user experience.
Answer: Unchecking "Use Size Classes" option and then coming back and re-checking it again fixes this issue.

In the project navigator, select a storyboard or xib file.
The file's contents open in Interface Builder.
Choose View > Utilities > Show File Inspector.
In the Interface Builder Document section, un-tick the "Use Size Classes" checkbox.
Leave the menu. Come back and tick the "Use Size Classes" checkbox again.


Compare two list iterators which point to different lists

Question: As pointed out in other questions here on SO, equality comparison between two iterators from different containers is UB.
In my case I have two list iterators, which might not be from the same container:
<code>std::list< int >::iterator a, b;
</code>
Suppose that I know for sure that none of them is an end iterator, my question is if I am allowed to do:
<code>&(*a) == &(*b)
</code>
Comment: Why not? if they are not end-iterators, dereferencing them yields an `lvalue`, whose address you surely can get.
Answer: Sure, you can do that, as you're not comapring the iterators but the addresses of their referands.
Assuming iterators are from different containers, this comparison cannot ever be true in a well-formed program, though.
Comment: Why not? If the two iterator belong to the same container and points to the same element how can it be false?
Comment: I though you said the iterators are not from the same container?
Comment: Sorry, what I really meant was *might* be from the same container, I'll fix that.
Comment: In that case, yes, it's fine and it can be true.


Show that $b_n > b_{n-1}$ where $\frac{a_n}{b_n}$ are the n:th harmonic number

Question: Let $H_n=\frac{a_n}{b_n}$ where $H_n$ is a n:th harmonic number and $a_n$ and $b_n$ are coprimes.
1/ If $n$ is a prime power, show that $b_n > b_{n-1}$
2/ Find the integer factorization of $b_{21}$
My progress so far is:
1/ By induction $H_{n}=H_{n-1}+\dfrac{1}{n}=\dfrac{a_{n-1}}{b_{n-1}}+\dfrac{1}{n}=\dfrac{na_{n-1}+b_{n-1}}{nb_{n-1}}$
Let $n=p^k$ where $p$ is a prime and $k$ an integer which makes $n$ a prime power.
$H_{n}=\dfrac{p^ka_{n-1}+b_{n-1}}{p^kb_{n-1}}$
When you shorten this fraction, I want to show that the $\mathit{denominator}>b_{n-1}$.
This is how far I have reached. How do I proceed?
2/This can easily be solved with a computer but the purpose is to do it using the harmonic number. I don't know how to do that in an easy way.
Thanks!
Answer: For $1)$ you don't need induction.
First observe that the common denominator for the sum in $H_n$ is $LCM \{1,2,3,..,n \}$. Now, after you bring the fraction to common denominator, it might cancel, but then, the denominator gets smaller.
From here you can deduce that  for all $n$
$$b_n  \mid  LCM \{1,2,3,..,n \} \,.$$
Now, assume that $n=p^k$. Then
$$b_{n-1} \mid  LCM \{1,2,3,..,n-1 \} \,.$$
As the power of $p$ in $LCM \{1,2,3,..,n-1 \}$ is exactly $k-1$, it follows that the power of $p$ in $b_{n-1}$ is at most $k-1$.
Write $b_{n-1}=p^\alpha m$ with $\alpha < k$ and $p \nmid m$.
Then
$$\frac{a_n}{b_n}=\dfrac{p^k a_{n-1}+p^\alpha m}{p^k p^\alpha m}=\dfrac{p^{k-\alpha} a_{n-1}+ m}{p^k  m} \,.$$
Or
$$p^k  m a_n =b_n ( p^{k-\alpha} a_{n-1}+ m) \,.$$
Now $p^k$ is relatively prime with $ p^{k-\alpha} a_{n-1}+ m$ (Why?) thus it must divide $b_n$.
$m$ is also relatively prime with $ p^{k-\alpha} a_{n-1}+ m$ (Why?) thus it must divide $b_n$.
Hence $p^k$ and $m$ are two relatively prime numbers, both dividing $b_n$.
Therefore $p^km \mid b_n$.
This proves that
$$b_n >b_{n-1} \,.$$
Actually you can prove something stronger in this case:
As
$$p^k  m a_n =b_n ( p^{k-\alpha} a_{n-1}+ m) \,.$$
$$b_n \mid p^k  m a_n \,.$$
But $b_n$ is relatively prime with $a_n$ therefore $b_n \mid p^km$.
This shows that in this case
$$b_n =p^k m$$
which might be helpful for $2)$.
As a side result, whenever $n$ is a power of a prime, $n \mid b_n$.
Here are some ideas for 2)
First, the only prime factors of $b_{21}$ can be $2,3,5,7,11,13,17,19$.
Also,
$$b_{21} \mid \operatorname{lcm}\{1,2,3.., 21 \} = 2^4 \cdot 3^2 \cdot 5 \cdot 7 \cdot 11 \cdot 13 \cdot 17 \cdot 19 \,.$$
You know that $2^4 \mid b_{16}, 3^2 \mid b_9, p \mid b_p$ for all the other.
The following Lemma can be very helpful.
Lemma If $p^k \mid b_{n-1}$ and $p^k \nmid n$ then $p^k \mid b_n$.
Combining this Lemma with $p \mid b_p$ and $2^4 \mid b_{16}$ you get that $b_{21}$ must be divisible by $2^4 , 11, 13, 17$ and $19$.
Thus
$$b_{21}=2^43^b 5^c 7 ^d \cdot 11 \cdot 13 \cdot 17 \cdot 19 \,,$$
with
$$ b \in \{ 0, 1, 2 \} ; c,d \in \{0,1\} \,.$$
This reduces the problem to only finding the powers of $3,5,7$ in $b_{21}$.
Moreover you know that $3^2 \mid b_{17}$, $5 \mid b_{9}$ and $7 \mid b_{13}$. The question is if any of these powers decreases before $b_{21}$.
I am not sure, but I think you might be able to study recursively $a_{n} \pmod{9, 5, 7}$ up to $n=21$ to settle this issue.