Gateway timeout with traefik and php fpm

Question: I have a problem with setting up mailcow with traefik, I encounter gateway timeouts. I also have this problem with nextcloud, so I would be really interested, what causes these issues with gateway timeout.
I guess it has to do with port 9000 and php-fpm upstream or sth.
But I want to know for sure, and how to deal with it.
My traefik.toml:
debug = true
checkNewVersion = true
defaultEntryPoints = ["http", "https"]

[web]
address = ":8080"
[web.auth.basic]
users = ["admin:undecipherablestring"]

[entryPoints]
  [entryPoints.http]
  address = ":80"
    [entryPoints.http.redirect]
      entryPoint = "https"
  [entryPoints.https]
  address = ":443"
    [entryPoints.https.tls]

[acme]
email = "firstname.lastname@example.com"
storage = "acme.json"
entryPoint = "https"
onHostRule = true

[[acme.domains]]
  main = "main.com"
  sans = ["monitor.main.com", "ports.main.com", "git.main.com", "cloud.main.com", "mail.main.com"]

My traefik docker-compose.yml:
version: '2'
services:
  proxy:
    image: traefik
    container_name: traefik
    restart: always
    command: |-
      --docker
      --docker.domain=docker.localhost
      --logLevel=DEBUG
    networks:
      - webgateway
    labels:
      - "traefik.frontend.rule=Host: monitor.main.com"
      - "traefik.port=8080"
    ports:
      - "80:80"
      - "443:443"
      - "8080:8080"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
      - ./traefik.toml:/traefik.toml
      - ./acme.json:/acme.json
      - acme:/opt/traefik/acme

networks:
  webgateway:
    driver: bridge

volumes:
  acme:
    driver: local

My mailcow docker-compose.yml:
version: '2.1'
services:

    unbound-mailcow:
      image: mailcow/unbound:1.0
      build: ./data/Dockerfiles/unbound
      command: /usr/sbin/unbound
      depends_on:
        mysql-mailcow:
          condition: service_healthy
      healthcheck:
        test: ["CMD", "nslookup", "google.com", "127.0.0.1"]
        interval: 30s
        timeout: 3s
        retries: 10
      volumes:
        - ./data/conf/unbound/unbound.conf:/etc/unbound/unbound.conf:ro
      restart: always
      networks:
        mailcow-network:
          ipv4_address: 172.22.1.254
          aliases:
            - unbound

    mysql-mailcow:
      image: mariadb:10.1
      command: mysqld --max_allowed_packet=128M
      healthcheck:
        test: ["CMD", "mysqladmin", "ping", "--host", "localhost", "--silent"]
        interval: 5s
        timeout: 5s
        retries: 10
      volumes:
        - mysql-vol-1:/var/lib/mysql/
        - ./data/conf/mysql/:/etc/mysql/conf.d/:ro
      environment:
        - MYSQL_ROOT_PASSWORD=${DBROOT}
        - MYSQL_DATABASE=${DBNAME}
        - MYSQL_USER=${DBUSER}
        - MYSQL_PASSWORD=${DBPASS}
      restart: always
      dns:
        - 172.22.1.254
      dns_search: mailcow-network
      networks:
        mailcow-network:
          ipv4_address: 172.22.1.250
          aliases:
            - mysql

    redis-mailcow:
      image: redis:alpine
      depends_on:
        unbound-mailcow:
          condition: service_healthy
      volumes:
        - redis-vol-1:/data/
      restart: always
      dns:
        - 172.22.1.254
      dns_search: mailcow-network
      networks:
        mailcow-network:
          ipv4_address: 172.22.1.249
          aliases:
            - redis

    clamd-mailcow:
      image: mailcow/clamd:1.1
      build: ./data/Dockerfiles/clamd
      restart: always
      environment:
        - SKIP_CLAMD=${SKIP_CLAMD:-n}
      dns:
        - 172.22.1.254
      dns_search: mailcow-network
      networks:
        mailcow-network:
          aliases:
            - clamd

    rspamd-mailcow:
      image: mailcow/rspamd:1.3
      build: ./data/Dockerfiles/rspamd
      command: >
        /bin/bash -c "
        sleep 5;
        /usr/bin/rspamd -f -u _rspamd -g _rspamd
        "
      depends_on:
        - nginx-mailcow
      volumes:
        - ./data/conf/rspamd/override.d/:/etc/rspamd/override.d:ro
        - ./data/conf/rspamd/local.d/:/etc/rspamd/local.d:ro
        - ./data/conf/rspamd/lua/:/etc/rspamd/lua/:ro
        - dkim-vol-1:/data/dkim
        - rspamd-vol-1:/var/lib/rspamd
      restart: always
      dns:
        - 172.22.1.254
      dns_search: mailcow-network
      hostname: rspamd
      networks:
        mailcow-network:
          ipv4_address: 172.22.1.253
          aliases:
            - rspamd

    php-fpm-mailcow:
      image: mailcow/phpfpm:1.0
      build: ./data/Dockerfiles/phpfpm
      command: "php-fpm -d date.timezone=${TZ}"
      depends_on:
        - redis-mailcow
      volumes:
        - ./data/web:/web:ro
        - ./data/conf/rspamd/dynmaps:/dynmaps:ro
        - dkim-vol-1:/data/dkim
      environment:
        - DBNAME=${DBNAME}
        - DBUSER=${DBUSER}
        - DBPASS=${DBPASS}
        - MAILCOW_HOSTNAME=${MAILCOW_HOSTNAME}
        - IMAP_PORT=${IMAP_PORT:-143}
        - IMAPS_PORT=${IMAPS_PORT:-993}
        - POP_PORT=${POP_PORT:-110}
        - POPS_PORT=${POPS_PORT:-995}
        - SIEVE_PORT=${SIEVE_PORT:-4190}
        - SUBMISSION_PORT=${SUBMISSION_PORT:-587}
        - SMTPS_PORT=${SMTPS_PORT:-465}
        - SMTP_PORT=${SMTP_PORT:-25}
      restart: always
      dns:
        - 172.22.1.254
      dns_search: mailcow-network
      networks:
        mailcow-network:
          aliases:
            - phpfpm

    sogo-mailcow:
      image: mailcow/sogo:1.3
      build: ./data/Dockerfiles/sogo
      depends_on:
        unbound-mailcow:
          condition: service_healthy
      environment:
        - DBNAME=${DBNAME}
        - DBUSER=${DBUSER}
        - DBPASS=${DBPASS}
        - TZ=${TZ}
        - MAILCOW_HOSTNAME=${MAILCOW_HOSTNAME}
      volumes:
        - ./data/conf/sogo/:/etc/sogo/
      restart: always
      dns:
        - 172.22.1.254
      dns_search: mailcow-network
      networks:
        mailcow-network:
          ipv4_address: 172.22.1.252
          aliases:
            - sogo

    dovecot-mailcow:
      image: mailcow/dovecot:1.4
      build: ./data/Dockerfiles/dovecot
      depends_on:
        unbound-mailcow:
          condition: service_healthy
      volumes:
        - ./data/conf/dovecot:/usr/local/etc/dovecot
        - ./data/assets/ssl:/etc/ssl/mail/:ro
        - ./data/conf/sogo/:/etc/sogo/
        - vmail-vol-1:/var/vmail
        - crypt-vol-1:/mail_crypt/
      environment:
        - DBNAME=${DBNAME}
        - DBUSER=${DBUSER}
        - DBPASS=${DBPASS}
      ports:
        - "${DOVEADM_PORT:-127.0.0.1:19991}:12345"
        - "${IMAP_PORT:-143}:143"
        - "${IMAPS_PORT:-993}:993"
        - "${POP_PORT:-110}:110"
        - "${POPS_PORT:-995}:995"
        - "${SIEVE_PORT:-4190}:4190"
      restart: always
      dns:
        - 172.22.1.254
      dns_search: mailcow-network
      hostname: ${MAILCOW_HOSTNAME}
      networks:
        mailcow-network:
          aliases:
            - dovecot

    postfix-mailcow:
      image: mailcow/postfix:1.2
      build: ./data/Dockerfiles/postfix
      depends_on:
        unbound-mailcow:
          condition: service_healthy
      volumes:
        - ./data/conf/postfix:/opt/postfix/conf
        - ./data/assets/ssl:/etc/ssl/mail/:ro
        - postfix-vol-1:/var/spool/postfix
        - crypt-vol-1:/var/lib/zeyple
      environment:
        - DBNAME=${DBNAME}
        - DBUSER=${DBUSER}
        - DBPASS=${DBPASS}
      ports:
        - "${SMTP_PORT:-25}:25"
        - "${SMTPS_PORT:-465}:465"
        - "${SUBMISSION_PORT:-587}:587"
      restart: always
      dns:
        - 172.22.1.254
      dns_search: mailcow-network
      hostname: ${MAILCOW_HOSTNAME}
      networks:
        mailcow-network:
          aliases:
            - postfix

    memcached-mailcow:
      image: memcached:alpine
      depends_on:
        unbound-mailcow:
          condition: service_healthy
      restart: always
      dns:
        - 172.22.1.254
      dns_search: mailcow-network
      networks:
        mailcow-network:
          aliases:
            - memcached

    nginx-mailcow:
      depends_on:
        - sogo-mailcow
        - php-fpm-mailcow
      image: nginx:mainline-alpine
      healthcheck:
        test: ["CMD", "ping", "php-fpm-mailcow", "-c", "5"]
        interval: 5s
        timeout: 5s
        retries: 10
      command: /bin/sh -c "envsubst < /etc/nginx/conf.d/templates/listen_plain.template > /etc/nginx/conf.d/listen_plain.active &&
        envsubst < /etc/nginx/conf.d/templates/listen_ssl.template > /etc/nginx/conf.d/listen_ssl.active &&
        envsubst < /etc/nginx/conf.d/templates/server_name.template > /etc/nginx/conf.d/server_name.active &&
        nginx -g 'daemon off;'"
      environment:
        - HTTPS_PORT=${HTTPS_PORT:-443}
        - HTTP_PORT=${HTTP_PORT:-80}
        - MAILCOW_HOSTNAME=${MAILCOW_HOSTNAME}
      volumes:
        - ./data/web:/web:ro
        - ./data/conf/rspamd/dynmaps:/dynmaps:ro
        - ./data/assets/ssl/:/etc/ssl/mail/:ro
        - ./data/conf/nginx/:/etc/nginx/conf.d/:rw
      expose:
        - "${HTTP_PORT:-80}"
      #ports:
        #- "${HTTPS_BIND:-0.0.0.0}:${HTTPS_PORT:-443}:${HTTPS_PORT:-443}"
        #- "${HTTP_BIND:-0.0.0.0}:${HTTP_PORT:-80}:${HTTP_PORT:-80}"
      restart: always
      dns:
        - 172.622.1.254
      dns_search: mailcow-network
      labels:
      - "traefik.frontend.rule=Host: ${MAILCOW_HOSTNAME}"
      - "traefik.backend=mailcow"
      - "traefik.port=80"
      - "traefik.frontend.entryPoints=http,https"
      - "traefik.docker.network=traefik"
      networks:
        mailcow-network:
          ipv4_address: 172.22.1.251
          aliases:
            - nginx
        traefik:

    acme-mailcow:
      depends_on:
        - nginx-mailcow
      image: mailcow/acme:1.12
      build: ./data/Dockerfiles/acme
      dns:
        - 172.22.1.254
      dns_search: mailcow-network
      environment:
        - ADDITIONAL_SAN=${ADDITIONAL_SAN}
        - MAILCOW_HOSTNAME=${MAILCOW_HOSTNAME}
        - DBNAME=${DBNAME}
        - DBUSER=${DBUSER}
        - DBPASS=${DBPASS}
        - SKIP_LETS_ENCRYPT=${SKIP_LETS_ENCRYPT:-n}
        - SKIP_IP_CHECK=${SKIP_IP_CHECK:-n}
      volumes:
        - ./data/web/.well-known/acme-challenge:/var/www/acme:rw
        - ./data/assets/ssl:/var/lib/acme/:rw
        - ./data/assets/ssl-example:/var/lib/ssl-example/:ro
        - /var/run/docker.sock:/var/run/docker.sock:ro
      # do not restart the container too often. Things get worse when we hit let's encrypt's ratelimit.
      restart: on-failure:1
      networks:
        mailcow-network:
          aliases:
            - acme

    fail2ban-mailcow:
      image: mailcow/fail2ban:1.5
      build: ./data/Dockerfiles/fail2ban
      depends_on:
        - dovecot-mailcow
        - postfix-mailcow
        - sogo-mailcow
        - php-fpm-mailcow
        - redis-mailcow
      restart: always
      privileged: true
      environment:
        - TZ=${TZ}
        - SKIP_FAIL2BAN=${SKIP_FAIL2BAN:-no}
      network_mode: "host"
      dns:
        - 172.22.1.254
      dns_search: mailcow-network
      volumes:
        - /lib/modules:/lib/modules:ro

    ipv6nat:
      image: robbertkl/ipv6nat
      restart: always
      privileged: true
      network_mode: "host"
      volumes:
        - /var/run/docker.sock:/var/run/docker.sock:ro
        - /lib/modules:/lib/modules:ro

