text:
Q: How do I make Docker forward a packet from remote when a packet from the dockerhost works? I have set up a docker container with a vpn. I added another container with a Squid proxy using the --net option, sharing the same network as the vpn. Running a traceroute from within the container I am able to see that traffic is routed through the vpn. Squid is running in the proxy container on it's default port 3128. If I configure a firefox to use this proxy, 172.17.0.2:3128, it will use the proxy to access the Internet using the vpn. However, why does this only work on my docker host machine? If I try this from my workstation I get a timeout. I can try the same thing using telnet,
On the docker host the following results in a timeout,
torbjorn@base telnet 192.168.1.100 3128

On the docker host the following result in a connection,
torbjorn@base telnet localhost 3128

I made further attempts with tcpdump and route and I get to the conclusion that packets get lost in the first case. One possibility that comes to mind is that perhaps docker added a route so that packets from the docker host is routed back to the host. Is it possible that packets originating somewhere else are routed down the vpn? What can I do to resolve this situation so that I can use this http proxy from other machines than the docker host?
I enabled ip forward on the docker host and on the docker containers.
Creating the docker containers
docker run --cap-add=NET_ADMIN --device /dev/net/tun --name vpn -p 3128:3128 --expose=3128 --volume /home/torbjorn/docker/troyc-openvpn-client:/vpn -d troyc/openvpn

docker run --cap-add=NET_ADMIN --device /dev/net/tun --name proxy -p 3128:3128 --expose=3128 --net=container:vpn --volume /home/torbjorn/docker/squid/cache:/var/spool/squid3 -d sameersbn/squid:3.3.8-5

Checking the containers
torbjorn@base:~$ docker ps
CONTAINER ID        IMAGE                     COMMAND                CREATED             STATUS              PORTS                    NAMES
72273f554ce7        sameersbn/squid:3.3.8-5   "/sbin/entrypoint.sh   2 weeks ago         Up 6 minutes                                 proxy
36161a9eb125        troyc/openvpn             "openvpn --cd /vpn -   2 weeks ago         Up 6 minutes        0.0.0.0:3128->3128/tcp   vpn

routing table of the docker host, containers are running
torbjorn@base:~$ sudo iptables -t nat -L -n
Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination
DOCKER     all  --  0.0.0.0/0            0.0.0.0/0            ADDRTYPE match dst-type LOCAL

