Mobile responsiveness not working on Samsung Note 21 and iPhone 14 but working on all other devices. Can't replicate error from Chrome dev tools

Question: I am currently having a unique error. A landing page is very responsive on all other mobiles I have tried: https://bluehedge.netlify.app. However, it seems to appear this way on the web owner's device:Samsung device iPhone device
Here is the HTML for the page:
<!DOCTYPE html>

  <meta charset="UTF-8" />
  <meta http-equiv="-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Bluehedge Realtors</title>
  <link rel="stylesheet" href="./styles.css" />

>! <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"
>! integrity="sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw=="
>! crossorigin="anonymous" referrerpolicy="no-referrer" />

>!

Welcome to Bluehedge Realtors

Our Socials

            <button id="facebook">

                Facebook

            </button>

            <button id="instagram">
              Instagram

            </button>

            <button id="whatsapp">

                WhatsApp

            </button>

            <button id="website">Our
                  Website</button>

BLUEHEDGE REALTORS

            Suite 205/232, Block H, Ikota Shopping Complex
            VGC, Lekki, Lagos.

The CSS:
@import url("");

body {
  background: url("./Atlantic.jpg");
  background-size: cover;

  overflow: hidden;
}

main {
  display: flex;
  justify-content: center;
  align-items: center;
  font-family: "Poppins", sans-serif;
}

.image {
  width: 70px;
  border-radius: 50%;
}

h2 {
  font-weight: 500;
  color: #fff;
}

.main-content {
  text-align: center;
}

.buttons-layout {
  z-index: 2;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  animation: reveal 1.5s 0.3s;
  /* margin-top: 40px; */
}

button {
  background-color: #fff;
  display: flex;
  font-size: 18px;
  justify-content: center;
  align-items: center;
  font-family: "Poppins", sans-serif;
  border-radius: 10px;
  /* background-color: transparent; */
  width: 550px;
  height: 55px;
  margin: 20px;
  cursor: pointer;
  /* border-width: 1px; */
  border: none;
  box-shadow: 1px 11px 12px -7px rgba(0, 0, 0, 0.63);
  -webkit-box-shadow: 1px 11px 12px -7px rgba(0, 0, 0, 0.63);
  -moz-box-shadow: 1px 11px 12px -7px rgba(0, 0, 0, 0.63);
  /* border-color: blue; */
}

button:hover {
  color: #fff;
}

button span:hover {
  transform: scale(1.1);
  transition: all 0.3s cubic-bezier(0, 0.48, 0.13, 1.03);
  color: #fff;
}

button a {
  text-decoration: none;
  color: black;
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
  align-items: center;
  /* width: 300px; */
  gap: 8px;
}

button:hover a {
  color: #fff;
}

button:hover .fa-brands {
  transform: scale(1.5);
  transition: all 0.2s linear;
}

button:hover .fa-solid {
  transform: scale(1.5);
  transition: all 0.2s linear;
}

#facebook:hover {
  background-color: #3b5998;
}

#whatsapp:hover {
  background-color: #25d366;
}

#instagram:hover {
  background: linear-gradient(
    45deg,
    #405de6,
    #5851db,
    #833ab4,
    #c13584,
    #e1306c,
    #fd1d1d,
    #f56040,
    #f77737,
    #fcaf45,
    #ffdc80
  );
}

#website:hover {
  background-color: #add8e6;
}

.address {
  width: 100%;
  background-color: white;
  font-style: italic;
  font-size: 12px;
  position: fixed;
  bottom: 0;
  font-weight: 400;
}

.address span {
  font-weight: bold;
}

@keyframes reveal {
  from {
    margin-top: 70px;
  }

  to {
    margin-top: 0px;
  }
}

@media (width <= 880px) {
  body {
    background: url("./mobile-bg.jpg");
    background-size: cover;
    height: 100vh;
  }
  h1 {
    font-size: 22px;
  }
  section {
    padding-top: 30px;
  }
  h2 {
    font-size: 18px;
  }
  .address {
    font-size: 10px;
  }

  button {
    width: 300px;
    height: 40px;
    margin: 15px;
  }
}

I have tried all responsive tools I can find. From Chrome/Edge developer tools to all other developer tools I can find to try to replicate that non-responsive screen. However, they all seem to appear fine on those tools except the owner's phones.
Comment: Are you just running out of space on the real devices? And I see no width or height settings for the flexes to have to conform to. FF=Firefox.
Comment: thats a reason why you should test on actual devices not on Chrome Dev Tools. Personally I would recommend the usage of FF for testing over Chrome and not to use `` as I see no approach to counter the loss of DPR feature that this meta tag cause. PS a responsive layout will work with relative units such as `em` and `rem`. It will not use hardcoded `px` units. Espacially with the loss of the DPR, `22px` as h1 font size is about 1/3 of the default size.
Comment: Sorry, what is FF?
Answer: Figured out the issue. It was the @media query syntax:
@media(width <= 700px) {
// Mobile responsiveness..
}

Apparently, not all mobile browsers seem to recognize that syntax making the phones render the desktop view instead.
Switched to the good old media query syntax:
@media only screen and (max-width: 600px) {}

...and it worked!!


Vue: standard way to hide template if no data or loading

Question: I've got a Vue component for Google Maps that looks like this:
Vue.component('user-map', {
  template: '
 \
    <gmap-map style="width: 630px; height: 200px" :center="coords" :zoom="13"> \
      <gmap-marker :position="coords"></gmap-marker> \
    </gmap-map> \

',
  data: function () {
    return {
      coords: {}
    }
  },
  mounted() {
    this.getCoords(window._client_code)
  },
  methods: {
    getCoords: function (clientCode) {
      this.$http.get(`${window.location.origin}/share/${clientCode}/map`)
          .then(response => {
        this.coords = response.body[0]
      }, response => {
        console.log('no coords')
      })
    }
  },
  computed: {
    finalLat: function() {
      return this.coords.lat
    },
    finalLng: function() {
      return this.coords.lng
    }
  }
})

How can I hide the template while it's loading the JSON response or if the response is null?
Comment: try:``
Comment: There is no "standard" way. That being said, you could do something as simple as a `v-if` checking whether or not `coords` has any data, and possibly a `v-else` if you want to display an alternative view while no data is being display (e.g. v-if="coords").
Answer: You can have a data field that gets set true/false on loading success, and v-show or v-if off that on <gmap-map />. I want to say most of the Vue UI frameworks I've seen just use a variable or computed that's true or false (Element uses 'loading')


Query quotes in execute statement