networks:
  mailcow-network:
    driver: bridge
    enable_ipv6: true
    ipam:
      driver: default
      config:
        - subnet: 172.22.1.0/24
        - subnet: fd4d:6169:6c63:6f77::/64
  traefik:
    external:
      name: traefik_webgateway

volumes:
  vmail-vol-1:
  mysql-vol-1:
  dkim-vol-1:
  redis-vol-1:
  rspamd-vol-1:
  postfix-vol-1:
  crypt-vol-1:

Comment: Heyo, serdmanczyk from reddit.  I took a look but not sure, sorry :/.
Comment: Just in case anyone has the same issue as me. I had a docker-compose file for my traefik setup in one folder and I was trying to run apache containers from another directory with a separate docker-compose file. This caused 504 gateway timeout errors for those apache containers. I (temporarily) moved everything in the same docker-compose file and it worked instantly. Adding the `traefik.docker.network` label didn't help.
Answer: I think I may have had a similar issue to what you are/were experiencing. Take a look at this GitHub issue: https://github.com/containous/traefik/issues/979
If your problem is the same as mine, here is the issue:
Traefik is on a "front facing" network, so is one of your services, but that service is also part of a "back facing" network. Traefik, by default, doesn't know what network to send requests to... so it sends them to a randomly chosen one of the two IP address options (picked at the creation of that container). If Traefik isn't part of that network, it wont be able to reach that container, and will give you a Gateway Timeout.
Solution: add a label to your container to directly specify to Traefik what network it should be communicating on:
 labels:
      - "traefik.enable=true"
      - "traefik.docker.network=<folder prefix>webgateway"
      - "traefik.backend=<backend service"
      - "traefik.frontend.rule=Host:<host setting>"

Pro tip: use docker network ls to figure out what the actual name of your network is, because it is not what docker-compose says in the file. The actual network name is prefixed based on the name of the folder that it is run in. (I don't know why, and I don't like it, but that is the world we live in)
Hence the <folder prefix> in my above example.
Comment: It's a silly nuance with Traefik config and Docker networking. The name specifying is more of a "work around" until a more "it just works" solution is available. It took me (sadly) about a week to track down why this was happening. And, as soon as I figured it out, I circled back to this StackOverflow to report my findings to help others! Glad it helped you!
Comment: Wow, this is the correct answer... I had to add the _full network name_, which is contrary to the GitHub issues, example configurations, and so many other places.
Comment: `- "traefik.docker.network=traefik"`

I already specified the network, because I already had a look at this issue. It still does not work, the question also is for me, which containers all need to be in this network.
Comment: All containers that need to talk to traefik need to be on this network. Also, make sure you run a `docker network ls`, because your actual network name will not be as simple as "traefik", the docker-compose command alters the name, prefixing the folder name that you're running the command. Use that real network name in your label.
Comment: @Coburn I feel your pain. If you had any idea how long it took me to track down the root cause...
Answer: What I do is define in a file called .env in the same dir as docker-compose.yml a variable for the project name (that ends as the prefix for all containers/networks/etc). It should only contain characters, no spaces, dashes, etc.
COMPOSE_PROJECT_NAME=myproject

Then, in your application label, you use the variable name appended with the created network separated by "_":
 - "traefik.docker.network=${COMPOSE_PROJECT_NAME}_mynetwork"

Answer: FWIW, if you define the network in the provider section in your traefik service definition, you do not need to add it to each service you add going forward.
Example:
version: "3.3"

services:
  traefik:
    image: "traefik:v2.2"
    container_name: "traefik"
    command:
      - "--api.insecure=true"
      - "--providers.docker=true"
      - "--providers.docker.network=traefik"     <=========
      - "--providers.docker.exposedbydefault=false"
      - "--entrypoints.web.address=:80"
    ports:
      - "80:80"
      - "8090:8080"
    networks:
      - traefik
    volumes:
      - "/var/run/docker.sock:/var/run/docker.sock:ro"

    networks:
      traefik:
        external: true

You should create the traefik network outside your compose file.
Comment: Mainly because you will reference that network on other compose files. I believe if you try to "docker-compose down" on the traefik directory, it will fail because the network is in-use on other compose files. By decoupling the network from the compose file, you can restart the traefik compose as needed without having to go stop the other "stacks".

For example if you needed to update traefik. Yes, when you stop the traefik compose you will have an "outage" but the apps behind traefik could/would stay up and working as expected while you bring traefik back "up".
Comment: Why should we create the `Traefik` network outside the Compose file ? Can't we create it in the Compose file when running a Swarm ?
Answer: I think this issue has been resolved by the traefik community. You can check this: https://github.com/containous/traefik/pull/1873
Comment: nope, I still receive gateway timeout and have no clue why this is happening.
Comment: I will give you the bounty, because it will expire, but this does not answer my question at all.
Comment: Thank you so much. I'm still digging on that. I hope I can help.
Comment: Your answer has helpful information, but does not resolve the question.  The 'traefik.docker.network=_network' label does answer the question.


Alternatives to three-way ANOVA with unbalanced and non-idependent data, non-normal distribution of the residuals and heterocedasticity

Question: I have a response variable ("Value") and three categorical variables for which I want to test the main effects and interactions. ALL DATA COMES FROM ONE INDIVIDUAL for which we have data over time. The factors I want to test their effects upon my response variable are:
1) Formula. I can use different formulas to create my response variable.
Levels: "Form1" and "Form2"
2) Time Interval. I split all data (3 days of continuous data) in different "Time intervals" for which I calculate (using either Form1 or Form2) my response variable.
Levels: "5s", "30s" and "60s"
3) Behaviour: my individual did two defined behaviours all, and I know for each time interval which behaviour was.
Levels: "Regular" and "Irregular"
I want to prove that one of the formulas (Form1) used for creating this response variable is not consistent among different time windows nor behaviours. That is when you use "Form1" the estimation of the response variable depends on the time interval and the behaviour. On the other hand, "Form2" is consistent among time intervals and behaviours. I attach an interaction plot with standard errors ("Plot1") where you can see what I am trying to explain.

I thought to use a "Three-way ANOVA" to test this. However, when I reviewed residual plots to check to whether my data meet the assumptions for an ANOVA, I found that they don't. Below I show the code and the diagnosis plots from the model:
model  <- lm(Value ~ Behaviour*Formula*Time.Interval, data = ValidationFormula)
par(mfrow=c(2,2))
plot(model)

I guess the histograms and boxplots below give some ideas about what is happening.

What can I do to analyze the main effect in Value of Time.Interval, Formula and Behaviour, and their interaction taking into account that data are 1) unbalanced, 2) non-normal and 3) heteroscedastic? I guess my data are not independent either since I divide time into different Time Intervals and, among other things, I am comparing the effect of dividing time into different time intervals.
Answer: One good alternative to ANOVA is ART-ANOVA, which could be applied to non-parametric data since it uses rank-transformed data.
You can find more information about the statistical method and  ARTool package in R here: http://depts.washington.edu/acelab/proj/art/index.html
Comment: Thanks!! I have to check if it is valid for non-independent and unbalance data. I guess heterocedasticity is not a problem either. Do you know something about that? Thanks again for the tip.
Comment: Unbalance data is generally ok for non-parametric methods. And heterocedasticity should not be a problem for this method since it has been originally developed for Likert-scale data (ordered ordinal). But I would suggest looking deeper into the method description to check if it is valid for non-independent data.
Comment: Thank you very much. I will deep on it!!!


Selenium - Java: Struggling to select a particular element

Question: I'm currently creating a few scripts for a web application. I'm currently stuck on picking up a particular button. I've spend a few hours on it and still no luck. Any advice or guidance would be much appreciated. I've added the source code below as well as an image.
My current unsuccessful attempts:
chromeDriver.findElement(By.linkText("uploadfile")).click();
chromeDriver.findElement(By.xpath("html/body/div[9]/input")).click();
chromeDriver.findElement(By.xpath("//iput[@name='uploadfile']")).click

div style="display: block; position: absolute; overflow: hidden; margin: 0px; padding: 0px; opacity: 0; direction: ltr; z-index: 16777270; left: 835px; top: 313px; width: 232px; height: 46px; visibility: hidden;">
<input name="uploadfile" style="position: absolute; right: 0px; margin: 0px; padding: 0px; font-size: 480px; font-family: sans-serif; cursor: pointer; height: 100%; z-index: 16777270;" type="file">

Comment: we need html code. Please share with us
Comment: After latest edit it's clear that the div containing the input is invisible (see style visibility: hidden on div). Selenium works with visible elements. You should either wait for that div to be visible (are you missing a step in your flow? are you not waiting using WebDriverWait for the change to happen to the DOM?) or force the div to be visible using the executeScript method from my previous comment.
Comment: What version of Selenium are you using? I assume your 3rd attempt was for "input" and not "iput". as @PotnuruRavi said, we need some more data, is the element you're selecting being added to the DOM as a result of a script? is it there from the start? is it visible? Selenium might have a problem with locating the element if it's not visible. In the worst case try to execute javascript from the driver with this command ((JavascriptExecutor) chromeDriver).executeScript()
Answer: Use this path:-
  //input[@name='uploadfile' and @style='position: absolute; right: 0px; margin: 0px; padding: 0px; font-size: 480px; font-family: sans-serif; cursor: pointer; height: 100%; z-index: 16777270;']


