Exchange 2016 Co-Existence - OWA Won't login when behind a load balancer

Question: I'm currently in the middle of developing a lab environment to migrate our mixed Exchange 2010 and 2013 environment to Exchange 2016.
I've been running 1x 2013 and 2x 2016 in co-existence in the lab for a few weeks now, and it's worked well - I've done testing for RPC, OWA, ActiveSync and EWS. Everything seems to work fine.
This week I've tried to finalise my deployment by introducing a load balancer in front, with a plan to provide round-robin LB between my 2013 and 2016 CAS nodes. From all I've researched 2013 and 2016 CAS are totally compatible for the CAS role in that they will gladly proxy between each other. And to be sure my manual testing via each CAS (without a load balancer) seems to show this.
But now that I've introduced HA Proxy in front, OWA seems to not want to work properly.
Symptoms
Here's some symptoms:

When I log in via 2016 OWA to a 2013 mailbox, it does login correctly, redirects me, and starts loading the inbox. But after a second or two of loading the inbox, I get redirected back to the OWA login page as if I'd never logged in.
I can repeat this multiple times and it seems to do the same thing, as long as I login via a 2016 CAS.
Sometimes when I login via 2016 it will just hang with "Still working on it". This is far less frequent then just logging me back out, though.
Some times it redirects back to the login page so quickly I can't even tell I logged in at all, and has no error message. It's just a flash then back to the login page.
I've tried from reasonably up to date versions of both Chrome and Firefox, on Mac and Windows 8.1. So it's not an end-device issue.
If I login to a 2013 mailbox via OWA on the 2013 CAS, even through the load balancer, it seems to login correctly first time.
I've got one IP on the load balancer which then proxies traffic to each CAS node in a round-robin fashion. This is what I use to test my LB. I've got other IPs pointing directly to individual CAS nodes.
If I login directly to a 2016 CAS node to a 2013 mailbox, this works fine. It's one one I login to a 2016 CAS via the load balancer that the issue appears.
Interestingly, I just noticed the exact same issues occur even if logging into a 2016 mailbox. So as long as I login to a 2016 CAS, it logs back out.
Once I login successfully via the 2013 CAS, I can refresh the page several times and the session will still stay open. To me this indicates that proxying must be working OK to some extent once the session is established, because my LB is round-robin so the traffic should be getting re-distributed over various CAS nodes each time I refresh the OWA page.

It seems pretty clear to me that there are others experiencing similar issues with Exchange 2010 - 2016 when behind a load balancer. Unfortunately this is our first time using a load balancer as we're moving from a single CAS to 3 with this upgrade to Exchange 2016.
I've found a fair few posts with similar symptoms:

https://devcentral.f5.com/questions/microsoft-exchange-2013-iapp-cant-login-to-owa-or-ecp-if-more-than-one-server-is-active-in-pool
http://www.360ict.nl/blog/owa-does-not-work-after-load-balancing-exchange-2016-while-using-kemp-loadbalancers/
https://devcentral.f5.com/questions/exchange-2013-session-affinity-once-again

What I've Tried

I've confirmed that all our SSL frontend (third-party CA) certificates match with the same thumprint and serial across all CAS nodes. I've read that this can impact things. I am using a production certificate to properly test my lab.
The backend certs are left as the default Microsoft Exchange certificate, and from what I've read this is fine. I actually tried using our wildcard cert on the backend anyway, and it seemed to break everything.
I've verified that when accessing the 2016 CAS without a load balancer, things seem to work fine. Based on this, I thinking if I was to enable full session persistence on the load balancer so a particular user only deals with one CAS, it would fix the problem. But then, I shouldn't have to do that. And it makes me worry there's a deeper error to solve.
I've enabled IIS Failed Request tracing. I've found some reports of 500 errors for powershell requests. But they seem related to failed health monitoring requests, and don't necessarily seem to line up time-wise with my OWA tests logging me back out.
I've done some basic checking via Wireshark to look for anything weird. I've noticed that a single OWA page load is definitely distributed at least over multiple CAS nodes. Sometimes both 2016 nodes, sometimes a 2016 and a 2013 node.
I did notice in my capture (on the load balancer) that during a single failed login attempt, I kept getting repeated 440 Login Timeout responses from the CAS nodes. In this case I got multiple of these, at least one from each CAS node.
There's so many individual HTTP requests after the initial login request, it's hard to pin-point where the problem is, but it seems like a bunch of OWA service.svc requests start to be sent by the browser, and at some point they all being to return the same 440 Login Timeout error as a response from the CAS node. Then eventually we are redirected back to the login page.
I haven't yet found anything through my research what is actually causing the 440 login timeouts, or if it's expected behaviour etc...
I've re-checked all my Virtual Directory settings against our production setup. They look OK.

EDIT: 2017-03-04

I have tried multiple different VirtualDirectory internal and external URL combinations. exchange.isp.com.au is the internal AD Domain (this matches the live setup). The external URL for the lab is exchlab.isp.com.au.
I have tried:

exchlab.isp.com.au for both internal and external.
exchange.isp.com.au for both internal and external.
I stuck with exchlab for external and exchange for internal. None of these combinations made a difference.

Since then, I have also added Cookie-based session persistence in HA Proxy, and it seems to have made a difference. I have only done persistence for OWA and ECP, but the rest are not persistent. Things to note:

I am no longer logged back out of OWA repeatedly. It's become much more stable.
It still happens the first time I log out of a mailbox (e.g. 2013) and login to a mailbox of a different version. (e.g. 2016). After I get logged out the first time, though, I can now log back in successfully.
If I log out of a mailbox and back in too fast (within 10 seconds) then I am often kicked back out instantly.

I also decided to proceed with my testing of HA Proxy for services besides OWA. And I can confirm:

Outlook Anywhere load balances over all 3 CAS nodes and works fine.
EWS also load balances over all 3 and works fine.
Active Sync seems to only want to go over the 2x 2016 CASes but also load balances fine.

Things I need to Try

Reset all my virtual directories
Resync the IIS IUSR accounts: https://technet.microsoft.com/en-us/library/dd789741(v=exchg.80).aspx
Verify IUSR Authorisation level.

I haven't actually done these yet as I feel like there's an actual configuration issue. Also since everything seems to work without the load balancer, I can't see this helping.
More Environment Info
Some more details on the lab environment I'm testing in.

Our load balancer config is taken from here: https://www.haproxy.com/doc/aloha/7.0/deployment_guides/microsoft_exchange_2013.html#aloha-configuration -- we're using the "SSL Offloading - HTTP Reverse Proxy" config (advanced version).
We are doing SSL Offloading based on this guide: https://serversforhackers.com/using-ssl-certificates-with-haproxy and this guide: https://jaapwesselius.com/2014/02/28/exchange-2013-sp1-ssl-offloading/
Our Exchange 2013 box is running SP1 \w CU11
Our Exchange 2016 boxes are running CU2. I'm intentionally avoiding upgrading to CU4 as I want to test and document a graceful upgrade procedure with the load balancers.
We are running 2x additional VMs as dedicated ADs. No AD on the Exchange nodes.
All Windows systems (including AD) are running Windows 2012 R2.
Our router is a Linux box doing NAT. The Load balancer is in the same /24 subnet as the Exchange servers and AD boxes.
LB HTTP front end is .7 and Exchange boxes are .1, .2 and .3
We are also running a simple HTTP redirect on dedicated IPs of each Exchange box on .4, .5 and .6. Though I'm planning to shift this simple redirect to the load balancer as it can easily do HTTP redirects.

Relevant bits of my load balancer config:
<code>    # This is the L7 HTTPS Front End
    # ------------------------------
    # We redirect to different backends depending on the URI
    # Each backend has its own separate health checks. So that each service can fail on an Exchange CAS node without affecting the other services.
    frontend ft_ISP_EXCHANGE_https
      bind 172.16.10.7:80 name INT_http
      bind 172.16.10.7:443 name INT_https ssl crt wildcard.isp.com.au.pem # Specify SSL Cert for offloading.
      mode http
      option http-keep-alive
      option prefer-last-server
      no option httpclose
      no option http-server-close
      no option forceclose
      no option http-tunnel
      timeout client 600s
      log global
      capture request header Host len 32
      capture request header User-Agent len 64
      capture response header Content-Length len 10
      # log-format directive must be written on a single line
      # it is splitted for documentation convnience
      log-format %ci:%cp\ [%t]\ %ft\ %b/%s\ %Tq/%Tw/%Tc/%Tr/%Tt\ %ST\ %B\ %CC\ %CS\ %tsc\ %ac/%fc/%bc/%sc/%rc\ %sq/%bq\ %hr\ %hs\ {%sslv/%sslc/%[ssl_fc_sni]/%[ssl_fc_session_id]}\"%[capture.req.method]\ %[capture.req.hdr(0)]%[capture.req.uri]\ HTTP/1.1
      maxconn 1000
      acl ssl_connection ssl_fc # Set ACL ssl_connection if ssl_fc returns TRUE

      # Route request to a different backend depending on the path:
      # http://serverfault.com/questions/127491/haproxy-forward-to-a-different-web-server-based-on-uri
      acl host_mail hdr(Host) -i exchange.isp.com.au
      acl path_slash path /
      acl path_autodiscover path_beg -i /Autodiscover/Autodiscover.xml
      acl path_activesync path_beg -i /Microsoft-Server-ActiveSync
      acl path_ews path_beg -i /ews/
      acl path_owa path_beg -i /owa/
      acl path_oa path_beg -i /rpc/rpcproxy.dll
      acl path_ecp path_beg -i /ecp/
      acl path_oab path_beg -i /oab/
      acl path_mapi path_beg -i /mapi/
      acl path_check path_end -i HealthCheck.htm
      # HTTP deny rules
      http-request deny if path_check
      # HTTP redirect rules
      http-request redirect scheme https code 302 unless ssl_connection # Force SSL
      http-request redirect location /owa/ code 302 if path_slash host_mail # Redirect / to /owa
      # HTTP routing rules -- This is where we decide where to send the request
      # Based on HTTP path.
      use_backend bk_ISP_EXCHANGE_https_autodiscover if path_autodiscover
      use_backend bk_ISP_EXCHANGE_https_ews if path_ews
      # other services go here
      default_backend bk_ISP_EXCHANGE_https_default

      # Backends
    # --------
    # Now we define each backend individually
    # Most of these backends will contain all the same Exchange CAS nodes, pointing to the same IPs
    # The reason we define each backend individually is because it allows us to do separate Health Checks
    # for each individual service running on each CAS node.

    # The failure of one service on a CAS node does not exclude that CAS node from participating in other
    # types of requests. This gives us better overall high-availability design.

    # HTTPS OWA
    # I have added additional comments on this definition, but the same applies to all Exchange HTTPS backends.
    backend bk_ISP_EXCHANGE_https_owa
      balance roundrobin # Use round-robin load balancing for requests
      option http-keep-alive # Enable HTTP Keepalives for session re-use and lowest latency for requests.
      option prefer-last-server # Prefer to keep related connections for a session on the same server.
      # This is not the same as persistence, and is mainly to try and take advantage of HTTP Keepalives.
      # See here for an example of why this is needed: http://stackoverflow.com/questions/35162527/haproxy-keep-alive-not-working-as-expected

      no option httpclose # Disable all options that are counter to keepalives
      no option http-server-close
      no option forceclose
      no option http-tunnel
      mode http # Operate in L7 HTTP Mode (vs TCP mode etc)
      log global
      option httplog
      option forwardfor # Enable insertion of the X_FORWARDED_FOR HTTP Header
      option httpchk GET /owa/HealthCheck.htm # Use L7 HTTP Health Check. This is recommended by Microsoft.
      http-check expect string 200\ OK
      default-server inter 3s rise 2 fall 3
      timeout server 60s
      # Define CAS Nodes for this service. We're using SSL offloading to allow L7 HTTP Checks
      # We've avoided SSL Bridging as that would halve our LB's throughput.
      server ISP_exch16_syd_01 172.16.10.2:80 maxconn 1000 weight 10 check
      server ISP_exch16_syd_02 172.16.10.3:80 maxconn 1000 weight 10 check
      server ISP_exch13 172.16.10.1:80 maxconn 1000 weight 10 check