Chain INPUT (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
DOCKER     all  --  0.0.0.0/0           !127.0.0.0/8          ADDRTYPE match dst-type LOCAL

Chain POSTROUTING (policy ACCEPT)
target     prot opt source               destination
MASQUERADE  all  --  172.17.0.0/16        0.0.0.0/0
MASQUERADE  tcp  --  172.17.0.2           172.17.0.2           tcp dpt:3128

Chain DOCKER (2 references)
target     prot opt source               destination
DNAT       tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:3128 to:172.17.0.2:3128
torbjorn@base:~$ sudo iptables -L -n
Chain INPUT (policy ACCEPT)
target     prot opt source               destination

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination
DOCKER     all  --  0.0.0.0/0            0.0.0.0/0
ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0            ctstate RELATED,ESTABLISHED
ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0
ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

Chain DOCKER (1 references)
target     prot opt source               destination
ACCEPT     tcp  --  0.0.0.0/0            172.17.0.2           tcp dpt:3128

Gateways of the docker host
torbjorn@base:~$ route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
default         DD-WRT.local    0.0.0.0         UG    0      0        0 eth0
172.17.0.0      *               255.255.0.0     U     0      0        0 docker0
192.168.1.0     *               255.255.255.0   U     1      0        0 eth0

Gateways on the docker container
root@36161a9eb125:/# route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
default         10.114.0.1      128.0.0.0       UG    0      0        0 tun0
10.114.0.0      *               255.255.0.0     U     0      0        0 tun0
128.0.0.0       10.114.0.1      128.0.0.0       UG    0      0        0 tun0
172.17.0.0      *               255.255.0.0     U     0      0        0 eth0
se3.mullvad.net 172.17.42.1     255.255.255.255 UGH   0      0        0 eth0

Some experiment with ip route
root@36161a9eb125:/# ip route get to 192.168.1.100 from 172.17.0.12
192.168.1.100 from 172.17.0.12 via 10.114.0.1 dev tun0
    cache
torbjorn@base:~/docker$ ip route get to 172.17.0.12 from 192.168.1.100
172.17.0.12 from 192.168.1.100 dev docker0
    cache
torbjorn@base:~/docker$ ip route get to 192.168.1.100 from 172.17.0.12
    RTNETLINK answers: Invalid argument

tcpdump
torbjorn@base:~$ docker exec -it proxy tcpdump -vv -n -i any port 3128|tee tcpdump_local.txt
tcpdump: listening on any, link-type LINUX_SLL (Linux cooked), capture size 65535 bytes
17:46:56.045708 IP (tos 0x0, ttl 64, id 7053, offset 0, flags [DF], proto TCP (6), length 60)
    172.17.42.1.42855 > 172.17.0.12.3128: Flags [S], cksum 0x825e (incorrect -> 0x2a32), seq 1327404614, win 29200, options [mss 1460,sackOK,TS val 46042571 ecr 0,nop,wscale 7], length 0
17:46:56.045744 IP (tos 0x0, ttl 64, id 0, offset 0, flags [DF], proto TCP (6), length 60)
    172.17.0.12.3128 > 172.17.42.1.42855: Flags [S.], cksum 0x825e (incorrect -> 0x388b), seq 284840194, ack 1327404615, win 28960, options [mss 1460,sackOK,TS val 46042571 ecr 46042571,nop,wscale 7], length 0
17:46:56.045773 IP (tos 0x0, ttl 64, id 7054, offset 0, flags [DF], proto TCP (6), length 52)
    172.17.42.1.42855 > 172.17.0.12.3128: Flags [.], cksum 0x8256 (incorrect -> 0xd792), seq 1, ack 1, win 229, options [nop,nop,TS val 46042571 ecr 46042571], length 0
17:46:56.045902 IP (tos 0x0, ttl 64, id 7055, offset 0, flags [DF], proto TCP (6), length 130)
    172.17.42.1.42855 > 172.17.0.12.3128: Flags [P.], cksum 0x82a4 (incorrect -> 0x65bd), seq 1:79, ack 1, win 229, options [nop,nop,TS val 46042571 ecr 46042571], length 78
17:46:56.045923 IP (tos 0x0, ttl 64, id 56520, offset 0, flags [DF], proto TCP (6), length 52)
    172.17.0.12.3128 > 172.17.42.1.42855: Flags [.], cksum 0x8256 (incorrect -> 0xd746), seq 1, ack 79, win 227, options [nop,nop,TS val 46042571 ecr 46042571], length 0
17:46:56.046150 IP (tos 0x0, ttl 64, id 56521, offset 0, flags [DF], proto TCP (6), length 2948)
    172.17.0.12.3128 > 172.17.42.1.42855: Flags [.], cksum 0x8da6 (incorrect -> 0x0688), seq 1:2897, ack 79, win 227, options [nop,nop,TS val 46042571 ecr 46042571], length 2896
17:46:56.046177 IP (tos 0x0, ttl 64, id 7056, offset 0, flags [DF], proto TCP (6), length 52)
    172.17.42.1.42855 > 172.17.0.12.3128: Flags [.], cksum 0x8256 (incorrect -> 0xcbc7), seq 79, ack 2897, win 274, options [nop,nop,TS val 46042571 ecr 46042571], length 0
17:46:56.046190 IP (tos 0x0, ttl 64, id 56523, offset 0, flags [DF], proto TCP (6), length 674)
    172.17.0.12.3128 > 172.17.42.1.42855: Flags [P.], cksum 0x84c4 (incorrect -> 0xb67b), seq 2897:3519, ack 79, win 227, options [nop,nop,TS val 46042571 ecr 46042571], length 622
17:46:56.046210 IP (tos 0x0, ttl 64, id 7057, offset 0, flags [DF], proto TCP (6), length 52)
    172.17.42.1.42855 > 172.17.0.12.3128: Flags [.], cksum 0x8256 (incorrect -> 0xc943), seq 79, ack 3519, win 296, options [nop,nop,TS val 46042571 ecr 46042571], length 0
17:46:56.046308 IP (tos 0x0, ttl 64, id 56524, offset 0, flags [DF], proto TCP (6), length 52)
    172.17.0.12.3128 > 172.17.42.1.42855: Flags [F.], cksum 0x8256 (incorrect -> 0xc987), seq 3519, ack 79, win 227, options [nop,nop,TS val 46042571 ecr 46042571], length 0
17:46:56.046464 IP (tos 0x0, ttl 64, id 7058, offset 0, flags [DF], proto TCP (6), length 52)
    172.17.42.1.42855 > 172.17.0.12.3128: Flags [F.], cksum 0x8256 (incorrect -> 0xc940), seq 79, ack 3520, win 296, options [nop,nop,TS val 46042572 ecr 46042571], length 0
17:46:56.046477 IP (tos 0x0, ttl 64, id 56525, offset 0, flags [DF], proto TCP (6), length 52)
    172.17.0.12.3128 > 172.17.42.1.42855: Flags [.], cksum 0x8256 (incorrect -> 0xc984), seq 3520, ack 80, win 227, options [nop,nop,TS val 46042572 ecr 46042572], length 0
^C
12 packets captured
12 packets received by filter
0 packets dropped by kernel
torbjorn@base:~$ docker exec -it proxy tcpdump -vv -n -i any port 3128|tee tcpdump_remote.txt
tcpdump: listening on any, link-type LINUX_SLL (Linux cooked), capture size 65535 bytes
17:47:11.169767 IP (tos 0x0, ttl 64, id 10042, offset 0, flags [DF], proto TCP (6), length 60)
    192.168.1.100.43194 > 172.17.0.12.3128: Flags [S], cksum 0x6e58 (incorrect -> 0xff57), seq 633650090, win 43690, options [mss 65495,sackOK,TS val 46046352 ecr 0,nop,wscale 7], length 0
17:47:12.166358 IP (tos 0x0, ttl 64, id 10043, offset 0, flags [DF], proto TCP (6), length 60)
    192.168.1.100.43194 > 172.17.0.12.3128: Flags [S], cksum 0x6e58 (incorrect -> 0xfe5d), seq 633650090, win 43690, options [mss 65495,sackOK,TS val 46046602 ecr 0,nop,wscale 7], length 0
17:47:14.170364 IP (tos 0x0, ttl 64, id 10044, offset 0, flags [DF], proto TCP (6), length 60)
    192.168.1.100.43194 > 172.17.0.12.3128: Flags [S], cksum 0x6e58 (incorrect -> 0xfc68), seq 633650090, win 43690, options [mss 65495,sackOK,TS val 46047103 ecr 0,nop,wscale 7], length 0
17:47:18.174355 IP (tos 0x0, ttl 64, id 10045, offset 0, flags [DF], proto TCP (6), length 60)
    192.168.1.100.43194 > 172.17.0.12.3128: Flags [S], cksum 0x6e58 (incorrect -> 0xf87f), seq 633650090, win 43690, options [mss 65495,sackOK,TS val 46048104 ecr 0,nop,wscale 7], length 0
17:47:26.190369 IP (tos 0x0, ttl 64, id 10046, offset 0, flags [DF], proto TCP (6), length 60)
    192.168.1.100.43194 > 172.17.0.12.3128: Flags [S], cksum 0x6e58 (incorrect -> 0xf0ab), seq 633650090, win 43690, options [mss 65495,sackOK,TS val 46050108 ecr 0,nop,wscale 7], length 0
17:47:42.206355 IP (tos 0x0, ttl 64, id 10047, offset 0, flags [DF], proto TCP (6), length 60)
    192.168.1.100.43194 > 172.17.0.12.3128: Flags [S], cksum 0x6e58 (incorrect -> 0xe107), seq 633650090, win 43690, options [mss 65495,sackOK,TS val 46054112 ecr 0,nop,wscale 7], length 0
17:48:14.270363 IP (tos 0x0, ttl 64, id 10048, offset 0, flags [DF], proto TCP (6), length 60)
    192.168.1.100.43194 > 172.17.0.12.3128: Flags [S], cksum 0x6e58 (incorrect -> 0xc1b7), seq 633650090, win 43690, options [mss 65495,sackOK,TS val 46062128 ecr 0,nop,wscale 7], length 0
^C
7 packets captured
7 packets received by filter
0 packets dropped by kernel


text:
Q: SQL View: Comparing an initial table with a profiling table to return values not present in initial table I have 2 tables in my database. The first table contains multiple Routes and patrols. Each route may have multiple patrols on it. For each patrol, a number of tags are submitted. The second table contains just routes and tags, basically the complete tag set for that route.
I need to for each patrol return the values from the second table that were not present (aka list the tags that were not recorded on that route and patrol).
**Table:Data Import:**
RouteID
PatrolID
TagID

**Table:Routes**
RouteID
TagID

Does this make sense? I have tried NOT IN, LEFT JOINS, and NOT EXISTS, but I cant seem to get my logic correct. My most recent attempt (in full) was as follows:
Oh and I am creating a view. I would like the coloumns below to be included in my output, but you need not use them in your response.
 CREATE VIEW TagsNotPresent AS
    SELECT
    [Data Import].[Company name],
    [Data Import].[Site name],
    [Data Import].[Patrol ID],
    [Data Import].[Route id],
    [Data Import].[Occurrence date],
    [Data Import].[Tag name]
    FROM [Data Import]
    LEFT OUTER JOIN Routes
    ON Routes.[Route id] = [Data Import].[Route id]
    AND Routes.[Tag name] = [Data Import].[Tag name]
    WHERE Routes.[Tag name] IS NULL

Any help would be much appreciated.

A: EXCEPT may help you:
SELECT r.RouteId,di.PatrolID,r.TagId
    FROM Routes r
    INNER JOIN (SELECT DISTINCT RouteId, PatrolID from DataImport) as di on di.RouteId = r.RouteId
EXCEPT
SELECT RouteId,PatrolID,TagId
FROM DataImport

A: Try it with the minus-SQL-order. I selected all possible route and tag-Combinations and subtracted all existing. I hope that is what you wanted.
  select distinct patrol_id, routes.*
   from data_import
   join routes
   on data_import.route_id = routes.route_id
 minus
   select patrol_id, routes.*
   from data_import
   join routes
   on data_import.route_id = routes.route_id and data_import.tag_id = routes.tag_id;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Web Services vs Server Side Methods With all the front end development frameworks now available.  I'd like to know if the generally accepted protocol is for a back end service to simply provide web services for the front end to consume?
For example: An application that may have displayed products in the past may have just generated the HTML on the server and sent it down to the client browser during the request.  It seems like the preferred way now would be to send the page template to the client, then the front end would make the request to get the list of products and display them using (Angular, Ember, React...)
Are there any performance cost to writing all client/server communication as web services?

A: As you say "web services" (not single service) you will be subjecting your users to multiple network requests to populate your page. This can be a bad thing, http 1.1 introduced the idea of keeping the connection open to request every page element in a single connection as it was quite faster, not to mention more efficient on the server.
There's also a question of security if your data-providing web services are directly connected to your untrusted clients.
As a result of these, its better to architect your page to make a single request to a single server that may then request multiple data sources and aggregate them into a single data set for the client. Whatever might look beautiful to the developer means nothing to the user who is going to have to wait for one block of data to arrive, then watch the page populate another set - it will seem far slower than simply having to wait for the old-style HTML request (regardless of the actual speed).
Of course the best way nowadays would be to use a websocket and stream data to the client continuously. This would require a single server on the back-end to serve this (last thing you want is many sockets opened on your server to serve a single user, that won't scale well)

A: There's a time & place for everything.  Sometimes the right answer is to offer a web service that's consumed by client-side code.
This gives you the benefit of clearly separating your presentation from your model and business logic.  One example is that you could completely replace your web interface with a native app.
There is of course a drawback to using a web service. It's often more complicated to code up, and it requires 2 round trips to the server - one for the template and one for the data.
To answer your question

Are there any performance cost to writing all client/server communication as web services?

Yes - it takes a little more developer concentration to code up and maintain, and it requires 2 round trips to the server to get the template and data.
However, that extra cost is often a good investment and well worth the effort.

A: There is no generally accepted practice.  There are different architectural patterns for web applications.
The server-side presentation pattern has the entire work of generating a page done on ther server side.  The navigation in the application is between pages rendered entirely by the server.  This is the oldest model as it has been supported as long as HTML itself.
The single page application has a server-provided application loader page that may be static.  This page references a fully client-side application that will render pages and obtain content via XHR (large infrequent requests), EventSource (text-based server side events), Websocket (streamed, binary content), or WebRTC (realtime peer to peer audio/video) depending on need.  This is a popular model for recent web applications.
There are also hybrids of both approaches that enable optimizations of page load time and resource consumption.  An often overlooked aspect of web application development is power consumption on mobile devices.  A particularly bad example of this is a periodic XHR to obtain updates.  It will trigger the cellular radio to come on right after it has idled maximizing battery consumption and maximizing latency.
There are no straight forward absolute answers here.  There are some principles with obvious wins though:

*

*Make as few requests as possible

*Send as little data as possible (use efficient representations and compression)

*Take advantage of caching (set Cache-Control and Last-Modified, and Etag headers correctly)

My personal experience with switching from server-side presentation to a single page application was a substantial improvement in responsiveness.  There are definitely downsides to having every data set on the page pulled down in a separate request.  The downsides are directly related to how they violate the principles above.     We had to learn to bundle data sets into fewer requests.
Interestingly with HTTP/2 the bundling is counter-productive because HTTP/2 supports multiple streams (standard requests or otherwise) on a single TCP connection.  Don't spend a lot of energy optimizing for HTTP/1.1 in ways that will hurt your app for HTTP/2.  This trade off is not completely straight-forward either as Khan Academy discovered.
In your case I would advise going with a client-side presentation framework.  It gives you more flexibility in rendering timelines and request counts.  More importantly it gives you an application that doesn't go to a white screen when the server processing a request chokes or disappears.  You can actually handle that as an exception on the client-side and provide user feedback and retry mechanisms.  I do not recommend server-side presentation frameworks except to facilitate more efficient delivery of single page applications.
Much more on this is available in Ilya Grigorik's High Performance Web Browser Networking.


text:
Q: Magento Fatal error: Class not found This is a stretch but hopefully someone has an idea of what's going on here.
I was working on adding a feature to an extension (Amasty Product Grid Editor) to add the in stock status to the grid and allow in-line editing.
I ultimately got this working, but in the process something odd happened.  I now have a problem with a completely unrelated extension (AheadWorks Facebook Integrator).
If the FB extension is enabled, I get almost no output in the browser on any page in the frontend or backend EXCEPT on the product grid in the admin.
On every other page it renders some of the header but bails after it tries to instantiate an instance of the FB Integrator helper class.
It throws this error:

Fatal error: Class 'AW_FBIntegrator_Helper_Data' not found in /var/www/vps_local_5/app/Mage.php on line 520

However, this file is there and all permissions are correct.  The only thing I can figure is that in my failed attempts to get the feature added to the product grid I screwed up the database or something, but I have no idea what would cause it to think that a class file isn't there when it really IS.
The site works fine otherwise if I disable the FB extension. If I disable or even revert my changes to the Product Grid extension it still doesn't work, so it's not a conflict either.
I am leaning towards database only because after I got the changes to the Product Grid extension working correctly on my local dev server I copied those files to our remote dev server and it works great with no issues or conflicts with the FB extension.
So I have to believe that it was something in my iterations that broke something but I'm at a loss as to what.
Any ideas?

A: Try returning the compilation process (Magento Compiler) -- only if you have it currently enabled.
Magento loads from /includes/src/ instead of app/code/local or app/code/community when the compiler is enabled.


text:
Q: How can I configure qmail to send using a different IP per domain? I would like to configure qmail to send email for certain domains using specific IPs for the outbound traffic.  All other domains could continue to use the system's primary IP as usual.  Is this possible?  If so, how would I configure it?

A: If your qmail include the bindroutes patch, and if you know the IP address if the MX you want to connect to, then you could do it, using /var/qmail/control/bindroutes (1.2.3.4 is the IP of the distant MX, 5.6.7.8 is the IP you want to bind, 5.6.7.88 is your "normal" IP):
1.2.3.4:5.6.7.8
:5.6.7.88

A: From my experience and what I searched in the manual, this doesn't seem possible with the unpatched version of qmail.
But, if you use patches from this page (which I use and would recommend anyway because it supports so much sane and interesting features), you can search in that page for the string 'newbind.patch'. The second match will probably give you a good solution to your problem. The main difference from the bindroutes patch is that you can configure IP address binding according to the recipent domain name instead of its IP address (which I find more convenient).
Anyway, I find that the site http://qmail.jms1.net is really useful. It had become my main source of documentation/script/patch in regard to qmail. It definitely deserve a not-so-short visit.


text:
Q: Changing background color if a list-item onClick and reset other items

for (const doc of docs) {
    // create a `div` element
    const div = document.createElement("li");
    div.classList.add("list-group-item");
    div.style.border = "none";

    // add a text node to it
    div.appendChild(document.createTextNode(doc.name));

    // add event listeners to change its background
    div.addEventListener("mouseover", e => { div.style.background = "#e9ecef"; });
    if (div.style.backgroundColor !== "#e9ecef") {
        div.addEventListener("mouseout", e => { div.style.background = "white"; });
    }
    // add a `click` listener
    div.addEventListener("click", e => {
        updateInput(doc);

        var listGroup = document.getElementById("list-group-row").getElementsByTagName('li');
    });

    // add the new div to the container
    container.appendChild(div);
}

This is a loop that I add list-items into my container.
The addEventListener for mouseover and mouseout gives an effect for changing background color when we hover and change back to white when hovered out.
My problem is in the addEventListener click part.
I tried to change the .style.backgroundColor of div, but obviously this changes the color of other list-items to since it's inside a for-loop.
What is the best way to make individual list-item to change backgroundColor onClick and change back when other item is clicked?
I also want to keep the mouseover and mouseout effect.
FULL CODE:
    VSS.getService(VSS.ServiceIds.ExtensionData)
    // the callback on the next line returns a promise, which the JavaScript engine will follow, so you don't need to nest the next `then`
        .then((dataService) => dataService.getDocuments('MyCollection2'))
        .then((docs) => {
            // keep a reference to the element instead of searching for it in each loop.
            const container = document.getElementById('items');

            // this loop will remove any existing children
            while (container.firstChild !== null) {
                container.removeChild(container.firstChild);
            }

            // `for...of` is a simpler way to iterate over a collection
            for (const doc of docs) {
                // create a `div` element
                const div = document.createElement("li");
                div.classList.add("list-group-item");
                div.style.border = "none";

                // add a text node to it
                div.appendChild(document.createTextNode(doc.name));

                // add event listeners to change its background
                div.addEventListener("mouseover", e => { div.style.background = "#e9ecef"; });
                div.addEventListener("mouseout", e => { div.style.background = "white"; });

                // add a `click` listener
                //get all the elements with calss list-group-item
                [...document.querySelectorAll('.list-group-item')].forEach(function(item) {
                    // iterate and add event lstener to each of them
                    item.addEventListener('click', function(elem) {
                        // check if any element have a class active
                        // if so then remove the class from it
                        let getElemWithClass = document.querySelector('.clicked');
                        if (getElemWithClass !== null) {
                            getElemWithClass.classList.remove('clicked');
                            getElemWithClass.classList.add('unClicked')
                        }
                        //add the active class to the element from which click event triggered
                        item.classList.add('clicked')

                    })
                })

                // add the new div to the container
                container.appendChild(div);
            }
        });

A: You may not need to attach the event inside the loop. Create a new function to attach the event but call this function only when the loop have finished it's execution depends on the availability of the element with class list-group-item

//get all the elements with calss list-group-item
[...document.querySelectorAll('.list-group-item')].forEach(function(item) {
  // iterate and add event lstener to each of them
  item.addEventListener('click', function(elem) {
    // check if any element have a class active
    // if so then remove the class from it
    let getElemWithClass = document.querySelector('.active');
    if (getElemWithClass !== null) {
      getElemWithClass.classList.remove('active');
    }
    //add the active class to the element from which click event triggered
    item.classList.add('active')

  })
})
.active {
  color: green;
  font-size: 24px;
}

 1

 2

 3

 4


text:
Q: Find orbits of adjoint representation of $SL(2,\mathbb{R})$ group I am studying group theory and I can't move further than understanding definitions.
So, I've got a group of two-dimensional matrixes with determinant 1 ( $ SL(2,\mathbb{R}))$.
Adjoint representation is defined by: $\operatorname{Ad}_g: h \rightarrow  ghg^{-1}, \forall g \in SL(2,\mathbb{R}), h \in sl(2, \mathbb{R}) $
Orbit of a group element $x$ is $G(x) = \{gx \in X: g \in G\}$ for each g in G.
Could you please explain at least key steps of finding orbits of adjoint representation of $ SL(2,\mathbb{R})$ ?

A: The Lie algebra $\mathfrak{sl}(2,\mathbb{R})$ is the set of $2\times 2$ matrices with real entries and trace 0,
$$\mathfrak{sl}(2,\mathbb{R}) = \{ h\in M_2(\mathbb{R}): \text{tr}(h) = 0\}.$$
As you say, the adjoint action is by matrix conjugation:
$$Ad_g(h) = ghg^{-1}.$$
Let's take a simple orbit and think back to what you know about linear algebra. Take the traceless matrix
$$ h = \left( \begin{array}{cc} 1 & 0 \\ 0 & -1 \end{array}\right).$$
Can you describe the set of matrices of the form $ghg^{-1}$, $g\in SL(2, \mathbb{R})$?  This set is the orbit of $h$,
$$\text{orbit of }h = \left\{ ghg^{-1} : g\in SL(2,\mathbb{R})\right\}.$$
What about a different traceless matrix, such as
$$ h = \left( \begin{array}{cc} 0 & 1 \\ 0 & 0 \end{array}\right)?$$

A: I think the following should be complete, if I am not mistaken somewhere:
$\mathfrak{sl}_2(\mathbb{R})$ are traceless $2\times 2$ matrices. One orbit is the zero orbit containing only the zero matrix, this one should be obvious. Then the orbit generated by the diagonal matrix
\begin{pmatrix}
       a & 0 \\
       0 & -a
   \end{pmatrix}
should contain exactly the matrices with eigenvalues $(a,-a)$. For starters, anything in the same orbit will have said eigenvalues. Then, you can see that conjugation by
\begin{pmatrix}
       1 & -c/2a \\
       0 & 1
\end{pmatrix}
will give you
\begin{pmatrix}
       a & c \\
       0 & -a
\end{pmatrix}
Similarly you can get matrices in the lower block. You can also exchange the position of $a,-a$ by conjugating with
\begin{pmatrix}
       0 & 1 \\
       1 & 0
\end{pmatrix}
I'll leave as an exercise how to get the rest of the matrices with same eigenvalues.
So we have one orbit (these are called semisimple orbits) for each $a\neq 0$. What about $a=0$? Here things become a little more interesting: You actually only have the zero matrix in the one orbit, but there is another orbit generated by
\begin{pmatrix}
       0 & 1 \\
       0 & 0
\end{pmatrix}
This is a nilpotent orbit. By conjugation with one of the matrices previously mentioned (which one?) you can actually also get
\begin{pmatrix}
       0 & 0 \\
       -1 & 0
\end{pmatrix}
which is therefore on the same orbit. What about
\begin{pmatrix}
       0 & -1 \\
       0 & 0
\end{pmatrix}?
Well actually calculations will show you that this belongs in a different orbit (as long as you are in $\mathbb{R}$ you will get a square there when you conjugate!).
To recap (please correct me if I forgot something):
We have one semisimple orbit for each $a\neq 0$. Every semisimple orbit is closed.
Two open nilpotent orbits. Their closure also contains zero.
The zero orbit.
By the way, notice that nilpotent orbits are smaller. Namely, the dimension of the semisimple orbits is 2, as you have a freedom in choosing $b,c$ in
\begin{pmatrix}
       a & b \\
       c & a
\end{pmatrix}
while the dimension of the open nilpotent orbits is 1.


text:
Q: error while using array in C int main() //task 10
{
    int num[9], i, counter = 0, minNum, maxNum = 0, sum = 0;
    for (i = 0; i <= 9; ++i)
    {
        scanf("%d", &num[i]);
        if (num[i] > maxNum)
        {
            maxNum = num[i];
            minNum = maxNum;
        }
        else if (num[i] < minNum)
            minNum = num[i];
        sum += num[i];
    }
    printf("minNum: %d, maxNum: %d\nThe average is:%d\n", minNum, maxNum, sum / 10);
    return 0;
}

While trying to run this program i get this error:
Run-Time Check Failure #2 - Stack around the variable 'num' was corrupted.
I would like to know what is wrong with my array.

A: Using code below you will read the array out of bounds
for (i = 0; i <= 9; ++i)

you can only access elements from 0 up to and including 8 in this case. Change to i < 9.
PS. There maybe other flaws in the logic (check some comments). This one here is also tricky
if (num[i] < minNum)

minNum is not initialized, so if above condition is evaluated in loop first, you will get undefined behaviour due to reading uninitialized variable.

A: Change <=9 in the for loop at the numbering starts at zero. Use <9 instead


text:
Q: Camera Access from iframe of different domain not working I am trying to add site https://example.com/ into https://client.com
I am using the following iframe:
<iframe src='https://example.com/' width='100%' height='675px' allow="geolocation *; microphone *; camera *; midi *; encrypted-media *" mozallowfullscreen='true' allowvr="yes" allowfullscreen="yes" ></iframe>

The camera is getting accessed on desktop but in mobile it's giving the following error:
Call to requestPermission() failed, reason: Source frame did not have the same security origin as the main page.
I have tried allow="camera https://example.com/;" also but in mobile (iphone safari and android chrome) its not getting the camera access.
Can anyone resolve the issue?
PS: we have added CORS headers in the abc.com server

A: allow="geolocation microphone camera midi encrypted-media vr"
Add this attribute to iframe


text:
Q: Rest Assured - Response body verification I have the below response and I need to validate the body.
Json :
[
   "Admin Login",
   "Admin Contact",
   "Administrator",
   "Ads-View"
]

Code :
@Test(groups = {"ITTest"})
public void testAdmin()
{
    com.jayway.restassured.response.Response testAdminResponse = get("/Admin");
    testAdminResponse.then().assertThat().statusCode(200);
    testAdminResponse.then().assertThat().body("$",equalTo("["Admin Login", "Admin Contact", "Administrator", "Ads-View"]"));
}

I tried hamcrest matchers - equalTo, containsString, hasItems, hasItem but all in vain
How do I validate the body completely ?

A: If you are looking to validate the response as a whole and if you know for certain that the response will be of the below format

[
         "Admin Login",
         "Admin Contact",
         "Administrator",
         "Ads-View"
      ]

Then you can, convert the response as a string and use Assert.assertEquals
Assert.assertEquals(**response**, "[\n" +
        "   \"Admin Login\",\n" +
        "   \"Admin Contact\",\n" +
        "   \"Administrator\",\n" +
        "   \"Ads-View\"\n" +
        "]");

I ran it locally and it works fine for me
RestAssured.baseURI = "http://127.0.0.1:3000/Admin";
String **response** = RestAssured.given().
when().get().then().extract().asString();
Assert.assertEquals(response, "");
System.out.println("Body is : " + response);


text:
Q: What is the location for pg_upgrade_dump log file? I am trying to run a pg_upgrade on my existing 12.8 postgres and migrate it to 14.3 with docker based installation. I got the below error :
Performing Upgrade
------------------
Analyzing all rows in the new cluster                       ok
Freezing all rows in the new cluster                        ok
Deleting files from new pg_xact                             ok
Copying old pg_xact to new server                           ok
Setting oldest XID for new cluster                          ok
Setting next transaction ID and epoch for new cluster       ok
Deleting files from new pg_multixact/offsets                ok
Copying old pg_multixact/offsets to new server              ok
Deleting files from new pg_multixact/members                ok
Copying old pg_multixact/members to new server              ok
Setting next multixact ID and offset for new cluster        ok
Resetting WAL archives                                      ok
Setting frozenxid and minmxid counters in new cluster       ok
Restoring global objects in the new cluster                 ok
Restoring database schemas in the new cluster
  template1
  myschema

*failure*

Consult the last few lines of "pg_upgrade_dump_1.log" for
the probable cause of the failure.

Can anyone help me with the location of pg_upgrade_dump_1.log and pg_upgrade_internal.log files?

A: Yes, as the user a_horse_with_no_name mentioned in his comment logs are created in the location where you executed pg_upgrade.
Several files are created like logs dumps and others.


text:
Q: post more than one data in asp.net with C# and get back the response I'm trying to post data at "http://www.indianrail.gov.in/cgi_bin/inet_srcdest_cgi_time.cgi" using asp.net with C#. The problem is that the code that i am using is not able to post more than one data. This code has worked properly when i had posted just one data at "http://www.indianrail.gov.in/cgi_bin/inet_trnnum_cgi.cgi" however this is not working when i am trying to post more than one data. Also there is one hidden field attached with each input data, so what do i have to do with that hidden field.
    ASCIIEncoding encoding = new ASCIIEncoding();
    string postData = "lccp_src_stncode=" + src;
    postData += ("&lccp_dstn_stncode=" + des);
    byte[] data = encoding.GetBytes(postData);
    HttpWebRequest myRequest =  (HttpWebRequest)WebRequest.Create("http://www.indianrail.gov.in/cgi_bin/inet_srcdest_cgi_time.cgi");
    myRequest.Method = "POST";
    myRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0";
    myRequest.ContentType = "application/x-www-form-urlencoded";
    myRequest.ContentLength = data.Length;
    Stream newStream = myRequest.GetRequestStream();
    // Send the data.
    newStream.Write(data, 0, data.Length);
    newStream.Close();

    HttpWebResponse response = (HttpWebResponse)myRequest.GetResponse();

    //Get the stream containing content returned by the server.
    newStream = response.GetResponseStream();

    // Open the stream using a StreamReader for easy access.
    StreamReader reader = new StreamReader(newStream,Encoding.UTF8);

    // Read the content.
    string responseFromServer = reader.ReadToEnd();

    File.WriteAllText(@"C:\Users\Zohaib\Documents\Visual Studio 2010\WebSites\WebSite4\App_Data\data.txt", responseFromServer);
    // Clean up the streams.
    reader.Close();
    newStream.Close();
    response.Close();

A: In a POST you simply provide a stream of data.  Is that stream is to contain "two" things, you simply serialize both to the stream.  In your case, if you want to send more thane one query string parameter, simply add that on to the string before you call GetBytes


text:
Q: Unable to fill missing hours with appropriate values in pandas dataframe I have a dataset which is basically a list of list
data = [[(datetime.datetime(2018, 12, 6, 10, 0), Decimal('7.0000000000000000')), (datetime.datetime(2018, 12, 6, 11, 0), Decimal('2.0000000000000000')), (datetime.datetime(2018, 12, 6, 12, 0), Decimal('43.6666666666666667')), (datetime.datetime(2018, 12, 6, 14, 0), Decimal('8.0000000000000000')), (datetime.datetime(2018, 12, 7, 9, 0), Decimal('12.0000000000000000')), (datetime.datetime(2018, 12, 7, 10, 0), Decimal('2.0000000000000000')), (datetime.datetime(2018, 12, 7, 11, 0), Decimal('2.0000000000000000')), (datetime.datetime(2018, 12, 7, 17, 0), Decimal('2.0000000000000000'))], [(datetime.datetime(2018, 12, 6, 10, 0), 28.5), (datetime.datetime(2018, 12, 6, 11, 0), 12.75), (datetime.datetime(2018, 12, 6, 12, 0), 12.15), (datetime.datetime(2018, 12, 6, 14, 0), 12.75), (datetime.datetime(2018, 12, 7, 9, 0), 12.75), (datetime.datetime(2018, 12, 7, 10, 0), 12.75), (datetime.datetime(2018, 12, 7, 11, 0), 12.75), (datetime.datetime(2018, 12, 7, 17, 0), 12.75)]]

It basically contains two lists each of them with a date and metric column. I need to extract the metric column values of each of the list and find a a coorelation between them.
Note: The dates are similar in each of the list
So first I load each of the list into pandas and set date index.
data1 = data[0]
data2 = data[1]

df1 = pd.DataFrame(data1)
df1[0] = pd.to_datetime(df1[0], errors='coerce')
df1.set_index(0, inplace=True)

df2 = pd.DataFrame(data2)
df2[0] = pd.to_datetime(df2[0], errors='coerce')
df2.set_index(0, inplace=True)

Now I merge the two data frames (both of them share the same dates).
df = pd.merge(df1,df2, how='inner', left_index=True, right_index=True)

Now my data frame looks something like this
                                     1_x    1_y
0
2018-12-06 10:00:00   7.0000000000000000  28.50
2018-12-06 11:00:00   2.0000000000000000  12.75
2018-12-06 12:00:00  43.6666666666666667  12.15
2018-12-06 14:00:00   8.0000000000000000  12.75
2018-12-07 09:00:00  12.0000000000000000  12.75
2018-12-07 10:00:00   2.0000000000000000  12.75
2018-12-07 11:00:00   2.0000000000000000  12.75
2018-12-07 17:00:00   2.0000000000000000  12.75

But if you see the final dataframe, it has missing hours. I need to ensure the missing hours are introduced with approprate values.
Now I saw this example which talks about reindexing https://www.tutorialspoint.com/python_pandas/python_pandas_reindexing.htm but I am not sure how to replicate this in my example. The values must be set using interpolate but this method only gives ffill,bfill and nearest.
How can I add missing hours with approate values?
Note: The dataset is a sql query output.To handle the Decimal type in the output, I used from decimal import Decimal.

A: Try:
df.resample('H').interpolate()

Output:
                          1_x    1_y
0
2018-12-06 10:00:00   7.000000  28.50
2018-12-06 11:00:00   2.000000  12.75
2018-12-06 12:00:00  43.666667  12.15
2018-12-06 13:00:00  25.833333  12.45
2018-12-06 14:00:00   8.000000  12.75
2018-12-06 15:00:00   8.210526  12.75
2018-12-06 16:00:00   8.421053  12.75
2018-12-06 17:00:00   8.631579  12.75
2018-12-06 18:00:00   8.842105  12.75
2018-12-06 19:00:00   9.052632  12.75
2018-12-06 20:00:00   9.263158  12.75
2018-12-06 21:00:00   9.473684  12.75
2018-12-06 22:00:00   9.684211  12.75
2018-12-06 23:00:00   9.894737  12.75
2018-12-07 00:00:00  10.105263  12.75
2018-12-07 01:00:00  10.315789  12.75
2018-12-07 02:00:00  10.526316  12.75
2018-12-07 03:00:00  10.736842  12.75
2018-12-07 04:00:00  10.947368  12.75
2018-12-07 05:00:00  11.157895  12.75
2018-12-07 06:00:00  11.368421  12.75
2018-12-07 07:00:00  11.578947  12.75
2018-12-07 08:00:00  11.789474  12.75
2018-12-07 09:00:00  12.000000  12.75
2018-12-07 10:00:00   2.000000  12.75
2018-12-07 11:00:00   2.000000  12.75
2018-12-07 12:00:00   2.000000  12.75
2018-12-07 13:00:00   2.000000  12.75
2018-12-07 14:00:00   2.000000  12.75
2018-12-07 15:00:00   2.000000  12.75
2018-12-07 16:00:00   2.000000  12.75
2018-12-07 17:00:00   2.000000  12.75


text:
Q: Improper integral limiting result If $\int_{a+}^bfdx$ exists, then show that $\int_{a+}^cfdx$ exists for any $c\in(a,b)$ and $\lim_{c\to a+}\int_{a+}^cfdx=0$.
I proved this as follows.
(i)By Cauchy's criterion, for given $\varepsilon>0$, there is $\delta>0$ such that $a<r\le s<a+\delta$ implies that $|\int_r^sfdx|<\varepsilon$. Fix $c\in(a,b)$. We have
$$
|\int_r^cfdx-\int_s^cfdx|=|\int_r^sfdx|<\varepsilon.
$$
It follows from Cauchy's criterion again that $\int_{a+}^cfdx$ exists for any $c\in(a,b)$.
(ii)Let $I=\int_{a+}^cfdx$. For given $\varepsilon>0$, there is $\delta>0$ such that if $a<d<a+\delta$ then $|I-\int_d^cfdx|<\frac{\varepsilon}{2}$. Fix $d\in(a,a+\delta)$. Since $f$ is Riemann integrable on $[d,c]$, $f$ is bounded on $[d,c]$, i.e. there is $M>0$ such that $|f(x)|\le M$ for all $x\in[d,c]$.
Now, letting $\delta'=\min(\delta,\frac{\varepsilon}{2M})$ and taking $d'<d$ with $c<d'<a+\delta$, we see that if $a<c<a+\delta'$ then
$$
|I|\le|I-\int_{d'}^cfdx|+|\int_{d'}^cfdx|<\frac{\varepsilon}{2}+M\delta'<\varepsilon.
$$
Is this argument correct? Any help will be greatly appreciated.


text:
Q: TensorFlow attention_decoder with RNNCell (state_is_tuple=True) I want to build a seq2seq model with an attention_decoder, and to use MultiRNNCell with LSTMCell as the encoder. Because the TensorFlow code suggests that "This default behaviour (state_is_tuple=False) will soon be deprecated.", I set the state_is_tuple=True for the encoder.
The problem is that, when I pass the state of encoder to attention_decoder, it reports an error:
*** AttributeError: 'LSTMStateTuple' object has no attribute 'get_shape'

This problem seems to be related to the attention() function in seq2seq.py and the _linear() function in rnn_cell.py, in which the code calls the 'get_shape()' function of the 'LSTMStateTuple' object from the initial_state generated by the encoder.
Although the error disappears when I set state_is_tuple=False for the encoder, the program gives the following warning:
WARNING:tensorflow:<tensorflow.python.ops.rnn_cell.LSTMCell object at 0x11763dc50>: Using a concatenated state is slower and will soon be deprecated.  Use state_is_tuple=True.

I would really appreciate if someone can give any instruction about building seq2seq with RNNCell (state_is_tuple=True).

A: I ran into this issue also, the lstm states need to be concatenated or else _linear will complain. The shape of LSTMStateTuple depends on the kind of cell you're using. With a LSTM cell, you can concatenate the states like this:
 query = tf.concat(1,[state[0], state[1]])

If you're using a MultiRNNCell, concatenate the states for each layer first:
 concat_layers = [tf.concat(1,[c,h]) for c,h in state]
 query = tf.concat(1, concat_layers)


text:
Q: Why do indices after 5 print altered and truncated? gallows = [
'''
---------
|       |
|       |
|
|
|
|
|
|
|
|
---------------
''',
'''
---------
|       |
|       |
|       O
|
|
|
|
|
|
|
---------------
''',
'''
---------
|       |
|       |
|       O
|       |
|       |
|
|
|
|
|
---------------
''',
'''
---------
|       |
|       |
|       O
|     __|
|       |
|
|
|
|
|
---------------
''',
'''
---------
|       |
|       |
|       O
|     __|__
|       |
|
|
|
|
|
---------------
''',
'''
---------
|       |
|       |
|       O
|     __|__
|       |
|      /
|     /
|
|
|
---------------
''',
'''
---------
|       |
|       O
|     __|__
|       |
|      / \
|     /   \
|
|
|
|
---------------
''',
'''
---------
|       |
|       X
|     __|__
|       |
|      / \
|     /   \
|
|
|
---------------
''']

counter = 0

for i in range(len(gallows)):
    print(gallows[counter])
    counter += 1

Partial code that is included in a hangman game I am creating for fun.  When printing index 6 and 7, the format of the figure is messed up, and shortened by two lines.  Is python simply truncating the characters in the list due to the length of each index?  I haven't been able to figure out what is happening, or how to get around it.  Any help is greatly appreciated.

A: The special character \ has to be escaped, write \\ instead:
'''
---------
|       |
|       X
|     __|__
|       |
|      / \\
|     /   \\
|
|
|
---------------
'''

A: Put an r at the beginning of each frame
gallows = [
r'''
---------
|       |
|       |
|
|
|
|
|
|
|
|
---------------
''',
r'''
---------
|       |
|       |
|       O
|
|
|
|
|
|
|
---------------
''',
r'''
---------
|       |
|       |
|       O
|       |
|       |
|
|
|
|
|
---------------
''',
r'''
---------
|       |
|       |
|       O
|     __|
|       |
|
|
|
|
|
---------------
''',
r'''
---------
|       |
|       |
|       O
|     __|__
|       |
|
|
|
|
|
---------------
''',
r'''
---------
|       |
|       |
|       O
|     __|__
|       |
|      /
|     /
|
|
|
---------------
''',
r'''
---------
|       |
|       O
|     __|__
|       |
|      / \
|     /   \
|
|
|
|
---------------
''',
r'''
---------
|       |
|       X
|     __|__
|       |
|      / \
|     /   \
|
|
|
---------------
''']

counter = 0

for i in range(len(gallows)):
    print(gallows[counter])
    counter += 1

A: You just add r to the string like this:
r'''
---------
|       |
|       X
|     __|__
|       |
|      / \
|     /   \
|
|
|
---------------
'''


text:
Q: Visualization of scheduling algorithms with matplotlib I am looking for a simple way (if possible) to represent the scheduling of a series of task on a cpu like on slide 5  here.
I would like to have different lines, one for each task, on which I can represent the arrival times, the deadlines and so on. I would like to do it using matplotlib, but at the moment I don't know what is an easy way to do so.

A: I would start with checking the matplotlib gallery for similar plots. Here subplot seem to be appropriate, thus starting with something like this might be an option.
As you want to remove some spines (axis) you can further check this example.
To get filled blocks I would use a standard fill_between or fill call with respective data points, see e.g. this example.
A simple example could be:
import matplotlib.pyplot as plt

cpu1_t = [0,1,1,3,3,4,5]
cpu1_p = [1,1,0,0,1,1,0]
cpu2_t = [0,1,1,3,3,4,5]
cpu2_p = [0,0,1,1,0,0,1]

fig = plt.figure()
# plot 1
ax1 = fig.add_subplot(211)
ax1.fill_between(cpu1_t, cpu1_p,0, color='b', edgecolor='k')
ax1.set_ylabel(r'$\tau_1$', size=14, rotation=0)
# plot 2
ax2 = fig.add_subplot(212)
ax2.fill_between(cpu2_t, cpu2_p,0, color='r', edgecolor='k')
ax2.set_ylabel(r'$\tau_2$', size=14, rotation=0)

# customize axis
for ax in [ax1, ax2]:
    ax.set_ylim(0,2)
    ax.spines['right'].set_visible(False)
    ax.spines['top'].set_visible(False)
    ax.yaxis.set_ticks_position('left')
    ax.xaxis.set_ticks_position('bottom')

You can further play with major and minor grids, ticks, etc.
Of course, this is only one possible approach to create such a plot.


text:
Q: Incorrect memory allocation for Yarn/Spark after automatic setup of Dataproc Cluster I'm trying to run Spark jobs on a Dataproc cluster, but Spark will not start due to Yarn being misconfigured.
I receive the following error when running "spark-shell" from the shell (locally on the master), as well as when uploading a job through the web-GUI and the gcloud command line utility from my local machine:
15/11/08 21:27:16 ERROR org.apache.spark.SparkContext: Error initializing     SparkContext.
java.lang.IllegalArgumentException: Required executor memory (38281+2679 MB) is above the max threshold (20480 MB) of this cluster! Please increase the value of 'yarn.s
cheduler.maximum-allocation-mb'.

I tried modifying the value in /etc/hadoop/conf/yarn-site.xml but it didn't change anything. I don't think it pulls the configuration from that file.
I've tried with multiple cluster combinations, at multiple sites (mainly Europe), and I only got this to work with the low memory version (4-cores, 15 gb memory).
I.e. this is only a problem on the nodes configured for memory higher than the yarn default allows.

A: Sorry about these issues you're running into! It looks like this is part of a known issue where certain memory settings end up computed based on the master machine's size rather than the worker machines' size, and we're hoping to fix this in an upcoming release soon.
There are two current workarounds:

*

*Use a master machine type with memory either equal to or smaller
than    worker machine types.

*Explicitly set spark.executor.memory and spark.executor.cores either using the --conf flag if running from an SSH connection like:
spark-shell --conf spark.executor.memory=4g --conf spark.executor.cores=2

or if running gcloud beta dataproc, use --properties:
gcloud beta dataproc jobs submit spark --properties spark.executor.memory=4g,spark.executor.cores=2

You can adjust the number of cores/memory per executor as necessary; it's fine to err on the side of smaller executors and letting YARN pack lots of executors onto each worker, though you can save some per-executor overhead by setting spark.executor.memory to the full size available in each YARN container and spark.executor.cores to all the cores in each worker.
EDIT: As of January 27th, new Dataproc clusters will now be configured correctly for any combination of master/worker machine types, as mentioned in the release notes.


text:
Q: Problem replacing Fragment within another one. (fragments overlapping) I try go to SaveRouteFragment from RecordRouteFragment. The result is that both fragments are overlapping on each other.
I was searching Internet and didn't find an anwer to my issue, although some people had similar issues with overlapping.

fragment_record_route.xml:
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".features.routerecording.ui.RecordRouteFragment">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/cl_frg_container">

        // content

    </FrameLayout>
</LinearLayout>

fragment_save_route.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

        // content

</androidx.constraintlayout.widget.ConstraintLayout>

onClickListener from RecordRouteFragment.kt
private val btStopRecordOnClick = View.OnClickListener()  {
        stopLocationService()
        viewModel.markRouteAsNotCurrent()

        childFragmentManager.commit {
            replace<SaveRouteFragment>(binding.clFrgContainer.id) //when I replace that with usual R.id.cl_frg_container - nothing changes
            setReorderingAllowed(true)
            addToBackStack("Save a route") // name can be null
        }
    }

What I am doing wrong?

A: I had to change background color of SaveRouteFragment to e.g. white.


text:
Q: SSH: Can I always trust a remote server with dynamic IP? I have a server that I need to connect to sometimes. It has a public IP, but the IP is renewed quite often. To combat that, I have a script that will update a DNS record to map ssh.myurl.com to my new IP.
This setup works, but once the IP changes, I get the error:

WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!

Then I have to delete the key from my client, using ssh-keygen -R ssh.myurl.com, and it works again.
But this seems redundant, as I can't really see how this adds any security. Can I configure this setup so that it always trusts this connection?
The setup is using ProxyJump if that would change anything.


text:
Q: Get subtotals excluding tax for each Tax Rate in Cart summary - Magento 2 I need to calculate the SubTotal for each tax rate in my cart summary.. How can I do this? I found calculation start in module_tax under vendor / magento folder.. but I did not found where to put my hand to change the way subtotals are calculated. I tried copying the folders magento_tax module  / design / frontend / web  / js in my child theme, then I modified some functions related to knockout framework.. but I cannot find a way to extract Tax Subtotals for each Tax Rate..
Any help will be appreciated.
I'm using Magento 2.3.5.
Follow an example of what I need:
In my Cart I have 3 products with 2 tax rates:
Product 1Product 2VAT 22%
Product 3MyTax 10%
In my cart summary I need to show something like this:
TAX SUBTOTALS
tax: VAT 22%    |  subtotal excl tax: 88€ (subtot excl tax of both product 1 and product 2)
tax: MyTax 10%  |  subtotal excl tax: 90€ (subtot excl tax for product 3)
         GrandTotal Excl. TAX    178€ (Totals excluding taxes)
         GrandTotal Incl. TAX    200€ (Total including taxes)

A: Hay yesss, I found a solution so I'm answering to myself, maybe this will be usefull to someone else with the same needing.
N.B. Sorry if the code is not too much pretty, since I'm not a developer... any suggestion or contribution in this way will be appreciated, I'll take care of keeping this post updated.
The files edited are:
vendor/magento/module_tax/view/frontend/web/js/view/checkout/cart/totals/tax.js
vendor/magento/module_tax/view/frontend/web/template/checkout/cart/totals/tax.html
The above files are copied in my child theme under "//Magento_tax/web/" folder, and then modified:

*

*in tax.js added this function at the bottom
 /**
  * return subtotalByRate
  */
 getSubTaxTotal: function (parent, percentage) {
     // get current rate
     var currentRate = percentage;
     // declare subtotalByRate var
     var subtotalByRate = 0;
     // target items in chart measuring array
     var itemsSegment = this.totals()["items"];
     // get qty of items in chart
     var ItemsQty = Object.keys(itemsSegment).length;
     // declare rates var
     var rates = 0;
     rates = parent.rates;
     _.each(rates, function (rate) {
         // extract total for tax rate function
         // start loop for chart items
         for(var i=0; i < ItemsQty ; i++) {
             // check if the item have the same taxRate,  then add rowPrice tax escluded
             if (itemsSegment[i].tax_percent == currentRate) {
                 subtotalByRate = subtotalByRate + itemsSegment[i].base_row_total;
             }
         }
     });
     // the loop is twice (don't know why..) so divide by 2
     subtotalByRate = subtotalByRate/2;
     return this.getFormattedPrice(subtotalByRate);
 }

*in tax.html added this HTML right after "ko forEach: rates" statement

This is the result on my cart


text:
Q: Template Formatting in v-for in vue.js This code give me all player value & then all monster value. But I want the output format will be like: one player value then one monster value   ,,  one player value then one monster value

new Vue({
  el: app,
  data: {
    output: {
      player: [1, 5, 61, 98, 15, 315, 154, 65],
      monster: [2,14, 15, 113, 19, 22,12,54,64],
    },
  },
});

Player value :{{pla}}

Monster value :{{mon}}

A: Loop through index, and wrap the player and monster in a template:

new Vue({
  el: app,
  data: {
    output: {
      player: [1, 5, 61, 98, 15, 315, 154, 65],
      monster: [2,14, 15, 113, 19, 22,12,54,64],
    },
  },
});

    <template v-for="i in output.player.length" :key="i">

Player value :{{output.player[i]}}

Monster value :{{output.monster[i]}}

    </template>

Note: This assumes player and monster always have the same length, you need to handle the edge cases if they are not the same size.


text:
Q: kurento: How to pass guint8 * to java server as an int[] I am trying to send the GstBuffer objects map.data to the java server. I have created an event with a parameter as int[] but when raising the event I am getting the following error at compile time.
error: no matching function for call to 'kurento::module::vadcustomfilter::BufferReceived::BufferReceived(std::shared_ptr<kurento::MediaObject>, const char [16], int*)'

BufferReceived event (shared_from_this (), "Buffer Received", ((int *)buffer));

map.data is of type guint8 *
is there something wrong am doing in type casting ?
I tried sending map.data as std::string but at java side I am not receiving the complete string.

A: Casting guint8* to char* is fine, because only the sign changes. Casting to int * is not OK because the size is different, in order to send this kind of events, you may need to copy the array of guint8 to an array of int. But think that this is not a fast operation, nor serializing this big event, so do not expect to have a great performance.
Furthermore, what kurento events expects (you should check the signature of BufferReceived) when you declare an array is a std::vector<int>, so in any case you need to create the array and copy the content.


text:
Q: How to deploy sagemaker.workflow.pipeline.Pipeline? I have a sagemaker.workflow.pipeline.Pipeline which contains multiple sagemaker.workflow.steps.ProcessingStep and each ProcessingStep contains sagemaker.processing.ScriptProcessor.
The current pipeline graph look like the below shown image. It will take data from multiple sources from S3, process it and create a final dataset using the data from previous steps.

As the Pipeline object doesn't support .deploy method, how to deploy this pipeline?
While inference/scoring, When we receive a raw data(single row for each source), how to trigger the pipeline?
or Sagemaker Pipeline is designed for only data processing and model training on huge/batch data? Not for the inference with the single data point?

A:
As the Pipeline object doesn't support .deploy method, how to deploy this pipeline?

Pipeline does not have a .deploy() method, no
Use pipeline.upsert(role_arn='...') to create/update the pipeline definition to SageMaker, then call pipeline.start() . Docs here

While inference/scoring, When we receive a raw data(single row for each source), how to trigger the pipeline?

There are actually two types of pipelines in SageMaker. Model Building Pipelines (which you have in your question), and Serial Inference Pipelines, which are used for Inference. AWS definitely should have called the former "workflows"
You can use a model building pipeline to setup a serial inference pipeline
To do pre-processing in a serial inference pipeline, you want to train an encoder/estimator (such as SKLearn) and save its model. Then train a learning algorithm, and save its model, then create a PipelineModel using both models


text:
Q: Libgdx how to get event on keypress? I'm newbie , i want make game like mario and i got problem about key press . This is my code.
public class MyGdxGame extends ApplicationAdapter implements InputProcessor{

private TextureAtlas myTexture;
private SpriteBatch sprite;
private TextureRegion solider;
private Vector2 position=new Vector2(0,0);

    @Override
    public void create () {
        sprite= new SpriteBatch();
        myTexture=new TextureAtlas("metal-slug.txt");
        solider=myTexture.findRegion("solider-run");
        Gdx.input.setInputProcessor(this);
}
    @Override
    public void render () {
        Gdx.gl.glClearColor(1, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        sprite.begin();
        sprite.draw(solider, position.x, 0);
        sprite.end();
}
    @Override
    public boolean keyDown(int keycode) {
        if (keycode== Keys.D){
            position.x+=10;
        }
        if (keycode== Keys.A){
            position.x-=10;
        }
        return false;
    }

    }

problem is object just move when i press key but when key release it stop ,  I want when press and hold key, object should move to right screen .

A: you can move your object by using a variable move.
public class MyGdxGame extends ApplicationAdapter implements  InputProcessor     {

  private TextureAtlas myTexture;
  private SpriteBatch sprite;
  private TextureRegion solider;
  private Vector2 position=new Vector2(0,0);
  private float move=0f;

@Override
public void create () {
    sprite= new SpriteBatch();
    myTexture=new TextureAtlas("metal-slug.txt");
    solider=myTexture.findRegion("solider-run");
    Gdx.input.setInputProcessor(this);
 }
@Override
public void render () {
    Gdx.gl.glClearColor(1, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    sprite.begin();
    sprite.draw(solider, position.x+move, 0);
    sprite.end();
}
@Override
public boolean keyDown(int keycode) {
    if (keycode== Keys.D){
        move=1;
    }
    if (keycode== Keys.A){
        move=-1;
    }
    return false;
}

}


text:
Q: Add OR WHERE statement in codeigniter using foreach loop I am using codeigniter framework and i want to create a OR WHERE statement using foreach loop,
Below is my code,
$wh_q = array('ec_date >' => $start, 'ec_date <=' => $end);

This will produce query as WHERE ec_details.date > '2016-11-01 00:00:00' AND ec_details.date <= '2017-01-07 00:00:00'
Now i want to append few more criteria in abover query string with AND ec_details.user_id = '5' OR ec_details.user_id = '6' and so on.
Now user_id, 5 and 6 are coming from array results,
$user_string = '5,6';
$users_array = explode(",",$user_string);

foreach ($users_array as $user) {
   $query = array('ec_details.user_id' => $user);
}

Then i am merging above $query array in original $wh_q array
$wh_q = array_merge($wh_q, $query);

And finally i select where as below,
$this->db->where($wh_q);

But this will not produce my required query, but will just create like below,
`WHERE `ec_details`.`date` > '2016-11-01 00:00:00' AND `ec_details`.`date` <= '2017-01-07 00:00:00'`AND `ec_details`.`user_id` = '6'`

How can i add AND OR WHERE statements using foreach loop in codeigniter?
Thank you,

A: You can try like this,
create a complete where string like this
$where = "name='Joe' AND status='boss' OR status='active'";
$this->db->where($where);

And check, this will work.
EDIT
OR you can give or condition like this
$this->db->where('name !=', $name);
$this->db->or_where('id >', $id);  // Produces: WHERE name != 'Joe' OR id > 50

A: Try as below...
$wh_q = array('ec_date >' => $start, 'ec_date <=' => $end);//condition first

$user_string = '5,6';
$users_array = explode(",",$user_string);

foreach ($users_array as $user) {
   $query []= array('ec_details.user_id' => $user);//second condition
}

//print_r($query) //multidimensional array

Query
$this->db->where($wh_q);

$total = count($query);
for($i=0;$i<$total;$i++){
    $this->db->or_where($query[$i]);
    }

A: If you you need to check only user id then better you can also user IN like below.
$user_string = '5,6'; $users_array = explode(",",$user_string);
$this->db->where_in('id', $users_array);

and If you want to use only OR and And statement
then use below code
$this->db->where('ec_date >',$start,false);
$this->db->where('ec_date <=', $end,false);
$user_string = '5,6';
$users_array = explode(",",$user_string);
$userqry = array();
foreach ($users_array as $user) {
   $userqry[] = "ec_details.user_id ='".$user."'";
}
$userqrystr = implode(" OR ",  $userqry);
$this->db->where($userqrystr,false,false);

This query look like
WHERE `ec_details`.`date` > '2016-11-01 00:00:00' AND `ec_details`.`date` <= '2017-01-07 00:00:00' AND (`ec_details`.`user_id` = '6' OR `ec_details`.`user_id` = '5')


text:
Q: AttributeError: function 'GetWindowLongPtrW' not found This is on windows x64 for python 2.7
from ctypes import *
user32 = windll.user32
GWL_STYLE = -16
style = c_long(0)
pstyle = pointer(style)
pstyle = user32.GetWindowLongPtrW(hwnd, GWL_STYLE)

Am getting the error in title.  Is this function not supported in ctypes? I'm using other user32 functions in this pyscript without a problem.

A: You need to use GetWindowLongW in a 32-bit process, and GetWindowLongPtrW in a 64-bit process.

A: Solved my problem. I had a 32 bit version of python installed on 64 bit windows 7. Above code worked after installing Python 2.7.8 x64.


text:
Q: Preferences not up-to-date when read from service I have the a very simple preferences implementation in my app. This is my Preferences activity:
public class Preferences extends PreferenceActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
    }
}

Every activity or service that reads preferences does this:
preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

Now, one of the settings is a server the app connects to. This is implemented as an unbound service because it's supposed to remain online even when the user left the app. When the service starts (onStartCommand), the socket information is read from the preferences.
The problem: After changing a preference and restarting the service it still has the old value.
I don't get it! Please help :)

Here's a little more detail since its still not working. My guess my error lies somewhere else ...
My service looks as follows.
public class XMPPService2 extends Service {
    SharedPreferences preferences;

public void onCreate() { ... }

public int onStartCommand(Intent intent, int flags, int startId) {
    preferences = getSharedPreferences("com.company.appname_preferences.xml", MODE_MULTI_PROCESS);
    Log.d(TAG, preferences.getString("server", "DEFAULT")); // this always prints the default value
}

public void onDestroy() { ... }

}

As far as I understand, there is not much more I have to do about it. I've also tried to
getPreferenceManager().setSharedPreferencesMode(MODE_MULTI_PROCESS);

before
addPreferencesFromResource(R.xml.preferences);

but this didn't help.
Now, I know that these methods are deprecated. However, I have to make sure the app runs on tablets as well as 2.3 devices.
I just wanted to mention that I'm still new to android and maybe I've misunderstood some basic concept. The answers I've gotten coincide with my web research, so i expect them to be correct.

A: If you are trying to access a shared preference from a different process (even though they are in same package), you need to use MODE_MULTIPROCESS.
Please use the following code:
 SharedPreferences pref = getSharedPreferences("com.mypackage.myapp_preferences", MODE_MULTI_PROCESS);

The important thing is to use MODE_MULTI_PROCESS and name of your preference file.

A: To share the preferences between processes, you need to have *MODE_MULTI_PROCESS* set on the preferences file. Problem is that you can't control flags of the default preferences file, right?
Well, There's a way. In your PreferenceActivity class, add these lines to onCreate():
PreferenceManager prefMgr = getPreferenceManager();
prefMgr.setSharedPreferencesName("preferences");
prefMgr.setSharedPreferencesMode(MODE_MULTI_PROCESS);

Then instead of using PreferenceManager.getDefaultSharedPreferences, get the preferences from the file using:
getSharedPreferences("preferences", MODE_MULTI_PROCESS);

A: It could be because the method addPreferencesFromResource() is depreciated in API 11:
Read more here
More likely there is a problem with how the preference is being committed. Could you post your XML?

A: You have to read your preferences from the same package. Move your service to the same package as the preference activity and you are done.

A: it seems to be a bug in android: https://code.google.com/p/android/issues/detail?id=66625


text:
Q: Wrong local state value when a handling a window event (React) I have a state value ccFormDetails with a an empty object as default value.
  const [ccFormDetails, setCCFormDetails] = useState({})

In first useEffect, I call a function the populates ccFormDetails with relevant data.
  const getCCFormData = async () => {
    const ccFormResult = await ContractService.getContractsCCFormData()
    const { ccFormData } = ccFormResult
    setCCFormDetails(ccFormData)
  }

In second useEffect, I create an a event named message and assign a handleCgEvent handler to it.
  useEffect(() => {
    window.addEventListener('message', handleCgEvent)
    return () => window.removeEventListener('message', handleCgEvent)
  }, [])

I'm rendering an iframe with a submit button that emits the message event when clicked.
Then, when I click the sumbit button in the iframe, the handleCgEvent handler fires and should extract the correct (updated, fecthed) value of ccFormDetails. (Which I can see populated correctly in the React components tree)
  const handleCgEvent = e => {
    if (e.data === 'reload_cg') {
      console.log('fail')
    }

    if (e.data['event_id'] === 'cg-success') {
      console.log('success')
      console.log('ccFormDetails1 ', ccFormDetails)
    }
  }

But what I get is {} meaning the original default state.
This should not happen per my knowledge of React.
Am I missing something/Does event handling messes state?

A: The problem here is you're using the handleCgEvent that's created when the component is mounted, and ccFormDetails is encapsulated within it using its default value. In order to get the most current state, you're going to have to use useRef. Something like:
  const [ccFormDetails, setCCFormDetails] = useState({})
  const formRef = useRef();

  formRef.current = ccFormDetails;

  const handleCgEvent = e => {
    if (e.data === 'reload_cg') {
      console.log('fail')
    }

    if (e.data['event_id'] === 'cg-success') {
      console.log('success')
      console.log('ccFormDetails1 ', formRef.current)
    }
  }

  useEffect(() => {
    window.addEventListener('message', handleCgEvent)
    return () => window.removeEventListener('message', handleCgEvent)
  }, []);

If it's okay for you to add and remove the event listener, then I would just add [ccFormDetails] as a dependency, assuming the entire object is recreated when its properties change.
For further reading about stale values in closures, this is a great blog entry: https://dmitripavlutin.com/react-hooks-stale-closures/


text:
Q: Django Form - Pass Extra Arguments (Dynamic Form Creation) I am trying to pass extra parameters (not provided by the Forms) in customize my template
In this case I am passing an icon font.
class AddForm(forms.Form):
    def __init__(self, *args, **kwargs):
      *passing some args*
       self.fields[field_key] = forms.CharField(**field_args)
       self.fields[field_key].icon = 'fa-font'

template.html
{% for field in form%}
    {{field.icon}}
    {{field}}
{% endfor %}

When I render the form to to the view, no icon is printed out.
How can I pass extra parameters to a form field?

A: Yeah sure bcs when you use constructor init in form you can change only values of your field like:
just_value = models.ModelChoiceField(
        queryset=YourModel.objects.none())

And then you can pass only .queryest in init
self.fields['just_value'].queryset = YourModel.objects.filter(something_there)

Im not sure about icons but you can style your field by add widget attrs:
just_value = models.ModelChoiceField(
        queryset=YourModel.objects.none(),
        widget=attrs{'class':'form-class')

I would like to recommend you package 'django-widget-tweaks` and render every of your fieild with {% render_field %}


text:
Q: How Do I Save The Connection Socket Writing Later In Nodejs? I'm trying to keep a tcp socket open after it successfully connects so I can write something through it later. Here is my attempt at doing that:
var sock = null;

var server = require('net').createServer( function (socket) {
  sock = socket;

  socket.on('data', function (data) {
    console.log(data.toString());
  });

});

server.listen(10005);

if (sock != null) {
  sock.write('command', 'utf-8');
else {
  console.log('sock is null');
}

I didn't realize it's asynchronous so the null check on sock happens first before the connectionCallback. I came from a C++ background so this is how I was trained to think program-atically. What is the proper way to do this in javascript?
I want the user to be able to write data through the connection socket. I want to reuse that same socket that was successfully connected for writing.
Thanks.

A: Instead of storing socket in a variable I would write a function to handle writing that would be called when the socket is created. Something like this:
function handleSocket(socket) {
  socket.write('command', 'utf-8')
}

var server = require('net').createServer(function (socket) {
  socket.on('data', function (data) {
    console.log(data.toString());
  });

  handleSocket(socket);
});

server.listen(10005);

I am not sure what else you want to do with the socket, but the pattern would be the same - you get some data and conditionally call some callback.


text: Q: Icon not show in google search result + description (react js) i have issue regarding my favicon not appearing in google search result + some time my description not show insteads it show you need to enable javascript to run this app


text:
Q: How to get difference between sql objects in Azure Sql database vs that created from sqlproj? Problem: We need to remove dead sql objects(tables,views,stored procs,etc) from Azure sql database which some devs have directly created on the sql db which are not in use and are not part of sql db projects(sqlproj).
So i wanted to know if there is a way to identify those dead sql objects or find out the difference between sql objects in Sql database vs that created from sqlproj ?
Is there a flag in Sql server Data tools which can help achieve this or anything which can get me the difference?

A: You can deploy using /Action:DeployReport
https://msdn.microsoft.com/library/hh550080(vs.103).aspx#Anchor_5
This will give you a list of objects which:

*

*Exist on both but are different

*Exist only in the dacpac

*Exist only in the live database

You can also do this using the compare tool inside visual studio (ssdt) or use something like redgate sql compare - if this is a one off I would probably just use that as I prefer the ui but I have a copy of it so can :)
This problem is normally solved by just deploying and anything in the database which isn't in source control is removed. If you always follow the process of deploying from dacpac you can't get in this situation.
It sounds like you probably want to do a one time thing to find out what is different and maybe test those changes somewhere before you drop them.
Everyone working with ssdt has at some point had this exact issue and the only way to fix it is to get either the sqlproj or the database into a known state and keep deploying from dacpac.
ed

A: You can use the Schema Compare Options available on SQL Server Data Tools (SSDT) as explained here and here.
You can download SSDT for free from here.
Hope this helps.


text:
Q: Saving users current location as geopoint using parse.com in javaScript Hi there I am new to javaScript. What I would like to do is get the users location and save it as a geoPoint to my parse.com database. I have searched their docs and worked out the basics of how to do it but need a little help. I am getting the geoPoint by performing the following:
var point = new Parse.GeoPoint.current;

and trying to save it by performing:
testObject.set("geoPoint", point);

In my geoPoint column on parse.com it gets saved as {"_rejected":false,"_rejectedCallbacks":[],"_resolved":false,"_resolvedCallbacks":[]}
I'm assuming this is because the location is attempting to be saved before the location has actually been found.
So my question is how do I wait until the location is found before sending it to parse?
In the parse docs they say to use Parse.GeoPoint.current(options)
but I'm not too sure how to go about this options part. I'm really hoping someone can give me some sample code on how to use options.success
Thanks for your time!

A:
 Parse.GeoPoint.current(options) Creates a GeoPoint with the
  user's current location, if available. Calls options.success with a
  new GeoPoint instance or calls options.error. Parameters: {Object}
  options An object with success and error callbacks.
  - https://www.parse.com/docs/js/symbols/Parse.GeoPoint.html

Bascially, you can do:
Parse.GeoPoint.current({
    success: function (point) {
        //use current location
        console.log(point);
    }
});


text:
Q: Deploying Machine Learning model to AzureML Web Service - how to deal with extreme high dimensionality? I want to deploy a Sklearn knn model onto Azure ML Web Service according the following tutorial.
from azureml import services
from sklearn.neighbors import KNeighborsClassifier

knn_model = KNeighborsClassifier(n_neighbors=5, n_jobs=-1, algorithm="auto")
knn_model.fit(X_train, Y_train)

@services.publish(workspace_id, authorization_token)
@services.types(input_1=int, input_2=int, input_3=int, input_4=int)
@services.returns(int)
def my_knn_predictor(input_1, input_2, input_3, input_4):
    return knn_model.predict([input_1, input_2, input_3, input_4])

This works indeed, but in the meantime I have to deploy a model where both the input and output dimensionality is very high (magnitude of thousands) so I do not want to type in the input_1, input_2, input_3, input_4 ... variable sequences by hand. Is there a way to extract these as a list from the X_train and Y_train and feed this list into the my_knn_predictor input/output definition? (Simple copy of the data frame headers is not enough because I have to add =int to the column names and remove the quotation marks.)


text:
Q: Is it possible to tell which hash algorithm generated these strings? I have pairs of email addresses and hashes, can you tell what's being used to create them?
aaaaaaa@aaaaa.com
BeRs114JrR0sBpueyEmnOWZfnLuigYTA

and
aaaaaaaaaaaaa.bbbbbbbbbbbb@cccccccccccc.com
4KoujQHr3N2wHWBLQBy%2b26t8GgVRTqSEmKduST9BqPYV6wBZF4IfebJS%2fxYVvIvR

and
r.r@a.com
819kwGAcTsMw3DndEVzu%2fA%3d%3d

A: First, the obvious even if you know nothing about cryptography: the percent signs are URL encoding; decoding that gives
BeRs114JrR0sBpueyEmnOWZfnLuigYTA
4KoujQHr3N2wHWBLQBy+26t8GgVRTqSEmKduST9BqPYV6wBZF4IfebJS/xYVvIvR
819kwGAcTsMw3DndEVzu/A==

And that in turn is base64. The lengths of the encodings wrt the length of the original strings are
plaintext  encoding
17         24
43         48
10         16

More samples would give more confidence, but it's fairly clear that the encoding pads the plaintext to a multiple of 8 bytes. That suggest a block cipher (it can't be a hash since a hash would be fixed-size). The de facto standard block algorithm is AES which uses 16-byte blocks; 24 is not a multiple of 16 so that's out. The most common block algorithm with a block size of 8 (which fits the data) is DES; 3DES or blowfish or something even rarer is also a possibility but DES is what I'd put my money on.
Since it's a cipher, there must be a key somewhere. It might be in a configuration file, or hard-coded in the source code. If all you have is the binary, you should be able to locate it with the help of a debugger. With DES, you could find the key by brute force (because a key is only 56 bits and that's doable by renting a bit of CPU time on Amazon) but finding it in the program would be easier.
If you want to reproduce the algorithm then you'll also need to figure out the mode of operation. Here one clue is that the encoding is never more than 7 bytes longer than the plaintext, so there's no room for an initialization vector. If the developers who made that software did a horrible job they might have used ECB. If they made a slightly less horrible job they might have used CBC or (much less likely) some other mode with a constant IV. If they did an again slightly less horrible job then the IV may be derived from some other characteristic of the account. You can refine the analysis by testing some patterns:

*

*If the encoding of abcdefghabcdefgh@example.com (starting with two identical 8-byte blocks) starts with two identical 8-byte blocks, it's ECB.

*If the encoding of abcdefgh1@example.com and abcdefgh2@example.com (differing at the 9th character) have identical first blocks, it's CBC (probably) with a constant IV.

Another thing you'll need to figure out is the padding mode. There are a few common ones. That's a bit harder to figure out as a black box except with ECB.

A: There are some tools online, and also some open source projects. For example:
https://code.google.com/archive/p/hash-identifier/
http://www.insidepro.com/


text:
Q: Compression while uploading scanned documents in Alfresco. Managing bulk of data Considering Alfresco as an ECM, how one can manage bulk amount of data in it?Usually scanned(black and white) image with 150 dpi is of 274K, thousands of such scanned images would be uploaded each day. Reducing the size of file using compression mechanism such as ccitt G4 or JBIG2 would be helpful.
I am new in this enterprise solution, please guide me how can I achieve this efficient handling of data to reduce the need of expensive hardware architecture. If it's not the responsibility of Alfresco then what other alternate approach should I adopt.

A: I hope you have found a solution in the meantime. When not and for the others who have the same question, Axel Faust further developed on his alfresco-simple-content-stores github project a compressingstore. You can install/integrate this project in your own and configure for which type of mimetypes of files you want to compress and how. This is a low level solution as it is totally transparent for the user and the compression is done when storing the document on the disk and decompressing when reading it to the user.
Hope it helps


text:
Q: Как получить произвольное количество GET параметров через MOD_REWRITE? Есть ссылки вида:
www.site.ru/city123
www.site.ru/city123/type54/project1198
www.site.ru/project1198/type54/

Иными словами, количество параметров (буквы+цифры) может быть произвольным, а может и вообще не быть.
вот такой код, помогает получить только первую пару буквы+цифры
RewriteRule ^([a-z]*)([0-9]*)/*$ index.php?$1=$2%{QUERY_STRING}

На выходе имею:
$_GET[city] => 123

Как в этом случае получить все GET параметры, если их количество может быть произвольным либо не быть вовсе?

A: Через .htaccess таким способом можно получить только 4 параметра, так как всего на группы с обратной связью выделено 9 позиций ($1 - $9) + $0 - вся строка запроса.
Пример
RewriteEngine On
RewriteRule ^([a-z]+)(\d+)/?$ index.php?$1=$2 [L,QSA]
RewriteRule ^([a-z]+)(\d+)/([a-z]+)(\d+)/?$ index.php?$1=$2&$3=$4 [L,QSA]
RewriteRule ^([a-z]+)(\d+)/([a-z]+)(\d+)/([a-z]+)(\d+)/?$ index.php?$1=$2&$3=$4&$5=$6 [L,QSA]
RewriteRule ^([a-z]+)(\d+)/([a-z]+)(\d+)/([a-z]+)(\d+)/([a-z]+)(\d+)/?$ index.php?$1=$2&$3=$4&$5=$6&$7=$8 [L,QSA]

Правильнее будет переадресовать запросы такого вида в роутер написаный на php, который будет разбирать строку запроса и формировать переменные на ее основе:


text:
Q: laravel 4 output json order desc I use laravel 4.2
How can I output json in desc order? Thanks.
Below is my code :
public function show($id) {
    $member = $this->getMember ();
    $transition = $member->getTransition ( $id )->first ();
    $transition_info = $transition-> transitionInfo;
    return ResponseWrapper::toJson ( $transition_info );
}

...
public function index() {
    $member = $this->getMember ();
    $transitions = $member->getTransitions ();

    return ResponseWrapper::toJson ( $transitions );
}

/* 12/28 update */
Maybe I should change in below model?
 (project/app/models/Member.php)
public function getTransitions()

{
$array = $this->hasMany('Transition', 'payeer_id', 'id')->select($this->transition_index_payeer_column)->get()->all();

$arrayb = $this->hasMany('Transition', 'remitter_id', 'id')->select($this->transition_index_remitter_column)->whereRaw('NOT (card_type_remitter = "focas" and focas_status = "")')->get()->all();

$reuslt = array_merge ( $array, $arrayb );
return $reuslt;
}

A: You should try this:
public function index() {

    $member = $this->getMember ();
    $transitions = $member->orderBy('id','desc')->getTransitions ();

    return ResponseWrapper::toJson ( $transitions );

}

A: Try this one,
public function index() {

    $member = $this->getMember ();
    $transitions = $member->getTransitions()->orderBy('id','desc')->get();

    return ResponseWrapper::toJson ( $transitions );

}

A: For Laravel V4 :
 $transitions = $member::orderBy('id', 'DESC')->getTransitions();


text:
Q: Left-to-right Tree in LaTex, not top-to-bottom? I'm looking to draw a tree where the root is on the left and each child node is drawn to the right.
It seems that the qtree package can't do this. Any one have any ideas?
I've found this document, which seems like it might help, but it's a bit obtuse.

A: Take a look at TikZ trees, it can be done here, by setting the parameter grow=right.
For example:
http://media.texample.net/tikz/examples/PNG/probability-tree.png
[Taken from the TikZ website]


text:
Q: NullPointerException: Starting a method with OnClickListener I am just trying to setOnClickListener to a method on a an image button and it leads to null pointer exception error.
Logcat shown below:
02-25 10:49:43.051 13936-13936/com.example.l33902.contactmanagment1512 E/AndroidRuntime: FATAL EXCEPTION: main
   Process: com.example.l33902.contactmanagment1512, PID: 13936
   java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.l33902.contactmanagment1512/com.example.l33902.contactmanagment.EditActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageButton.setOnClickListener(android.view.View$OnClickListener)' on a null object referenceat android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3155)
   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3263)
   at android.app.ActivityThread.access$1000(ActivityThread.java:197)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1687)
   at android.os.Handler.dispatchMessage(Handler.java:102)
   at android.os.Looper.loop(Looper.java:145)
   at android.app.ActivityThread.main(ActivityThread.java:6897)
   at java.lang.reflect.Method.invoke(Native Method)
   at java.lang.reflect.Method.invoke(Method.java:372)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
   at com.example.l33902.contactmanagment.EditActivity.onCreate(EditActivity.java:158)
   at android.app.Activity.performCreate(Activity.java:6550)
   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1120)
   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3108)
   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3263)
   at android.app.ActivityThread.access$1000(ActivityThread.java:197)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1687)
   at android.os.Handler.dispatchMessage(Handler.java:102)
   at android.os.Looper.loop(Looper.java:145)
   at android.app.ActivityThread.main(ActivityThread.java:6897)
   at java.lang.reflect.Method.invoke(Native Method)
   at java.lang.reflect.Method.invoke(Method.java:372)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)