Naive Bayes: Understanding the Entropy equation

Question: I am trying to understand the entropy equation:
<code>-p1*log2(p1) - p2*log2(p2) - pn*log2(pn)
</code>
Specifically why do we multiply each log by the probability? In the tutorial from Udacity, they begin explaining how we originally multiply each of the probabilities:
<code>p1 * p2 * ... * pn
</code>
But since the product of many terms can leave us with a very small number, we sub in logs (and reverse sign since p < 1) - ok, cool.
So we should have:
<code>- log2(p1) - log2(p2) - ... - log2(pn)
</code>
Why do we then multiply each log term by its probability, e.g. -p1log2(p1)?
Does it have to do with weighting the terms?
Thank you!
Comment: I've found that the 1st chapter of "Pattern Recognition and Machine Learning" by Bishop does a good job at motivating the formula for entropy: https://www.goodreads.com/book/show/55881.Pattern_Recognition_and_Machine_Learning
Comment: Thank you @ValentinWaeselynck . Might you be able to paraphrase the specific section here for other viewers and so I can mark the answer correct?
Answer: One way to motivate the entropy formula is to interpret each of the $-log_2(p_i)$ terms as the amount of 'surprise' or 'gained information' yielded by observing outcome $i$.
The idea is 'surprise' of observing 2 i.i.d variables should be the sum of the 'surprise' for each variable, should be positive, and should be a function of the probability, hence the negated logarithm.
Entropy is then just the expectation of this 'surprise' term, hence the $p_i$ factor.
Comment: Nice. Josh Starmer from StatQuest explained entropy using Surprise too: https://www.youtube.com/watch?v=YtebGVx-Fxw


What does clearing and then swapping a std::vector with a copy of itself do?

Question: std::vector<weight> decoy;

void clear_decoy() {
    decoy.clear();
    std::vector<weight>(decoy).swap(decoy);
}

In the above method clear_decoy(), what does vector<weight>(decoy).swap(decoy); mean please?
Does the method clear decoy or not? Thanks!
Comment: Remember to accept answers you feel are best by clicking the checkmark by them
Answer: I've never seen that form before.
I have seen it written as:
vector<weight>().swap(decoy);

Which means "create a new empty vector, and swap it with the existing one.
vector<weight> (decoy).swap(decoy);
To understand that, break in to parts.
vector<weight>(decoy)  create a new vector (with it's contents copied from the now empty decoy).  The new vector is an anonomous temporary, so let's pretent it's name is newvector.
newVector.swap(decoy);  swaps the new vector with decopy.
(Updated per comments to fix bug)
Comment: +1 for suggesting a better (and more) common construction of the same thing.
Comment: That has to be `vector().swap(decoy)`. You can call member functions on temporaries, but you can't pass them as non-const reference arguments.
Comment: @Matthieu: yes, it's called `shrink_to_fit`, but the implementation doesn't have to honour it.
Comment: I think C++0x STL definition adds a `shrink` method to reduce the memory footprint based on the actual size... or is this wishful thinking ?
Comment: Well, the implementation doesn't have to reduce the capacity to 0 even for an empty vector either. They could even apply the small string optimization to the vector class too, I just thought worth mentioning it :)
Answer: It creates a new vector of Weight objects (which will be empty) and swaps it with decoy.
The reason for this is that by default, std::vector<t>::clear often doesn't actually reduce the storage used by a vector, it merely destroys all the objects contained there. This way, the vector has room to store more objects without reallocation in the future.
Sometimes, however, you want to trim the capacity in the vector. Swapping with a newly created vector (which lives until the end of it's line, and is therefore destroyed there) frees all the memory allocated by the vector.
Comment: Oh dear! My darling C++, you make trouble for those who love you by being smarter than we are.
Comment: This is very C++y. C++ exposes memory management here so you have the chance to customize things for your needs. By default C++ tries to be as fast as it can, and so if you don't follow this code you're going to get faster code. In cases where you have a very large vector and you remove many of its elements then you can use this idiom to free resources to the OS, on the expense of speed. Usually you don't want to do that (i.e., don't fix what's not broken).
Comment: Being smart have a social cost.
Answer: That code is a failed attempt to use a common trick to ensure the memory allocated by the vector is freed. It may or may not actually do that, depending on whether or not the vector's copy constructor allocates memory to match the other vector's size, or its capacity.
To reliably free the memory, use the following:
void clear_decoy() {
    vector<weight>().swap(decoy);
}

This creates a temporary empty vector (with little or no memory allocated), swaps this with decoy so that the memory is now owned by the temporary, then destroys the temporary, freeing the memory.
Comment: While this is true, no sane STL implementation is going to allocate based on capacity here.
Comment: @Billy: Indeed; the clumsy clear-copy-swap dance is very likely to work, but the simpler version is guaranteed to work.
Answer: clear removes all entries from the vector, but may not necessarily deallocate the space.  This swap idiom restores the vector to having no space allocated.
Comment: Actually `clear` *can* deallocate the space the vector occupies. But it does not *have* to. It usually does not in most STL implementations though.
Answer: As 0A0D mentions, the effect of swap is to exchange the underlying controlled memory between the two vectors.  But this warrants a little more explanation.
When you clear a vector, the elements are removed from it at least as far as the programmer is concerned.  size() becomes zero and capacity() may or may not change.  But the Standard doesn't guarantee that the memory used by the vector will actually be returned back to the operating system.  So if you had 1000 elements in the vector before the clear() and each took 1000 bytes memory, after the clear() each element's destructor is called, but the vector may still be holding on to a 1,000,000 byte allocation.
This is sometimes undesirable.  The 'swap trick' you note above has the effect of exchanging the controlled memory between the two vectors.  Hence decoy ends up with it's controlled memory reset.
Here is what is happening step-by-step:

decoy elements are each erased.
The elements' destructors are
called, and the vector's size()
becomes zero.  The actual memory may
not be deallocated.
A new vector is constructed on the stack (vector<weight> (decoy)) and the elements from decoy are copied in to it.  Since decoy was just clear()ed, no elements are copied in to the temporary vector.  However, see edit below.  You don't know that the controlled memory is not swapped.
The temporary vector's and decoy's memory are swapped (.swap(decoy);) resulting in decoy being both cleared and it's memory transferred to the temporary.
The temporary falls off the stack, resulting in it's memory being deallocated.

This is referred to as "the swap trick".
EDIT: As Mike mentions, the original programmer is doing it wrong.  The temporary should not be constructed based on decoy, it should just be default constructed.  You don't know for sure that swap() will only copy the elements and not the controlled memory underneath.
Answer: With clear,

All the elements of the vector are
  dropped: their destructors are called,
  and then they are removed from the
  vector container, leaving the
  container with a size of 0.

Swap just swaps the two vectors,

Swap content
Exchanges the content of the vector by
  the content of vec, which is another
  vector of the same type. Sizes may
  differ.
After the call to this member
  function, the elements in this
  container are those which were in vec
  before the call, and the elements of
  vec are those which were in this. All
  iterators, references and pointers
  remain valid for the swapped vectors.

It seems you are swapping nothing really and just restores to default allocation. Clear can deallocate but it sometimes does not. You are not only reducing the size but lessening the space allocated with the swap statement.
Comment: @ladyfafa: With the swap statement, the amount of space allocated is reduced. That is the nice part of vectors.


What is the difference between WPF Command and Event in WPF?

Question: I was just googling the difference between WPF Command and Event in WPF. i landed on the following page of stackoverflow where the discussion is going on.
What is the difference between WPF Command and Event?
I am only able to understand following from there

Commands can be written in business layer while event only in presentation
A single command can be associated with many controls but event can only be associated with only one control.

Am I right? Is there any other difference between them?
Answer: You're right but only partly.

The main concern there is that events doesn't fit
well into MVVM paradigm. Simply saying events are hardly pluggable, you can't bind to event handler. Nevertheless there is no limit to use commands in presentation layer but there is no benefits of doing so. As well as you could catch your control in BLL and attach event handler to it but this case is even worse.
No. Event handlers also could be associated to
different controls as long as event args type match.

Also commands gives you some free benefits. For example using command element'll be disabled if CanExecute() returns false. Another benefit is that using commands forces you to fo follow Separation of concerns principle.
Answer: An Event is a trigger that occurs when something happens in the UI.
A Command is how this event is handled by your domain model.


Name of the monotone-like property "$f(x)\geq f(x\wedge y)$ implies $f(x\vee y)\geq f(x)$" on a lattice

Question: Let $(X,\leq)$ be a lattice. There is a function $f$ that has the following property.

$f(x)\geq f(x\wedge y)$ implies $f(x\vee y)\geq f(x)$

where strict inequality on the left-hand side implies strict inequality on the right-hand.
At a first glance, the property looks like some type of monotonicity as $f$ should be increasing in its arguments.. but it is more general than the monotonicity.
Anyone happens to know the name of this property?
Answer: Let me rewrite the question here:
Let $(X,\leq)$ be a lattice. There is a function $f$ that has the following properties:

$f(x)\geq f(x\wedge y)$ implies $f(x\vee y)\geq f(x)$,
 strict inequality on the left-hand side implies strict inequality on the right-hand side.

Claim I. A function $f$ satisfies Condition 1. if and only if $f$ is a monotone function.
Claim II.  A function $f$ satisfies both 1. and 2. if and only if $f$ is a constant function.
Reasoning for Claim 1.
Assume that $f$ satisfies the implication in Condition 1.
We have
$$\begin{array}{rll}
y\geq x&\to x=x\wedge y&\\
&\to f(x)=f(x\wedge y)&\textrm{($f$ is a function)}\\
&\to f(x\vee y)\geq f(x)&\textrm{(Condition 1.)}\\
&\to f(y)\geq f(x)&\textrm{($x\vee y =y$)}.
\end{array}
$$
This shows that $y\geq x$ implies $f(y)\geq f(x)$.
Conversely, if $f$ is any monotone function with domain $X$,
then since $x\vee y\geq x$ we have $f(x\vee y)\geq f(x)$.
This shows that the conclusion of the implication in
Condition 1. always holds
for monotone functions.
Reasoning for Claim 2.
To prove that a function $f$ satisfying
Conditions 1. and 2. is constant, it suffices to prove that
$f(x)=f(y)$ whenever $x,y\in X$ are comparable.
(Justification: Suppose that we have shown that $f(x)=f(y)$ when $x$ and $y$
are comparable. Given arbitrary $u, v\in X$, both $u$ and $v$
are comparable with $u\wedge v$, so  $f(u) = f(u\wedge v) = f(v)$, implying that $f$ is constant.)
We argue by contradiction. Assume that $f$ satisfies Conditions 1. and 2. but that $X$ contains $x\geq y$
for which $f(x)\neq f(y)$. Necessarily $x>y$. By Condition 1., $f$ is monotone, so we must have $f(x)>f(y)\;\;(=f(x\wedge y))$.
Applying Conditions 1.+2. to $f(x)>f(x\wedge y)$, we must have $f(x\vee y)>f(x)$. But $x=x\vee y$, so this reduces to $f(x)>f(x)$, which is false.  This contradiction proves Claim 2.
Comment: Thanks for the answer. It looks like the two claims are mainly driven by the case $y\geq x$. If I impose the property 1 to be hold true only for $y\ngeq x$,  would there be a lot of changes to the answer? My guess is that f should monotonically increase or decrease.


I'm getting a CORS error although Access-Control-Allow-Credentials is not set

Question: I wrote a server app with node.js and express. The app uses the cors node package for POST requests with origin "*" because I need to be able to post from mobile apps.
Here is how CORS is enabled in the app:
var cors = require('cors');

var app = express();

app.configure(function() {
  app.use(cors());
});

When I try to POST a request from a browser, I get this error:

XMLHttpRequest cannot load url. A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'null' is therefore not allowed access.

However, I don't see any Access-Control-Allow-Credentials header in the response. Here is the failing request and the response in Chrome's network tab:

Why does it complain about the credentials flag?
Comment: Could you show us how do you enable and configure CORS in your app?
Comment: I added a code snippet.
Comment: Be aware that `app.configure` is removed in Express 4.x https://github.com/strongloop/express/wiki/Migrating-from-3.x-to-4.x
Answer: We finally solved this. Here are our findings and the train of thought that led us to the solution:

The CORS issue happened only with POST, not GET.
The CORS issue happened only when I made the request from a local HTML whose URL starts with file://. There was no issue when I requested it from http://localhost.
When initiating a POST request from the file:// protocol, the origin is null. Turns out that the issue was that null is not covered by the wildcard *.
Setting Allow-Access-Control-Origin to null was not enough, because apparently a request from origin null includes credentials, so I had to set Allow-Access-Control-Credentials to true.

So here is my updated server code that accepts POST requests from any source, including a web view in a mobile app that works with file://:
var cors = require('cors');

var app = express();

app.configure(function() {
  app.use(cors({ origin: 'null', credentials: true }));
});


Understanding subtraction by addition and difference between one's complement and two's complement

Question: This week our lecturer in microprocessor architecture showed us how the two's complement and the ten's complement can be used to do subtract by doing addition.
For example:
15 - 7
maximalNumberOfTheCurrentRange - numberToSubtract + 1
=> 99 - 7 + 1 = 93
Then
  15
+93
===
108 as intermediate result.
Now remove the leading 1. => It becomes the final result 8 !
But how does that work?
I mean: I understand how to do the algorithm. But I would to understand the trick which is used here.
Can someone explain it to me in an easy to understand way?
I would very appreciate it.
I'm not much into academic mathematics I should mention ...
Moreover: What's the difference between the so-called "one's complement" and the "two's complement"?
Comment: What you not understand in above method?
Comment: How shall I say? ... How does it work? Why does: Adding the number, which is necessary to reach the next digit in the number system, then adding, then removing the most highest digit have this effect?
Answer: 1.) In above method -
If we have carry then we can ignore it.
So in 108. Carry digit is ignored and we have 08 as final answer.
See this for reference and example.
2.) I am trying to differentiate one's and two's complement using main advantage of 2's complement. Advantage of two's complement over one's complement is that two's complement only has one value for zero. One's complement has a "positive" zero and a "negative" zero.
Next, to add numbers using one's complement you have to first do binary addition, then add in an end-around carry value.
Two's complement has only one value for zero, and doesn't require carry values.
For reference see this.
Comment: Okay. I think I get it finally. By discarding the carry-value we get an effect as if we would subtract. The addition of 1 (+1) is for including the 0 which is actually a digit too.
Comment: Have just remembered some older type of clock and it helped me a lot. Please see: https://uhrforum.de/attachments/657891d1374414901-kundo-2000-prismenuhr-dscn2168.jpg
Comment: Mine pleasure bro :-)