Question: I have this correct query (I am getting the value from a procedure, my problem is with the quotes):
EXECUTE IMMEDIATE ('insert into TABLES (table_name)
  values ('||''''||TABLE_NAME||''''||')');

When I try to add another column, I get an error, can anybody add the correct quotes? This one is incorrect:
EXECUTE IMMEDIATE ('insert into TABLES (table_name,column_name)
  values ('||''''||TABLE_NAME||''''||'',''||column_name||''''||')');

Comment: There is no need to use native dynamic sql(`execute immediate` statement), use static, simple `insert into` statement. 2) Do not just say you are getting an error, provide the error message as well.
Comment: If you do have to use dynamic SQL (and you don't for this example) it's useful to put the command into a string variable so you can use `dbms_output` to display it - then you can see exactly what is being executed, which make debugging much easier. You should also use bind variables.
Answer: For the statement you have:
EXECUTE IMMEDIATE ('insert into TABLES (table_name,column_name)
  values ('''||TABLE_NAME||''','''||column_name||''')');

But you should use bind variables, which are much easier to construct and read as well as much safer:
EXECUTE IMMEDIATE ('insert into TABLES (table_name,column_name)
  values (:table_name,:column_name)') USING TABLE_NAME, COLUMN_NAME;

And as noted in comments this doesn't need to be dynamic at all; or at least it wouldn't if you had called your variables something different to the column names - which still works but looks ambiguous:
insert into TABLES (table_name,column_name)
values (TABLE_NAME,COLUMN_NAME);

You can specify the scope to make things clerarer; assuming your procedure is called MY_PROC you can do:
insert into TABLES (table_name,column_name)
values (MY_PROC.TABLE_NAME,MY_PROC.COLUMN_NAME);

Answer: Assuming you even need dynamic sql - I don't know the context in which you're attempting this - your quotes problem would be sorted as follows:
EXECUTE IMMEDIATE ('insert into TABLES (table_name) values ('''||TABLE_NAME||''')');

EXECUTE IMMEDIATE ('insert into TABLES (table_name,column_name) values ('''||TABLE_NAME||''','''||column_name||''')');

But really you should be using bind variables:
declare v_table_name varchar2(30);

begin

    -- get your v_table_name here

    EXECUTE IMMEDIATE ('insert into TABLES (table_name) values (:TABLE_NAME)')
    USING v_table_name;

end;

Query quotes in execute statement


Positioning A Form From A SysTray Icon

Question: I'd like to display a form off of a systray icon event, which just shows some information next to the taskbar and disappears itself after some time.  The main issue I'm running into is positioning the form in a way that it is both in the correct position and visible.  I found a couple of ways to determine where the icon is, but in testing I found them inconsistent based on OS (I attempted this in another app and ended up giving up and using a centered modal form).  For example:
procedure GetWorkAreaRect(var outrect: TRect);
// returns the dimensions of the work area.
begin
  Systemparametersinfo(SPI_GETWORKAREA, 0, @outrect, 0);
end;

The problem when that works is determining from there where to put the form (above, below, left, right).  Any suggestions?
Edit: The problem is in positioning the form in relationship to the system tray icon, not necessarily determining where the system tray icon is.  I made another attempt and got it working as long as some conditions are met. Most notably, it doesn't work if the taskbar is set to auto-hide, because the assumption is made that the click is made outside of the work area.  This is not true when the form is set to auto-hide.
function PositionForm(X, Y, Width, Height: Integer): TPoint;
// receives mouse-click position in X and Y, form width and height in width and height
// returns Left and Top in TPoint.X and TPoint.Y.
var
  workrect: TRect;
  resrect: TPoint;
begin
  GetWorkAreaRect(workrect);
  if Y > WorkRect.Bottom then  // taskbar is on bottom
    begin
      resRect.X := WorkRect.Right - Width;
      resrect.Y := WorkRect.Bottom - Height;
    end
  else
  if X > WorkRect.Right then   // taskbar is on right
    begin
      resrect.X := WorkRect.Right - Width;
      resrect.Y := WorkRect.Bottom - Height;
    end
  else
  if X < WorkRect.Left then  // taskbar is on left
    begin
      resrect.X := WorkRect.Left;
      resrect.Y := WorkRect.Bottom - Height;
    end
  else
  if Y < WorkRect.Top then   // taskbar is on top
    begin
      resrect.X := WorkRect.Right - Width;
      resrect.Y := WorkRect.Top;
    end;
  Result := ResRect;
end;

So on the surface, it seems the issue is to find an independent way to determine where the taskbar resides...or could the logic be extended above to take care of this?
Comment: The question has changed somewhat. Can you tell me how you obtain X and Y?
Comment: My answer now tells you how to locate the taskbar.
Answer: When your notification icon receives the message corresponding to an action, you can query at that point to find out an associated point on the screen.
For example if you are handling WM_RBUTTONUP, WM_CONTEXTMENU etc. in your icon's message procedure you can call GetMessagePos to find out the position on the icon associated with the message.
I wrap this up with the following function so that I can decode the message into a TPoint:
function MessagePoint: TPoint;
begin
  Result := TSmallPoint(GetMessagePos());
end;

So what you can do is, in your icon's message procedure, make a note of this point. When you need to show the form, use this point to determine where your icon lives. Since the point can be in the taskbar, you'll need to clip it into the work area.

After your question update it seems you want to know how to find out the location of the taskbar. Do that by calling SHAppBarMessage passing ABM_GETTASKBARPOS.
Answer: Windows does not expose a native way to query where system tray icons are positioned, or even if they are visible at all.  But you can do it manually with some lower level API trickery, as demonstrated in the following article:
CTrayIconPosition - where is my tray icon?
That works up to XP, at least, maybe even Vista.  Windows 7 drastically redesigned the way the system tray acts, so I do not know if these techniques still work anymore.
Answer: You can use TJvDesktopAlert to display simple notifications, if you have JCL and JVCL.
procedure TForm1.ShowDesktopAlert(const AHeader, AMessage: string);
begin
  with TJvDesktopAlert.Create(nil) do
  begin
    StyleOptions.DisplayDuration := 5000;
    HeaderText := AHeader;
    MessageText := AMessage;
    AutoFree := True;
    Execute;
  end;
end;

Comment: How does this relate to the location of a notification icon?
Comment: @DavidHeffernan It does not.
Comment: OK, then how does it address the question?
Comment: @DavidHeffernan A notification window next to the task bar which hides automatically. Isn't that the reason behind this question?
Comment: Well, Glenn already appears to have made a form. Perhaps he wants things on his form that don't fit the `TJvDesktopAlert` mould. Also, Glenn wants the form to appear next to the notification icon, hence the question.

Positioning A Form From A SysTray Icon


How to secure barbed 1/8" fitting?

Question: What would be a good way to make sure a 1/8" plastic tube doesn't come off a barbed fitting? (It's under pressure from a water tank.)
I was thinking of a clamp with a tightening screw, but they don't seem to come in such small size. Is there a better alternative?
Comment: If you can, use a compression fitting rather than a barb. They make a much more reliable connection for small diameter tubes.
Comment: As far as I know, a cable tie is a common solution.
Answer: The other answer is a good starting point. However you may want to look at using this style of spring hose clamp. They exert their pressure over a greater area of the hose and depending upon the hose material prevent cracking of the hose material as it ages.
Answer: Use a wire spring type hose clamp. They make them in many sizes, including 1/8". They work well initially and have the added benefit of applying constant tension even if the hose softens or shrinks (as opposed to a zip-tie or worm-drive hose clamp).
Comment: I like this answer. Those are the sort of clamps often used on car engine hoses.
Answer: A nylon zip-tie works just fine, too.  That's what I'm using in my computer for a few connections that have barbs rather than compression fittings.

How to secure barbed 1/8" fitting?


Definition and Properties of Dihedral Group

Question: Definition: Here is equivalent definition of dihedral group $$\begin{align}D_{2n}&=\{\sigma \in S_n\mid \sigma(a+1)\equiv\sigma(a)+1\pmod n, \forall 1\leq a\leq n\} \bigcup \{\sigma \in S_n\mid \sigma(a+1)\equiv \sigma(a)-1\pmod n, \forall 1\leq a\leq n\} \\ &= \{T:\Bbb{R}^2\to \Bbb{R}^2\mid T(P)=P \text{ and } T \text{ is isometry}\}\\ &= \{\text{"symmetry" of $n$-gon}\} \end{align}$$

Fix a regular $n$-gon centered at the origin in an $x$, $y$ plane and label the vertices consecutively from $1$ to $n$ in a clockwise manner. Let $r$ be the rotation clockwise about the origin through $2\pi /n$ radian. Let $s$ be the reflection about the line of symmetry through vertex $1$ and the origin. We leave the details of the following calculations as an exercise
$(1)$ $1,r,r^2,…,r^{n-1}$ are all distinct and $r^n=1$, so $|r|=n$.
$(2)$ $|s|=2$.
$(3)$ $s\neq r^i$, for any $i$.
$(4)$ $sr^i \neq sr^j$, for all $0\leq i,j \leq n- 1$ with $i\neq j$, so $$D_{2n}=\{1,r,r^2,…,r^{n-1},s,sr,sr^2,…,sr^{n-1}\}$$ i.e. each element can be written uniquely in the form $s^kr^i$ for some $k=0$ or $1$ and $0\leq i\leq n-1$.
$(5)$ $rs=sr^{-1}$. [First work out what permutations effects on $\{1,2,...,n\}$ and then work out separately what each side in this equation does to vertices $1$ and $2$.] This shows in particular that $r$ and $s$ do not commute so that $D_{2n}$ is non-abelian.
$(6)$ $r^i s=sr^{-i}$, for all $0\leq i \leq n$. [Proceed by induction on $i$ and use the fact that $r^{i+1}s=r(r^is)$ together with the preceding calculation.] This indicates how to commute $s$ with powers of $r$.

My attempt: Let symmetry $r^p$ ($0\leq p\leq n-1$) and $s$ correspond to permutation $\sigma_p$ and $\mu$, respectively. Then $\sigma_p:J_n\to J_n$ such that $\sigma_p(a)=a+p$ (addition taken "modulo $n$"), $\forall a\in J_n$. It's easy to check, $\sigma_p(b+1)=\sigma_p(b)+1$ for all $b$. By induction, $\sigma_p=(\sigma_1)^p$ for all $0\leq p\leq n-1$. Knowing image of two adjacent vertex, let say $1$ and $2$, completely determine the permutation (see third paragraph). Then $\mu:J_n\to J_n$ such that $\mu (1)=1$ and $\mu (2)=n$. It's easy to check, $\mu (b+1)=\mu (b)-1$ for all $b$. Let $\sigma ,\tau\in D_{2n}$. Then $\sigma=\tau$ if and only if $\sigma(1)=\tau (1)$ and $\sigma (2)=\tau (2)$.
$(1)$ Let $i,j$ such that $0\leq i\lt j\leq n-1$. Then $1\leq 1+i\lt 1+j\leq n$. So $\sigma_i(1)=1+i\neq 1+j=\sigma_j(1)$. Thus $\sigma_i\neq \sigma_j$, if $i\neq j$. Hence $\sigma_0,\sigma_1,…,\sigma_{n-1}$ are all distinct. Let $\sigma_n=(\sigma_1)^n$. Since addition taken modulo $n$, we have $\sigma_n(a)=a+n=a$, $\forall a\in J_n$. So $\sigma_n=\sigma_0$. Thus $|\sigma_1|=n$.
$(2)$ We have $\mu ^2(1)=\mu (1)=1$ and $\mu^2(2)=\mu (n)=2$. Thus $\mu^2(1)=\sigma_0(1)$ and $\mu^2(2)=\sigma_0(2)$. Hence $\mu^2=\sigma_0$ and $|\mu|=2$.
$(3)$ We have $\sigma_i(1)=1+i$ and $\sigma_i(2)=2+i$. We have $\mu (1)=1$ and $\mu (2)=n$. Assume towards contradiction $\sigma_i=\mu$, for some $i$. Then $\sigma_i=\mu$ iff $\sigma_i(1)=\mu (1)$ and $\sigma_i(2)=\mu (2)$ iff $i=0$ and $i=n-2$. So $n=2\geq 3$. Thus we reach contradiction. Hence $\sigma_i\neq \mu$.
$(4)$ Assume towards contradiction $sr^i=sr^j$, for some $0\leq i\lt j\leq n-1$. Then $sr^i(r^i)^{-1}=sr^j(r^i)^{-1}=s=sr^{j-i}$. So $1=r^{j-i}$. Since $i\lt j$, we have $0\lt j-i\leq n-1$. By $(1)$, $1\neq r^{j-i}$. Thus we reach contradiction. Hence $sr^i\neq sr^j$ for all $0\leq i,j\leq n-1$ with $i\neq j$. That is $s,sr,…,sr^{n-1}$ are all distinct. I think we also need to show $r^i\neq sr^j$, for all $0\leq i,j\leq n-1$. Assume towards contradiction $r^i=sr^j$, for some $i,j$. Then $r^i(r^i)^{-1}=sr^j(r^i)^{-1}=1=sr^{j-i}$. By $(2)$, $s^2=1$. So $s=r^{j-i}$. Since $|r|=n$, we have $r^{j-i}\in \{1,r,…,r^{n-1}\}$. But by $(3)$, $s\neq r^{j-i}$. Thus we reach contradiction. Hence $1,r,…,r^{n-1},s,sr,…,sr^{n-1}$ are all distinct. Since $|D_{2n}|=2n$, we have $$D_{2n}=\{1,r,r^2,…,r^{n-1},s,sr,sr^2…,sr^{n-1}\}.$$
$(5)$ We have $\sigma_1\circ \mu(1)=\sigma_1 (1)=2$ and $\sigma_1 \circ \mu (2)=\sigma_1 (n)=1$. Since $\sigma_1(n)=1$ and $\sigma_1(1)=2$, we have $\sigma_1^{-1}(1)=n$ and $\sigma_1^{-1}(2)=1$. So $\mu \circ \sigma_1^{-1}(1)=\mu (n)=2$ and $\mu \circ \sigma_1^{-1}(2)=\mu (1)=1$. Thus $\sigma_1\circ \mu (1)=\mu \circ \sigma_1^{-1}(1)$ and $\sigma_1\circ \mu (2)=\mu \circ \sigma_1^{-1}(2)$. Hence $\sigma_1\circ \mu = \mu \circ \sigma_1^{-1}$, or equivalently $rs=sr^{-1}$. We claim $rs\neq sr$. Assume towards contradiction $rs=sr$. Then $rs=sr^{-1}=sr$. So $r^{-1}=r$. That is $|r|=2\geq 3$. Thus we reach contradiction. Hence $D_{2n}$ is non abelian.
$(6)$ $r^i s=sr^{-i}$, for all $0\leq i \leq n$. Base case: $i=1$. By $(5)$, $rs=sr^{-1}$. Inductive step: suppose $r^i s=sr^{-i}$, for some $0\leq i$. By inductive hypothesis, $r^{i+1}s=r(r^{i}s)=r(sr^{-i})$. By $(5)$, $r(sr^{-i})=(rs)r^{-i}=sr^{-1}r^{-i}=sr^{-(i+1)}$. So $r^{i+1}s=sr^{-(i+1)}$. By principle of mathematical induction, $r^i s=sr^{-i}$, for all $0\leq i \leq n$. Is my proof correct?
Que: Can we explicitly show  permutation $\mu$, not just $\mu (1)$ and $\mu (2)$, like we did for $\sigma_p$? I think we have to consider two cases, first $n$ is even, second $n$ is odd.
Comment: This needs focus.
Comment: Yes. ${}{}{}{}$
Comment: Following is a simpler proof of $(4)$: Assume towards contradiction $sr^i=sr^j$, for some $0\leq i\lt j\leq n-1$. Since $s^2=1$, we have $r^i=r^j$. Which contradicts result of $(1)$.
Comment: In [this](https://math.stackexchange.com/q/2986043/861687) post I found permutation $\mu$. It is defined as $\mu(a) \equiv 2-a \pmod n$, for all $a\in J_n$. Apparently in my above proofs, especially $(3)$, I mixed up modulo addition with usual addition. Which is a rookie mistake.
Answer: Your very first definition $D_n=$ is false. Anyway, you don't have to translate Dummit's geometric definitions and propositions about $r,s,D_n$ into statements about permutations. It is much simpler to reason directly:

$r^k$ is the rotation of $k\frac{2\pi}n\pmod{2\pi}$ Since these angles are distinct for $k=0,1,\dots,n-1,$ the rotations $1,r,\dots,r^{n-1}$ are distinct. And since $n\frac{2\pi}n\equiv0\pmod{2\pi},$ $r^n=1.$

$s$ is a reflection.

a reflection reverses the orientation, whereas a rotation preserves it.

if $0\leq i\le j<n$ and $sr^i=sr^j,$ then $r^{j-i}=0$ hence by 1), $i=j.$ Similarly $sr^i\ne r^j$ by 3), hence $r^i\ne sr^j$ by 2). This proves that the $2n$ elements $sr^k,r^k(0\le k<n)$ are distinct. Let us now prove that any symmetry $t$ of the $n$-gon is one of them. Consider the symmetry $u$ of the $n$-gon equal to $st$ if $t$ is a reflection, and to $t$ if $t$ is a rotation. In both cases, $u$ is a rotation of the $n$-gon. Let $k$ be the number of the vertex to which $u$ maps the vertex number $1.$ Then $u=r^k,$ and we are done ($t=$ either $sr^k$ or $r^k$).

Denote by $v_k$ the vertex number $k.$ Then, $rs(v_1)=r(v_1)=v_2$ and $sr^{-1}(v_1)=s(v_n)=v_2.$ Since both $rs$ and $sr^{-1}$ are reflections and coincide on $0$ and $v_1,$ they are equal. Ok with your end of 5).

ok.

Re. $\mu(1)=1,\mu(2)=n,\mu(3)=n-1,\dots.$
Comment: I do not assume that $t$ is obtained by reflection rotation reflection (which would then be a rotation) or by any such composition. I know beforehand that [the linear isometries of the plane are rotations and reflections](https://en.m.wikipedia.org/wiki/Rotations_and_reflections_in_two_dimensions).
Comment: Yeah I know. I just took an example. Anyway that link is useful and answer symmetry $t$ is either rotation or reflection.
Comment: Nope. Thank you so much for the answer.
Comment: My main reason for translating symmetry into permutation is to make definition of $D_{2n}$ independent of "axis of symmetry" and "rotation axis". I think these notions are studied in physics, in particular classical mechanics. It is reasonable to ask, what if we flip (or rotate) $n$-gon about arbitrary axis? Yeah I should have written $\sigma (a+1)\equiv \sigma (a) +1\pmod n$. In 4), is your proof of $sr^i\neq r^j$ uses orientation argument? If yes, then you don't have to use 2) to show $r^i\neq sr^j$, 3) proves both. In my opinion there is some vagueness in proof of $t=sr^k$ or $r^k$.
Comment: I freely took advantage of 2 only to deduce *immediately* $r^i\ne sr^j$ from $sr^i\ne r^j,$ the latter following from  $s\ne r^{j-i}$ i.e. from 3. So, I do not re-use the orientation argument in 4. It is encapsulated in 3. What are your doubts in the proof of $t=sr^k$ or $t=r^k$?
Comment: You're characterizing symmetry with rotation and reflection. Let say symmetry $t$ is obtained by reflection rotation reflection (read from right to left). With help of "physical intuition" $t$ is rotation. How do we rigioursly show symmetry $t$ is either rotation or reflection?
Comment: Yes, this is what allowed me to define $u$ by cases. So, no more doubts in the proof of $t=sr^k$ or $t=r^k?$


tryCatch - namespace?

Question: I am quite new to R and I am confused by the correct usage of tryCatch. My goal is to make a prediction for a large data set. If the predictions cannot fit into memory, I want to circumvent the problem by splitting my data.
Right now, my code looks roughly as follows:
tryCatch({
  large_vector = predict(model, large_data_frame)
}, error = function(e) { # I ran out of memory
  for (i in seq(from = 1, to = dim(large_data_frame)[1], by = 1000)) {
    small_vector = predict(model, large_data_frame[i:(i+step-1), ])
    save(small_vector, tmpfile)
  }
  rm(large_data_frame) # free memory
  large_vector = NULL
  for (i in seq(from = 1, to = dim(large_data_frame)[1], by = 1000)) {
    load(tmpfile)
    unlink(tmpfile)
    large_vector = c(large_vector, small_vector)
  }
})

The point is that if no error occurs, large_vector is filled with my predictions as expected. If an error occurs, large_vector seems to exist only in the namespace of the error code - which makes sense because I declared it as a function. For the same reason, I get a warning saying that large_data_frame cannot be removed.
Unfortunately, this behavior is not what I want. I would want to assign the variable large_vector from within my error function. I figured that one possibility is to specify the environment and use assign. Thus, I would use the following statements in my error code:
rm(large_data_frame, envir = parent.env(environment()))
[...]
assign('large_vector', large_vector, parent.env(environment()))

However, this solution seems rather dirty to me. I wonder whether there is any possibility to achieve my goal with "clean" code?
[EDIT]
There seems to be some confusion because I put the code above mainly to illustrate the problem, not to give a working example. Here's a minimal example that shows the namespace issue:
# Example 1 : large_vector fits into memory
rm(large_vector)
tryCatch({
  large_vector = rep(5, 1000)
}, error = function(e) {
  # do stuff to build the vector
  large_vector = rep(3, 1000)
})
print(large_vector)  # all 5

# Example 2 : pretend large_vector does not fit into memory; solution using parent environment
rm(large_vector)
tryCatch({
  stop();  # simulate error
}, error = function(e) {
  # do stuff to build the vector
  large_vector = rep(3, 1000)
  assign('large_vector', large_vector, parent.env(environment()))
})
print(large_vector)  # all 3

# Example 3 : pretend large_vector does not fit into memory; namespace issue
rm(large_vector)
tryCatch({
  stop();  # simulate error
}, error = function(e) {
  # do stuff to build the vector
  large_vector = rep(3, 1000)
})
print(large_vector)  # does not exist

Comment: check the second edit of my answer, I added a small tip there which could come in handy in some situations.
Answer: I would do something like this :
res <- tryCatch({
  large_vector = predict(model, large_data_frame)
}, error = function(e) { # I ran out of memory
  ll <- lapply(split(data,seq(1,nrow(large_data_frame),1000)),
         function(x)
             small_vector = predict(model, x))
  return(ll)
})
rm(large_data_frame)
if(is.list(ll))
  res <- do.call(rbind,res)

The idea is to return a list of predictions results if you run out of the memory.
NOTE, i am not sure of the result here, because we don't have a reproducible example.
Comment: @Jenny Note that you can use deallocate here in the finally block. `finally = {rm(large_data_frame)}`.
Comment: @Hemmo I see that :) but I like your idea of simplified version to explain your purpose ( explain code by code).
Comment: That actually does work! I tried returning variables from the error function before, however I missed assigning the return of the `tryCatch` call to a variable (`res` in this case). Thanks a lot!
Comment: +1, this is much nicer solution than the one I tried to make in the spirit of the original question. And @agstudy's comment makes my answers small merit pointless :)
Comment: there seems to be a small bug in the solution... instead of `if(is.list(ll)) ` it should be `if(is.list(res))`
Comment: Gosh this was a 9 year old answer. Still if there was a bug let;s correct it for people who land up here.
Answer: EDIT: Let's try again:
You can use finally argument of tryCatch:
step<-1000
n<-dim(large_data_frame)[1]
large_vector <- NULL
tryCatch({
  large_vector <- predict(model, large_data_frame)
}, error = function(e) { # ran out of memory
  for (i in seq(from = 1, to = n, by = step)) {
    small_vector <- predict(model, large_data_frame[i:(i+step-1),]) #predict in pieces
    save(small_vector,file=paste0("tmpfile",i)) #same pieces
  }
 rm(large_data_frame) #free memory

},finally={if(is.null(large_vector)){ #if we run out of memory
   large_vector<-numeric(n) #make vector
   for (i in seq(from = 1, to = n, by = step)){
     #collect pieces
     load(paste0("tmpfile",i))
     large_vector[i:(i+step-1)] <- small_vector
   }
}})

Here's a simplified version to see what is going on:
large_vector<-NULL
rm(y)
tryCatch({
  large_vector <- y
}, error = function(e) {# y is not found
  print("error")
},finally={if(is.null(large_vector)){
 large_vector<-1
}})
> large_vector
[1] 1

EDIT2: Another tip regarding the scope which could be useful for you (although maybe not in this situation as you didn't want to declare large_vector beforehand): The <<- operator, from R-help:

The operators <<- and ->> are normally only used in functions, and
  cause a search to made through parent environments for an existing
  definition of the variable being assigned...

Therefore you could use above example code like this:
large_vector<-NULL
rm(y)
tryCatch({
  large_vector <- y
}, error = function(e) {# y is not found
  large_vector <<- 1
  print("error")
})
> large_vector
[1] 1

Comment: The code was intended mainly to illustrate my problem, therefore I said it looks "roughly" like this. Sorry it is not reproducible this way. Actually your solution requires me to allocate large_vector before the tryCatch clause, which is not possible due to memory restrictions. Also, the assignment of large_vector inside the error function will still not take place (since it is still a function with own namespace)
Comment: Ok, I though that the problem was in the memory allocation inside of `predict` function, not in allocating the `large_vector`. But you are right about the second point, the assignment wont of course work here. Sorry.
Comment: @Jenny, I edited my answer to show another solution. Although @agstudy's answer is more neat as it doesn't need any temporary files etc, this might be useful as an example of `finally` argument in `tryCatch`.
Answer: The code below is quite self explanatory. Indeed the problem is that anything inside the error function is not by default applied to the parent environment.

b=0
as explained, this doesn't work:
tryCatch(expr = {stop("error1")}, error=function(e) {b=1})
b
SOLUTION 1: assign to the parent environment
tryCatch(expr = {stop("error2")}, error=function(e) {assign(x = "b", value =
2, envir = parent.env(env = environment()))})
b
SOLUTION 2: the most simple (only works if you are assigning to b in both expr and error)
b = tryCatch(expr = {stop("error3")}, error=function(e) {b=3;return(b)})
b

tryCatch - namespace?


Sqlite select multiple rows into a single row

Question: I need a query that takes selects a bunch of entries, and then with those entries selects a bunch of rows into a single row. A typical entry is shown below, along with what a typical result would need to look like.
table1
id
-------
3

table2
id      value       table1
--------------------------
5       value1      3
6       value2      3

table3
id      value       table1
-------------------------
9       value3      3
10      value4      3

table4
id      table1
---------------
14      3
15      3

table5
id      value       table4
-------------------------------
19      value5      14
20      value6      14
21      value7      15

result
result1 result2     result3     result4
------------------------------------------------------
3       value1      value3      value5, value6; value7

Only the first result of Table 1 and Table 2 are needed. Table 2 can often be null, value3 would need to go into result2.
At the moment I select each entry with a statment like below which only returns result1, and then for each entry I do seperate queries for each result
SELECT DISTINCT id FROM (
    -complicated select in here
) AS temp;

And then for each id separably execute:
SELECT value FROM table2 WHERE table1 = id LIMIT 1;

SELECT value FROM table3 WHERE table1 = id LIMIT 1;

SELECT value, table4.id FROM table4, table5 WHERE table4.id = table5.table4 AND table1 = id;

and use code to format it into something like the results table.
The problem is only the first query is done on a background thread, while the rest of them are done on the UI thread. I'd like to do it all in one query, but am having trouble table4 into a single row and only selecting the first result of table2 and table3.
Comment: How should the result be computed? Why do `value2` and `value4` not show up?
Comment: `Table 2 can often be null, value3 would need to go into result2`.  At this point you should be asking yourself whether your database design is a good one. There is a lack of simplicity here that raises red flags.
Comment: But check this out : IFNULL  http://www.sqlite.org/lang_corefunc.html#ifnull
Comment: Tim, I'm aware of the database design issues, and the only way I can simply issues like that is to duplicate data, so that could be a solution.
Answer: For conditional relationships like this you will have a much easier time running multiple selections, or creating a temporary table, filling it with keys in stages and then doing a final selection against the temporary table.
Looking at result4, in effect you are attempting to denormalise and then renormalise the data in the table using outer joins with conditional logic, it is probably possible to do, but would run against the grain of 'wise' database development and you are likely to end up with a query that is all but impossible to debug if you run into problems.
I know that sqlite is meant to be a simple implementation of the SQL standard for using in lightweight environments, so I'm not sure how complex your SQL can be before it gets into trouble.
It's not entirely clear to me what you are trying to achieve, but a workaround might be using several UNION statements like this:
SELECT DISTINCT source, id FROM (
    SELECT table2.table1 AS table1, 'table2' AS source, value AS id FROM table2
    UNION
    SELECT table3.table1, 'table3', value FROM table3
    UNION
    SELECT table4.table1, 'table5', value FROM table5, table4
    WHERE table4.id = table5.table4)
WHERE table1 = 3;

Then you would get result like this:
source    | id
-----------------------
table2    | value1
table3    | value3
table4    | value5
table4    | value6
table4    | value7

Your other option is to create a view with all the unions (and all three columns, not just the two selected above) and then you can just select the value for table1 to get the same result.
Comment: Hi i have applied `InnerJoin` on `2 Tables` 1 column that is primary key in `First Table` is foreign in the `Second Table`. Second table have 3 rows associated with the Foreign key i have managed to rawquery but don't know how to read the cursor let say having 1 row from first table and 3 rows from the second table in one query.


What type of plywood for shower bench?

Question: I'm framing in a 40" x 16" shower bench and I plan on using 3/4" plywood.
I plan on using granite to sit on top of the seat.
I would like to know what kind of plywood I should use for the seat?
Should I use pressure treated? I've heard that pressure treated wood is not recommended to use inside the home.
What about sheathing plywood?
Comment: What role do you intend for the plywood to play in this situation? [This question](http://diy.stackexchange.com/questions/107799/do-i-need-a-plywood-base-to-install-granite-countertops/107803#107803) about support for granite countertops has at least 1 answer which might be enlightening...
Comment: Yes, the larger design of your shower would seem to be relevant here. How you plan on managing moisture is important.
Answer: I would skip the plywood and use Kerdi board. It will cost a bit more but it's very easy to cut, very light weight so it's easy to handle, and it is completley  impervious to moisture.
You can get it 4x8 sheets and build a custom seat or one of their pre-made seats, if you can find one in a size you can work with.
Here's a video from the maker of Kerdi-Board about making a bench out of the material.
Comment: @bigmike7801 You may need to look for tile shops. They mainly serve contractors and don't advertise to laypeople, making them harder to find. If you can'd find or don't have them, try Home Depot. They don't have much Schluter on hand (usually just Ditra and some edging) but then can order most Schluter products with a short turnaround - I got some Rondec from them not too long ago and it only took 2 days. You won't fnid it on their website - get a part or product number from the Schluter web and go to the customer service desk or pro desk. They should have a special order book there.
Comment: I would love to use Kerdi Board and all of the Schluter products, however there's nobody that carries them on-hand in my area.
Comment: Holy jesus.  That bench material is going overboard.  I will make mine out of wood and waterproof.  No way I am trusting foam.    Other than just another thing to sell I am really missing the whole point.  So if the membrane works well why do you need the foam?  When I install the membrane I have less joints and my joints aren't at critical areas.   This just makes my head explode.
Comment: People use it all the time and it's been in use for years. It's a proven material with genuine advantages. It's lightweight, easy to cut, strong, and completely waterproof. It's not like XPS or Styrofoam, it's much more dense and stiff.
Comment: What I am saying is why wouldn't you use concrete board or plywood plus membrane vs the method on the video.  All of the seams are on the edges of the bench which in my opinion is crap.  I guess Kerdi doesn't care because under and behind is waterproofed.  Just seems like overkill for no reason.
Comment: @DMoore the cost is only a bit higher than plywood. It's lighter, easier to work with, and cuts quickly and accurately with a knife.. It doesn't kick up dust or make a mess like cutting wood or Hardie board. Schluter has a great warranty if it's properly installed. The time savings and ease of install more than make up for the marginal increase in cost.
Seams get sealed with Keri membrane. I think they made a mistake in the video, as the final shot is missing membrane on about 8" of seam from the floor on up. I'd have sealed that. Why do something just good enough when "overkill" is easier?
Answer: The answer is - it depends.
If you are using Kerdi membrane plywood would be acceptable.  Actually Pine sheathing plywood is the common type I have seen used for benches and steps in showers by my tile guys.
I personally wouldn't use PT plywood.  PT is perfectly acceptable to use in a home but its purpose is to handle water/moisture that should be common to the situation.  Basement outer wall framing is a perfect example - and bottom plates is a requirement in most areas.  However I have dealt with PT dimensional lumber and plywood and there is a significant chance of warping - even if you get your stuff from a good lumber yard.  If big box you have a 80% chance it warps unless you secure its shape.  The point is the last thing you want is a bow in the plywood on day 4.
The lumber used to frame your shower should never get wet.  So you don't need PT.  And even if your shower framing got wet, that would be the very least of your worries.  Meaning get quality wood but not PT.
So I would answer that this should be plastic plus plywood with kerdi membrane over or it should be hardiboard plus some sort of roll-on waterproofing like redgard (I do not plastic behind hardiboard as I feel it doesn't weep so putting plastic would cause an area that retains water that doesn't dry which will weep down and destroy whatever is below it).
Note:  Make sure you slope your bench in (doesn't need to be dramatic).  The back of the bench is the most vulnerable part of the whole shower.  I would make sure my waterproofing is perfect there.  You don't know how many benches I have seen with no slope or sloped towards the wall.
Comment: Thank you for your detailed answer. I got a little confused when you said "plastic plus plywood". Are you saying I should use a plastic vapor barrier?Also, I have sloped the bench about 5/8" for the 16" bench.
Comment: Yep plastic vapor barrier.  5/8" is perfect.  That will give you some leeway because the granite will want to sit straight.
Answer: I would recommend kendi as well, but no matter what you do, you need to encapsulate it all with a membrane.  RedGuard is a common product.
The ability for the material it to deal with moisture shouldn't be the issue, making sure moisture doesn't ever get to it should be the priority.
Answer: I would consider using cement board.
Comment: What kind of framing under cement board would be required? If I were going to use plywood over the 2 x 4 framing, then cement board over that, I would use marine plywood. But maybe just heavy polyethylene or vinyl shower pan sheeting under the cement board would protect standard plywood. I wonder if the 2x lumber should be pressure treated.
Comment: You can use the 3/4" plywood. Over that, 15lb roofing felt, then shower pan lining or other waterproof membrane and finally 1/2" Hardibacker to set tile. And YES, a 1/4" slope from wall to shower floor. Proper caulking of bench-to-wall joint with wet-area silicone caulk and using a great sealer on the grout joints will make this virtually waterproof.

What type of plywood for shower bench?


"ERROR: (gcloud.asset.export) User does not have permission" only when authenticated with a service account

Question: I'm trying to export project assets with Google Cloud Asset Inventory and gcloud command (version 314.0.0) authenticated with a service account :
# 1. authenticate with service account my-service-account@$PROJECT_ID.iam.gserviceaccount.com
gcloud auth activate-service-account --key-file=/path/to/my/key.json

# 2. export assets to BQ
gcloud asset export \
    --project=$PROJECT_ID \
    --bigquery-table=projects/$PROJECT_ID/datasets/$DATASET_ID/tables/$TABLE_ID \
    --output-bigquery-force \
    --content-type=resource

And got the following error :

ERROR: (gcloud.asset.export) User [my-service-account@$PROJECT_ID.iam.gserviceaccount.com] does not have permission to access project [$PROJECT_ID:exportAssets] (or it may not exist): The caller does not have permission

My service account have the following roles on $PROJECT_ID :

roles/cloudasset.viewer
roles/bigquery.jobUser
roles/bigquery.dataEditor

Note that gcloud asset export works when I'm logged with my own personal account, which have the same roles as my service account.
Adding --verbosity=debug flag to gcloud does not add additional info :

apitools.base.py.exceptions.HttpForbiddenError: HttpError accessing https://cloudasset.googleapis.com/v1/projects/$PROJECT_ID:exportAssets?alt=json

with the following content :
{
  "error": {
    "code": 403,
    "message": "The caller does not have permission",
    "status": "PERMISSION_DENIED"
  }
}

I don't understand the difference between being logged with the service account (gcloud auth activate-service-account) and my own personal account (gcloud auth login), both should work since I have exactly the same permissions.
Any idea would be appreciated.
Comment: Does the export work if you restrict the asset types with the `--asset-types` gcloud flag? Does it work if you give the service account permissions on storage and try the export to GCS instead of BQ? Just throwing some ideas on how to restrict the possible root causes of a permission error...
Comment: @Jofre thanks for your comment. It does not work with `--asset-types` but it seems to work on GCS. I just needed to add `firstname.lastname@example.com` as storage admin. I'll try to do the same with BigQuery.
Comment: Yup, that issue seems documented here: https://cloud.google.com/asset-inventory/docs/faq#how_do_i_export_assets_to_tables_that_dont_belong_to_the_current_project
Answer: It is an opened investigation on this issue:
permission denied error when exporting asset to GCS or BigQuery
It seems that you have to impersonate the built-in service account firstname.lastname@example.com and to add the Storage Admin role to it.
Also you will have to add the roles roles/bigquery.jobUser and roles/bigquery.dataEditor to the service account firstname.lastname@example.com  where xxxxxx is the project id.
Comment: ok, I updated my answer. I am happy that your issue was solved.
Comment: Thanks for your answer. In fact, I had to add `firstname.lastname@example.com` (`xxxxxxxx` = project ID of my service account) the roles `roles/bigquery.jobUser` and `roles/bigquery.dataEditor`). Could you update your answer with that additional info so I can accept it ? Thanks.
Comment: also, service account is not auto-created. see here: https://stackoverflow.com/questions/63785247/gcp-managed-service-account-is-not-created-for-cloud-asset-api


Restrict video download

Question: I want to block users to download video from apache/tomcat. I am using videoJS which streams video content. However it does allow users to download the video once the link to the video is accessed through browser. How can I restrict that?
Video streaming API is getting partial content (206) in its response. Usually download is only GET 200 response. Is there anyway in which we can restrict 206 response and allow 200 for a request from Apache?
Please help.
Thanks.
Answer: I resolved restricting download of videos by denying requests without referrer. I added referrer against a download url. If there is a referrer then download will be allowed by Apache else not.
Note - Couldn't restrict based on full or partial content.

Restrict video download


Read out Datetime from SQLite with C#

Question: I create a programm with a sqllite DB where i can save Data (id/date/name).
DB:
1 - 15.09.2016 00:00:00 - Test
2 - 28.06.2018 00:00:00 - Test2

Type: Numeric
I try to read this out with a SQLite Reader.
Code:
String sql = $"SELECT * FROM test";
SQLiteCommand command = new SQLiteCommand(sql, dbConnection);
SQLiteDataReader reader = command.ExecuteReader();
while (reader.Read())
{
  Console.WriteLine($"Date: {reader["date"]}");
  ...
}

Output:
15,09
28,06

If i convert this to Datetime i get only the year 2018:
15.09.2018
28.06.2018

How can i read out the Datetime in correct format with year ?
Comment: Type are important, You can use a SQLiteDataAdapter. https://www.devart.com/dotconnect/sqlite/docs/Devart.Data.SQLite~Devart.Data.SQLite.SQLiteDataAdapter.html
Comment: Try following : reader["date"].ToString("dd.MM.yyyy")
Comment: @jdweng, I thought SQLite don't have DateTime Data type. And we had to parse ISO8601 string.
Comment: SQLListe may not have a datetime but the driver may be converting to a datetime.  It is like Excel using General formatting which attempts to automatically recognize data types.   With Excel it is the driver either Jet Engine or ACE that does the conversion.  The SQLite driver may also be the Jet Engine which is what is really giving the issue.
Comment: Arg I can't test it. but there is a `GetDateTime` on the reader so is should/could works.
Comment: @DragandDrop Numeric. sry forget it
Answer: https://www.sqlite.org/datatype3.html
SQLite don't have DateTime Datatype. You should parse the string ISO8601.
DateTime myDateTime = DateTime.ParseExact(myString, myFormat, CultureInfo.InvariantCulture);

SqliteDataReader got a GetDateTime method.
reader.GetDateTime(1).ToString("dd.MM.yyyy")

Read out Datetime from SQLite with C#


Git hook not running 2 consecutive commands

Question: I'm trying to create a pre-push hook to run php-cs-fixer before every push.
This is the current pre-push hook I have:
#!/bin/sh

exec php-cs-fixer fix . --config-file=".php_cs" && git commit -am 'PSR-2'

The first command gets trigger without a problem.
Only the git commit -am 'PSR-2 doesn't. To be more precise, the php-cs-fixer runs followed by this error error: failed to push some refs to ..
I also tried the following without luck:
#!/bin/sh

php-cs-fixer fix . --config-file=".php_cs" && git commit -am 'PSR-2'

-
#!/bin/sh

(php-cs-fixer fix . --config-file=".php_cs" && git commit -am 'PSR-2')

According to this stackoverflow question, it should run only if cmd1 has succeeded.
Comment: Remove `exec`: `exec` replaces the current process by the command given in argument and never returns. It's both wrong and useless here.
Comment: The `git commit -am` _will be executed_ ***only if*** _`php-cs-fixer`_ ***succeeds***.
Comment: Did you try `exec (php-cs-fixer fix . --config-file=".php_cs" ; git commit -am 'PSR-2')`?
Comment: As a side note, your shebang is wrong: it should be `#!/bin/sh` (with no spaces between `#!` and `/bin/sh`).
Comment: Same happens when removing `exec`. I edited the question with the error given after `php-cs-fixer` runs.
Comment: So your first command failed (you have explicit errors—fix them!) and the second command is not executed. So all is as expected, isn't it? By the way, you second version with enclosing parentheses is useless! VonC mislead you with wrong/useless/random/inappropriate informations. Now your problem is about fixing `php-cs-fixer`. Good luck.
Comment: Yes the first command 'failed', in the sence that `php-cs-fixer` fixed some files. This is expected behaviour, nothing wrong with `php-cs-fixer`. That is why there's a `git commit -am` command to commit those changes before pushing.
Comment: Oh I see! need to use `;` instead of `&&`. Thank you!, works like a charm now :)
Comment: Or just put the two commands on separate lines.
Answer: The exec builtin command replaces the shell with the given program. It does NOT fork a new process to execute php-cs-fixer.
Since the shell is replaced by the php-cs-fixer program the && git commit ... is never executed.
Take a look at the manpage of exec

If command is specified, it replaces the shell. No new process is created.

The first line of php-cs-fixer should look like this
#!/usr/bin/env php

and the php-cs-fixer should have execute permissions chmod +x php-cs-fixer.
Than you can just use it
php-cs-fixer fix . --config-file=".php_cs" && git commit -am 'PSR-2'

Comment: Since OP's shebang is `#!/bin/sh`, maybe the POSIX reference is more appropriate than the Bash reference about `exec`: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_20_01
Comment: Hm thanks for you reply. Using `#!/usr/bin/env php

php-cs-fixer fix . --config-file=".php_cs" && git commit -am 'PSR-2'` shows the text (line break in between), but doesn't execute it. php-cs-fixer has executable rights. (I can run it outside the git hook)


What are the best fonts to use in a text heavy screen in smartphones?

Question: I am designing app for a online service provider. Most of the screens are text heavy. So which fonts are better to use?
Answer: Being a very legible font designed for user interfaces and with mobile device usage in mind, Droid Sans would not be an unreasonable font choice to go with.
A Google search (which I'm sure you've done already) will give you plenty of lists, but Ian Hex's article What Should I Look For In a UI Typeface?  on Design-by-IZO is definitely one of the better and more useful ones and coincidentally reaches the same conclusion I did above.

Note: Ariana Grande is not a font


How to count how much providers suppose the 80%

Question: I am trying to calculate with DAX the number of suppliers suppose the 80% of my buys.
I have a table with the name of the provider(NOMBRE PROVEEDOR), his category(código estadístico) and how much i have bought from each one of them(SUMA TODOS). Then i created a measured columns in Power Bi with DAX
 like folowing:
    TotalAmount = SUM('proveedor-estadistico'[SUMA TODOS])

AmountAllProduct = CALCULATE([TotalAmount];ALL('proveedor-estadistico'[NOMBRE PROVEEDOR]))

ProductRank = RANKX(ALL('proveedor-estadistico'[NOMBRE PROVEEDOR]);[TotalAmount])

ParetoValueProduct = SUMX(TOPN([ProductRank]; ALL('proveedor-estadistico'[NOMBRE PROVEEDOR]);[TotalAmount]);[TotalAmount])

Pareto%Product = DIVIDE([ParetoValueProduct];[AmountAllProduct];BLANK())

With this i obtain the Pareto(80/20), now what i need is too count the number of providers which is 80% of my purchases.
I tried this:
cuantos en 80 = CALCULATE(DISTINCTCOUNT('proveedor-estadistico'[NOMBRE PROVEEDOR]);FILTER('proveedor-estadistico';[Pareto%Product]<0,8))

but not Works, ¿What is wrong here?
-----------------------------------------------------------EDIT------------------------------------------------------------------
What i want is that if there are 10 suppliers (a, b, c, d, e, f, g, h, i, j) and we have bought a total of 100:
a -> 40
b -> 40
c -> 2.5
d -> 2.5
e -> 2.5
f -> 2.5
g -> 2.5
h -> 2.5
i -> 2.5
j -> 2.5

then 80% would do the suppliers a and b, so what I hope is that it will return 2
HERE I PUT AN IMAGE TO CLARIFY

Here we can see that when apply a filter the result is 7 providers, and what i want is to put a card(or another visualization) in which they appear how many suppliers represent 80% (0.8 out of 1) of the purchases, for this I have created a measure called Pareto%Product, but when I try to use it in a filter it appears as value 1
Comment: Can you please provide sample data and an example of what is your desired outcome?
Comment: I edited the question with a example
Answer: SQLBI has an awesome article about counting ABC classification,
which could be easily changed to pareto.
Simply speaking, you should not create a measure, but calculated column and label it there.
Article:
https://www.daxpatterns.com/abc-classification/


How to circumvent the fallacy of Python's os.path.commonprefix?

Question: My problem is to find the common path prefix of a given set of files.
Literally I was expecting that "os.path.commonprefix" would do just that. Unfortunately, the fact that commonprefix is located in path is rather misleading, since it actually will search for string prefixes.
The question to me is, how can this actually be solved for paths? The issue was briefly mentioned in this (fairly high rated) answer but only as a side-note and the proposed solution (appending slashes to the input of commonprefix) imho has issues, since it will fail for instance for:
os.path.commonprefix(['/usr/var1/log/', '/usr/var2/log/'])
# returns /usr/var but it should be /usr

To prevent others from falling into the same trap, it might be worthwhile to discuss this issue in a separate question: Is there a simple / portable solution for this problem that does not rely on nasty checks on the file system (i.e., access the result of commonprefix and check whether it is a directory and if not returns a os.path.dirname of the result)?
Comment: Related issue: http://bugs.python.org/issue10395. A patch is in the pipe line.
Comment: @bluenote10, Maybe we could changed accepted answer to the one for "cjac"?
Answer: It seems that this issue has been corrected in recent versions of Python.  New in version 3.5 is the function os.path.commonpath(), which returns the common path instead of the common string prefix.
Comment: Thanks!  This is Yet Another Reason to switch to python 3 -- glad I finally did it last year.
Answer: Awhile ago I ran into this where os.path.commonprefix is a string prefix and not a path prefix as would be expected. So I wrote the following:
def commonprefix(l):
    # this unlike the os.path.commonprefix version
    # always returns path prefixes as it compares
    # path component wise
    cp = []
    ls = [p.split('/') for p in l]
    ml = min( len(p) for p in ls )

    for i in range(ml):

        s = set( p[i] for p in ls )
        if len(s) != 1:
            break

        cp.append(s.pop())

    return '/'.join(cp)

it could be made more portable by replacing '/' with os.path.sep.
Comment: This gives a reasonable answer with both file or directory names, but in the general case you can't know for certain if the result of the function is a file or directory name without doing more work (such as by controlling the input). Also, I believe this returns the exact same result as `os.path.dirname(os.path.commonprefix([p + '/' for p in l]))`?
Comment: I accepted this answer since it is fairly robust while maintaining good brevity. It is interesting to see that in contrast to a solution based on `os.path.commenprefix` (see Dan Getz's answer), the component-wise comparison does not depend on whether the input paths are file or directory names (simply because filenames are unique components). For a more robust approach I recommend EOL's answer and to learn more about the problems of `os.path.commonprefix` Dan Getz' answer is very instructive. Thank you all!
Comment: @DanGetz It apparently does not do the same. I just tried it on windows by replacing it with `os.path.sep` and the code provided by @DanD results in the correct common path while your snippet returns `None`
Comment: @thatsIch what inputs cause that? I was unaware `dirname` *could* return `None`.
Comment: @DanGetz I must have messed it up somewhere. I just tried it again in a fresh environment and it works. My bad.
Answer: Assuming you want the common directory path, one way is to:

Use only directory paths as input. If your input value is a file name, call os.path.dirname(filename) to get its directory path.
"Normalize" all the paths so that they are relative to the same thing and don't include double separators. The easiest way to do this is by calling os.path.abspath( ) to get the path relative to the root. (You might also want to use os.path.realpath( ) to remove symbolic links.)
Add a final separator (found portably with os.path.sep or os.sep) to the end of all the normalized directory paths.
Call os.path.dirname( ) on the result of os.path.commonprefix( ).

In code (without removing symbolic links):
def common_path(directories):
    norm_paths = [os.path.abspath(p) + os.path.sep for p in directories]
    return os.path.dirname(os.path.commonprefix(norm_paths))

def common_path_of_filenames(filenames):
    return common_path([os.path.dirname(f) for f in filenames])

Comment: When I was thinking about this idea I rejected it initially, because I though appending a slash is a problem when working with relative paths, like a blank file name in the current directory. However, when wrapping all paths into `os.path.abspath`, even a mixture of relative and absolute paths should be no problem, right?
Comment: @bluenote10 Right, `abspath` instead of `normpath` will handle the relative paths. Not sure about blank file names, because that's ambiguous with duplicated path separators. Does anyone allow zero-length file names?
Comment: Oh, I didn't mean empty file names, just `"aSimpleFileName"`.
Comment: One should probably mention that it all depends on whether `paths` are _file_ paths or _directory_ paths (this must be a convention in case we want to avoid file system access). In my problem `paths` would be in fact files not directories. I think in this case the proper order is: (a) convert to abspath to deal with mixture of relative/absolute paths; (b) apply dirname to convert to a proper directory. From that point I think we can safely apply your solution.
Comment: Oh, now I see it, good point. You need to know in advance if your string is a file or directory path. I thought I was getting around that, but instead I was just assuming directories.
Comment: I think it is important to mention that one cannot simply take the dirname on the input. I tried to edit the question to make that clear. Feel free to revert if I screwed things up :).
Comment: Hey, looks like someone already reverted it. I looked at what you wrote, and tried to rewrite my answer to make it clearer about how you need to be careful to not use file paths (that is, to get the directory path first).
Comment: In my edit I tried to explain why what you suggested does not work for files. I think it is not possible to call dirname on the input to `common_path`. This would discard information on relative paths, because `abspath(dirname("somefile.txt")) != dirname(abspath("somefile.txt"))`. Imho it is necessary to have a separate version of `common_path`, which internally does _first_ abspath _then_ dirname (the other way around compared to applying dirname to the argument). Don't know why my edit was discarded :(.
Comment: For a relative path, I see no problem. Are you talking about file links? Do you have an example where it really is true that `abspath(dirname(x)) != dirname(abspath(x))`? They're equal for the example you gave.
Comment: You're right! I was wrongly assuming that abspath of an empty string would be evaluated to "the absolute path that does not even contain the root slash", i.e., another empty string. I'm glad I finally see the cause of my confusion. Thanks for making that clear!
Answer: A robust approach is to split the path into individual components and then find the longest common prefix of the component lists.
Here is an implementation which is cross-platform and can be generalized easily to more than two paths:
import os.path
import itertools

def components(path):
    '''
    Returns the individual components of the given file path
    string (for the local operating system).

    The returned components, when joined with os.path.join(), point to
    the same location as the original path.
    '''
    components = []
    # The loop guarantees that the returned components can be
    # os.path.joined with the path separator and point to the same
    # location:
    while True:
        (new_path, tail) = os.path.split(path)  # Works on any platform
        components.append(tail)
        if new_path == path:  # Root (including drive, on Windows) reached
            break
        path = new_path
    components.append(new_path)

    components.reverse()  # First component first
    return components

def longest_prefix(iter0, iter1):
    '''
    Returns the longest common prefix of the given two iterables.
    '''
    longest_prefix = []
    for (elmt0, elmt1) in itertools.izip(iter0, iter1):
        if elmt0 != elmt1:
            break
        longest_prefix.append(elmt0)
    return longest_prefix

def common_prefix_path(path0, path1):
    return os.path.join(*longest_prefix(components(path0), components(path1)))

# For Unix:
assert common_prefix_path('/', '/usr') == '/'
assert common_prefix_path('/usr/var1/log/', '/usr/var2/log/') == '/usr'
assert common_prefix_path('/usr/var/log1/', '/usr/var/log2/') == '/usr/var'
assert common_prefix_path('/usr/var/log', '/usr/var/log2') == '/usr/var'
assert common_prefix_path('/usr/var/log', '/usr/var/log') == '/usr/var/log'
# Only for Windows:
# assert common_prefix_path(r'C:\Programs\Me', r'C:\Programs') == r'C:\Programs'

Answer: I've made a small python package commonpath to find common paths from a list. Comes with a few nice options.
https://github.com/faph/Common-Path
Comment: Cool little package! :)


390 MHz Garage Door Opener and Raspberry Pi

Question: I have a lovely Genie garage door opener (I couldn't find a model number but it looks like this) that I've been wanting to upgrade for a while. I'd like to open it with an RF transmitter attached to a Raspberry Pi, as I'm uncomfortable wiring the Pi directly into the opener as some tutorials suggest.
I have been using a Genie GT90-1 remote to open the garage for years, and it seems as though it should be simple to use LIRC with an RF transceiver on the right frequency. This is where I've run into trouble, because while the opener and remote appear to operate on the 390 MHz frequency (reference one and two) I am having trouble finding any sort of 390 MHz transmitter/receiver that will connect properly to the Pi, most devices operating at 390 MHz appear to be Genie replacement remotes.
Is there any way I can make this project work, or is it DOA? The main obstacle seems to be finding a transmitter and receiver. Can I use something of lower/higher frequency, or some other alternative?
Thanks
Comment: The next problem is knowing WHAT to transmit on 390 MHz.  Genies intellicode was invented specifically to make it rather difficult to open a different door.   Just transmitting at 390 MHz is half the battle--the other is you must know what data to send.
Comment: @Tyson as I understand it I can use lirc to record the signal from the remote and then retransmit that.
Comment: Lirc works with infrared remotes.  Garage door remotes are RF since they must work from outside. Non-compatible technologies.
Comment: @Tyson but if I tell it it's an infrared bulb it won't know the difference. It's just for capturing and replaying the timings
Comment: Good luck, have fun.
Comment: Expanding on @Tyson response - Most modern garage door openers do not repeat their transmission patter; they have a "rolling" code specifically to prevent recording and replaying the signal (https://en.wikipedia.org/wiki/Rolling_code). This means you cannot just record the signal, but need to know the algorithm used to produce each subsequent pattern.
Comment: @Roberto my car can open the garage door. Shouldn't that be the same thing? I think this opener is older than rolling security
Comment: Garage door openers built into cars only work because the major garage door open companies licence the automakers and provide the chip to make it work.  There is two steps to programming in car remotes.  Step 1 envoles identifing which type of remote you have, in step 2 the car transmitter handshakes with the opener to initialize the rolling codes.  Without rolling codes anyone could open any garage door with very little effort.
Comment: You should tell us why you want the pi to controller the garage door.  Will the pi always be local?  or are you trying to carry the pi with you and use it as a remote?  Or are you trying to figure out how to build a burglar tool?  You are truly currently presnting this in classic [X-Y problem](http://xyproblem.info/) style.
Comment: @Tyson that Genie is older than rolling codes. You set it with DIP switches and yes you can hack them open in under 3 minutes by trying all the code combinations with a special transmitter. The newer openers have rolling codes with 2+ billion possibilities.
Comment: @Tyson I have a spare pi that I want to sit on my desk and automate my garage door, so I can open it with my phone w/o buying a new opener. All I really want from this post is a way to operate on 390 MHz RF, or to hear that it's impossible without using another remote.
Comment: If it's on 390mhz it's not older than rolling codes.. I took a quick look on mouser and the parts are available, it's not quick and easy or cheap tho.
Comment: If you want to proceed study this: http://www.mouser.com/ds/2/268/21143b-64900.pdf
Comment: @Tyson I am 90% sure this opener does not use rolling/hopping codes. The remote has dip switches in it, and as far as I can tell dip switches and rolling codes are mutually exclusive. Is there a scenario where both could coexist in my system?
Comment: If it's in the 300-400mhz range it's code hopping.  The dip switchs provide the seed for the psuedo random number generator.  If it was older than code hopping technology it would be in the VHF range (a frequency in the 100's).  For more background read the "remote control" section of [this](https://en.m.wikipedia.org/wiki/Garage_door_opener) article.
Comment: @Tyson this is what I found. "These systems required a garage door owner to preset a digital code by switching eight to twelve DIP switches on the receiver an transmitter... [Criminals] could also make code grabbers to record and re-transmit a signal, or code scanners, that would attempt every possible combination in a short time." Retransmitting the signal sounds like exactly what I want to do. Did I misread?
Answer: You're making this more difficult than it needs to be. Use a relay connected to the R pi. If you want it wireless, then have the relay switch the button on the remote. If you want it wired, connect the relay directly to the garage door opener to its terminals to open/close it.
Comment: I would like to avoid hardwiring it, as I said in my post. I would also like my remote to remain separate. However, I understand the complexity of this project and will probably end up buying a second remote to do as you suggest
Answer: A second remote is probably the best wireless option, different makes an models of garage door remotes will have varying levels of difficulty interfacing with the buttons. It is almost guaranteed that  soldering will be involved.  If you are placing the Pi anywhere near the vicinity of the garage door I would wire a relay directly across the existing button.   If your PI is not going to be in the garage and assuming you have WiFi in the garage you could consider an ESP8266 with a relay controlled over WiFi with your Pi you could even use this setup to install a sensor to tell you if your door is open or closed.


Missing ipmi Device (Remote Access Card) / ipmitool Failue: Could not open device at /dev/ipmi0 ... No such file or directory

Question: I recently bought second-hand a HP Proliant N36L Microserver, and I'm having trouble configuring it for remote access on Ubuntu Server 20.04 LTS.
It came with a HP Remote Access card, but when I try to access its web server (following this setup guide) and enter the default credentials ("admin" / "password"), the credentials are incorrect.
The remote access card user manual (page 63) gives a method to reset the credentials:

Under Linux shell:
    Get the user name:
      ipmitool raw 0x6 0x46 0x02 (the value "2" is the User ID)
    Set user password:
      ipmitool raw 0x6 0x47 0x02 0x02 + password (Password is ASCI value: 16 bytes)

The problem I have is that when I try and run the ipmitool command, I am presented with the following error message:
Could not open device at /dev/ipmi0 or /dev/ipmi/0 or /dev/ipmidev/0: No such file or directory
There is a similar known issue in that additional "Configuration Required for IPMITOOL Management Utility to Function on any HP ProLiant Server With an Integrated Lights-Out 2 (iLO 2) and Running Ubuntu Linux 9.04 Server"
It states you need to load the following modules with the following commands:
modprobe ipmi_msghandler
modprobe ipmi_devintf
modprobe ipmi_si

... which I have done, to get ipmitool to work.
I've also added them to the /etc/modules files so they load during boot.
When I run lsmod | grep ipmi, I get the following:
ipmi_devintf           65536  0
ipmi_si                20480  0
ipmi_msghandler       106496  2 ipmi_devintf,ipmi_si

so clearly the modules have been loaded and are running... right?
From what I understand, in Ubuntu, the ipmi service/daemon starts automatically when these commands are run.
Despite all this, even when I run the ipmitool command without any arguments, it fails with the main Could not open device at... error.
Why isn't the /dev/ipim0 device being created automatically?
Do I need to create the /dev/ipim0 device manually?
I did try to create the device manually following this guide but even afterwards the ipmitool command still gave the same error.
How can I solve this issue?
Answer: I ran into the same problem ... just recently ;)
Just tried to follow the way to add some paraemeters to the kernel so that the address of the device is correct ... ( if I understand well )
Found this solution via link : http://bodgitandscarper.co.uk/tag/microserver/ look at one of the topics. He found the answer to his problem at http://patgardner.blogspot.co.uk/2013/03/hp-microserver-remote-management-card.html ...
Adding the parameters "ipmi_si.type=kcs ipmi_si.ports=0xca2" to the kernel startup command in grub did the trick for me in Ubuntu 18 lts.
After reboot:
sudo ipmitool chassis status
--> worked
sudo ipmitool raw 0x6 0x46 0x02
--> worked
Hope this helps you,
Greetings
Jan.


center the horizontal sub menu corresponding to the menu hovered

Question: I have creted a horizontal submenu
http://www.theawesomecoder.com/lifecloud/
but its always left aligned i want to be centered from the menu it is hovered
the left and right ends of menu should be at equal distance from the menu hovered
presently i am using this code :
ul#topnav {
    margin: 0; padding: 0;
    float: left;
    width: 970px;
    list-style: none;
    position: relative;
    font-size: 1.2em;
    background:#000;
}
ul#topnav li {
    float: left;
    margin: 0; padding: 0;
    border-right: 1px solid #555;
}
ul#topnav li a {
    padding: 10px 15px;
    display: block;
    color: #f0f0f0;
    text-decoration: none;
}
ul#topnav li:hover { background: #1376c9 ; }
ul#topnav li span {
    float: left;
    padding: 15px 0;
    position: absolute;
    left: 0; top:35px;
    display: none;
    width: 970px;
    background: #1376c9;
    color: #fff;
    -moz-border-radius-bottomright: 5px;
    -khtml-border-radius-bottomright: 5px;
    -webkit-border-bottom-right-radius: 5px;
    -moz-border-radius-bottomleft: 5px;
    -khtml-border-radius-bottomleft: 5px;
    -webkit-border-bottom-left-radius: 5px;
}
ul#topnav li:hover span { display: block; }
ul#topnav li span a { display: inline; }
ul#topnav li span a:hover {text-decoration: underline;}
</style>

Home

        About

            The Company |
            The Team |
            Careers

        Services

            What We Do |
            Our Process |
            Testimonials

        Portfolio

            Web Design |
            Development |

Contact

Answer: You have a position:absolute;, but you do not have a corresponding parent having position:relative;. If you add it as below, your issue would be resolved.
Here is what you need to do.
.navbar .nav > li {
    display: block;
    float: right;
    margin: 0 0 0 10px;
    padding: 0;
    position: relative;
}

Secondly, to make it at the center, add the below.
.navbar .nav li span {
    color: #0000CC;
    display: none;
    float: left;
    font-family: Arial,Helvetica,sans-serif;
    left: -90px;
    padding: 15px 0;
    position: absolute;
    top: 45px;
    width: 970px;
}

Hope this helps.


FileNotFoundException in apache spark(1.6) job during shuffle files

Question: I am working on spark 1.6, it is failing my job with following error

java.io.FileNotFoundException: /data/05/dfs/dn/yarn/nm/usercache/willir31/appcache/application_1413512480649_0108/spark-local-20141028214722-43f1/26/shuffle_0_312_0.index (No such file or directory)
          java.io.FileOutputStream.open(Native Method)
          java.io.FileOutputStream.(FileOutputStream.java:221)
          org.apache.spark.storage.DiskBlockObjectWriter.open(BlockObjectWriter.scala:123)
          org.apache.spark.storage.DiskBlockObjectWriter.write(BlockObjectWriter.scala:192)
          org.apache.spark.util.collection.ExternalSorter$$anonfun$writePartitionedFile$4$$anonfun$apply$2.apply(ExternalSorter.scala:733)
          org.apache.spark.util.collection.ExternalSorter$$anonfun$writePartitionedFile$4$$anonfun$apply$2.apply(ExternalSorter.scala:732)
          scala.collection.Iterator$class.foreach(Iterator.scala:727)
          org.apache.spark.util.collection.ExternalSorter$IteratorForPartition.foreach(ExternalSorter.scala:790)
          org.apache.spark.util.collection.ExternalSorter$$anonfun$writePartitionedFile$4.apply(ExternalSorter.scala:732)
          org.apache.spark.util.collection.ExternalSorter$$anonfun$writePartitionedFile$4.apply(ExternalSorter.scala:728)
          scala.collection.Iterator$class.foreach(Iterator.scala:727)
          scala.collection.AbstractIterator.foreach(Iterator.scala:1157)
          org.apache.spark.util.collection.ExternalSorter.writePartitionedFile(ExternalSorter.scala:728)
          org.apache.spark.shuffle.sort.SortShuffleWriter.write(SortShuffleWriter.scala:70)
          org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:68)
          org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:41)

I am performing join operations. When i carefully look into the error and check my code i found it is failing while it is writing back to CSV from dataFrame. But i am not able to get rid of it. I am not using hdp,  i have separate installation for all components.
Comment: It's funny that you have the exact same stacktrace as this guy back in 2014 http://apache-spark-user-list.1001560.n3.nabble.com/FileNotFoundException-in-appcache-shuffle-files-td17605.html
Answer: This types of errors typically occur when there are deeper problems with some tasks, like significant data skew. Since you don't provide enough details and job statistics the only approach that I can think off is to significantly increase number of shuffle partitions:
<code>sqlContext.setConf("spark.sql.shuffle.partitions", 2048)
</code>


How can I see the full stacktrace in Android?

Question: I'm using intelliJ. My problem is the "... 8 more" as seen at the bottom of the stacktrace. I need to know those 8 more lines. What is causing this? How can I show all lines????
<code>06-25 00:02:39.459: ERROR/System(4065): Uncaught exception thrown by finalizer
06-25 00:02:39.459: ERROR/System(4065): java.io.IOException: close failed: EIO (I/O error)
        at libcore.io.IoUtils.close(IoUtils.java:41)
        at java.io.FileInputStream.close(FileInputStream.java:121)
        at java.nio.FileChannelImpl.implCloseChannel(FileChannelImpl.java:91)
        at java.nio.channels.spi.AbstractInterruptibleChannel.close(AbstractInterruptibleChannel.java:80)
        at java.io.FileInputStream.close(FileInputStream.java:118)
        at java.io.FileInputStream.finalize(FileInputStream.java:142)
        at java.lang.Daemons$FinalizerDaemon.doFinalize(Daemons.java:186)
        at java.lang.Daemons$FinalizerDaemon.run(Daemons.java:169)
        at java.lang.Thread.run(Thread.java:856)
        Caused by: libcore.io.ErrnoException: close failed: EIO (I/O error)
        at libcore.io.Posix.close(Native Method)
        at libcore.io.BlockGuardOs.close(BlockGuardOs.java:75)
        at libcore.io.IoUtils.close(IoUtils.java:38)
        ... 8 more
</code>
Answer: You are seeing a deliberate optimization.  The 8 lines are the same as the last 8 lines in the stack trace just preceding it.
Comment: There are no references to any classes in my app. I believe they are hidden in those 8 lines. Why is the stacktrace not originating my app?
Comment: No, I've just done some Googling and my error is caused by some file not being closed properly somewhere. I will bound in on the issue using manual debugging and report my findings shortly. thanks!
Comment: I have 3 services, but I am not calling startActivity from any of them...how can I bound in on this issue given I have no idea how to reproduce it??
Comment: Finalizers are run outside your own code.  The actual object with the finalizer is allocated elsewhere and not properly closed.  It looks like a FileInputStream object - do you have any of these in your code?


How to make "n" level folder tree by mkdir -p or bat script on windows?

Question: As you may know, md -p can create a tree folder like:
mkdir -p
but how to create a "n" deep folder by script such as bat or any other?
Directory tree sample:
 - C:\
 -- 001
 --- 002
 ---- 003
 ..............
 ----- n
Thanks anyway
Rover
Comment: cmd's `mkdir` / `md` command is already equivalent to Unix `mkdir -p`. There is no '-p' option.
Comment: How do you know what you're going to call the subdirectories? Or is it literally going to be 001/002/003/etc?
Answer: This script will create 999 folders inside each other (from 001 to 999):
@ECHO OFF
FOR /L %%i IN (1,1,999) DO (
    IF %%i LSS 10 (
        MD 00%%i
        CD 00%%i
    ) ELSE (
        IF %%i LSS 100 (
            MD 0%%i
            CD 0%%i
        ) ELSE (
            MD %%i
            CD %%i
        )
    )
)
PAUSE

Comment: Or in this simpler way: `for /L %%i in (1001,1,1999) do (set i=%%i & md !i:~1! & cd !i:~1!)`, but the resulting folders will probably exceed the maximum length for a name supported by Windows.
Comment: Thank you MichaelS ! you are the answer!
Answer:  ( for /l %a in (1 1 10) do md %a & cd %a ) & cd "%cd%"

To be used from command line. To use it inside a batch file, percent signs need to be escaped, replacing %a with %%a
For a padded version you can use
cmd /v /c "for /l %a in (1001 1 1005) do (set "x=%a" & md !x:~-3! & cd !x:~-3!)"

Comment: Thank you MC ND ! you are the answer!
Comment: According to your explanation, my understanding is :
[For bat]
for /l %%a in (1 1 10) do md %%a & cd %%a & cd "%cd%"
Comment: @SkyRover, the parenthesis in the code are needed. The last `cd "%cd%"` (that simply return to the starting point) should be executed when the `for` has ended creating the hierarchy.
Answer: If Command Extensions are enabled (the default) then MD command will create all intermediate directories in the given path if they don't exists, so you just need to enter something like this:
md C:\001\002\003

Comment: Thanks Aacini, I know md could make all directories, but waste time if I need to create 100 level just by typing in hand.....


Improper Integral with product of series

Question: I am trying to solve $$ \int_0^\infty \left(x-\frac{x^3}{2}+\frac{x^5}{2\cdot 4}-\frac{x^7}{2\cdot 4\cdot 6 }+\cdots\right)\left(1+\frac{x^2}{2^2}+\frac{x^4}{2^2\cdot 4^2}+\frac{x^6}{2^2\cdot 4^2\cdot 6^2 }+\cdots\right)\text dx$$
but failed, even the left hand side can be expressed as $x\cdot e^{-x^2 /2}$, I can still not deal with the second parenthesis. Is there anyway to evaluate this integral when integrand involved series which is a sum of squares ?
Comment: For the second series, look here ($\nu=0$): https://dlmf.nist.gov/10.25#E2
Comment: The second parenthesis is the modified Bessel function of the first kind $I_0(x)$
Comment: Thanks for informing me this, I would try to understand Bessel function.
Answer: Rather than knowing the series on the right outside of a general term, try distributing what you do know and make another series that you can integrate with.
I know it seems vague, but that's how I got the answer and I figured you want to solve this on your own.
If you want me to explain what I did, I can.
Comment: Arrr.... Yes, I forgot this trick, to distribute the terms with $x\cdot e^{-x^2/2}$. The rest part is not hard. Actually, I was told that this problem is from Putnam.


Javascript Array - Create Map with items within a tolerance

Question: Take the following Javascript Array:
<code>["21587569", "21587570", "21587572", "31856855", "31856854"]
</code>
You can visually see that the first 3 items are within a limit of 5 of any other item in that "group", the same can be said for the items at index 3 & 4.
How can I group these "similar" items using Javascript array functions, such as the following output array?
<code>[{"21587569", "21587570", "21587572"},{"31856855", "31856854"}]
</code>
The items may not always be presented in order as they are in the example input array.
Comment: Does each number need to be within 5 digits of ANY item in the group, or EVERY item?
Comment: I believe you are looking for ***clustering*** algorithms. You may want to Google for it.
Comment: @404 - that's a good point. Each item needs to be within 5 of ANY of the other items.
Comment: please add an exampel for it. what about the order? what if you have `21587575` as well. should it be alone or take a smaller item as well, and how much?
Comment: @NinaScholz - This data is a subset of a larger set of data and the numbers in question are sequence numbers. Therefore they will always be unique. A real-world example is: 25932906,25932910,25932912,25932995,25932996,25933013,25933014
These sequence numbers all occurred within the same millisecond of this smaller dataset and therefore. Items with grouped or almost grouped sequence numbers are likely to be related (nanosecond timing is not available in this dataset).
Answer: You could sort and get groups if the delta of last items is smaller than five.

<code>const
    data = [21587569, 21587570, 21587572, 31856855, 31856854],
    result = [...data]
        .sort((a, b) => a - b)
        .reduce((r, v) => {
            const last = r[r.length - 1];
            if (!last || v - last[last.length - 1] > 5) r.push([v]);
            else last.push(v);
            return r;
        }, []);

console.log(result);
    </code>
Comment: This is exactly what I was looking for, thanks!


Bitronix transaction getting exception while loading mule

Question: I just put an entry like this in aboveof flow <bti:transaction-manager />
The below exception i got it.
caused by:

org.mule.api.config.ConfigurationException: Line 12 in XML document from URL [file:/D:/mule-standalone-3.8.1/mule-standalone-3.8.1/apps/inbound3/inbound3.xml] is invalid; nested exception is org.xml.sax.SAXParseException: cvc-complex-type.2.4.a: Invalid content was found starting with element 'bti:transaction-manager'. One of {"http://www.mulesoft.org/schema/mule/core":annotations, "http://www.mulesoft.org/schema/mule/core":description, "http://www.springframework.org/schema/beans":beans, "http://www.springframework.org/schema/beans":bean, "http://www.springframework.org/schema/context":property-placeholder, "http://www.springframework.org/schema/beans":ref, "http://www.mulesoft.org/schema/mule/core":global-property, "http://www.mulesoft.org/schema/mule/core":configuration, "http://www.mulesoft.org/schema/mule/core":notifications, "http://www.mulesoft.org/schema/mule/core":abstract-extension, "http://www.mulesoft.org/schema/mule/core":abstract-shared-extension, "http://www
  .mulesoft.org/schema/mule/core":abstract-mixed-content-extension, "http://www.mulesoft.org/schema/mule/core":abstract-agent, "http://www.mulesoft.org/schema/mule/core":abstract-security-manager, "http://www.mulesoft.org/schema/mule/core":abstract-transaction-manager, "http://www.mulesoft.org/schema/mule/core":abstract-shared-transaction-manager, "http://www.mulesoft.org/schema/mule/core":abstract-connector, "http://www.mulesoft.org/schema/mule/core":abstract-shared-connector, "http://www.mulesoft.org/schema/mule/core":abstract-global-endpoint, "http://www.mulesoft.org/schema/mule/core":abstract-exception-strategy, "http://www.mulesoft.org/schema/mule/core":abstract-flow-construct, "http://www.mulesoft.org/schema/mule/core":flow, "http://www.mulesoft.org/schema/mule/core":sub-flow, "http://www.mulesoft.org/schema/mule/core":abstract-model, "http://www.mulesoft.org/schema/mule/core":abstract-interceptor-stack, "http://www.mulesoft.org/schema/mule/core":abstract-filter, "http://www.mules
  oft.org/schema/mule/core":abstract-transformer, "http://www.mulesoft.org/schema/mule/core":processor-chain, "http://www.mulesoft.org/schema/mule/core":custom-processor, "http://www.mulesoft.org/schema/mule/core":abstract-empty-processor, "http://www.mulesoft.org/schema/mule/core":invoke, "http://www.mulesoft.org/schema/mule/core":set-payload, "http://www.mulesoft.org/schema/mule/core":abstract-global-intercepting-message-processor, "http://www.mulesoft.org/schema/mule/core":custom-queue-store, "http://www.mulesoft.org/schema/mule/core":abstract-processing-strategy}' is expected. (org.mule.api.lifecycle.InitialisationException) (org.mule.api.config.ConfigurationException)
Answer: Have you added bitronix namespaces in the xml headers? Make sure that you add the below XML namespaces for Bitronix transaction manager to work.
Check more details at https://docs.mulesoft.com/mule-user-guide/v/3.8/using-bitronix-to-manage-transactions
Comment: If i deployed it in mule standalone server it throw exception. If i run it in Any point studio its working fine.@RamakrishnaN
Comment: Are you using community standalone or enterprise standalone server?
Comment: I down loaded from the below link [link]https://repository-master.mulesoft.org/nexus/content/repositories/releases/org/mule/distributions/mule-standalone/3.8.1/mule-standalone-3.8.1.zip
Comment: Bitronix Transaction Manager is a Mule enterprise feature. You can't run that on the Mule community standalone server.


Spring cloud gateway default routing doesn't work

Question: I want enable default routing in my spring cloud gateway (no zuul) by service ids registered in eureka (application names) but I always got 404 error.
In my chat service's bootstrap.yml
I have defined application name
spring:
  application:
    name: chat-service

and in application properties:
eureka:
  instance:
    preferIpAddress: true
  client:
    healthcheck:
      enabled: true
    serviceUrl:
      defaultZone: http://${EUREKA_HOST:localhost}:${EUREKA_PORT:8761}/eureka/

when I go to eureka's dashboard I can see registered my chat service and gateway as well.
Eureka's configuration in gateway application is same as chat service, but I also have this:
spring:
  application:
    name: gateway
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true

and next I also tried add explicit routes which din't work as well, but if I have discovery locator enabled set to true this shouldn't be needed right?
  routes:
    - id: chat-service-route
      uri: lb://chat-service
      predicates:
        - Path=**

I created test endpoint which I tried call directly on chat service and also with gateway. Direct call works fine so issue will be with routing.
@RestController
@RequestMapping
public class TestController {

    @GetMapping
    public String test() {
        return "chat-service ready";
    }
}

What I did wrong? I am little desperate. I am using spring boot 2.2.2 and Hoxton.RELEASE cloud dependencies version
Comment: Can you explain what "doesn't work" means? What url did you try?
Comment: @spencergibb I'm sorry I should wrote it more cleaner. I always got 404 error for rest endpoint in chat service when I call it from gateway
Comment: What url are you calling on the gateway?
Comment: @spencergibb gateway runs on 8080 so I call localhost:8080/chat-service
Comment: And does chat service respond to /chat-service? Otherwise you need to rewrite the path
Comment: in logs is called eureka and looks like match with chat-service, also I tried call actuator on /chat-service/actuator and return some info about port where runs chat service
Comment: Not what I'm asking. Does http:///chat-service work?
Comment: I am little confused I dont have /chat-service endpoint in chat service. I tried it and no, I got 404 .. but when I try access directly without gateway isn't right behavior?
Answer: Try removing explicit routes and add below property to application yml. This works for me.
spring:
  cloud:
    gateway:
      discovery:
        locator:
          lower-case-service-id: true

Answer: In the end service:
server.port=8993
spring.application.name=department-service
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/
management.endpoints.web.exposure.include=*
eureka.instance.hostname=localhost

In the api-gateway project:
server.port=9191
spring.application.name=api-gateway
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/

management.endpoints.web.exposure.include=*

logging.level.root=INFO
logging.level.org.springframework.cloud.gateway=TRACE
logging.level.org.springframework.cloud.gateway.route=INFO

spring.cloud.gateway.discovery.locator.enabled=true
spring.cloud.gateway.discovery.locator.lower-case-service-id=true

Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


What kind of electrical projects are safe for DIY in the US?

Question: I have a lot of ideas for electrical projects — upgrading electrical sockets to USB combo sockets, changing light fixtures, adding new sockets...ect.
As a general rule of thumb, what kinds of electrical projects are safe to as a DIYer?
Comment: How does Ohms law factor into replacing an output or switch? You don't have to understand the relation between resistance, voltage and current to know that making a good electrical connection is important, and no amount of understanding of Ohms law will tell you why it's important to get hot and neutral (and ground) connected correctly even if the outlet would work even if it's not -- all you need to know is that you get shocked (possibly fatally) when you touch 120V.
Comment: I would have to say, if you don't have a basic understanding of Ohm's Law, none. If you have at least that, then the next question would be, just how much electrical knowledge do you have?
Comment: I have no understanding of Ohm's law. I can do basic carpentry and other DIY tasks. I can follow instructions.
Answer: It all depends on how much you are willing to learn. If you are confident in your ability to do it safely, go for it. If not, do more research until you are or hire an electrician.
Personally I am confident doing anything up to replacing a main electrical panel. That is something I would have to hire an electrician for, even though I could in theory do it, because you need permits and the hydro company's involvement and such.
Replacing outlets and light fixtures is pretty easy once you know how to work around electrical safely.  One small tip though - when you pull them out, but before you disconect anything - take lots of photos of how all the wires were hooked up.  Just having those photos would prevent tons of the electrical questions we get here.
Comment: Ditto on the photos. Especially since photos are so darned easy these days with nearly everyone carrying around a smart phone. The photos are actually of more benefit to the DIY'er than they are to the folks who answer questions here.
Comment: Hell, I take photos (sometimes video so I can explain something) when I'm *done* sometimes - it recently saved me from having to figure out how I'd wired a couple junction boxes 4 years ago.
Comment: @comintern every renovation project I take photos of every walll before all the drywall goes up - very handy years later when I want to change something, or need to know exactly where a pipe or wire is.


Changing height of all elements with same type of ids at once

Question: I have the following code:

Now I want to change the height of all elements with id's ending with _vertical to be automatically set to its parent height, I mean it should get resized automatically in case its parent's div's height increses that increase will be due to addition on some more elements to its botherly div.
For example:
On adding some stuff to mainDiv313 will increase its parent height i.e. mainDiv31 height which in turn should increase mainDiv31_vertical
What should be assigned to height of mainDiv31_vertical so that it exhibits this behavior. i would prefer not changing it by JS or Jquery as it increases processing...
Already set it to inherit as it will make it inherit the height from parent.
Please suggest something.
EDIT
i want something like
div1 -->div11
       >div1_vertical
       >div12

this means div1 has these 3 other div in it on change div11 height div1_verticalheight should change automatically without some js or jquery i want some css property
i haven' mentioned any height on div1 so it automatically adjusts it children
Comment: I'd simplify that layout and use classes. For some CSS3 selectors, look here: http://www.w3.org/TR/css3-selectors/#selectors
Answer: You can do this with jQuery:
$("div[id$='_vertical']").height(function(){
  return $(this).parent().height();
});

But dear lord, you shouldn't. IDs should be unique and semantic, not descriptive of a property. That's what classes are for. Use a class="vertical" instead
Comment: In his exemple ids are uniques but i agree a class is more accurate.
Comment: i know we should use unique ids and i am using them uniquely. but i was not using power of jQuery before and was using plane javascript thats why needed identifier for those special divs hence created like it
Answer: To set all div elements with an id that ends with _vertical, this should do the trick:
$("div[id$='_vertical']").height(function(){
    return $(this).parent().height();
});

However, it is not possible to do this automatically when the parent height is changed because there are no events to bind to when it comes to DOM manipulation and mutation.
I also agree with Roland that you shouldn't have _vertical in your id, but rather as a separate class.
Here's an example using CSS with relative/absolute positioning that might work for you.
CSS
div.vertical {
    position: relative;
}

div.vertical div {
    position: absolute;
    top: 0;
    bottom: 0;
}

HTML

Comment: I forgot to wrap my parent height in a function, oops. But you missed an ending bracket, ha! Denmark-Sweden 1-1
Comment: @Jens, Haha! Actually, the bracket is in there but it's not showing?! [See proof](http://gyazo.com/784bacbfaf2330b6ff8c7b9bcc03f5a1.png) Edit: Ah, must be a cache issue. I see that you edited my answer. Thanks!
Comment: this wont change the height of element with vertical at the end of id when a divs height is increased that is child of parent of vertical
Comment: @Valun, I'm not sure I'm following. Do you want to change the height of the parent or the child? You are stating in your question that you want to set the height of the newly appended child to the same of its parent, or did I misunderstand that?