Below are my relevant codes:
ImageButton saveButton;

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.edit_activity);

saveButton = (ImageButton) findViewById(R.id.edit_activity_save);
 displayNameEditText = (EditText) findViewById(R.id.edit_activity_text_cal_name);
    displayNameEditTextLyout = (TextInputLayout) findViewById(R.id.edit_activity_text_cal_name_layout);

 saveButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                save();
            }
        });

}

 private void save() {
        if (displayNameEditText.getText().length() == 0) {
            displayNameEditTextLyout.setError(getString(R.string.edit_activity_error_empty_name));
        } else {
            displayNameEditTextLyout.setError(null);
            if (edit)
                updateCalendar();
            else
                addCalendar(EditActivity.this);
        }
    }

private void updateCalendar() {
        CalendarController.updateCalendar(mCalendarId, displayNameEditText.getText()
                .toString(), colorPicker.getColor(), getContentResolver());
        finish();
    }

In my layout xml:
<ImageButton
                    android:id="@+id/edit_activity_save"
                    android:layout_width="64dp"
                    android:layout_height="64dp"
                    android:contentDescription="@string/edit_activity_save"
                    android:src="@drawable/ic_save_white_24dp"/>

I cannot figure what is the error about as I seem to have declared and point everything to the correct method.

A: In your code the displayNameEditText is not initialized, you can first initialize the view then use then.