Alterar valor vindo do back para o front end (na service)

Question: Estou recebendo um objeto de back distinto (normalmente tenho um back padrao) por conta disso os valores dos id vieram divergentes do que preciso, gostaria de altera-los na service para que se encaixe no meu front porem não sei como fazer isso.
por exemplo
Eu espero um objeto com id e value
o back esta me retornando codigo e valor
segue o que tentei fazer
Ajuste(model: any): PessoaFisica {
  if (!model) {
    return model;
  }

  return {
    ...model,
idade && idade.codigo{idade.id}

}
mas não funcionou
espero que dê pra entende
Comment: Na verdade não deu pra entender não, como assim **"Estou recebendo um objeto de back distinto"**?
Comment: eu geralmente consulto um back e vem tudo bonitinho, mas esse dados em particular então vindk de outro sistema, não posso alterar back, pelo fato de ja estar sendo utilizado
Comment: Bom se entendi basta no seu model (creio que haja um) no Angular, adicionar as propriedades que estão faltando e utilizá-las.
Answer: Você está utilizando o HttpClient? Se sim, você pode usar o operator map do RxJs para mudar o tipo, assim:
this.objetoConvertido = this.httpClient.get<ObjetoIdValue>('suapibackend').pipe(map(resposta =>{
  const conversion = {id: resposta.codigo, value: resposta.valor}
  return conversion;
}));


Regarding Resolution, "downwards" is how a dissonance "wants" to resolve, rather than moving UP.... so help me understand B up to C (G7-C)

Question: During a V-I resolution in C Major, the Leading Tone is B.
B is the 3rd of the G7 chord. It wants to resolve to the Tonic note of C in C Major (C-E-G)
But, I've often read that dissonances want to resolve by moving DOWN, not up.
So, other than being a half-step (m2) interval, doesn't this nullify the whole idea of notes wanting to resolve down?
Generally speaking, when people say lines like "things often want to resolve down", isn't it misleading, until you deal with "in-context", specific moments of a progression?
So, when people use C Major to V7 (C-G7), that is moving UPWARDS of a 5th. (ie Circle of 5ths)
Although, it just came to be that, perhaps when people say "things want to resolve downwards", they may be referencing the entire CHORD (say G7) wanting to resolve down to the tonic (C)??
Comment: IMO it's plain wrong to say dissonances want to resolve down. Most classical example is the augmented sixth chord: the aug-6 is certainly a dissonance (enharmonic to a minor 7), but it resolves upwards.
Answer: It's ultimately a question of your reference point when you use the term "dissonant": in other words, when you say a particular pitch is dissonant, be mindful of what you're saying it's dissonant against.
When we say that dissonances typically want to resolve down, we're specifically talking about dissonances in relation to the current chordal root. This is why the F of a G7 chord wants to resolve down: it's the seventh of the chord, and because the seventh is a dissonance, it wants to resolve downwards.
But the B that you mention is the chordal third of the G7 chord. And since thirds are consonances, there is no similar urge to resolve this B down.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/132725/discussion-between-richard-and-aaron).
Answer: In a melodic line progressing in 2nds (stepwise)  a tone altered by a flat "wants" to lead downwards (e.g. b7, b6), when altered by a sharp it leads upwards (e.g. augmented 2nds, 4ths, 5ths, 6ths).
In your exampel the tritonus Fa Ti produces  a strong dissonance with two tendings: Fa resolves down, Ti is leading tone and resolves upwards. ( B is dissonant with F , but consonant to G.)
So we'll have to think in melody lines.


Using PHP to Dynamically create multiple unique buttons

Question: I want to dynamically create multiple buttons which eventually will have unique click events.  The "title or name" of each button is stored in a DB.  I have verified, independently, the code to create a dynamic button works and I have also verified my query works properly as well as my "while" loop.  Following is my code:
$q="SELECT sess_desc, sess_butt, sess_tag FROM Sessions ORDER BY DateEstab";
$r = mysqli_query ($dbc, $q);
if ($r) {
   while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
    $image = imagecreate(248,53);
    $blue = imagecolorallocate($image, 0, 0, 255); //text box background color
    $white = ImageColorAllocate($image, 255,255,255); //Font color
    if(!isset($_GET['size'])) $_GET['size'] = 18;  //text size
    if(!isset($_GET['text'])) $_GET['text'] = $row['sess_butt']; //button lable
imagettftext($image, $_GET['size'], 0, 20,35, $white, "tahoma",$_GET['text']);

echo '
' . imagepng($image) . imagedestroy($image) .'
      ' . $row['sess_desc'] . '
      '	' . $row['sess_tag'] . '
';
}
}