</code>
Comment: I more see a setup like CAS HA than using a third party load balancer. (http://www.msexchange.org/articles-tutorials/exchange-2016-articles/high-availability-recovery/load-balancing-exchange-server-2016-part1.html or that one for 2013, but better wrote; http://practical365.com/exchange-server/exchange-2013-client-access-server-high-availability/) (+1 for the well wrote question btw)
Comment: @yagmoth555 Thanks for the upvote. Definitively considering removing the load balancer completely, and it's becoming more and more likely I will need to. But it would make maintenance so much easier, so I'd rather figure out how to keep it in place.
Comment: We are using a hardware load balancer and used the following [howto here to migrate from Exchange 2010 to 2016](http://www.admin-enclave.com/en/articles/exchange/206-migrate-from-exchange-2010-to-exchange-2016.html) for the migration. This linked to an OWA issue mentioned [here](http://www.admin-enclave.com/en/articles/exchange/254-resolved-exchange-2010-2016-co-existence-issues-with-rpc.html). So maybe you can check that one to be sure you didn´t have a similar issue. Another point here is to use sticky sessions on your loadbalancer. Without a trace it might be a jump between the CAS server.
Answer: I ended up reasonably working around this issue. Several posts had mentioned for similar issues that adding Cookie-based persistence on their load balancer had solved the issue for them.
I had resisted this "because I shouldn't have to", all the technical articles from Microsoft say this is no longer needed, and indeed not recommended.
But I caved, and ended up adding persistence for both OWA and ECP. The result was the issue was not completely resolved, but it became barely noticeable. The only time I experience issues is if I log out of OWA on one mailbox, and then immediately log into another. Even then, it kicks you out once, but if you try to login again it works fine.
There is no ongoing issue after this. Furthermore, I noticed the remaining issue only when moving from a 2013 to 2016 mailbox.
This isn't something our end users are likely to do, and we're nearly finished moving all our mailboxes to 2016. So I'm considering this work around "good enough".
Since we're using HA Proxy, it wasn't a big deal to add some layer 7 cookie-based persistence in the config. In fact, it only took about 5 minutes all up to figure out:
<code># HTTPS Outlook Web App (OWA)
backend bk_EXCHANGE_https_owa
  cookie LB01 insert indirect nocache # <-- Added this
  balance roundrobin
  mode http

  ...

  # Added the "cookie <name>" at the end of each CAS node definition
  # These names must be unique to each node.
  server n1_exch16_syd_01 172.16.10.2:80 maxconn 1000 weight 10 check cookie EXCH16-SYD-01
  server n1_exch16_syd_02 172.16.10.3:80 maxconn 1000 weight 10 check cookie EXCH16-SYD-02
  server n1_exch13 172.16.10.1:80 maxconn 1000 weight 10 check cookie EXCH13-SYD
</code>


How to use external JSON API to create/update node's fields?

Question: I have a content type: siteinfo.
This content type has multiple fields: text, entity reference etc.
I want to use an external API to automatically fill some fields of the created node.
The API I want to use says that:

API returns consistent and well-structured data in XML & JSON
  format. Returned data contains parsed fields that can easily be
  used by your application. This is a RESTful based API.

And this is the API's output:
{
    "status": 1,
    "api_query": "siteinfo",
    "whois_record": {
        "domain_name": "example.com",
        "query_time": "2016-05-05 14:01:12",
        "create_date": "1995-08-14",
        "update_date": "2015-08-14",
        "expiry_date": "2016-08-13",
        "domain_registrar": {
            "iana_id": 376,
            "registrar_name": "RESERVED-INTERNET ASSIGNED NUMBERS AUTHORITY",
            "whois_server": "whois.iana.org",
            "referral_url": "http://res-dom.iana.org"
        },
        "name_servers": [
            "a.iana-servers.net",
            "b.iana-servers.net"
        ],
    },
}

How can I use this external API?
Answer: If there's no complicated authentication/request method for the service (e.g. a simple HTTP GET for http://service.example.com/api/siteinfo/1), then a combination of Feeds, Feeds extensible parsers, & Libraries with the JMESPath library installed works great here.
The Feeds module has an HTTP fetcher that can be used in conjunction with the JSON JMESPath parser that allows you to enter JMESPath queries for each field you want parse and insert/update into a node (e.g. in the parser settings you'd could put "@" (root) as the Context & "whois_record. domain_name" if you wanted to map that object's property to a node field).
In this solution, Feeds is handling the import/update bookkeeping while you're tasked with figuring out the correct queries to parse the data. If you go this path, it's very helpful to study JMESPath syntax while using the Feeds Import Preview module to test your imports before execution.
If you need your URL to vary for each import, you can wrap a programmatic invocation of a Feeds import into a function and call it for each imported URL in a drush eval or some other arbitrary location in your environment. For example:
//$url = Is your imported feed.
//$my_feed = Your imported feed machine name
//(i.e. the MY_FEED_MACHINE_NAME in http://example.com/import/MY_FEED_MACHINE_NAME)
function MYMODULE_import_feed($url, $my_feed) {
  $feeds_source = feeds_source($my_feed);
  $feeds_config = $feeds_source->getConfigFor($feeds_source->importer->fetcher);
  $feeds_config['source'] = $url;
  $feeds_source->setConfigFor($feeds_source->importer->fetcher, $feeds_config);
  $feeds_source->save();
  $feeds_source->startImport();
}

//Example execution
function MYMODULE_cron() {
  $import_titles = array('title_1', 'title_2');
  foreach ($import_titles as $title) {
    MYMODULE_import_feed("http://service.example.com/api/siteinfo/$title",'MY_FEED_MACHINE_NAME');
  }
}

Comment: @herci `create a generic Feed importer such as http://service.example.com/api/siteinfo/[NODE:TITLE]`I am afraid it is not possible, but you can make it possible by building a custom module and using [hook_node_presave()](https://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook_node_presave/7.x) Also, see [Updating a field programmatically, hook_node_update](http://drupal.stackexchange.com/questions/21023/updating-a-field-programmatically-hook-node-update) to auto fill out the feed url field. PS: Make sure you're usin [attach to content type](http://i.stack.imgur.com/uguQo.jpg)
Comment: @herci, I've updated the solution to your particular scenario while addressing generic URL importing.
Comment: Thanks for your detailed answer. Actually, I'm already using the **Simple** method (Feeds + Feeds Ex) but there were some problems for me: For each node I had to create a different Feed importer but I don't want to do this. What I want to do is to create a **generic** Feed importer such as `http://service.example.com/api/siteinfo/[NODE:TITLE]` and every time I create a node then the Feeds importer works automatically and the node's fields filled with the external data. **Is this possible?** // Sorry if I mis-explained the situation in the question. Thanks.
Answer: The no coding, clean hands, solution:
Feeds + Feeds JSONPath Parser
Coding, dirty hands, solution:
Using REST with Webservices you can Get and then Post/Patch. You would also need to comeup with a way to schedule your code so it runs every x amount of time (create a cron job); in contrast, Feeds already has that feature.
Comment: Thanks for your answer. I'm already using the "new" version of the Feeds JSONPath Parser. Please see my comment on other answer: http://drupal.stackexchange.com/questions/200217/how-to-use-external-json-api-to-create-update-nodes-fields#comment242276_200393


ratio of 3 numbers with a given a number

Question: My sister has a homework but I cannot understand the question correctly (do not know if it is correct as well)

3 numbers are in the ratio of "3:4:5". 28 is the middle number, what are the other 2 numbers

If I will solve the problem what I'm going to do is to create this equation
$\frac{3}{4} = \frac{x}{28}$
$x = 28 \times \frac{3}{4}$
$x = 21$
and 3rd number will be 35. Is this the correct solution?
Comment: Yes, correct. I imagine it as $$3k:4k:5k,$$ where $4k=28$, so $k=7$ etc.
Comment: What don't you check if $\frac{28}{35}=\frac{4}{5}$?
Comment: thanks, your method is more elegant
Comment: Another approach is to put them in proportional form... $3+4+5=12$ so $\displaystyle 3:4:5\equiv \frac{3}{12}:\frac{4}{12}:\frac{5}{12} \equiv \frac{1}{4}:\frac{1}{3}:\frac{5}{12}$ so $28\equiv \frac{1}{3}$ so the whole is $84$ and $\displaystyle\frac{1}{4}\equiv 21$ and $\displaystyle\frac{5}{12}\equiv 35$.
Answer: $28$ corresponds to the middle number in the ratio $3:4:5$
This implies that $1$ corresponds to $\frac{28}{4}$
The first number would therefore be $\frac{28}{4} \times 3$ , you can the same method to discover the third number.


template inheritance C++ iterator

Question:     template<class T, template<typename> class Seq>
    class SequenceWithApply : public Seq<T*>
    {
    public:
      // 0 arguments, any type of return value:
      template<class R>
      void apply(R (T::*f)()) {
        iterator it = begin();
        while(it != end()) {
          ((*it)->*f)();
          it++; }
      }

      // 1 argument, any type of return value:
      template<class R, class A>
      void apply(R(T::*f)(A), A a) {
        iterator it = begin();
        while(it != end()) {
          ((*it)->*f)(a);
          it++; }
      }

      // 2 arguments, any type of return value:
      template<class R, class A1, class A2>
      void apply(R(T::*f)(A1, A2),
                 A1 a1, A2 a2) {
        iterator it = begin();
        while(it != end()) {
          ((*it)->*f)(a1, a2);
          it++;
        }
      }
    }; ///:~

//: C03:applyGromit2.cpp
// Test applyMember.h
#include "Gromit.h"
#include "applyMember.h"
#include <vector>
#include <iostream>
using namespace std;
int main() {
  SequenceWithApply<Gromit, vector> dogs;
  for(int i = 0; i < 5; i++)
    dogs.push_back(new Gromit(i));
  dogs.apply(&Gromit::speak, 1);
  dogs.apply(&Gromit::eat, 2.0f);
  dogs.apply(&Gromit::sleep, 'z', 3.0);
  dogs.apply(&Gromit::sit);
} ///:~

I did not quite understand why compiler complain about iterator here. Since this snippet code implemente a class SequenceWithApply based on the template. In this case,
SequenceWithApply is actually a based class of vector. iterator should be visible in this base class. I really appreciate that someone can help me figure this out.
Comment: I know there's a dupe somewhere out there, but `typename Seq::iterator`.
Comment: It is not just `iterator`, but also `begin()` and `end()`. I have no clue why this does not work. :(
Comment: If I could find a dupe, it would explain that these names are looked up before the template is instantiated, which means that it can't know which concrete base type to look in.
Comment: @chris you should create a canonical duplicate :)
Comment: @chris So This post is a duplicated question? If it is, I will delete this post. :)
Comment: No, we don't delete duplicate questions, we just redirect them to the duplicate. But it's hard to find a good one in this case
Comment: Is there any reason not to simply write the apply function as a free template function? the standard already has `std::for_each(iter, iter, func)`.
Comment: @RichardHodges I am learning template programming right now. This is a snippet I copied from books.
Comment: @zhexuany ok, in that case I'll post an alternate way of handling this, just for the sake of interest
Answer: The compiler looks for iterator on first-phase lookup, which is before the template is ever instantiated. In order to know from which type the class derives, the template must be instantiated (so that Seq<T*> is an actual type). Thus, the compiler never finds iterator in the base class yet.
You can get around this in two easy ways:
A one-off:
typename Seq<T*>::iterator

A type alias in your derived class:
using iterator = typename Seq<T*>::iterator;

All of these unambiguously specify to which type iterator belongs, looked up in the second phase of lookup when Seq and T are known. More on typename.
You can do the same for your functions:
A one-off:
Seq<T*>::begin()
this->begin() // if inside a member function

A using declaration:
using Seq<T*>::begin;

Comment: Thanks for your post. We also need add `Seq::` to `begin()` and `end()`. In addition, there is another question about the code. On the first line of this snippet, we need add variadic templates. ie. `template class Seq>`
Comment: @zhexuany, `std::vector` has more than one type parameter. Other standard containers have differing numbers. To support their usage more uniformly, you can accept any number of type parameters.
Comment: Yeah. Your answer is great. Thanks for your kindly help.
Comment: `decltype(*this)` is going to be a reference type that you can't use `::` on.
Comment: @T.C., That's what I get for not instantiating the template when testing. I removed them. While `std::decay_t::iterator` should work to not repeat the type, it's getting a bit ridiculous at that point.
Answer: The book you're using may be out of date. These days c++ has moved in the direction of using free functions for better decoupling.
Example:
#include <vector>
#include <iostream>

// an example Gromit
struct Gromit
{
    Gromit(int index) : index(index) {};

    void speak(int i) { std::cout << name() << " speaking " << i << std::endl; }
    void eat(float f) { std::cout << name() << " eating " << f << std::endl; }
    void sleep(char c, double f) { std::cout << name() << " sleeping " << c << " " << f << std::endl; }
    void sit() { std::cout << name() << " sitting" << std::endl; }

private:
    std::string name() const {
        return "Gromit " + std::to_string(index);
    }
    int index;
};

// apply some function object to each item in a container
template<class Container, class F>
void apply(Container& container, F f)
{
    for (const auto& p : container)
    {
        f(p);
    }

}

int main() {
    std::vector<std::unique_ptr<Gromit>> dogs;
    for(int i = 0; i < 5; i++)
        dogs.emplace_back(new Gromit(i));

    using namespace std::placeholders;

    // apply dog.speak(1) to each dog in dogs...
    apply(dogs, std::bind(&Gromit::speak, _1, 1));

    // dog.eat(2.0f) for each dog in dogs...
    apply(dogs, std::bind(&Gromit::eat, _1, 2.0f));

    // ...etc
    apply(dogs, std::bind(&Gromit::sleep, _1, 'z', 3.0));
    apply(dogs, std::bind(&Gromit::sit, _1));
}

expected output:
Gromit 0 speaking 1
Gromit 1 speaking 1
Gromit 2 speaking 1
Gromit 3 speaking 1
Gromit 4 speaking 1
Gromit 0 eating 2
Gromit 1 eating 2
Gromit 2 eating 2
Gromit 3 eating 2
Gromit 4 eating 2
Gromit 0 sleeping z 3
Gromit 1 sleeping z 3
Gromit 2 sleeping z 3
Gromit 3 sleeping z 3
Gromit 4 sleeping z 3
Gromit 0 sitting
Gromit 1 sitting
Gromit 2 sitting
Gromit 3 sitting
Gromit 4 sitting

template inheritance C++ iterator


Ajuda - C# como atualizar comboBox? tipo autocomplete

Question: Primeiramente eu estou desenvolvendo um sistema em C# e usando Sql Server como banco.
Eu gostaria de realizar a seguinte tarefa:
Quando algo for digitado no comboBox eu atualizo o próprio, por meio de uma pesquisa no banco, exemplo:
Eu digito A no comboBox e carrega ele com o retorno do selecte.
Outro Exemplo: Igual a busca do google, americanas, extra e etc. Estilo um autocomplete, sendo que é necessário o uso do comboBox, pois nele eu tenho que trazer o nome no display e o código no value do comboBox.
Estilo um autocomplete, mas eu preciso que seja um comboBox pois nele eu trago junto um código.
Eu programei da seguinte forma:
exe:
comboBox.DataSource = dataTable;
comboBox.DisplayMember = "Nome";
comboBox.ValueMember = "codigo;

Dentro do TextChanged do comboBox.
O select esta certo e o dataTable ta certo, mas estou tendo o seguinte problema o comboBox pega a primeira linha que retorna e não deixa eu continua digitando, nem altera para registro de baixo (OBS: Retorna mais de uma linha) nem ao menos ele mostra a lista, simplesmente "trava" no primeira linha.
Eu não sei se tem que configura alguma propriedade do comboBox ou realizar em um evento especifico ...
Primeiramente eu tinha feito um autocomplete em um textBox, funciona mas eu não consigo pega o código da opção é selecionado.
E eu não queria carrega o comboBox com todos os registros. Pra não fica algo pesado.
Mais especificamente eu estou fazendo um form relacionado a venda, e eu que pesquisa o cliente dessa forma. Nem sei se tem como.
Desde já fico grato com qualquer sugestão.
Atualização --
códio do textChanged do comboBox
    private void cmbNome_Cliente_TextChanged(object sender, EventArgs e)
    {
        Cliente cliente = new Cliente();
        cliente.Nome = cmbNome_Cliente.Text;
        cliente.Razao_social = cmbNome_Cliente.Text;

        cmbNome_Cliente.DataSource = cliente.CarregaClienteNome(); "Isso retorna um dataTable"
        cmbNome_Cliente.DisplayMember = "Nome - Razao Social";
        cmbNome_Cliente.ValueMember = "Código";
    }

//Pesquisar Cliente para o ComboBox pelo nome ##atualizado
    public DataTable CarregaClienteNome()
    {
        SqlDataAdapter da = new SqlDataAdapter();
        DataTable dt = new DataTable();

        try
        {
            conn.Open();
            cmd.Connection = conn;

            cmd.CommandText = "select top(5) cli.cod_cliente as Código, ";
            cmd.CommandText += "(case when pes.cod_tipo_pessoa = 1 then Nome else Razao_Social end) as 'Nome - Razao Social' ";
            cmd.CommandText += "from tab_Pessoa pes ";
            cmd.CommandText += "inner join tab_Cliente cli on pes.cod_pessoa = cli.cod_pessoa ";
            cmd.CommandText += "where pes.nome like '" + Nome + "%' or pes.razao_social like '" + Razao_social + "%'";
            cmd.CommandText += " order by 'Nome - Razao Social'";

            da.SelectCommand = cmd;
            da.Fill(dt);
            cmd.ExecuteNonQuery();
        }
        catch (Exception e)
        {
            MessageBox.Show(e.Message);
        }
        finally
        {
            conn.Close();
        }

        return dt;
    }

//Autocomplete - teste que eu fiz com autocomplete em um textBox, ele esta funcionando. Porem não consigo obter o código
private void txtTeste_TextChanged(object sender, EventArgs e)
    {
        Cliente cliente = new Cliente();

        cliente.Nome = txtTeste.Text;
        cliente.Razao_social = txtTeste.Text;

        DataTable dt = new DataTable();

        var source = new AutoCompleteStringCollection();

        dt =cliente.CarregaClienteNome();

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            source.Add(dt.Rows[i][1].ToString());
        }

        txtTeste.AutoCompleteCustomSource = source;

    }

Comment: mostra o código completo do "TextChanged" da combobox
Comment: Porque não usa um textBox com comboBox, escreve em um, mostra em outro?
Comment: Outro detalhe, tive um problema parecido quando eu preencheia alguns campos que alteravam o comboBox, ele não era atualizado... Tente colocar comboBox1.DataSource = null; antes de atribuir o retorno da função a ele e se você estiver usando um DataTable na função CarregaClienteNome() coloque nomeDataTabledtResultado.Clear(); antes de preenche-lo. e ao final, embaixo de cmbNome_Cliente.ValueMember = "cod_cliente"; coloque comboBox1.Refresh();
Comment: Seria interessante colocar o código da CarregaClienteNome();
Comment: Vi que você estava com dificuldade em pegar a seleção do autoComplete, Posso te ajudar. acho que ficaria melhor com o textobox e o autoComplete. O que acha?
Comment: O autoComplete tem um seguinte problema eu não consigo pega o código do cliente selecionado.
Comment: Na primeira vez eu fiz com autocomplete no textBox, a lógica é aquela porem não consigo obter o código.
Comment: Marconi se tiver alguma forma de se obter o código utilizando o autocomplete, seria bem útil. Eu atualizei o post com um teste que eu tinha feito utilizando o autocomplete em um textBox.
Comment: Por que não usa o autocomplete do Jquery Ui.
Olha o exemplo que coloquei.
Se precisar de ajuda pode me adicionar no skype.
marconi.barroso92
Answer: A pedido do amigo @LuisFelipeMicaideJesus vou colocar um exemplo usando autoComplete.
 <asp:TextBox ID="txtPesquisarHipotese" runat="server" Width="300px"></asp:TextBox>
 <asp:HiddenField ID="hdfPesquisarHipotese" runat="server" Value="" />

txtPesquisarHipotese ==> Textbox que irá colocar o AutoComplete.
hdfPesquisarHipotese ==> hiden que irá esconder a Seleção do usuário.
Quando uso a função select eu pego o valor que o usuário selecionou e guardo no HiddenField.
Se precisar de mais detalhes, especifique nos comentarios que eu edito a resposta.
$(function () {
    $("#<%=txtPesquisarHipotese.ClientID%>").autocomplete(
                    {
                        source: function (request, response) {
                            $.ajax({
                                url: '<%=ResolveUrl("../ws/AutoComplete.asmx/GetEscopo")%>',
                                data: JSON.stringify({
                                    'prefixText': request.term
                                }),
                                dataType: "json",
                                type: "POST",
                                contentType: "application/json; charset=utf-8",
                                success: function (data) {
                                    response($.map(data.d, function (item) {
                                        return {
                                            label: item.split('#')[1],
                                            val: item.split('#')[0]
                                        }
                                    }))
                                },
                                error: function (response) {
                                    alert(response.responseText);
                                },
                                failure: function (response) {
                                    alert(response.responseText);
                                }
                            });
                        },
                        select: function (e, i) {
                            $("#<%=hdfPesquisarHipotese.ClientID%>").val(i.item.val);
                        },
                        minLength: 1
                    });
});

Código dentro do meu aquivo .asmx
Obs: Se você quiser pode usar a url para acessar  um WebMethod dentro de sua página.
    [WebMethod]
    public string[] GetEscopo(string prefixText)
    {
        SqlConnection conn = null;
        List<string> resultado = new List<string>();

        try
        {
            using (conn = new SqlConnection(Conexao))
            {
                SqlCommand cmd = new SqlCommand("select Escopo from Escopos where Escopos.Escopo like @prefixText group by Escopo order by Escopo", conn);
                SqlParameter param = new SqlParameter();
                cmd.Parameters.Add("@prefixText", SqlDbType.VarChar);
                cmd.Parameters["@prefixText"].Value = "%" + prefixText + "%";
                conn.Open();

                using (SqlDataReader dr = cmd.ExecuteReader())
                {
                    while (dr.Read())
                    {
                        resultado.Add(dr["Escopo"].ToString());
                    }
                    dr.Close();
                }
            }
        }
        catch { }
        finally
        {
            if (conn != null)
            {
                conn.Close();
            }
        }
        return resultado.ToArray();
    }

Comment: @Luis Felipe Micai de Jesus Deu certo?


How to get getIntent() to return null after Activity called with an Intent set

Question: This question was similar to my original question, but I think there is a better way to approach a solution.
getIntent returns wrong intent when setIntent is followed by a rotation
Basically, in my main Activity, which extends FragmentActivity, there are two instances where in a Fragment I pass an Intent to this Activity.
This is the code that is having the problem:
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(...);

    if (getIntent() != null && getIntent().getData() != null) {
        String data = getIntent().getDataString();
        //setIntent(null);

The setIntent was an attempt to solve my problem but it failed to work.
What happens is when I click on a link that goes back to my Activity as an Intent, then I go to the next Fragment, then I rotate the phone, the Intent that was passed two Fragments ago shows up again when I call getIntent.
So, when I get the data out of the Intent, how can I set it so the next call to getIntent will return null?  Or, would it make sense to just have the data in the Intent be null instead?
I am trying to avoid updating information in the SharedPreferences to handle this.
Answer: I found a solution that appears to work, but I expect there is a better way to do it.
    if (getIntent() != null && getIntent().getData() != null) {
        String data = getIntent().getDataString();
        getIntent().setData(null);
        setIntent(null);

I think the setIntent isn't of any use, but the setData(null) seems to do the trick.
Comment: Does not work on API 27, Haven't tested on other APIs.


Preselect explanatory variables with PCA for a further multivariate analysis

Question: I have dataset composed of samples (here corresponding to sites), species, environmental variables linked to the species (e.g.: species biomass, abundance and size) and explanatory variables (Temperature, oxygen,…). The number of explanatory variables is quite consequent. So I wanted to do a PCA on the explanatory variables of the different sites to do a data reduction of explanatory variables. And after include the selected variables on an MDS or a dbRDA with the sites, species and the environmental variables.
Does it make sense?
In my reasoning, if the explanatory variables are not considered as important in contributing to the selected components of the PCA (and then does not influence the dissimilarity among sites). By extension, they will not contribute to influence environmental variables.
Answer: What you propose seems to be to identify predictors that make major contributions to to the first few principal components of the predictor matrix, remove the other predictors, then proceed to model with the remaining predictors.
This could be considered a type of data reduction without reference to the outcome variable, which can be a good idea in general. Frank Harrell discusses several methods for unsupervised data reduction in Section 4.7 of his RMS course notes.
A potential difficulty with your particular approach is how it will deal with 2 or more highly correlated predictors, as correlated predictors tend to be similarly represented in individual principal components. For such sets of predictors you might want instead to devise some type of combined cluster score. If you just choose one of a set of correlated predictors, your choice might depend heavily on the particular data set.
You also will have to figure out how to explain your predictor-selection approach clearly to others so that they could reproduce your results.
You might also consider methods like ridge regression, LASSO, or their combination in elastic net. If you have multiple outcome variables, an approach like canonical correlation analysis or partial least squares could be useful.
Comment: Yes that is correct, my idea is to do a data reduction. Thank you for that answer, you provided all the tools I need.
To avoid highly correlated predictors, my plan was to apply a preliminary VIF (Variance Inflation Factor), on the dataset.


Create a dictionary from a nested structure (with arrays of other Structures) Swift

Question: I am using the Post method of Alamofire; so I need to create the parameters from an existing nested Model that contains arrays of other models
I was looking for a way to do but in vain, anyone can help, please!
I AM A BEGINNER IN SWIFT, PLEASE STOP UNRATING MY QUESTION
Like this example
struct Car: Codable{
var id :Int,
var name:String,
var users:[User],
..

 var dictionaryRepresentation: [String: Any] {
        return [
            "id" : id,
            "name" : name,
            "users" : users,  XXX WRONG XXX
        ]
    }
}

I am having a hard time making the right format for the "users: [User]" field
struct User: Codable{
var id :Int,
var name:String,
var email:String,
..

 var dictionaryRepresentation: [String: Any] {
        return [
            "id" : id,
            "name" : name,
            "email" : email,
        ]
    }
}

with this Wrong Format I am facing this error :
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (__SwiftValue)'

Thank you,
Comment: Where is the part where you convert to JSON? Your use of Codable suggests you are going to use JSONEncoder, so where is the code where you do that?
Answer: You need to map it to the dictionaryRepresentation to make it work like this:
"users" : users.map { $0.dictionaryRepresentation }

A better approach would be to pass the var car: Car object since it already conforms to Codable Alamafire does the encoding for you, ie., you don't have to make the dictionaryRepresentation for passing it as the parameter in Alamorire request.
Comment: Thank you for your response, but how can I use Alamofire for that ? when i use the jsonDecoder it gives me a variable of type Data not a dictionary, so i can't use it as the parameters
Comment: Did you mean json encoder? If so, you don't have to use it, just pass the object and alamofire will take care of the encoding as I've mentioned in my post.
Comment: I tried it but it gives me this error :
Cannot convert value of type 'Car' to expected argument type 'Parameters?' (aka 'Optional>')
Comment: Add another post regarding this if you're still facing an issue, will try to figure out where you've gone wrong.
Comment: Well, I solved the issue with the help of your answer, but I just wanted to know one more efficient way to do it using Alamofire (Because I didn't know about it )
Comment: Yeah, no harm in asking about it in another post. Post the link below and I'll try to take a look and help you out.
Comment: Thank you! I figure it out! it is actually way easier to use the default encoding of Alamofire!
Comment: Hello, @Frankenstein I am having a similar problem with Alamofire can you take a look at this question, please? [https://stackoverflow.com/questions/63627077/append-nested-data-as-in-parameters-of-multi-form-swift-alamofire]


PhpStorm: Less Filewatcher: define output folder

Question: I'm using the Filewatcher for Less inside PhpStorm which works nicely using this argument:
--clean-css="--s1 --advanced --compatibility=ie8" --no-color $FileName$ `c:/xampp/htdocs/myproject/css/$FileNameWithoutExtension$.css`

It will compile all .less files (which are located in /less/ ) into my /css folder.
What I want to do now is using subfolders inside my less folder like the following:
/less/_modules/email/style.less

so the compiler should put it there:
/_modules/email/css/style.css

I know i can use the Macros from the File Watches Dialog but the Problem is that there's no Macro which removes /less/ from the source path.
Any ideas what does the trick?
Answer: I found the answer by myself:
--clean-css="--s1 --advanced --compatibility=ie8" --no-color $FileName$ $ProjectFileDir$/$FileDirPathFromParent(less)$/css/$FileNameWithoutExtension$.css


Make shorter replace, splitting and conversion C#

Question: How can I make my code shorter? This is my input (it are coordinates):
(51.01407864998378, 4.15557861328125)

I want the coordinates to split in two different variables.
here is my code:
StringBuilder text = new StringBuilder(); // creation of stringbuilder

text.Append("(51.01407864998378, 4.15557861328125)"); //append my string
text.Replace("(", ""); // remove the round brackets and white space.
text.Replace(")", "");
text.Replace(" ", "");
text.Replace(",", "_"); //in europe we use a comma as separator for decimal numbers, not a point.
text.Replace(".", ",");

string[] parts = text.ToString().Split('_'); // splitting and convert it.

decimal lng = Convert.ToDecimal(parts[0]);
decimal lat = Convert.ToDecimal(parts[1]);

results are 51.01407864998378 in variable lng and 4.15557861328125 in lat.
Can anyone make this code shorter? I use C#.Thanks
Comment: also, why are you sending lat/long to this method in this format?
Comment: What are you *actually* trying to do? Simply extract the values?
Comment: tbh you only need lat/long to six decimal places. right now you are trying to bring accuracy to the atomic level, which is fairly useless.
Comment: @PanagiotisKanavos yes, I need only to extract the values
Comment: @user1666620: well I have a google map. when the user click on a location, there must be send a lat/long to the server. I save that coordinate temporary into a hidden field and now I go use it on the server. The coordinates are stored like that in my hidden field.
Answer: You can do it with  regex.
var coord = "(51.01407864998378, 4.15557861328125)";
Match match = Regex.Match(coord, @"\(([\d]*.[\d]*),[^\d]*([\d]*.[\d]*)\)$", RegexOptions.IgnoreCase);

if (match.Success)
{
      decimal lng = Convert.ToDecimal(match.Groups[1].Value, CultureInfo.GetCultureInfo("en-US"));
      decimal lat = Convert.ToDecimal(match.Groups[2].Value, CultureInfo.GetCultureInfo("en-US"));

      Console.WriteLine(lng);
      Console.WriteLine(lat);
}

Results
51.01407864998378
4.15557861328125
Comment: This is only half the answer. It's not enough to capture the *text*, you also have to parse the numbers ensuring `.` is used instead of `,` as the decimal separator
Comment: It's not part of the question, no one knows where the coordinats comes from and which culture the OP is, but especially for you I've added the parsing step to the answer.
Comment: The US locale is a bad choice, because it uses a unique date format. To ensure unambiguous parsing the preferred culture is `CultureInfo.InvariantCulture`
Answer: If you are trying to extract the values, the shortest way would be to use a regular expression, like
\((?<lon>\d+\.\d+),\s+(?<lat>\d+\.\d+)\)

By using named capture groups you can extract specific parts by name.
After that, you just need to parse the text specifying the InvariantCulture, to ensure . is used as the decimal separator eg:
var coordRegex=new Regex(@"\((?<lon>\d+\.\d+),\s+(?<lat>\d+\.\d+)\)");

var input = "(51.01407864998378, 4.15557861328125)";
var match = coordRegex.Match(input);

if (match.Success)
{
   var lonText=match.Groups["lon"].Value;
   var latText=match.Groups["lat"].Value;

   var lon=decimal.Parse(lonText,CultureInfo.InvariantCulture);
   var lat=decimal.Parse(latText,CultureInfo.InvariantCulture);
}

Regex.Match is thread safe which means you can create a single static Regex object and avoid rebuilding the object, eg:
static readonly Regex _coordRegex=new Regex(@"\((?<lon>\d+\.\d+),\s+(?<lat>\d+\.\d+)\)");

A regex is also much faster because it avoids generating temporary strings until you request a specific group using Value. Until that point, the Match object contains only pointers to the original string. This means that there are fewer object allocations, less memory pressure and fewer garbage collections.
This leads to significant performance gains when processing files with many coordinates. In such cases, most of a program's memory usage is due to the generated temporary objects.
Answer: You can split more simply, and use decimal.Parse to not care about dots and commas:
string src = "(51.01407864998378, 4.15557861328125)";

var temp = src.Split(new[] { '(', ',', ')' }, StringSplitOptions.RemoveEmptyEntries);
var lng = decimal.Parse(temp[0], CultureInfo.InvariantCulture);
var lat = decimal.Parse(temp[1], CultureInfo.InvariantCulture);

Comment: Why? It isn't *simpler* than a regex but it *does* generate a lot of temporary strings and is, as a consequence, slower. If you used this to parse a file of coordinates, there would be a significant performance hit, both due to the string generation and garbage collection.
Comment: @Panagiotis: It's a lot simpler than a regex, imo. And what makes you think that using a regex wouldn't create lots of temporary strings and other garbage? I haven't run any tests, but I would guess that this method is probably more efficient than your own answer (in terms of both speed and garbage generated).
Comment: I suggest you run the tests then. I discovered this by processing large files, when I found that splits caused memory usage to continuously increase. As for the explanation, it's in my answer and  the [.NET reference code](http://referencesource.microsoft.com/#System/regex/system/text/regularexpressions/RegexCapture.cs,98a52e6ee2014292). Regex doesn't split strings, it *parses* them, generating objects only for successful captures The captures contain only pointers to the input string


How to Manually Xen bridging setup on OpenSUSE for two DomU

Question: I've been having problems with Xen networking on OpenSUSE, specifically with getting Dom0 opening a TCP connection to the DomU.  Other machines on the network can open TCP connections to all 3, so I'm hoping a manual network configuration will let me resolve the Dom0 -> DomU issue.
So I need help to manually configure my Dom0 network, bridge, and 2 VIF interfaces in OpenSUSE.  Ideally I'll have 3 mac addresses, two randomly generated for each VIF and one for the Dom0.  This way my internal DHCP/DNS server can assign each a IP and all machines on the lan can connect to all 3 servers.  All 3 machines should be on the same internal network with everything else (no VLAN or NAT).  NOTE: You can assume this is a static network setup, I'm just using DHCP with static MACs for convenience, but I expect the IPs of Dom0, and DomUs to be fixed.
1) How do I configure this network start to finish in YaST?
or
2) Please provide sample /etc/sysconfig/network scripts, and any other config file scripts to set this up.
Thanks
Answer: I create the bridges manually using the ifcfg- files in /etc/sysconfig/network.  I have a bridge attached to eth0 that gets passed to domUs.  Below are my ifcfg-eth0 and ifcfg-br5000 files.  It's slightly different if you need to bridge a VLAN, but since you don't indicate as much, I assume that's not needed.
eth0:
BOOTPROTO='static'
#IPADDR='172.16.30.221/24'
IPADDR='0.0.0.0/24'
BROADCAST='172.16.30.255'
MTU=9000''
STARTMODE='onboot'
NAME='Ethernet Network Card'

br5000:
BOOTPROTO='static'
BRIDGE='yes'
BRIDGE_FORWARDDELAY='0'
BRIDGE_PORTS='eth0'
BRIDGE_STP='off'
BROADCAST=''
ETHTOOL_OPTIONS=''
IPADDR='172.16.30.221/24'
MTU='9000'
NAME=''
NETWORK=''
REMOTE_IPADDR=''
STARTMODE='auto'
USERCONTROL='no'

Comment: That's half of it.  How would I manually create the two VIF interfaces so they can use the bridge, giving them 2 different MAC and IP addresses.
Comment: You don't create the vifs, Xen does when it creates the VM.  In your domU config file, you would set a line like: vif = [ 'mac=00:16:3e:42:49:01, bridge=br5000']  Then, in the domU, you can get an IP via DHCP or set it statically.  Or set it in the domU configuration file.
Comment: Yeah, that much works right... And I can RDesktop from a laptop to the DomU.  But RDesktop form Dom0 to DomU doesn't work.

So I was thinking if I could set up the VIF in SuSE, then I can just tell XEN use this VIF
Comment: What versions of:  OpenSuSE dom0, Xen, domU ?
Comment: OpenSUSE 11.4 , kernel is 188.8.131.52-0.9, xen is `/boot/xen-4.0.2_52`. I tried your scripts, commented out the vif-script and network-script. My VM vif line is. `vif=[ 'mac=08:00:27:11:D9:B1,ip=192.168.1.211,type=ioemu,bridge=br0' ]`.  Still, it's the same error where dom0 can ping, but not open a TCP connection to DomU.  I asked this on Xen-Users too.
Answer: I am more familiar with XEN under SLES, but I think OpenSuSE will be similar.
If bridging is available via yast network try that one (works on SLES11, not on SLES10).
If bridging is not available via yast look into /etc/xen/scripts. There you should find a script called network-bridge. Use that wrapper-script to move your Dom0-Interface onto the bridge (look into the head of the script for parameters).
I found it to be necessary to put a configuration /etc/sysconfig/network/ifcfg-$BRIDGE with startmode manual so that the bridge will be up after the network-bridge-script runs.
The basic trick of the wrapper-script is to move the MAC (and IP) from the physical interface to the bridge-device. The original interface will be added to the bridge and renamed to PETH - serving as "uplink" to the network.


Prove limit of three variables using (ε, δ)-definition

Question: Prove limit of three variables using (ε, δ)-definition.
$$\lim_{(x, y, z)\to (0, 1, 2)} (3x+3y-z)=1$$
I have no idea how to do this with three variables.
Answer: You have to prove that for every $\epsilon > 0$, there exists some $\delta > 0$ such that if $$\sqrt{x^2+y^2+z^2} < \delta$$ then $|3x+3y-z-1| < \epsilon$.

To do that, here's a hint:

If $\sqrt{x^2+(y-1)^2+(z-2)^2} < \delta$, then $|x|<\delta$ and $|y-1|<\delta$ and $|z-2|<\delta$.
$3x+3y-z = 3x + 3(1+(y-1)) - (z-2) -2$
Answer: We need to show that for every $\varepsilon > 0$, there is a value $\delta \gt 0$ such that $\left|x - 0\right| \lt \delta, \left|y-1\right| \lt \delta, \text{and } \left|z-2\right| \lt \delta$ imply that $\left|3x + 3y - z - 1 \right| \lt \varepsilon$


Upper part of a view with rounded corners while on top of an ImageView Android-Java

Question:
All I want to know is how to achieve the highlighted part in the image whereas the upper part of a view has rounded corners while on top of another View where that view acts as the background, I've tried following Material Design's guidelines as to how use shapes or looking around the internet for something similar, yet came up with nothing.
XML FILE
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/background_light"
    android:theme="@style/gymTheme"
    android:fitsSystemWindows="true"
    >

    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/main.appbar"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        android:fitsSystemWindows="true"
        >
    <com.google.android.material.appbar.CollapsingToolbarLayout
        android:id="@+id/main.collapsing"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_scrollFlags="scroll|exitUntilCollapsed"
        android:fitsSystemWindows="true"
        app:contentScrim="?attr/colorPrimary"
        app:expandedTitleMarginStart="48dp"
        app:expandedTitleMarginEnd="64dp"
        >

        <ImageView
            android:id="@+id/backdrop"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scaleType="centerCrop"
            android:fitsSystemWindows="true"
            android:src="@drawable/aagym"
            app:layout_collapseMode="parallax"
            />

        <com.google.android.material.appbar.MaterialToolbar
            android:id="@+id/main.toolbar"
            android:layout_width="match_parent"
            app:title="@string/search_hint"
            android:layout_height="?attr/actionBarSize"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            app:layout_collapseMode="pin"
            />
    </com.google.android.material.appbar.CollapsingToolbarLayout>
</com.google.android.material.appbar.AppBarLayout>

<androidx.core.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:navGraph="@navigation/specific" />

</androidx.core.widget.NestedScrollView>

<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:layout_margin="10dp"
    android:src="@drawable/ic_baseline_favorite_border_24"
    app:layout_anchor="@id/main.appbar"
    app:layout_anchorGravity="bottom|right|end"
    />

<com.google.android.material.bottomnavigation.BottomNavigationView
    android:id="@+id/bottom_navigation"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"

    android:layout_marginBottom="10dp"
    app:menu="@menu/gym_details_menu"
    app:layout_behavior="@string/hide_bottom_view_on_scroll_behavior"
    />
</androidx.coordinatorlayout.widget.CoordinatorLayout>

This is how my Layout looks like
Comment: You can use cardview for that and can modify that cardview using shape in the drawable folder
Comment: @youcantseeme I tried, it doesn't overlay the image, meaning the area that's been cropped its background is set to the White color instead of having the image view underneath it
Answer: Why are you using fragment inside nested scrolled view? You can replace it with a custom view or include a view.
To achieve this you need to put a shape drawable with rounded corners, then add it as background in the first parent view of the nested fragment of yours. Finally, add some margin-top to the nested scroll view so you can hide the empty spaces from the rounded corners. Keep in mind that your parent's view must not have a background color just the child under the shape.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="@color/colorAccent" />
    <corners
        android:bottomLeftRadius="0dp"
        android:bottomRightRadius="0dp"
        android:topLeftRadius="40dp"
        android:topRightRadius="40dp" />
</shape>


Run-time error '6335' when run code paste

Question: Run-time error '6335' when run code paste, as below picture

Run-time error '6335'

Anyone who knows how to solve this problem? Thank you very much
sub test
selection.MoveDown unit:=wdLine, count:=2
selection.EndKey unit:=wdLine, Extend:=wdExtend
selection.Cut
selection.MoveDown unit:=wdLine
selection.Paste
end sub

Comment: Can you paste the code in the question as well? Plus a screenshot of the selection?
Comment: Screenshot of the selection...
Comment: `https://www.experts-exchange.com/questions/29003014/Word-VBA-Run-time-error-'6335'-in-Office-2016.html `  I found the same problem on this site but it did not solve it
Comment: Have you tried to restart your PC and run the code again? This seems to be the accepted solution?
Comment: What kind of content are you trying to paste? Are you able to paste it as a user, or do you also get an error? To what kind of target are you pasting? In the middle of text? In a table? In a graphic? ...?
Comment: This site is offering a fix. This is NOT a recommendation of the advertised product (I didn't try it and have no opinion about it) but I liked the explanation of error 6335. http://www.registryquick.net/runtime/Fix-Runtime-error-6335-How-to-Fix-Runtime-error-6335-61891.html
Comment: @variatus Thanks
Answer: Just try like this, it could be that you are missing some references:
Sub TestMe()
    Selection.Cut
    Selection.PasteAndFormat (16)
End Sub

Comment: Yes, but I do not know which reference is missing
Comment: @K.R.pnx - if the code above works, then it is the Word reference.
Answer: "the error '6335' the action was blocked by organisation policy." well i think the error appears maybe because some other application is trying to access the clipboard.
You have to shut down all applications that access the clipboard before you run the MS Word macro.
i was trying to generate the pdf in word document when this error appeared. finally i closed a process named "beyond compare clipboard" after which the macro worked smoothly.


What note type in the 7th of a chord? - Music Theory

Question: If this diagram is accurate, would the 7th of a Bmin7 be formed from a minor 7th interval or a major 7th interval, e. g. A-natural or A-sharp? I'm assuming A-natural. If this line of thinking is wrong, what is the proper way to denote the 7th interval and also, while at it, how to determine the 9th?
Update:
I've narrowed down my confusion: the composition of a triad chord is the 1st, 3rd, and 5th interval from the root. However, some cases notes in this triad are a sharp or flat note. Is there any system or rule set that can be universally followed to determine those cases? or is it just by memory?
Another Update
Ok so I've narrowed down (based on answers below) that whether a note is a sharp or flat is determined on the key. So I guess the answer to my question is how to determine a key of a note through some sort of rule set, as in do this, this, and this to determine the key of C. If this doesn't exisit, I will result to memorization I assume.
Also have determined so far that the diagram below is wrong because occasionally a chord will start with a sharp and have sharps as the 3rd interval, so that isn't represented below.
Another Update
So based on feedback below, to know whether notes in a chord are sharp are flat is basically knowing the scale. The pattern I was seeking was TTSTTTS, thanks tim. It is Tone & Semi Tones. I will have to do some more research but thank you everyone for contributing. Please feel free to add more thoughts below.
Comment: Use the A for both min.7th and dom.7th, and the A# for maj.7th. This will put all 3 chords right.There seems to me to be a lot of mis-information out there in the big wide web.
Comment: This chart seems to me to be unhelpful, as in 7th notes,or will other relevant notes shine blue for other chords?It appears to show that note A is the same A in maj. and min. It isn't.
Comment: The sharps and flat bits are purely down to whether the appropriate notes in the triad  or tetrachord are sharp or flat in the key  to which they are .
Comment: The way this chart currently stands, the acceptable 7th would be a major or minor A and either of those two notes would be blue. I think I'm learning that this method is inaccurate
Comment: @Tim - agreed, I just posted an answer that will hopefully add some good information to the web.
Comment: @Tim So to really understand this, I should I should learn how to determine the series of notes in a key?
Comment: That's the top and tail of it. Yes, absolutely.Start with C major, as that has no # or b, and work from there. The minor(s) all change certain notes, from the major starting point. TTSTTTS is the formula to know.
Answer: The pitches in a Bmin7 chord are B D F# A. "A-natural" is the seventh scale degree of the B minor scale, and forms a minor 7th interval from the tonic note of B natural.
Comment: Thanks, is there any pattern or method to determining when a note is sharp or flat within a chord? Im not exactly clear as to when F# became F# rather than just F. And with F# being in the chord, that makes this chart incorrect? It was supposed to display when Maj, min, Aug, Dim, and perfect notes are acceptable.
Answer: There are four parts to reading macro-analytical chord nomenclature, which I will break down below.  First, let's take the chord from the question:
Bm7

B
^
The first part of the chord "B" will tell you what pitch-class the triad is based off of.  In this case, it's B.  If you saw the chord "Am7", the first part of the chord would indicate some type of "A" chord.

m
^
The second part of the chord "m" will indicate the quality of the chord. A lower-case "m" is used for minor, an upper-case "M" for major (when not dealing with 7th chords,) and "dim" or "aug" used for diminished or augmented chords respectively.  Now, there is alternative notation such as a "-" used to signify minor and a "+" to signify augmented.
Alternatively, you may see "°" for diminished chords and a line through the same circle for half-diminished chords.

7
^
The last part of the chord denotes either how the seventh will be treated and / or how any extensions will be treated if used.  The "quality" component of the chord and this last component are a little intertwined as a half-dim symbol would obviously apply to the seventh and not the triad.  In a seventh chord the 7th is always flatted when presented by itself:
D7 = D, F#, A, C
B7 = B, D#, F#, A
Ebm7 = Eb, Gb, Bb, Db
etc.
The seventh is only different when specifically notated to be so:
BM7 = B, D#, F#, A#
CmM7 = C, Eb, G, B
F#°7 = F#, A, C, Eb
This portion of the chord is also where any special alternations to the original triad might be located, for example, a commonly different spelling for a half-diminished chord is "m7b5" such that:
Am7b5 = A, C, Eb, G

The last part of the chord is where compound intervals are located.  These are also know as upper-tertian extensions.  Here you'll see 9ths, 11ths, and 13ths added or altered in chords:
Bm7(9) = B, D, F#, A, C#
Bm7(b9) = B, D, F#, A, C
Bm7add11 = B, D, F#, A, E
Bm7add13 = B, D, F#, A, G#
If all notes up to a compound interval are expected to sound, then the 7th is dropped and the extension takes the place:
Bm9 = B, D, F#, A, C#
B13 = B, D#, F#, A, C#, E, G#
As you can see, in both cases the 7th is still flatted. This is due to historical and contemporary performance practice.  The rule still applies.  If the 7th is to be altered, it must be notated as such:
BM7(13) = B, D#, F#, A#, C#, E, G#
Upper-tertian extensions may be altered in any way:
Bm7(#9)(addb13) = B, D, F#, A, C##, G
As you can see, because I "added" the 13, the 11th was omitted.

Obviously, there is more nomenclature, notation, and other shorthand elements, but above are outlined the basic premise and process of reading chord nomenclature.
Comment: @BrianAnthonyDillingham - I suggest you take a look at the circle of fifths, funny things called *tetrachords*, and how major scales are built.
Comment: This is great and informative! thank you for explaining. Can you touch on when or why a note becomes a sharp or flat though? Im looking for some sort of explanation or system that determines that.
Comment: I can determine which notes to use in a chord, but when it is sharp or flat or natural eludes me. Thank you for your thorough explanations!
Comment: Think of the chords in terms of intervals, i.e. # of semitones, from the root. Depending on your root, sometimes those intervals will fall on a note representable without sharp/flat, and sometimes you need a sharp/flat.

As an example, any chord with root C will have all of its notes a semitone higher than a chord with root B, so for many of them, you need sharps/flats in one root or the other.
Answer: You've maybe been confused by the fact that Bmin. scale sometimes has A# in it. The Bmin. harmonic always does, whereas the Bmin. natural never does, and the Bmin. melodic sometimes does !! Confusing. Yes, very. However, the standard Bm7 , as Wheat states, is B-D-F#-A, using the minor seventh interval of B to A. There is another chord which does use A#, and it's called Bminor major 7, sounding not too stable and often used as a bridging chord .
To understand this lot more easily, use Cmaj. as a starting point. Count TTSTTTS as you go through the scale. It gives CDEFGABC. This will translate , starting at D, for example, as DEF#GABC#D.All maj. scales work in this way, and you need to keep 'black' notes as either # OR b. Don't mix them ! Working on to minors, use the major as a template, but for example, on natural min., flat the 3rd, 6th and 7th notes. If they happen to be #, then they'll become naturals. If they're naturals, they become flats.This is a fair simplification,but I hope it's enough to get you well on the way.
Comment: Thanks, is there any pattern or method to determining when a note is sharp or flat within a chord? Im not exactly clear as to when F# became F# rather than just F. And with F# being in the chord, that makes this chart incorrect? It was supposed to display when Maj, min, Aug, Dim, and perfect notes are acceptable.
Comment: @BrianAnthonyDillingham - yes, please see my answer.
Answer: I would advise you not to learn the types of chords like this. You need to understand what it means for a chord to be minor / Major and what it means to be Augmented / Diminished. If you only have notes that are in the scale of the Key then sure there are patterns that arise but no composer is forced to only play notes that are comprised of in the scale.
There are a plethora of reasons why a composer would like to use chords that do not form part of the scale. If you do not know what it means for a chord to have this characteristic then somehow you are now unable to discern what type of chord you are seeing. Which is bad.
To teach theory in this way. To simply make it a memory exercise to me is to teach it in non intellectually engaging manner which will not lead to theory success.
Answer: The "base" for naming or constructing any chord is the major scale starting on the root of the chord - the note that gives it it's name.  This is completely independent of context - a C major chord will consist of C, E and G whether it is acting as the tonic in the key of C major, the bVII of D major or anything else.
Get rid of the idea that every note and chord in a piece of music must be in one particular scale, or imply a modulation to another key.  A C chord is perfectly valid as bVII of D major.


Functional square root of $f(x)=x^2-1$???

Question: What I'm looking for is a function $\phi(x)$ such that $\phi(\phi(x))=f(x)$, where $f(x)=x^2-1$.
I am aware of this stack exchange post:
Square root of a function (in the sense of composition)
and furthermore, the post that was mentioned within that post:
https://mathoverflow.net/questions/17605/how-to-solve-ffx-cosx/44727#44727
However, using the resources in the latter link, I'm not sure how to start to come to a conclusion. In the top answer in the latter link, two criteria must be met (quoted straight from the answer):
1) The superfunction(flow) of f(x) grows not faster than an exponent
2) Runge phenomenon does not appear.
I have no idea how to test #1; that lies beyond the scope of my mathematical knowledge, and looking at the link for the Runge Phenomenon in #2 seems understandable enough, and testing with the analytic solution provided, it seems to lead to that phenomenon, but I have no idea how to come to that conclusion for sure. The answer also mentions that there are ways to combat Runge Phenomenon, but that also lies beyond the scope of my mathematical knowledge.
Comment: If you're interested, the functional square root of the similar function
$$g(x)=2x^2-1$$
is
$$g^{1/2}(x)=\cos(\sqrt{2}\arccos(x))$$
Answer: In General: Suppose we have $f(\alpha) = \alpha,$ while $f'(\alpha) = s$ with $0 < s < 1,$ also $f'(x) > 0$ and $f(x) \neq x$ for $x \neq \alpha,$  $C < x < D,$ for constants $C < \alpha < D.$ The first thing we do is move the fixpoint to the origin, with
$$ g(x) = f(x + \alpha) - \alpha.  $$
Then $g'(0) = s.$ As a result, pages 122-123 in KCG or pages 46-47 in Alexander or pages 77-79 in Milnor, we can solve Schroeder's equation
$$   \psi(g(x)) = s \psi(x)  $$
with $$ \psi'(0) = 1 $$
by
$$ \psi(x) = \lim_{n \rightarrow \infty} \frac{g^n(x)}{s^n}, $$
where $g^1(x) = g(x)$ and then
$$ g^n(x) = g \left( g^{n-1}(x) \right)   $$
From above,
$$  s \psi(x) = \psi(g(x)) $$ so
$$ \psi^{-1} (s \psi(x)) = g(x ) = f(x+\alpha) - \alpha. $$
Substitute $x \mapsto x - \alpha$ to get
$$  \psi^{-1} (s \psi(x - \alpha)) =  f(x) - \alpha.  $$
At this point, we can use $\sqrt s$ to  define the half-iterate,
$$  h(x) = \alpha +  \psi^{-1} \left( \sqrt s \; \psi(x - \alpha) \right)  $$
We will need the evident
$$  \psi \left( h(x) - \alpha \right) = \sqrt s \; \psi(x - \alpha)  $$
We may now simply calculate
$$ h(h(x)) =  \alpha +  \psi^{-1} \left( \sqrt s \; \psi(h(x) - \alpha) \right)   $$
$$ h(h(x)) =  \alpha +  \psi^{-1} \left( \sqrt s \; \psi( \alpha +  \psi^{-1} \left( \sqrt s \; \psi(x - \alpha) \right) - \alpha) \right)   $$
$$ h(h(x)) =  \alpha +  \psi^{-1} \left( \sqrt s \; \psi(   \psi^{-1} \left( \sqrt s \; \psi(x - \alpha) \right) ) \right)   $$
$$ h(h(x)) =  \alpha +  \psi^{-1} \left( \sqrt s \;  \left( \sqrt s \; \psi(x - \alpha) \right)  \right)   $$
$$ h(h(x)) =  \alpha +  \psi^{-1} \left( s \; \psi(x - \alpha)   \right)   $$
$$ h(h(x)) =  \alpha +  f(x) - \alpha = f(x).  $$
==========================================================================
This one has the advantage that the fixpoint at $\phi = \frac{1 + \sqrt 5}{2}$ has the function's derivative greater than one. This means that there is a real analytic half iterate for, at least, $x > 0.$ All you need to do is solve the Schroeder equation around $\phi.$ I will need to look up some things, but the references you want are Alexander  and KCG.
Oh: it is not difficult to prove that there can be no answer for this that extends to the entire complex plane, or even extends to the entire real line. That is, however, not the end of the story.
Alright, pages 46 and 47 in Alexander, A History of Complex Dynamics. We need to use the inverse function to get derivative below $1,$ so we define
$$  h(x) = \sqrt {1+x}.  $$  Or pages 122-123 in Kuczma, Choczewski, and Ger, Iterative Functional Equations.
I need some more time to make an actual computer program. I have done the more difficult case with derivative $1,$ including program, http://mathoverflow.net/questions/45608/formal-power-series-convergence/46765#46765   and later http://math.stackexchange.com/questions/911818/how-to-obtain-fx-if-it-is-known-that-ffx-x2x/912324#912324
Anyway, as I said, your problem is conceptually far simpler.
It is necessary to move the fixpoint to the origin, so
$$ g(x) = \sqrt {\phi^2 + x \;} - \phi.  $$
We will then get the Schroeder function
$$ \psi(x) = \lim_{n \rightarrow \infty} (2 \phi)^n g^n(x), $$
where $g^1 (x) = g(x)$ and then $$g^n(x) = g (g^{n-1}(x))$$
Here is an example  with $x=1,$ showing $\psi(1) \approx 0.88523$
1    0.2840790438404122    0.9192990968507166
2    0.08552494260243937    0.8956288264762806
3    0.02621627545939931    0.888431399703
4    0.008081094572713665    0.8862183392045823
5    0.002495271498931473    0.8855355193262247
6    0.0007708976551425994    0.8853246168742123
7    0.0002382029425400667    0.8852594540251384
8    7.360708310000241e-05    0.8852393185124893
9    2.274567970927954e-05    0.8852330963800049
10    7.028786312091029e-06    0.8852311736375063
11    2.172012962375902e-06    0.8852305794564203
12    6.711887781118975e-07    0.8852303957800051
13    2.074087255277135e-07    0.8852303388330724
14    6.40928197181978e-08    0.8852303215475368
15    1.98057703570953e-08    0.8852303146984961
16    6.120319584468348e-09    0.8852303085424645
17    1.891282686017348e-09    0.885230272694271
18    5.844384975972616e-10    0.8852302824650963
19    1.806013116834038e-10    0.8852297127013157
20    5.580891304646229e-11    0.8852303238549764

===========================================================
int main()
{

 double phi = ( 1 + sqrt(5) ) / 2;
 double phi2 = 1 + phi;
cout.precision(16);
   cout << endl << phi << "  "  << phi2 << endl;

  double x = 1.0;
  double mult = 1;
  for(int n = 1; n <= 20; ++n)
  {
    mult *= 2 * phi;
    x = sqrt( phi2 + x) - phi;
    cout << n << "    " << x <<  "    "  << mult * x << endl;
  }

  return 0;
}

==========================================================
Answer: Your function has a fixpoint in the positive numbers where also the tangent (derivative of $f(x)$) is positive, although it is not attracting but repelling. Anyway, a recentering of the polynomial on $f(x)$ allows a polynomial in $g(x)$ without constant term.
From this a powerseries $g_{05}(x)$ representing the halfiterate of $g(x)$ can be constructed.
In this situation of asking only for the functional squareroot (and not for the full fractional iteration to any noninteger iteration-height) the extremely simple "Newton-algorithm" for finding the squareroot of a number can be involved - of course after adaption for finding the squareroot of a formal powerseries. This looks quick&dirty, but gives a correct solution.

I used the software Pari/GP for this.
Definition of the function:
f(x)  = x^2 - 1
                 fi(x) = sqrt(1+x)   \\ the inverse (not needed here)

Define a new function whose power series is centered around the attracting fixpoint (this is $t_0$ here):
     t0=(1+sqrt(5))/2  \\ fixpoint t0  at 1.61... (repelling)
     t1=(1-sqrt(5))/2  \\ fixpoint t1  at -0.61... (attracting) not needed here

g(x) = x^2+2*t0*x       \\ = f(x+t0)-t0  function f() recentered around t0
                    gi(x)= sqrt(x+t0^2)-t0  \\ inverse of g(x), not needed here

Iterative Newton-algorithm for finding the squareroot of a number, here adapted for formal powerseries:
\\ initializing newton-algo for finding (functional-) squareroot
\ps 64            \\ precision of involved powerseries (64 terms)
g05= x + O(x^64)  \\ initalizing the power series for halfiterate of g(x)

for(k=1,40,g05=(g(serreverse(g05))+g05)/2) \\ iterate(40 times for precis.)
        \\ in g05 is now a well approximated formal powerseries

Make a proper functional expression out of it for Pari/GP-calls:
hg(w) = subst(Pol(g05),x,w)  \\ halfiterate of g(x)
hf(x) = hg(x-t0)+t0          \\ halfiterate of f(x) by recentring hg(x)

Testing:
\\ test some values
x0 = 0.2
   x05= hf(x0)
   x1 = hf(x05)

\\ show comparision
[x0,x05,x1;x0,x0,f(x0)]

\\ output:
\\  x0            x05              x1
[0.200000000000 -0.459584198682 -0.960000001849]  by hg() resp hf()
[0.200000000000 --------------- -0.960000000000]  by f(x)

Make a plot:
ploth(x=-1,3,[x,hf(x),f(x)])

(Plot edited using excel for labeling)


Is it possible to use drush migrate-import to import custom fields?

Question: I am trying to migrate a Drupal 7 site to Drupal 8 on a new server
I have copied the db so it can be used locally.
I have run the drush migrate command and migrate-status shows a bunch of things that are ready for import.
I can import users with drush migrate-import d7_upgrade_users. However the users have custom fields associated with them and I can't find how to import those fields through drush.
Trying to export a csv from the old host is virtually impossible as it crashes out trying to do the export.
Is it possible to import all user data including passwords and custom fields from the command line using drush (or other command line tools) without the need to import everything?
Answer: I am currently working on a similar migration and had a similar problem. In my case the custom fields were part of the Profile2 module in D7. I installed the D8 Profile module and added a patch that fixes the Profile2 import
https://www.drupal.org/files/issues/2018-05-16/profile-migrate-from-profile2-D8-2957256-4.patch
After that, the custom fields were automatically created, populated and linked to the correct user.
Not sure if that is what you need.
Comment: Thanks for that and apologies it took me a while before I saw this answer. I got this working in the end but with some rubbish left over in the DB.


Dynamic Access Controls limit user access to file based on file metadata and SQL Server table

Question: I'm looking into Dynamic Access Controls as a way to limit user access to files in my file share, but I don't know if it can do what I am trying to do.
All of the files in my share have custom metadata that describe the category the file falls into (Finance, Project 1, Project 2, Human Resources, etc.) I also have an SQL table that holds Username -> Category key value pairs.
Is there a way to build a policy that that determines access based on something like this:
File.Category ANY_OF SQL_Table[Username]

Where SQL_Table[Username] is a list of all of the categories the user has access to, as recorded in the SQL table?
I don't want to use Security Groups because I don't want everyone to know who is in what projects, and creating a Security Group would expose the membership
Answer: Dynamic Access Control (DAC) doesn't have any functionality to use SQL Server as a source for authorization information like you're describing. The current versions of the product just don't do that.
Active Directory attributes and file classification properties are the only factors that DAC can take into account when making an authorization decision. You're stuck either using an existing AD attribute or extending the schema to create a new attribute to do what you're looking for.
Hiding security group membership isn't a completely lost cause, though you're definitely changing the default behavior of the product. The US Family Educational Rights and Privacy Act (FERPA) has caused some need in the higher education community for AD groups with hidden membership. There have been some discussions on the ActiveDir.org mailing list about this in the past. The University of Washington Windows Infrastructure article on Course Group Privacy Configuration would be something to look at, too.
Comment: Thank you so much for your information!  Very thorough answer


Create a zip file from a list of selected files and make the zipped file downloadable in Drupal 8

Question: How to create zip file programatically based on the files selected in Drupal 8? Is there any class already existing in Drupal 8?
As per below answer I'm using following code to generate zip file:
$file = \Drupal\file\Entity\File::load($fileId);
$fileUri = \Drupal::service('file_system')->realpath($file->getFileUri());

$zip = \Drupal::service('plugin.manager.archiver')->getInstance(['filepath' => '/foo/bar.zip']);
$zip->add($fileUri);

The bar.zip file above should exist in the referenced path above: /foo/bar.zip.
Also how do I flatten the the zip file folder structure so that the file sites/default/files/myimage.png is myimage.png?
Comment: Yes. Archiver has existed since Drupal 7.
Answer: Use the ArchiverManager and get the instance by calling the getInstance() method. A Zip class is returned. The Drupal Zip class uses PHP's ZipArchive class to perform the heavy lifting.
Example (edited after remark @Clive):
$file = \Drupal\file\Entity\File::load($fileId);
$fileUri = \Drupal::service('file_system')->realpath($file->getFileUri());

$zip = \Drupal::service('plugin.manager.archiver')->getInstance(['filepath' => '/foo/bar.zip']);
$zip->add($fileUri);

Comment: Don't instantiate the object manually, always use services for this type of thing. `$zip = \Drupal::service('plugin.manager.archiver')->getInstance(['filepath' => '/foo/bar.zip']);` (and preferably inject the service if in a viable context too)
Comment: Thanks a lot Clive! Did not realize that it had a service. Updated my answer for future reference.
Comment: I tried your method mentioned above. But when run the code the 'bar.zip' file should exist in the mentioned the path. Also for the given fid the file adding to the zip file by including all the folder structure.. Inside zip file having following folder structure 'sites/defualt/files/myimage.png'. I only want that file alone inside zip file. Not all the file path folders.
Comment: Just found the `getArchive()` method on the `Zip` class. So I would use the `plugin.manager.archiver` service, retrieve the PHP `ZipArchive` class by calling `$zip->getArchive()` and call the `addFile()` method on that. This way you are still using services which is better practice.
Comment: @Gun5m0k3, have any idea on my above comment?
Comment: I am afraid that the Drupal `Zip` class does not provide methods to use a local name. The `add()` method calls the PHP `ZipArchive` method `addFile()` with only the first parameter. I guess that you have to create a `ZipArchive` instance yourself (instead of using the `plugin.manager.archiver` service) and call the `addFile()` method with the full file path and the local file name: `$zip->addFile('full/path/to/myimage.png', 'myimage.png')`.
Comment: Yep!!! I already tried that...It worked.. Thank you.
Comment: For me, once you get the ZipArchive class, you can AddFile(). Once you have finished addFile() on each File entity it was only then this class made the close() method available. Now we're cooking, because without that method my zip file was always 0 bytes and unfinished.
Answer: Below sample code is working fine to create zip file in Drupal 8.
$file = File::load($file_id);
$filename = $file->getFilename();
$file_path = \Drupal::service('file_system')->realpath($file->getFileUri());
$destination = \Drupal::service('file_system')->realpath('public://foldername');
$zip = new \ZipArchive;
$zip->open($destination . "\dump.zip", constant("ZipArchive::CREATE"));
$zip->addFile($file_path, $filename);
$zip->close();

Please check Backup and Migrate module soruce code for more reference.
Note :

Create the destination folder before execute this above code.
Please make sure php zip and gd libraries should be installed and enabled
in the server.
Recommended to use external zip creation library when the server doesn't support zipArchive class.


Durett Example 3.2.4 Waiting for rare events

Question: I am trying to understand  an example in Durret's Probability theory textbook.
Let $X_p$ bet the number of trials needed to get a success in a sequence of independent trials with success probability $p$. Then
$$\mathbb{P}(X_p\ge n)=(1-p)^{n-1}$$
I don't understand how this is true shouldn't
$$\mathbb{P}(X_p\ge n)=\sum_{j=n}^{\infty}(1-p)^{j-1}$$
and then the example states that as $p\rightarrow 0$
$$\mathbb{P}(pX_p\ge x)\rightarrow\text{exp}(-x)$$
I am trying to make sense as to how they went from a discrete to a continuous random variable and concluded with the statement above
Comment: Do you see how he got $e^{-x}$, assuming that the passage to a continuous variable is legitimate?
Comment: @saulspatz I believe that they are simply using $\mathbb{P}(X_p>\frac{x}{p})=(1-p)^{\frac{x}{p}}\rightarrow \text{exp}(-x)$. The part I am missing is how they make that leap of evaluation $\mathbb{P}(X_p>\frac{x}{p})=(1-p)^{\frac{x}{p}}$ assuming what I have above is correct.
Comment: That's it, except that it should be $\mathbb{P}(X_p>\frac{x}{p})=(1-p)^{\frac{x}{p}\color{red}{-1}}\rightarrow \text{exp}(-x)$
Comment: @saulspatz But how are they able to make that leap from a discrete to a continuous
Answer: The probability it takes you $\ge n$ coinflips to get heads is the same as the probability the first $n-1$ coinflips are tails. And that's just $(1-p)^{n-1}$ from independence. I think the formula you wrote down is motivated by $$ P(X_p\ge n) = \sum_{j=n}^\infty P(X_p=j),$$ but $P(X_p=j)$ is not $(1-p)^{j-1},$ it is $p(1-p)^{j-1},$ so we have $$ P(X_p\ge n) = (1-p)^{n-1}=p\sum_{j=n}^\infty (1-p)^{j-1}$$ and you can verify that the infinite sum does work out to make this equation true.
For the second part, $P(pX_p\ge x) = P(X_p\ge x/p)$, and $$ P(X_p\ge x/p) = (1-p)^{\lceil x/p\rceil-1}\to e^{-x}.$$ If you're worried about evaluating that limit with the ceiling function there, you can do it more carefully by observing $x/p\le \lceil x/p\rceil\le x/p+1 $ and using the squeeze theorem.


How to swap two keys in a map

Question: Is there a way to swap two keys in a map in Java?
ex. for list there is Collections.swap(ArrayList,1,2);
Answer: You can use this one liner:
map.put('a', map.put('b', map.get('a')));

Comment: just to clarify this works because map.put() returns the previous value, so when you put the new value of 'b', the return would be the old value, which is then put in 'a'.  Hence the swap.
Answer: If you need to handle boundary cases, like one of the keys not actually being in the map, you can do something like this:
public static <K,V> void swap(Map<K, V> map, K k1, K k2) {
    if (map.containsKey(k1)){
        if (map.containsKey(k2)){
            map.put(k1, map.put(k2, map.get(k1)));
        } else {
            map.put(k2, map.remove(k1));
        }
    } else if (map.containsKey(k2)){
        map.put(k1, map.remove(k2));
    }
}

Otherwise, use the on-liner in Abdullah Jibaly's answer.

How to swap two keys in a map


Definition for non-degenerate module

Question: [QUESTION] If $R$ be a ring, what is the meaning of a non-degenerate $R$-module?
In a previous question post at (What is a non-degenerate module?), some experts said that if $M$ is a $R$-module such that $M=RM:=\{\displaystyle{\sum_{i=1}^n}r_im_i\mid r_i\in R,m_i\in M,n\in\mathbb{Z}_{>0}\}$, then $M$ is called non-degenerate $R$-module.
However, I read the lecture note "REPRESENTATION OF p-ADIC GROUPS" by professor Joseph BERNSTEIN (http://www.math.harvard.edu/~gaitsgde/Jerusalem_2010/GradStudentSeminar/p-adic.pdf), "non-degenerate module" first defined in DEFINITION 4 (2) on page 9, where $\mathcal{H}$ is an algebra and $M$ is a $\mathcal{H}$-module. Then $M$ is called a non-degenerate $\mathcal{H}$-module if $\mathcal{H}M=M$. However it seems that $\mathcal{H}M$ is defined as a set $\{hm\mid h\in\mathcal{H},m\in M\}$ instead of a submodule generated. There are at least two evidences in his note. One is in the proof of LEMMA 4 on page 13, and there is a sentence: "each element $M$ has the form $hm$"; the other is in the proof of LEMMA 7 on page 19, there is another sentence: "there exists an $h\in\mathcal{H}$ such that $hw_1=w_2$".
Hence, I shall be grateful if any expert here who read this note before gives any comment on this question. Thanks!
Answer: There are certainly omissions in the notes, but $\mathcal{H}M$ is not defined as a set; it's a module.  It is, however, equal to the set $\{hm\}$ in this context.
$\mathcal{H}$ is an idempotented algebra, which means that, for any finite collection $h_i\in\mathcal{H}$, there is an idempotent $e\in\mathcal{H}$ with $eh_i = h_i e = h_i$ for all $i$.  This last equality doesn't show up in these notes, which is likely to be an error.
Anyway, if $M$ is non-degenerate, and $m\in M$, then we have $m = \sum_i h_i m_i$.  But, by the definition, there is an idempotent $e\in\mathcal{H}$ such that $eh_i = h_i$ for all $i$.  Then $em = m$, so $m$ is of the required form.
Comment: Oh, yes! "idempotent" is crucial, which makes $\mathcal{H}M:=\{hm\mid h\in\mathcal{H},m\in M\}$ be an $\mathcal{H}$-submodule of $M$. Thank you!!!

Definition for non-degenerate module


Java: How to get intercept on Filter after it returns from the controller

Question: I have implemented a Filter like this but this triggers only when the request is coming in. I would like to intercept the response on its way out i.e. when the response is returned from controller.
I know about Spring Interceptors which give you the functionality to handle the request before and after it hits the controller. I would like to do something like that.
public class ServiceSessionManagementInterceptor implements Filter{

@Override
public void init(FilterConfig filterConfig) throws ServletException {
    // TODO Auto-generated method stub

}

@Override
public void doFilter(ServletRequest request, ServletResponse response,  FilterChain chain) throws IOException, ServletException {
    // TODO Auto-generated method stub
    Map<String, String[]> maps = request.getParameterMap();

    System.out.println("test");
chain.doFilter(request, response);
}

@Override
public void destroy() {
    // TODO Auto-generated method stub

}

}
Comment: Put code after chain.doFilter() that you want executed on the way out.
Answer: The doFilter() is where magic happens. Whatever you put before it will be executed before the servlet and everything you put after it will be executed after the servlet service() method returns (including a forward/include, etc.).
@Override
public void doFilter(ServletRequest request, ServletResponse response,  FilterChain chain) throws IOException, ServletException {

    System.out.println("before");
    chain.doFilter(request, response);
    System.out.println("after");
}

This way you could wrap the ServletRequest and ServletResponse objects with your own implementations to add functionality, ex: compression.
Note that a Spring Interceptor is called before and after the handler method gets executed. A servlet Filter gets executed before and after a Servlet.
Comment: A note , don't try to change anything to the response at that point ( changing Headers, adding cookies, etc) after the doFilter() because the response will most likely be committed already and your action will have no effect
Comment: [FilterChain.doFilter](https://docs.oracle.com/javaee/7/api/javax/servlet/FilterChain.html#doFilter-javax.servlet.ServletRequest-javax.servlet.ServletResponse-) supports the answer.
Comment: @sam so what is the alternative approach to modify response after it returns from controller.
Comment: As you might imagine, I have not a single memory of that subject, after 8 years


Inverse of Cartan matrix

Question: The Cartan matrix of the root system $A_n$ looks like, denote it by $A'_n$
$$A'_n= \begin{bmatrix}
       2 & -1 & 0 & 0&\ldots & 0          \\[0.3em]
       -1 & 2 & -1 & 0 & \ldots & 0 \\[0.3em]
       0 &-1 &2  & -1 & \ldots & 0   \\[0.3em]
      \vdots & & &\ddots & 2& -1  \\[0.3em]
0 & \ldots & & & -1&2
     \end{bmatrix}$$
I need to find the inverse matrix explicitly. I know that $det A'_n=n+1$, using this and the fact that $$b_{ij}:=(A'_n)_{ij}^{-1}=(-1)^{i+j}\frac{\text{det}(A''_n)_{ij}}{\text{det}(A'_n)_{ij}}$$(Where $(A''_n)_{ij}$ is the matrix $A'_n$ with i-th row and j-th column removed) For the first row I could find that $$ b_{1k} =  \frac{n-k+1}{n+1} $$
But this nice pattern does not continue for other rows....
Is there an easier way to approach this problem ? I would appreciate any hints/suggestions/answers for this problem.
Thank you,
Answer: The inverse of the Cartan matrix has the following formula:
$(A_n^{-1})_{ij}=\min\{i,j\}-\frac{ij}{n+1}$, for the inverse of other simple Lie algebra, there is a paper https://arxiv.org/pdf/1711.01294.pdf
Answer: I do not know if this would be helpful, for $A_{6}$ the inverse is the following:
$$
\left(
\begin{array}{cccccc}
 \frac{6}{7} & \frac{5}{7} & \frac{4}{7} & \frac{3}{7} & \frac{2}{7} & \frac{1}{7} \\
 \frac{5}{7} & \frac{10}{7} & \frac{8}{7} & \frac{6}{7} & \frac{4}{7} & \frac{2}{7} \\
 \frac{4}{7} & \frac{8}{7} & \frac{12}{7} & \frac{9}{7} & \frac{6}{7} & \frac{3}{7} \\
 \frac{3}{7} & \frac{6}{7} & \frac{9}{7} & \frac{12}{7} & \frac{8}{7} & \frac{4}{7} \\
 \frac{2}{7} & \frac{4}{7} & \frac{6}{7} & \frac{8}{7} & \frac{10}{7} & \frac{5}{7} \\
 \frac{1}{7} & \frac{2}{7} & \frac{3}{7} & \frac{4}{7} & \frac{5}{7} & \frac{6}{7} \\
\end{array}
\right)
$$
and for $A_{10}$ is the following:
$$
\left(
\begin{array}{cccccccccc}
 \frac{10}{11} & \frac{9}{11} & \frac{8}{11} & \frac{7}{11} & \frac{6}{11} & \frac{5}{11} & \frac{4}{11} & \frac{3}{11} & \frac{2}{11} & \frac{1}{11} \\
 \frac{9}{11} & \frac{18}{11} & \frac{16}{11} & \frac{14}{11} & \frac{12}{11} & \frac{10}{11} & \frac{8}{11} & \frac{6}{11} & \frac{4}{11} & \frac{2}{11} \\
 \frac{8}{11} & \frac{16}{11} & \frac{24}{11} & \frac{21}{11} & \frac{18}{11} & \frac{15}{11} & \frac{12}{11} & \frac{9}{11} & \frac{6}{11} & \frac{3}{11} \\
 \frac{7}{11} & \frac{14}{11} & \frac{21}{11} & \frac{28}{11} & \frac{24}{11} & \frac{20}{11} & \frac{16}{11} & \frac{12}{11} & \frac{8}{11} & \frac{4}{11} \\
 \frac{6}{11} & \frac{12}{11} & \frac{18}{11} & \frac{24}{11} & \frac{30}{11} & \frac{25}{11} & \frac{20}{11} & \frac{15}{11} & \frac{10}{11} & \frac{5}{11} \\
 \frac{5}{11} & \frac{10}{11} & \frac{15}{11} & \frac{20}{11} & \frac{25}{11} & \frac{30}{11} & \frac{24}{11} & \frac{18}{11} & \frac{12}{11} & \frac{6}{11} \\
 \frac{4}{11} & \frac{8}{11} & \frac{12}{11} & \frac{16}{11} & \frac{20}{11} & \frac{24}{11} & \frac{28}{11} & \frac{21}{11} & \frac{14}{11} & \frac{7}{11} \\
 \frac{3}{11} & \frac{6}{11} & \frac{9}{11} & \frac{12}{11} & \frac{15}{11} & \frac{18}{11} & \frac{21}{11} & \frac{24}{11} & \frac{16}{11} & \frac{8}{11} \\
 \frac{2}{11} & \frac{4}{11} & \frac{6}{11} & \frac{8}{11} & \frac{10}{11} & \frac{12}{11} & \frac{14}{11} & \frac{16}{11} & \frac{18}{11} & \frac{9}{11} \\
 \frac{1}{11} & \frac{2}{11} & \frac{3}{11} & \frac{4}{11} & \frac{5}{11} & \frac{6}{11} & \frac{7}{11} & \frac{8}{11} & \frac{9}{11} & \frac{10}{11} \\
\end{array}
\right)
$$
I think the pattern is quite clear, but I do not know what is a good proof of it.
Answer: With a couple of years of delay, I can answer you that on p. 95 of Roselfeld's "Geometry of Lie groups" there are the inverses of the Cartan matrices of simple complex Lie algebras.
EDIT: Up to transposition and without the typos in Rosenfeld, you can also find the same info on p. 295 of Onishchik-Vinberg.

Inverse of Cartan matrix