A: You need to check the identity of Image buttin in the xml layout.
saveButton = (ImageButton) findViewById(R.id.edit_activity_save);

Perhaps you seems to used wrong identity.
See android document for more detail.
http://developer.android.com/reference/android/app/Activity.html#findViewById(int)
findViewById function returns null if no found view.
Enjoy good coding!

A: Try this corrected code:
ImageButton saveButton;
EditText displayNameEditText //declare it first
EditText displayNameEditTextLyout //if it's an EditText

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.edit_activity);

saveButton = (ImageButton) findViewById(R.id.edit_activity_save);
//add this line
displayNameEditText = (EditText) findViewById(R.id.your_particular_xml_id);  //your_particular_xml_id must exist in your xml file
//add this line
displayNameEditTextLyout = (EditText) findViewById(R.id.particular_xml_id);  // particular_xml_id must exist in your xml file

saveButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                save();
            }
        });

}

 private void save() {
        if (displayNameEditText.getText().length() == 0) {
            displayNameEditTextLyout.setError(getString(R.string.edit_activity_error_empty_name));
        } else {
            displayNameEditTextLyout.setError(null);
            if (edit)
                updateCalendar();
            else
                addCalendar(EditActivity.this);
        }
    }

private void updateCalendar() {
        CalendarController.updateCalendar(mCalendarId, displayNameEditText.getText()
                .toString(), colorPicker.getColor(), getContentResolver());
        finish();
    }