Here is the beginning of the results when I run the script (it continues).
   �PNG  IHDR�5��;RPLTE�����������__�����??��`!5IDATX��ԻO�P ��TڎJ��Fѹ&>ƶ�:����>��#q�����
I was expecting blue rectangular buttons with a white label.  What do I need to do to make this work using php or do I need to look for a solution using JS (I do not know JS very well)?  I have looked at "similar question", the php manual and other articles I found searching the internet.
Is this even possible?  I ran the script for creating a button and it works fine if I define $_GET['text']= "Hello Everyone", but I am trying to pull the "text" from a DB table.  Again, I want to create multiple buttons from multiple entries in the DB. Specifically, the sess_butt column.  I even limited my query to "1" and that did not work either...same results.
Comment: You should check the manual for: `imagepng()`. It does NOT output a HTML-image tag. It outputs the actual image content. [imagepng()](http://php.net/manual/en/function.imagepng.php)
Answer: If you'd like to embed images into your HTML, you need to have them base64 encoded. Something like:

I also recommend you not to do this and generate url's instead which will be hitting your other script which will be just doing the image generation.
Comment: I think you missed some PHP-tags...  and it's just `base64_encode()`.
Comment: @MagnusEriksson It is not supposed to be exact php code, just a rough direction to move into
Comment: Sorry, that did not help.  I modified my question in hopes of being a little more clear on what I want and what I tried.
Comment: What do you see in html when you try that?
Comment: I get the alt message "Embedded Image"
Comment: @Learner post your html code for the generated page please. Probably you'll have to upload it to external service like github and post a link here


systemd service produces Exec format error

Question: I have created the following systemd service to automatically keep an autossh tunnel open between two servers:
#Systemd unit file for autossh
[Unit]
Description=Autossh Tunnel

[Service]
Type=forking

ExecStart=/usr/bin/autossh -M 20009 -f -N -L 3307:127.0.0.1:3306 remoteServer
ExecStop=pkill autossh

User=ubuntu
Group=ubuntu
UMask=0007
RestartSec=1
Restart=always

[Install]
WantedBy=multi-user.target

The file is loacted in /etc/systemd/system/autossh-tunnel.service
When I run it I get the following error message:
ubuntu@verifier:~/.ssh$ sudo systemctl daemon-reload
ubuntu@verifier:~/.ssh$ sudo service autossh-tunnel start
Failed to start autossh-tunnel.service: Unit autossh-tunnel.service is not loaded properly: Exec format error.
See system logs and 'systemctl status autossh-tunnel.service' for details.
ubuntu@verifier:~/.ssh$ systemctl status autossh-tunnel.service
● autossh-tunnel.service - Autossh Tunnel
   Loaded: error (Reason: Exec format error)
   Active: inactive (dead)

which autossh yields:
ubuntu@verifier:~/.ssh$ which autossh
/usr/bin/autossh

I have also tried to run the exact same command /usr/bin/autossh -M 20009 -f -N -L 3307:127.0.0.1:3306 remoteServer in the console and I did not have any problems. However, as a systemd service it fails.
What is wrong here? I have another server with the same setup and there this script runs without any issues. So I do not understand what is going on here...
Answer: Quick answer: Make sure to check the output of /var/log/syslog for detailed error messages.
Long answer:
Okay, I found out what the problem is.
Shortly after calling sudo service autossh-tunnel start I check the output in sudo tail -n 200 /var/log/syslog and I got the output:
Mar 27 20:29:01 verifier systemd[1]: /etc/systemd/system/autossh-tunnel.service:9: Executable path is not absolute: pkill autossh
Mar 27 20:29:17 verifier systemd[1]: /etc/systemd/system/autossh-tunnel.service:9: Executable path is not absolute: pkill autossh

So I changed the service file to call /usr/bin/pkill instead of just pkill.
That did solve the prolem. Now sudo tail -n 200 /var/log/syslog yields:
Mar 27 20:29:59 verifier systemd[1]: Starting Autossh Tunnel...
Mar 27 20:29:59 verifier systemd[1]: Started Autossh Tunnel.

And a ps aux | grep autossh also shows me that it is running.


Grouping multidimensional array

Question: So I currently have an array that looks like this.
Array
(
    [name] => Array
        (
            [1] => Array
                (
                    [0] => 500aqua.jpg
                )

            [2] => Array
                (
                    [0] => 500beige.jpg
                    [1] => 500beige-zoom.jpg
                )

            [3] => Array
                (
                    [0] => P1040485.JPG
                    [1] => P1040486.JPG
                    [2] => P1040487.JPG
                )
        )

    [type] => Array
        (
            [1] => Array
                (
                    [0] => image/jpeg
                )

            [2] => Array
                (
                    [0] => image/jpeg
                    [1] => image/jpeg
                )

            [3] => Array
                (
                    [0] => image/jpeg
                    [1] => image/jpeg
                    [2] => image/jpeg
                )
        )

    [tmp_name] => Array
        (
            [1] => Array
                (
                    [0] => C:\xampp\tmp\php5F9.tmp
                )

            [2] => Array
                (
                    [0] => C:\xampp\tmp\php5FA.tmp
                    [1] => C:\xampp\tmp\php5FB.tmp
                )

            [3] => Array
                (
                    [0] => C:\xampp\tmp\php60C.tmp
                    [1] => C:\xampp\tmp\php63B.tmp
                    [2] => C:\xampp\tmp\php66B.tmp
                )
        )

    [error] => Array
        (
            [1] => Array
                (
                    [0] => 0
                )

            [2] => Array
                (
                    [0] => 0
                    [1] => 0
                )

            [3] => Array
                (
                    [0] => 0
                    [1] => 0
                    [2] => 0
                )
        )

    [size] => Array
        (
            [1] => Array
                (
                    [0] => 133659
                )

            [2] => Array
                (
                    [0] => 148940
                    [1] => 211420
                )

            [3] => Array
                (
                    [0] => 3939511
                    [1] => 4742470
                    [2] => 4345899
                )
        )

)

And I want it to look something like this
Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [name] => 500aqua.jpg
                    [type] => image/jpeg
                    [tmp_name] => C:\xampp\tmp\php5F9.tmp
                    [error] => 0
                    [size] => 133659

                )
        )
    [1] => Array
        (
            [0] => Array
                (
                    [name] => 500beige.jpg
                    [type] => image/jpeg
                    [tmp_name] => C:\xampp\tmp\php5FA.tmp
                    [error] => 0
                    [size] => 148940
                )
            [1] => Array
                (
                    [name] => 500beige-zoom.jpg
                    [type] => image/jpeg
                    [tmp_name] => C:\xampp\tmp\php5FB.tmp
                    [error] => 0
                    [size] => 211420
                )
        )
    [2] => Array
        (
            [0] => Array
                (
                    [name] => P1040485.JPG
                    [type] => image/jpeg
                    [tmp_name] => C:\xampp\tmp\php60C.tmp
                    [error] => 0
                    [size] => 148940
                )
            [1] => Array
                (
                    [name] => P1040486.JPG
                    [type] => image/jpeg
                    [tmp_name] => C:\xampp\tmp\php63B.tmp
                    [error] => 0
                    [size] => 148940
                )
            [2] => Array
                (
                    [name] => P1040487.JPG
                    [type] => image/jpeg
                    [tmp_name] => C:\xampp\tmp\php66B.tmp
                    [error] => 0
                    [size] => 148940
                )
        )
)

I've tried the following code but it only seems to get each of the last 3 in the arrays.
foreach ($data as $d) {
    foreach ($d as $key => $e) {
        foreach ($e as $key2 => $f) {
            $result[$key2][$key] = $f;
        }
    }
}

Like
Array
(
    [0] => Array
        (
            [name] => P1040485.JPG
            [type] => image/jpeg
            [tmp_name] => C:\xampp\tmp\php60C.tmp
            [error] => 0
            [size] => 3939511
        )

    [1] => Array
        (
            [name] => P1040486.JPG
            [type] => image/jpeg
            [tmp_name] => C:\xampp\tmp\php63B.tmp
            [error] => 0
            [size] => 4742470
        )

    [2] => Array
        (
            [name] => P1040487.JPG
            [type] => image/jpeg
            [tmp_name] => C:\xampp\tmp\php66B.tmp
            [error] => 0
            [size] => 4345899
        )

)

Thanks in advance.
Answer: Try this one:
foreach ($data as $key1 => $value1) {
    foreach ($value1 as $key2 => $value2) {
        foreach ($value2 as $key3 => $value3) {
            $result[$key2][$key3][$key1] = $value3;
        }
    }
}

You forgot to include the Key on the first level ($key1): name, type etc.
Answer: Try this:
foreach ($data as $field => $field_values) {
    foreach (array_values($field_values) as $index_1 => $index_1_values) {
        foreach ($index_1_values as $index_2 => $value) {
            $result[$index_1][$index_2][$field] = $value;
        }
    }
}

Grouping multidimensional array


Better way to write this lambda expression?

Question: I'm trying to write a lambda expression that looks at an array of objects ('fields') that may or may not have specific items in it.  I would like to retrieve values if they exist; if no field in the array has a code of 'SomeCode', then there is no value to retrieve.  I'm curious if there is a cleaner way to write the below, since I'll need to do this for a lot of fields and done want to run through the 'FirstOrDefault' call twice.
if (fields.FirstOrDefault(x => x.Code == "SomeCode") != null)
{
    obj.CodeValue = fields.FirstOrDefault(x => x.Code == "SomeCode").Value;
}

EDIT: Thanks for any insight on doing this in a 'Lambda only' fashion; I'd like to improve my skills in this area and figured that there would be something cleaner than either calling it twice or simply assigning it to an interim object.
Comment: Do you want to set `obj.CodeValue` at all if there are no matches? Would it be *harmful* to do so?
Comment: if you're only expecting one value, it may also make sense to use `SingleOrDefault`.
Comment: @JonSkeet - It may be (harmful) if the value ends up being nullable.  Thanks, Brad - Good call; thanks, since I am expecting at most only one value.
Answer: Just cache the return value from FirstOrDefault and then compare it.
var item = fields.FirstOrDefault(x => x.Code == "SomeCode");
if (item != null)
{
    obj.CodeValue = item.Value;
}

In your current code you are querying twice, once for checking null, later to access value.
Comment: I'm doing this now; I thought that there might be a 'lambda-only solution.  Thanks, though.
Comment: @EvConrad, I am not sure What you mean by "Lamda-only" solution, but in your current code you are querying twice, the code in answer will query once.
Answer: Try this:
var field = fields.FirstOrDefault(x => x.Code == "SomeCode");

if (field != null)
    obj.CodeValue = field.Value;


I need some help understanding implementing queue using stack

Question: I found the code which is below. I just want to know how does the "else" part in remove function works. If anybody can elaborate the steps for me, I would be thankful.
insert(E value)
{
    stack.push(value);
}

E remove()
{
    E top = stack.pop();
    if(stack.isEmpty())
        return top;
    else
    {
        E result = remove();
        stack.push(top);
        return result;
    }
}

Answer: A queue will insert into the back and remove from the front. However, the front of the queue is at the bottom of the stack.
The remove algorithm recursively iterates through the stack until it reaches the bottom, and returns that element as the result of the removal. As the recursion unwinds, the members it had popped off to reach the bottom are pushed back onto the stack. Thus, the original order of the queue is restored, minus the front of the queue (which was the bottom of the stack).

In a comment, you write:

I need help in understanding the steps, like where are the popped elements stored and how are they pushed during recursion etc and how does the recursive call manage all this.

A recursive function call is not any fundamentally different from a regular function call. Consider the following pseudo code:
E foo_2 ()
{
    return stack.pop();
}

E foo_1 ()
{
    E top = stack.pop();
    if(stack.isEmpty())
        return top;
    else
    {
        E result = foo_2();
        stack.push(top);
        return result;
    }
}

So, a call to foo_1 results in a function local variable called top getting the result of stack.pop(). If the stack is now empty, it returns the top. If the stack is not yet empty, it saves the return value of foo_2 in result, then pushes top back on to stack, and then returns the saved result.
If you understand that the local function variable top in foo_1 is not affected by the call to foo_2, then you already understand that local function variables reside in a protected area particular to the call to foo_1. This protected area is sometimes referred to as an activation record. The call to foo_1 creates an activation record for that call to hold the local function state (like variables, return values, which line of code is currently being run, etc.), and if foo_1 calls another function, a new activation is pushed on top of the current one to handle the local function state of that function call. When that function call returns, its activation record is popped, and the current activation record returns to that of the caller, foo_1. Because of the pushing of an activation record for a function call, and the popping of the activation record when the function call returns, the structure of the activation records is referred to as a call stack (and activation records are also known as stack frames).
The only trick to a recursive call is that the function calls itself. But, a new activation record is pushed onto the call stack just like a regular function call.
Just as a quick illustration, consider that the queue has three elements, 1, 2, 3, where 1 is at the front of the queue. So the activation records after the recursive remove reaches the bottom would look like:
top: 1
----
top: 2
result: ? (waiting for result of remove())
----
top: 3
result: ? (waiting for result of remove())
----

At the top of the call stack, the stack used by queue is now empty, so 1 is returned, so the activation record stack changes:
top: 2
result: 1
----
top: 3
result: ? (waiting for result of remove())
----

In this activation record, the 2 is pushed back onto the stack, and result is returned, so the activation record stack changes:
top: 3
result: 1
----

And in this activation record, the 3 is pushed back onto the stack, and the result is returned, and the activation record stack is now empty with respect to the initial call to remove.
Comment: could you also elaborate the recursive steps by taking a simple example? Sorry for the trouble, but what you said I already understood that, I need help in understanding the steps, like where are the popped elements stored and how are they pushed during recursion etc and how does the recursive call manage all this. I read somewhere that the system uses a stack to manage recursive calls but I'm unclear about the real picture.
Comment: @LedZeppelin: I've expanded the answer. Hope this helps.


ServerManager does not commit changes to IIS (new application)

Question: I am on Win7 with vs2013 & I have installed the Microsoft.Web.Administration package into VS. From this I have a reference to the Microsoft.Web.Administration.dll and all works just fine when connecting to my IIS server and I can see all my sites.
I create a new application using this straight forward code:
ServerManager iisManager = new ServerManager();
Microsoft.Web.Administration.Site site = iisManager.Sites["Default Web Site"];
site.Applications.Add("/Test", @"c:\blah\blah");
iisManager.CommitChanges();

The Application is added because I can see that site.Applications.Count has increased but I don't see the application in the IIS console and when I re-create the ServerManager object and check Sites.Applications the application is missing. Any ideas?
Answer: OK I found the problem - it is related to the instance of ServerManager calling CommitChanges. In my pseudo code I used
Microsoft.Web.Administration.Site site = iisManager.Sites["Default Web Site"];

but in reality I have a routine that gets the reference to the site and in that routine I was creating a new instance of ServerManager. As soon as I used the  same instance of ServerManager to get the site and to commit changes all was ok. A bit obscure...


How is Test MSE being calculated here?

Question: I'm reading Andrew Ng's CS229 course notes on machine learning, and I'm at the part about Bias-Variance Tradeoff. Here, we're modeling our data as $y_i = f(x_i) + \epsilon_i$ where $\epsilon_i$ are i.i.d. with $\mathbb{E}[\epsilon_i]=0$ and $\text{Var}[\epsilon_i] = \sigma^2$. We learn a model $\hat{f}$ based off the training samples (and so this $\hat{f}(x)$ is actually a random variable for all $x$ in our test set).
Now, they go on to calculate the Test MSE as follows:
$$
\begin{aligned}
\text{Test MSE} & = \mathbb{E}\left((y-\hat{f}(x))^2\right) \\
& = \mathbb{E}\left((\epsilon + f(x) - \hat{f}(x))^2\right) \\
& = \mathbb{E}\left(\epsilon^2\right) + \mathbb{E}\left((f(x) - \hat{f}(x))^2\right) \\
& = \sigma^2 + \left(\mathbb{E}(f(x) - \hat{f}(x))\right)^2 + \text{Var}(f(x) - \hat{f}(x)) \\
& = \sigma^2 + \left(\text{Bias}(\hat{f})\right)^2 + \text{Var}(\hat{f})
\end{aligned}
$$
I don't really have any problem with the formulas above, I can go from one to the next. What I don't understand is what the expectation is being taken over in the first place. What exactly does $\mathbb{E}((y - \hat{f}(x))^2)$ mean?
My intuition is telling me it's being taken over the training set $(x, y)\in\text{Test Set}$, with samples being drawn uniformly, but this doesn't make a lot of sense to me because I thought the whole point is that $\hat{f}$ is a random variable over the samples $\epsilon_i$, so shouldn't the expectation be over the $\epsilon_i$'s? If so, then are $x$ and $y$ just an arbitrary sample from the test set? How is $\text{Var}(\epsilon) = \sigma^2$, is $\epsilon$ our random variable here?
I'm just so confused about how exactly each of these expectations is being calculated. I get the gist of it, and I have no problem with formulas involving the expectation (like the fact that $\mathbb{E}[\epsilon^2] = \text{Var}(\epsilon) + \mathbb{E}[\epsilon]^2 = \text{Var}(\epsilon)$), I just don't understand what these expectations are being taken with respect to.
Comment: f(x) is the prediction of your model. If the model perfectly predicts y, then y-f(x) is zero, and that is the loss function being minimized here. When averaging this squared error over samples in the training/test set, you have a cost function called the mean squared error. Is all of this clear?
Comment: @hirschme Yes I suppose, so you're saying the expectation is averaged over pairs $(x, y)$ in the training set? What exactly is $\epsilon$ then?
Comment: Because you are modeling y to be equal to f(x) plus some additional noise $\epsilon$, then the best your model can perform is that error term, as it can't be predicted.
Comment: @hirschme Yes, that makes sense, but that doesn't help me understand the precise meaning of the formulas above unfortunately. I can talk about Test MSE and the model learning in English confidently, but I can't really prove much about the formulas without knowing what they precisely correspond to (in English).
Comment: If you now understand why we choose the term $\mathbb{E}((y - \hat{f}(x))^2)$ to describe the performance of a model $f(x)$ on data $(x,y)$ (regardles if it is training or test), then the rest is just algebra. In this case, the stochastic noise term $\epsilon$ is chosen to be standard gaussian noise, which has characteristics $\mathbb{E}(\epsilon) = 0$ and $Var(\epsilon) = \sigma^2$ ($\epsilon$ ~ $N(0, \sigma^2)$)
Comment: @hirschme I understand why $\mathbb{E}((y - \hat{f}(x))^2)$ makes sense to describe $f$ on data. What I don't understand is how this corresponds to the usual formula I've learned, which is $\mathbb{E}(X) = \sum_x x p(x)$.
Comment: The expected value of a distribution can be computed like you say if we know the true underlying probability function $p(x)$. Whenever we don't know that, we use the 'average' value, weighting the samples by their frequency instead of the probability, which is the same as the mean value. The expected value here corresponds to the mean value across N sampled pairs $(x_i,y_i)$ , $i = 1,..N$
Comment: Okay, I'm starting to get it, thanks. Now, if the expected value is over the $N$ sampled pairs $(x_i, y_i)$, then is $\hat{f}$ _truly_ a random variable in this context?
Comment: $\hat{f}(x; \omega)$ is an estimate on y, governed by the input data $x$ and a parameterization $\omega$. These variables are also drawn from a distribution $x$ ~ $X$ and $\omega$ ~ $\Omega$, plus additional things like learning algorithm stochasticity, model choice, etc. Therefore the output $f(x; \omega)$ will also have a distribution, therefore an expected value, bias and variance, in respect to an unknown 'true model' $f(x) = y $
Comment: @hirschme, sorry just to clarify, you have $\hat{f}$ written at the top there, and then $f$ written twice afterwards. Are you saying $f$ is a random variable, or $\hat{f}$ is, or both?
Comment: Sorry the second f should be $\hat{f}$. $\hat{f}(x)$ is our estimate of $f(x)$, which is a perfect model defined as $f(x) = y + \epsilon$. We never see $f(x)$ (only indirectly through y), we only deal with $\hat{f}(x)$ which can be seen as a random variable, and use $f(x)$ to compute bias and variance of our model $\hat{f}(x)$. They are both random variables, as $f(x) = y +\epsilon$ you can see it has stochasticity included through the stochastic noise term $\epsilon$ ~ $N(0,\sigma^2)$
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/86350/discussion-between-user3002473-and-hirschme).
Answer: In order to have a measure of the perfomance of our model $f(x)$ on approximating the map $x \rightarrow y$, we define an error (cost) function that measures the distance between our target $y$ and our estimate $\hat{y} = f(x)$ which we desire to minimize. An usual error term choice is the mean squared error MSE, which is the squared (direction insensitive) residuals, averaged over all sampled data pairs $(x_i,y_i), i=1,...,N$. This average is our approximation of the expected value of this residuals and can be written $\mathbb{E}[(y - f(x))^2]$.
The values of $f(x)$ will follow a distribution, governed by the inputs $x_i$, and other factors such as model choice, parameterization and so on. We can compare the performance of this model against a 'perfect' model $y = f(x) + \epsilon$. Having defined this perfect model $f(x)$, we call our model an estimate of this, thus now called $\hat{f}(x)$ and used in you equations.

How is Test MSE being calculated here?


Trouble on "If" statement on TI-84 Plus C Silver Edition

Question: I've got a small code in TI BASIC on my TI-84 Plus C Silver Edition calculator that will determine correct dosage of drugs based on the patient's weight. For example, if aspirin is given at 5 mg per kg of patient weight (it isn't), then the code should tell me to give a 100kg patient 500mg of aspirin.
However, the code is solving for every possible drug. Here it is:
PROGRAM:DRUG1
:Input "PATIENT WEIGHT: ",W
:Input "AGENT NAME: ",A
:If A=IPPI
:Disp "DOSAGE",W*2
:If A=NEVO
:Disp "DOSAGE", W*0.5

So in this case, the two drugs are IPPI and NEVO. If I give a patient weight of 100kg, and choose IPPI, then I would expect to see
DOSAGE                 200

However, what I do see is
DOSAGE              200
DOSAGE               50

so apparently both "if" statements are running, even though I've given a only one value (IPPI). [The same error occurs when I set A as NEVO].
I've tried enclosing both If statements within Then...End as well, so the code would look like:
PROGRAM:DRUG1
:Input "PATIENT WEIGHT: ",W
:Input "AGENT NAME: ",A
:If A=IPPI
:Then
:Disp "DOSAGE",W*2
:End
:If A=NEVO
:Then
:Disp "DOSAGE", W*0.5
:End

but that changes nothing.
I'm pretty new to BASIC, so I'm sure there's a simple error that I can't see, but I'm stumped at the moment.
Answer: You need to change the second Input command so the information is stored to a string instead of the numeric variable A. TI-84 series calculators have ten string variables in the [VARS][7] menu for this purpose.
Note also that you must compare the string against the string "IPPI" rather than the sequence of letters (numeric variables) IPPI. So your code could be:
:Input "PATIENT WEIGHT: ",W
:Input "AGENT NAME: ",Str1
:If Str1="IPPI"
:Disp "DOSAGE: ",W*2
:If Str1="NEVO"
:Disp "DOSAGE: ",W*0.5

or more concisely:
:Input "PATIENT WEIGHT: ",W
:Input "AGENT NAME: ",Str1
:Disp "DOSAGE:"
:If Str1="IPPI"
:Disp 2W
:If Str1="NEVO"
:Disp .5W

Comment: The DelVar is not necessary, because it is only possible to skip the Input command with the ON button, which terminates the program.
Comment: Thank you! I also added a line at the beginning "DelVar Str0" (I used Str0 instead of Str1), so that a previous value for Str0 wouldn't be carried over--just in case.
Answer: You're trying to use variable names as strings.
:If A=IPPI

This isn't comparing a string to "IPPI", it's comparing a numeric variable A to the numeric value I*P*P*I, which I'm guessing results in 0 in your case.
Similarly, when you take input, if you enter IPPI, it's going to multiply those variables and assign A to be that product.
You'll need to use a string variable and quotes.
Comment: Thank you, that seems to be my problem. :) I've looked up using a string variable, and all I can seem to find is some thing on Equ->String that I can't understand, so if you could please give me an example, I'd really appreciate it! I just need to see once what I need to do.
Comment: @FredBarclay if you use STR1 instead of A, you don't need to put in quotes
Answer: The main problem with your program is that you aware assigning a string to a variable that only supports numbers. That leaves the new value of the variable the Boolean value of the string, True, which in the case of TI-BASIC is the value, 1. To fix this you need to assign it to a variable which supports characters in a string, in this case you can use STR1.
Comment: This is wrong. Strings are not converted to booleans. If you enter `IPPI` at the `Input A` prompt, the numeric variable A will contain I*P*P*I, as MattPutnam's answer states.
Comment: @lirtosiast yes, but even if he fixes it and does it as MattPutnam's answer stated, there would still be this issue


Output the first paragraph in a Wordpress post

Question: I want to put just the first paragraph of my posts on my index.php
in my functions.php I have
<?php

{
global $post;

$output = get_the_content();

$wanted_number_of_paragraph = 1;

$tmp = explode ('
', $output);
for ($i = 0; $i < $wanted_number_of_paragraph; ++$i) {
if (isset($tmp[$i]) && $tmp[$i] != '') {
   $tmp_to_add[$i] = $tmp[$i];
}
}
$output = implode('
', $tmp_to_add) . '
';

echo $output;

}
?>

then in my index.php
<?php wpden_excerpt(); ?>

However it posts the entire post (including pictures) and not just the first paragraph.
Comment: possible duplicate of https://wordpress.stackexchange.com/questions/127159/grab-the-first-paragraph-of-each-post
Comment: Is '' appended to the contents of index.php or replacing the contents of index.php?
Comment: Agree with @charan kumar
Comment: That is where I looked first to see how others have done it. But couldn't get it to work
Answer: I wold recommend you to use the Wordpress get_extended() function for this purpose. In your post you split the content with the "more" tag, after inside your template you can have something like:
global $post;
// gets the content of your post as an array of 2 parts
$content_parts = get_extended( $post->post_content );

and after this you can echo the part before the "more" tag like:
<?=$content_parts['main'];?>

the part after the "more" tag you can echo like:
<?=$content_parts['extended'];?>

Also, if you chose this option I'll recommend you to check the wpautop() , since you may need to wrap these 2 parts with it, for example:
<?=wpautop($content_parts['extended']);?>


Using Views to List a Member's Organic Groups (7.x-2.3)

Question: I am migrating a site from using OG 7.x-1.4 to OG 7.x-2.3. The migration seemed to go fine, but it broke the view that shows the current users group (i.e. groups the user is a member of). In the original view for 1.4, it had a contextual filter:

(OG membership from OG group) We pass to the "Entity ID" the User ID.

And the following relationships:

OG group: OG group from Node
(node being the OG group) OG group: OG membership from OG group

However, the new Organic Groups 7.x-2.3 now uses the OGMembership data model and I cannot figure out how to recreate this view using OGMembership, as I am not clear exactly how it works and I cannot seem to find any in-depth documentation for this kind of thing.
Answer: This is how to get the OG membership ID:s to start with.
Add new view.
Show -> OG membership (important!)
Then in some display add a contextual filter -> OG membership: Entity id.
Provide default value -> Type -> User ID from logged in user.
Override title: %1's groups.
Specify validation criteria -> User.
Now you have the list of ID:s.
Next to get the actual titles of the groups (as the base table is OG membership, not node), Add a relationship -> Group Node from OG membership.
Add a field -> Content: Title.
Relationship -> Group node from OG membership.
Now you have the titles too. Add some filters and sort criterias to taste.
Comment: Thanks so much for the great answer. That worked like a charm! I did not realize you could create a view of OG memberships. That was an eye opener. If it's permissible to ask a follow up question, can you tell me how I'd show the number of members in each group?
Comment: No, sorry. Here is the discussion everybody is linking to: http://drupal.org/node/1101102
Comment: Don't forget to accept the answer. It helps you, me, and the community. http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work
Comment: Thanks for pointing that out. I didn't understand. I tried to upvote but didn't have a high enough reputation, and I didn't see the checkmark icon.
Answer: Here is the export for a view that does the job as described by Kari Kääriäinen above.
<code>$view = new view();
$view->name = 'my_groups';
$view->description = 'List of Groups I\'m Subscribed To';
$view->tag = 'default';
$view->base_table = 'og_membership';
$view->human_name = 'My Groups';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'My Groups';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'role';
$handler->display->display_options['access']['role'] = array(
  2 => '2',
);
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '200';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['pager']['options']['id'] = '0';
$handler->display->display_options['pager']['options']['quantity'] = '9';
$handler->display->display_options['style_plugin'] = 'table';
/* Field: OG membership: Delete link */
$handler->display->display_options['fields']['delete_membership']['id'] = 'delete_membership';
$handler->display->display_options['fields']['delete_membership']['table'] = 'og_membership';
$handler->display->display_options['fields']['delete_membership']['field'] = 'delete_membership';
$handler->display->display_options['fields']['delete_membership']['label'] = 'Remove';
/* Field: OG membership: Edit link */
$handler->display->display_options['fields']['edit_membership']['id'] = 'edit_membership';
$handler->display->display_options['fields']['edit_membership']['table'] = 'og_membership';
$handler->display->display_options['fields']['edit_membership']['field'] = 'edit_membership';
$handler->display->display_options['fields']['edit_membership']['label'] = 'Edit';
/* Field: OG membership: Rendered OG membership */
$handler->display->display_options['fields']['rendered_entity']['id'] = 'rendered_entity';
$handler->display->display_options['fields']['rendered_entity']['table'] = 'views_entity_og_membership';
$handler->display->display_options['fields']['rendered_entity']['field'] = 'rendered_entity';
$handler->display->display_options['fields']['rendered_entity']['link_to_entity'] = 1;
$handler->display->display_options['fields']['rendered_entity']['bypass_access'] = 0;
/* Contextual filter: OG membership: Entity id */
$handler->display->display_options['arguments']['etid']['id'] = 'etid';
$handler->display->display_options['arguments']['etid']['table'] = 'og_membership';
$handler->display->display_options['arguments']['etid']['field'] = 'etid';
$handler->display->display_options['arguments']['etid']['default_action'] = 'default';
$handler->display->display_options['arguments']['etid']['default_argument_type'] = 'current_user';
$handler->display->display_options['arguments']['etid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['etid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['etid']['summary_options']['items_per_page'] = '25';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'my_groups';
$handler->display->display_options['menu']['type'] = 'tab';
$handler->display->display_options['menu']['title'] = 'My Groups';
$handler->display->display_options['menu']['description'] = 'Groups that I am subscribed to';
$handler->display->display_options['menu']['weight'] = '0';
$handler->display->display_options['menu']['context'] = 0;
$handler->display->display_options['menu']['context_only_inline'] = 0;
$translatables['my_groups'] = array(
  t('Master'),
  t('My Groups'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort by'),
  t('Asc'),
  t('Desc'),
  t('Items per page'),
  t('- All -'),
  t('Offset'),
  t('« first'),
  t('‹ previous'),
  t('next ›'),
  t('last »'),
  t('Remove'),
  t('Edit'),
  t('Rendered OG membership'),
  t('All'),
  t('Page'),
);

$view = new view();
$view->name = 'my_groups';
$view->description = 'List of Groups I\'m Subscribed To';
$view->tag = 'default';
$view->base_table = 'og_membership';
$view->human_name = 'My Groups';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'My Groups';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'role';
$handler->display->display_options['access']['role'] = array(
  2 => '2',
);
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '200';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['pager']['options']['id'] = '0';
$handler->display->display_options['pager']['options']['quantity'] = '9';
$handler->display->display_options['style_plugin'] = 'table';
/* Field: OG membership: Delete link */
$handler->display->display_options['fields']['delete_membership']['id'] = 'delete_membership';
$handler->display->display_options['fields']['delete_membership']['table'] = 'og_membership';
$handler->display->display_options['fields']['delete_membership']['field'] = 'delete_membership';
$handler->display->display_options['fields']['delete_membership']['label'] = 'Remove';
/* Field: OG membership: Edit link */
$handler->display->display_options['fields']['edit_membership']['id'] = 'edit_membership';
$handler->display->display_options['fields']['edit_membership']['table'] = 'og_membership';
$handler->display->display_options['fields']['edit_membership']['field'] = 'edit_membership';
$handler->display->display_options['fields']['edit_membership']['label'] = 'Edit';
/* Field: OG membership: Rendered OG membership */
$handler->display->display_options['fields']['rendered_entity']['id'] = 'rendered_entity';
$handler->display->display_options['fields']['rendered_entity']['table'] = 'views_entity_og_membership';
$handler->display->display_options['fields']['rendered_entity']['field'] = 'rendered_entity';
$handler->display->display_options['fields']['rendered_entity']['link_to_entity'] = 1;
$handler->display->display_options['fields']['rendered_entity']['bypass_access'] = 0;
/* Contextual filter: OG membership: Entity id */
$handler->display->display_options['arguments']['etid']['id'] = 'etid';
$handler->display->display_options['arguments']['etid']['table'] = 'og_membership';
$handler->display->display_options['arguments']['etid']['field'] = 'etid';
$handler->display->display_options['arguments']['etid']['default_action'] = 'default';
$handler->display->display_options['arguments']['etid']['default_argument_type'] = 'current_user';
$handler->display->display_options['arguments']['etid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['etid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['etid']['summary_options']['items_per_page'] = '25';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'my_groups';
$handler->display->display_options['menu']['type'] = 'tab';
$handler->display->display_options['menu']['title'] = 'My Groups';
$handler->display->display_options['menu']['description'] = 'Groups that I am subscribed to';
$handler->display->display_options['menu']['weight'] = '0';
$handler->display->display_options['menu']['context'] = 0;
$handler->display->display_options['menu']['context_only_inline'] = 0;
$translatables['my_groups'] = array(
  t('Master'),
  t('My Groups'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort by'),
  t('Asc'),
  t('Desc'),
  t('Items per page'),
  t('- All -'),
  t('Offset'),
  t('« first'),
  t('‹ previous'),
  t('next ›'),
  t('last »'),
  t('Remove'),
  t('Edit'),
  t('Rendered OG membership'),
  t('All'),
  t('Page'),
);
</code>


Generators of the group of integers exercise

Question: Let $a,b \in \mathbb Z$.
(1) Prove that $\{a,b\}$ is a system of generators of $\mathbb Z$ if and only if $(a,b)=1$, where $(a,b)$ is the greatest common divisor between $a$ and $b$.
(2)Show that $\mathbb Z$ has a system of minimal generators of $n$ elements for all $n$ in $\mathbb N$.
I suppose that saying $\{a,b\}$ is a system of generators of $\mathbb Z$ is equivalent to $<a> \cup <b>=\mathbb Z$. I am not so sure how to solve this exercise.
Suppose that the group is generated by those two elements, then any $z \in \mathbb Z$ can be written as $$z=as+bt, \space s,t \in \mathbb Z$$
How can I deduce from here that $(a,b)=1$?
I think I could do the other implication:
Suppose $(a,b)=1$, then $1$ can be written as a linear combination $$aq+br=1, \space, q,r \in \mathbb Z$$ Take an arbitrary integer $z$, then $$z=z(aq+br)=a(zq)+b(zr),$$ this means that $\{a,b\}$ generates $\mathbb Z$.
I would appreciate some help to prove the first implication and to show (2) I don't get the definition of "minimal generators system". Is my proof of the other implication correct? Thanks in advance.
Comment: $\{a,b\}$ is a system of generators iff $=\mathbb Z$. Here $=\{na+mb\mid n,m\in\mathbb Z\}$. **Not** $\cup$ as you suppose.
Comment: For 1. think to Bezout's theorem.
Comment: If $(a,b) = d>1$, then $as+bt$ is divisible by $d$, so you cannot express all integers in this form.
Answer: Hint 1: There exist $s, t$ such that $as+bt=\gcd(a, b)^{\dagger}$...so, what do you want the $\gcd$ to be?
You say you do not understand what a "minimal generating system" is. This is simply a set of elements $\{g_1, \ldots, g_n\}$ such that a proper subset will not generate your group.
Hint 2: Cycle primes. For example, $\{p_1p_2, p_2p_3, p_3p_1\}$ works for $n=3$. (Secondary hint: you will need to increase the lengths of your products as $n$ increases...)
$^{\dagger}$ This has a name: Bézout's identity. Although I have only ever heard people call it by name on the internet...
Comment: Further hint: the following works for $n=4$, where the $p_i$ are distinct primes.$$\{p_1p_2p_3, p_2p_3p_4, p_3p_4p_1, p_4p_1p_2\}$$
Comment: @user what is the gcd of the whole set?
Comment: @user It can, but it is not obvious! You may want to try and prove it properly yourself, by inducting on the number of integers.
Comment: I could show that if $\{a,b\}$ is a system of generators, then $(a,b)=1$, for this I've used the fact that $am+bn=1$ for some $m,n$ integers. I am still pretty lost with (2), I've understood the definition of minimal generating system.
Comment: Ok, I got your idea, I choose $n$ distinct primes, and I define $\{\{a_1,...,a_j\} : a_j=\prod_{1\leq i \leq n, i \neq j}p_i\}$. I am not so sure how to show it generates $\mathbb Z$ and that it is minimal generating system.
Comment: $1$, now I got it, I didn't know Bezout could be extended to more than two integers.


Where can I find out who is in a test flight group

Question: I am on the app store connect page, looks like I can click to add a build to test amoungst beta tester.
How can I see how is in this group called, "outside Beta Testers"?
I've looked everywhere
Answer: It looks like one of two things:

You don't have sufficient permission.
Your screen is small (or your zoom is large) and the responsive design has hidden the list of testers.

If you click on the "v" next to iOS Builds you should get a drop down and if you scroll down, there should be a heading External Testing with the lists there.  Then you can click on the list and see who is in it.
On my desktop, this isn't hidden, and everything that shows on the drop down shows to the left of the list of builds.
It's possible you don't have permission, but I don't think that's the case.  You need Admin, Account Holder or App Manager role - I think you've probably got App Manager in order to get to that screen.


value not ignored "(argaddr(0, &fva)"

Question: I am looking to add xv6 page table functionality. However, for some reason I am getting errors with argaddr and argint. Why?
Lab reference: xv6 page table
int sys_pgaccess(void){
  uint64 fva;
  int pnum;
  uint64 abits;
  int res = 0;
  pte_t* pte_addr;
  pte_t pte;

  if(argaddr(0, &fva) < 0) {
    return -1;
  }
  if(argint(1, &pnum) < 0) {
    return -1;
  }

kernel/sysproc.c: In function 'sys_pgaccess':
kernel/sysproc.c:105:6: error: void value not ignored as it ought to be
  105 |   if(argaddr(0, &fva) < 0) {
      |      ^~~~~~~~~~~~~~~~
kernel/sysproc.c:108:6: error: void value not ignored as it ought to be
  108 |   if(argint(1, &pnum) < 0) {
      |      ^~~~~~~~~~~~~~~~

I am a beginner so I looked at the code for argaddr, etc., but could not understand it.
Comment: Where did you get the idea that these functions return a value `<0` in case of error? Did you find any manual for these functions indicating that?
Answer: The compiler is telling you that argaddr and argint are void functions, and do not return a value.
You cannot compare nothing with an integer.
Looking at kernel/syscall.c from mit-pdos/xv6-riscv, we can see the RISC-V function definitions:
// Fetch the nth 32-bit system call argument.
void
argint(int n, int *ip)
{
  *ip = argraw(n);
}

// Retrieve an argument as a pointer.
// Doesn't check for legality, since
// copyin/copyout will do that.
void
argaddr(int n, uint64 *ip)
{
  *ip = argraw(n);
}

The contents of the lab linked deal with RISC-V.
It appears you should simply remove the conditionals:
int sys_pgaccess(void)
{
  uint64 fva;
  int pnum;
  /* ... */

  argaddr(0, &fva);
  argint(1, &pnum);
  /* ... */
}

For completeness, the x86 versions of these functions do return values, so you may have read the wrong documentation.
syscall.c from the no longer maintained mit-pdos/xv6-public contains the x86 definitions:
// Fetch the int at addr from the current process.
int
fetchint(uint addr, int *ip)
{
  struct proc *curproc = myproc();

  if(addr >= curproc->sz || addr+4 > curproc->sz)
    return -1;
  *ip = *(int*)(addr);
  return 0;
}

// Fetch the nth 32-bit system call argument.
int
argint(int n, int *ip)
{
  return fetchint((myproc()->tf->esp) + 4 + 4*n, ip);
}

// Fetch the nth word-sized system call argument as a pointer
// to a block of memory of size bytes.  Check that the pointer
// lies within the process address space.
int
argptr(int n, char **pp, int size)
{
  int i;
  struct proc *curproc = myproc();

  if(argint(n, &i) < 0)
    return -1;
  if(size < 0 || (uint)i >= curproc->sz || (uint)i+size > curproc->sz)
    return -1;
  *pp = (char*)i;
  return 0;
}

value not ignored "(argaddr(0, &fva)"


Jquery how to read which li element is clicked

Question: Hello i am trying to make my custom made combobox with using jquery and ul li menus. So when mouse clicked to the li element i have to read its value and set its parent to the clicked element value etc. Basic selecting method.
So how can i read the clicked li element value and set that value to the parent of it. Here my structure.

Home

All Abilities

Fire Master

Great Attack

Manyak Ability

Super Ability

Deneme Ability

Here the jquery code
        $(document).ready(function () {

        $("ul.subnav").parent().append(""); //Only shows drop down trigger when js is enabled - Adds empty span tag after ul.subnav

        $("ul.topnav li").click(function () { //When trigger is clicked...

            //Following events are applied to the subnav itself (moving subnav up and down)
            $(this).find("ul.subnav").slideDown('fast').show(); //Drop down the subnav on click

            $(this).hover(function () {
            }, function () {
                $(this).find("ul.subnav").slideUp('slow'); //When the mouse hovers out of the subnav, move it back up
            });

            //Following events are applied to the trigger (Hover events for the trigger)
        }).hover(function () {
            $(this).addClass("subhover"); //On hover over, add class "subhover"
        }, function () {    //On Hover Out
            $(this).removeClass("subhover"); //On hover out, remove class "subhover"
        });

        $("ul.topnav li ul.subnav li a").click(function () { //When trigger is clicked...

            //****************** none of these working*************************//
            var srVal1 = $(this).find("ul.subnav").val();
            var srVal2 = $(this).find("subnav").val();
            var srVal3 = $(this).find("li a").val();
            var srVal4 = $(this).find("a").val();
            var srVal5 = $(this).parent("li").val();
            var srVal5 = $(this).find("li").val();
            var srVal6 = $(this).val();
            var srVal7 = $(this).parent("li a").val();

        });
    });

Answer: You want $(this).text(), .val() is for form elements.
Here's a jsfiddle for ya: http://jsfiddle.net/JbRqM/1/
Notice I used .parents('li') to select the parent
 tag of the nested ul:
$(this).parents('li').html($(this).text());

Comment: how exactly use ? i tried but not working     var srVal9 = $(this).text;
Comment: I just edited my answer, you can view a working example at the jsfiddle link and the important line is: `$(this).parents('li').html($(this).text());
`
Comment: not working edited version too check link : http://img835.imageshack.us/img835/1572/notworkingd.png
Answer: $('ul.topnav li ul.subnav li a').click(function(){

    $(this).parents('ul.subnav').siblings('a').html($(this).text());

});

Comment: Hmm, weird cause it worked on my implementation using your own markup. This does the replacing part by the way.

`$(this)` in this context would refer to the `a` clicked. All this does is select the `ul.subnav` that holds it, then select the nearest `a` ('All Abilities') and then replace its content with `$(this).text()`. Pretty straightforward.
Comment: i found the problem. if i make the script like this it works :   $("ul.topnav li ul.subnav li").click(function () { //When trigger i
Answer: use $(this).parents("li") instead of $(this).parent("li")
.parent("li") only looks in the immediate parent to the element, which is

.parents("li") looks through all of the parent collections. More specifically, use .parents("li:first")
Comment: how exactly use. i tried this way but not worked        var srVal11 = $(this).parents("li").val();
Comment: Oh, you just want the clicked one? try `alert($(this).text());`
Comment: not working unfortunately :( here the image : http://img807.imageshack.us/img807/1813/notworking2.png


Prove that W is $T^{-k}$ invariant for every $k$

Question: Show that if $T\colon V\to V$ is an invertible linear transformation, and $W$ is a $T$-invariant subspace, then $W$ is also a $T^{-k}$ invariant subspace for every natural $k$.
My thought is to do this with induction but I am struggling with the process. Help would be appreciated.
Comment: A stronger approach is to show that the composition of two operators having $W$ as an invariant subspace has $W$ as an invariant subspace, and that the inverse of an invertible operator having $W$ as an invariant subspace has $W$ as an invariant subspace.
Answer: $\def\inv{^{-1}}$
It's true, as Kyle pointed out, that finite dimensionality is essential, but only $W$ needs to be finite dimensional.  Assume $W$ finite dimensional. Then $T_{|W} : W \to W$ is linear and injective, hence surjective.  Thus for $w \in W$, there exists $w'\in W$ such that $T(w') = w$.  Applying $T\inv$ to both sides of this equation gives $w' = T\inv(w)$.  This shows $W$ is invariant under $T\inv$.
Exercise: Construct an example with $V$ infinite dimensional.
Answer: If $T,T':V\to V$ are linear transformations with $W$ an invariant subpace, then $T(T'(W))\subset T(W)\subset W$, so $T\circ T'$ has $W$ as an invariant subspace.  If you are not comfortable working with image sets, you can take $w\in W$, and reason that $T'(w)\in W$, so $T(T'(w))\in W$.
If $T:V\to V$ is an invertible linear transformation with $W$ an invariant subspace of a finite dimensional vector space $V$.  Decompose $V$ as $W\oplus W'$, by which I mean choose a basis of $W$ and extend the basis to a basis of $V$, the extra vectors are the basis of $W'$.  With respect to this basis, the block matrix of $T$ looks like
$$\begin{pmatrix}A&B\\0&C\end{pmatrix}$$ where $A,B,C$ are matrices, with $A,B$ square and invertible.  That $0$ matrix represents the fact that $W$ is an invariant subspace.  The inverse is
$$\begin{pmatrix}A^{-1}&-A^{-1}BC^{-1}\\0&C^{-1}\end{pmatrix}$$
which means $W$ is still an invariant subspace for $T^{-1}$.
I'll leave the induction for $T^{-k}=(T\circ\dots\circ T)^{-1}$ to you.

Finite-dimensionality is essential.  Consider $V=\mathbb{R}^{\mathbb{Z}}$, the vector space of infinite sequences of real numbers going in both directions.  Let $T:V\to V$ be the right-shift operator: $T(v)_i=v_{i-1}$.  The subspace $W$ of all sequences $v$ with $v_i=0$ for all $i\leq 0$ is invariant under $T$.  But, if $w$ is the vector with $w_1=1$ and $w_i=0$ for all $i\neq 1$, $w\in W$ but $T^{-1}(w)\not\in W$.