I am assuming you have also defined addCalendar() method in your code.If not, you have to because you have used it in save() method.
I hope it helps.


text:
Q: Bad owner or permissions on ~./ssh/config after upgrade to Windows 1809 I'm using Windows 10 OpenSSH version. After update to Windows 1809 I've got
C:\Windows\System32\OpenSSH\ssh.exe myhost
Bad owner or permissions on C:\\Users\\XXX/.ssh/config

But execution
c:\Windows.old\Windows\System32\OpenSSH\ssh.exe myhost

is successful.
Versions are slightly different
C:\Windows.old\Windows\System32\OpenSSH\ssh.exe -V
OpenSSH_for_Windows_7.6p1, LibreSSL 2.6.5
C:\Windows\System32\OpenSSH\ssh.exe -V
OpenSSH_for_Windows_7.7p1, LibreSSL 2.6.5

I've tried to 'cleanup' permissions like described but it doesn't help.

A: I had a similar issue and fixed it by changing file's DACL (permissions) by removing inheritance and leaving only the user, SYSTEM and Administrators to have Full control access:
icacls C:\Users\xxx\.ssh\config
C:\Users\xxx\.ssh\config NT AUTHORITY\SYSTEM:(I)(F)
                            BUILTIN\Administrators:(I)(F)
                            DOMAIN\xxx:(I)(F)

I used explorer's GUI for that, but it can be done by icacls as well.
Example:
> icacls.exe .\.ssh\config /grant everyone:f
> ssh 127.0.0.1
Bad owner or permissions on C:\\Users\\xxx/.ssh/config
> icacls.exe .\.ssh\config /inheritance:d
> icacls.exe .\.ssh\config /remove everyone
> ssh 127.0.0.1
ssh 127.0.0.1
Warning: Permanently added '127.0.0.1' (ECDSA) to the list of known hosts.
xxx@127.0.0.1's password:

A: I had similar problem, after the upgrade to 1809 Windows installed it's own ssh.exe.
Ssh delivered with Cygwin works just fine:
There are following ssh.exe installed:
C:\Users\ebajgrz\.ssh>where ssh
C:\Windows\System32\OpenSSH\ssh.exe
c:\cygwin64\bin\ssh.exe

The ssh client from Windows complains about permissions:
C:\Users\ebajgrz\.ssh>C:\Windows\System32\OpenSSH\ssh.exe myserver
Bad owner or permissions on C:\\Users\\ebajgrz/.ssh/config

Cygwin's ssh works just fine:
C:\Users\ebajgrz\.ssh>C:\cygwin64\bin\ssh.exe myserver
Last login: Wed Feb 19 09:01:35 2020 from 100.93.177.156
[ebajgrz@myserver ~]$


text:
Q: jax-ws vs axis2 - help needed I need help with the following :
Q.1) Performance comparison between -
1) lot of war files containing jax-ws based web services deployed on Jetty
2) lot of web services deployed on axis2 running on Jetty
Q.2) Also, if there are many types of clients, like .net, java, c++ based, which are gonna use these web services then which approach should I go with - axis2 as SOAP engine or jax-ws??
Q.3) if I am not interested in WS-* standards then what should I use axis2 or jax-ws?
Q.4) In general why are SOAP engines required?? only for WS-* standard support or do they have more benefits to them???

A: Java API for XML Web Services (JAX-WS) is just an API.
You need to use a SOAP stack implementation (SOAP engine).
There are 2 major implementations:

*

*Axis2

*Metro
Since Metro provides the Reference Implementations and is shipped with JDK, I assumed you have been calling jax-ws to the RI. But metro is a full SOAP Stack implementation.
Now you that you now the names, and the places, you can start your quest for your favorite implementation. Both have pros and cons.
Keep in mind that both provide you the WS-* standards support, and since SOAP is "programing language independent" doesn't matter the client types.
I personalty prefer Metro, since it is much more easer to use.


text:
Q: How does OpenGL compute shader threads map to warps? In CUDA, threads with id 0-31, 32-63, ... always execute in the same warp. However, I can't find any similar statement in OpenGL spec or wiki. Does OpenGL provide the same guarantee, or is it safe to assume that for most OpenGL implementations?

A: OpenGL spec does not say anything about warps, which are nVidia specific implementation detail.
In OpenGL parlance the shader invocations are divided into workgroups. The number of shader invocations in a workgroup is specified by the layout(local_size_x = X, local_size_y = Y, local_size_z = Z) in; declaration in the shader. The number of workgroups is specified in the glDispatchCompute call. The way they are mapped into CUDA warps is an implementation detail which is transparent to you as a user.

A: For ARM-based GPUs (in phones) like Mali, you do not have warps. Rather, every core goes the whole pixel pipeline. Read this
https://community.arm.com/groups/arm-mali-graphics/blog/2014/04/23/arm-mali-compute-architecture-fundamentals


text:
Q: Wordpress on Heroku and localhost with different databases: Can't log in to Heroku WP dashboard As the (long) title suggest, I have a Wordpress blog that is running on localhost for development and Heroku for production. I modified the wp-config file so that when the site is on localhost, it pulls a local database and on Heroku it pulls a Xeround database.
I can log in just fine on localhost, but I can't on the Heroku version.
When I go to http://myappname.herokuapp.com/wp-login.php and I enter information, it just refreshes the page.
Oddly, when I go to http://myappname.herokuapp.com/wp-admin it auto-redirects to http://myappname.herokuapp.com/wp-login.php?redirect_to=http%3A%2F%2Fmyappname.herokuapp.com%2Fwp-admin%2F&reauth=1 and after entering information it redirects to the login screen im stuck on above.
I have tried:

*

*setting the WP_HOME and WP_SITEURL options in my wp-config.

*setting the above fields in my respective databases

*messing with the .htaccess file

Any help in this matter would be greatly appreciated! I can not get this figured out!


text:
Q: Plural acronym verb form: "PGCs stand for" vs. "PGCs stands for" Is it right to say:

PGCs stands for primordial germ cells.

PGCs is a plural, so is it correct to use the singular verb form stands with it?

A: It's more common to give the meaning of an acronym in singular form:

PGC stands for primordial germ cell.

If you've given this definition, it's obvious to readers that PGCs is the plural.

If you were to give the definition of "PGCs," you would still use the singular form of the verb:

PGCs stands for primordial germ cells.

This is because the subject is the acronym "PGCs," not the primordial germ cells themselves. For example, the sentence could be reworded to more clearly show that it is the acronym that is the subject:

The acronym "PGCs" stands for primordial germ cells.