Splitting one row into multiple rows with mutate error

Question: I have a df akin to df1 where I want to break out the rows so that the Hrs_Time_Worked column is in intervals of 4, shown in df2.
I have been using the following code, but it throws an error:
df2 = df1 %>%
 group_by(Row)%>%
 mutate(S=START_DATE_TIME,
        Hrs_Time_Worked=list((n<-c(rep(4,Hrs_Time_Worked%/%4),Hrs_Time_Worked%%4))[n!=0]))%>%
 unnest()%>%
 mutate(E=START_DATE_TIME+hours(cumsum(Hrs_Time_Worked)),
        S=E-hours(unlist(Hrs_Time_Worked)),
        START_DATE_TIME=(S),
        END_DATE_TIME=(E),
        S=NULL,E=NULL)

Error in mutate_impl(.data, dots) : Evaluation error: invalid class
  Period object: periods must have integer values.

The following are required:
All categorical data must remain the same on child rows (e.g., TIME_RPTG_CD
   stays the same on every child row)
If there is a remainder that is
   less than four, the remainder amount should be listed on the last
   line (e.g., df2; row 3)
If a child row starts or ends on the next
   date the date column should be updated accordingly (e.g., df2; row 2-3)
df1 (current)
   Row EMPLID TIME_RPTG_CD START_DATE_TIME     END_DATE_TIME       Hrs_Time_Worked
       <chr>  <chr>        <dttm>              <dttm>                        <dbl>
     1 X00007 REG          2014-07-03 16:00:00 2014-07-03 02:00:00            10.0

df2 (desired)
Row EMPLID TIME_RPTG_CD START_DATE_TIME     END_DATE_TIME       Hrs_Time_Worked
    <chr>  <chr>        <dttm>              <dttm>                        <dbl>
1   X00007 REG          2014-07-03 16:00:00 2014-07-03 20:00:00            4.0
2   X00007 REG          2014-07-03 20:00:00 2014-07-04 24:00:00            4.0
3   X00007 REG          2014-07-04 24:00:00 2014-07-04 02:00:00            2.0

Comment: Please share the output of `dput(df1)`
Comment: Here is the solution that's worked: https://stackoverflow.com/questions/50690217/splitting-single-data-frame-row-into-multiple-rows-while-performing-calculation
Answer: One of the approach could be
library(dplyr)
library(tidyr)
library(lubridate)

df %>%
  rowwise() %>%
  mutate(START_DATE_TIME = paste(seq.POSIXt(START_DATE_TIME, END_DATE_TIME, by = "4 hour"), collapse = ",")) %>%
  separate_rows(START_DATE_TIME, sep = ",") %>%
  group_by(Row) %>%
  mutate(END_DATE_TIME   = ymd_hms(lead(START_DATE_TIME, order_by = Row, default = as.character(END_DATE_TIME))),
         START_DATE_TIME = ymd_hms(START_DATE_TIME),
         Hrs_Time_Worked = as.numeric(difftime(END_DATE_TIME, START_DATE_TIME, units = "hour"))) %>%
  filter(Hrs_Time_Worked > 0)

which gives
    Row EMPLID TIME_RPTG_CD START_DATE_TIME     END_DATE_TIME       Hrs_Time_Worked
1     1 X00007 REG          2014-07-03 16:00:00 2014-07-03 20:00:00            4.00
2     1 X00007 REG          2014-07-03 20:00:00 2014-07-04 00:00:00            4.00
3     1 X00007 REG          2014-07-04 00:00:00 2014-07-04 02:00:00            2.00

Sample data:
df <- structure(list(Row = 1L, EMPLID = "X00007", TIME_RPTG_CD = "REG",
    START_DATE_TIME = structure(1404403200, tzone = "UTC", class = c("POSIXct",
    "POSIXt")), END_DATE_TIME = structure(1404439200, tzone = "UTC", class = c("POSIXct",
    "POSIXt")), Hrs_Time_Worked = 10), .Names = c("Row", "EMPLID",
"TIME_RPTG_CD", "START_DATE_TIME", "END_DATE_TIME", "Hrs_Time_Worked"
), row.names = c(NA, -1L), class = "data.frame")

#  Row EMPLID TIME_RPTG_CD     START_DATE_TIME       END_DATE_TIME Hrs_Time_Worked
#1   1 X00007          REG 2014-07-03 16:00:00 2014-07-04 02:00:00              10

Comment: Thanks for the response. For both this solution and @Moody_Mudskipper I get an error message: "Error in mutate_impl(.data, dots) : Evaluation error: wrong sign in 'by' argument." Any advice on how to address this?
Comment: I think there is some `END_DATE_TIME` which is less than `START_DATE_TIME` in your data which could potentially be the culprit behind this error message. You can test it using `sum(difftime(df$END_DATE_TIME, df$START_DATE_TIME) < 0)` which shouldn't be greater than zero. If it is the case then you need to remove those rows and then run the code on remaining data else you may need to share the reproducible example to analyze further.
Comment: You may want to see this [link](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) as well.
Answer: Similar to @Prem's but using list columns and unnest :
df %>%
  rowwise %>%
  mutate(START_DATE_TIME = list(seq.POSIXt(START_DATE_TIME, END_DATE_TIME, by = "4 hour")),
         END_DATE_TIME = list(c(tail(START_DATE_TIME,-1),END_DATE_TIME))) %>%
  unnest %>%
  mutate(Hrs_Time_Worked = difftime(END_DATE_TIME,START_DATE_TIME, "hours"))

# # A tibble: 3 x 6
#     Row EMPLID TIME_RPTG_CD Hrs_Time_Worked START_DATE_TIME     END_DATE_TIME
#   <int> <chr>  <chr>        <time>          <dttm>              <dttm>
# 1     1 X00007 REG          4               2014-07-03 16:00:00 2014-07-03 20:00:00
# 2     1 X00007 REG          4               2014-07-03 20:00:00 2014-07-04 00:00:00
# 3     1 X00007 REG          2               2014-07-04 00:00:00 2014-07-04 02:00:00

It is more efficient to use map than rowwise, though less readable in my opinion, to use map you can do this :
df %>%
  mutate(START_DATE_TIME = map(START_DATE_TIME,~seq.POSIXt(., END_DATE_TIME, by = "4 hour")),
         END_DATE_TIME = map2(END_DATE_TIME,START_DATE_TIME,~c(tail(.y,-1),.x))) %>%
  unnest %>%
  mutate(Hrs_Time_Worked = difftime(END_DATE_TIME,START_DATE_TIME, "hours"))

#   Row EMPLID TIME_RPTG_CD Hrs_Time_Worked     START_DATE_TIME       END_DATE_TIME
# 1   1 X00007          REG         4 hours 2014-07-03 16:00:00 2014-07-03 20:00:00
# 2   1 X00007          REG         4 hours 2014-07-03 20:00:00 2014-07-04 00:00:00
# 3   1 X00007          REG         2 hours 2014-07-04 00:00:00 2014-07-04 02:00:00

In this case the output is not a tibble but a standard data.frame, which explains why the Hrs_Time_Worked column prints differently. Use as_tibble to get the same output. Or use as.numeric on any solution to have it as double.


Time is wrong when get datetime in yii2

Question: I have a problem when I get datetime in my yii2 project. When I get datetime, the date is true but the time is wrong. I execute my code and the result is :

2016-05-02 12:30:28

whereas the time in my laptop is : 19:30. What's the problem? I use time in Indonesia. This is my code:
$time = new \DateTime('now', new \DateTimeZone('UTC'));
$model->tanggal_sampai = $time->format('Y-m-d H:i:s');

Answer: First, Find out the timezone for Indonesia from List Of Supported TimeZones - php Manual
Then, make it common for all places using config.php file. Add 'timeZone'=>'Your TimeZone', after components section.
Example : config.php
<?php

$params = require(__DIR__ . '/params.php');

$config = [
  'id' => 'basic',
  'basePath' => dirname(__DIR__),
  'bootstrap' => ['log'],
  'components' => [
        .
        .
        .
    ],
    'timeZone'=>'Asia/Kolkata',
    'params' => $params,
];

Comment: This helped me. Thanks.
Answer: You are asking for the time in the UTC time zone with new \DateTimeZone('UTC').  Either ask for it in your own time zone, which I think is WIB:
$time = new \DateTime('now', new \DateTimeZone('WIB'));

or without a time zone:
$time = new \DateTime('now');

Comment: @ariefsibuea : If this answer helped you. Please mark this answer as correct. As it will help other user to find it easily. And, if you don't know how to mark answer as correct answer. Please go through this link http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work
Comment: Thank you for your suggestion

Time is wrong when get datetime in yii2


Homeomorpic spaces

Question: We define the two following sets:
$ E_1 =\{ (L,v) \in \mathbb{R}P \times \mathbb{R}^{1} \mid  v  \in  L \ or \ v=0\}  $
and
$A=([0,1] \times \mathbb{R})/\sim $    . Where $\sim$ is the equivalence defined by $(0,t) \sim  (1,-t)$
I need to show that these to set is homeomorphic.
First I noticed that $A$ is homeomorphic to the open möbius band, but I cant really go on from here.    Thanks
Comment: I think you mean $E_1 = \{(L, v) \in \mathbb{RP}^1\times\mathbb{R}^2 \mid v \in L\}$.
Comment: Just a remark: if $[L]\in\mathbb{R}P^n$ then $L$ is a line passing throught the origin in $\mathbb{R}^{n+1}$. Hence $0\in L$ and $E_1$ is the tautological vector bundle to  $\mathbb{R}P^n$.
Answer: These are clearly not homeomorphic as you wrote them. For one thing, the first space $E_1$ is a differential variety of dimension $n+1$ while the second one has dimension $2$. As Michael Albanese remarked, this means that you should really set $n=1$ in your first space.
Now the projective line $\mathbb P^1(\mathbb R)$ is a very simple beast since it is homeomorphic to the circle. This means that $E_1$ is naturally a line bundle over the circle $\mathbb P^1(\mathbb R)$, with the map $(L,v) \mapsto L$. An idea could be to see $A$ as another line bundle over the circle, for example by $(t, x) \mapsto t$ (which is compatible to the equivalence relation).
Now if you know enough about line bundles, it should be easy to see that $E_1$ and $A$ are isomorphic as line bundles over the circle, but we may also write an elementary proof. Namely, to an element $(t, r)$ of $A$ we associate the point $(\cos \pi t, \sin \pi t)$ of the circle (more precisely: the quotient of the circle by the half-turn map, which is a nice model of the projective line), and the line $L \subset \mathbb R^2$ with equation $L(t): x \sin \pi t - y \cos \pi t = 0$. This suggests mapping $(t, z)$ to the pair $(L(t), v(t) = (r \cos \pi t, r \sin \pi t))$ of $E_1$ (where we check that $v(t) \in L(t)$ as required). Proving that this is indeed an homeomorphism should be easy (just show the inverse map).
Note that there is nothing special about the map $t \mapsto (\cos \pi t, \sin \pi t)$, any homeomorphism between $[0,1]/\sim$ and $\mathbb P^1(\mathbb R)$ would have worked. This one is just a bit easier to write.
Comment: ty. I did write the sets wrong. as already mentioned at $E_1$ n should be replaced with 1. The other space should be $([0,1]\times \mathbb{R})/\sim$ with relation as before
Comment: Yup, I did only expand a bit on why the problem as asked was wrong and how we could guess how to fix it.

Homeomorpic spaces


Incorrect Placement of an Accidental?

Question: This is a very quick and blunt question but here we have a deliberately incorrect notation and below it is the corrected version (the black circles).
How come the eight note before the last (the pink) still has a flat accidental? That Cb note has been covered by the key signature anyway. The natural ends its effect as soon as the first bar is over, so that doesn't explain why this accidental has been placed either..
Comment: The OP states the first example is "deliberately incorrect", probably from a textbook to help students recognize errors. Congrats, you all found them. :)
Comment: That Cb note is an Eb note - note the bass clef.
Comment: The top signature is actually Cb, Fb, Bb, Gb (note the clef placement). Still doesn't make much sense to me.
Comment: @Dekkadeci Not to mention a key signature of 8/9!
Comment: How'd you create the top example? Its key signature has E flat, D flat, **F flat**, and **G flat**.
Comment: @Dekkadeci - being pedantic - the clef is an F clef, so top line would have to be F - making the flats C, F, B and G, in that order. Still no better than rubbish!
Comment: Yeah, I misread two of the flats in the key signature earlier.
Answer: The Cb note you mentioned is actually an Eb since this passage is in bass clef, not treble clef.
The accidental in bar 5 is a courtesy accidental (also called a cautionary or reminder accidental) and is not necessary but used to remind the player that the previous accidental has been cancelled. They typically are used a bar or two after the original accidental occurs (and preferably in parentheses) but sometimes they are used several bars after, as in this case.
Comment: There is no standard for this type of thing, it's up to the composer, copyist and publisher I suppose. I think they're good to have when sight reading and use them in my own charts  if the next bar has a cancelled accidental but 3 or more bars later? I think it's unnecessary. Still, a lot of published music has them bars later.
Comment: @Tim, I should have mentioned the parentheses (I'll remember to do it next time), not having them can actually defeat the whole purpose, it gives you that split second of: "What? Oh."
Comment: See this type of question has popped up a lot recently. What I don't understand is if it is normal practice for an accidental to only last a bar* why courtesy ones are added anyway? A few bars away seems awkward. Are they necessary for sight readers perhaps?
Comment: Some publishers are just too kind! Maybe this one has a personal rule that whenever there's an accidental, the reminder gets printed on the very next time that note occurs again, but in its original form. But that could be twenty bars away! Where does one draw the line (no, not the barline...) ansd anyway, there should be a law saying 'always use parentheses for cautionaries'!
Comment: When I was a teacher, I always blamed the parentheses - come to think, still do...
Comment: Here the courtesy accidental makes sense to me. The "melody" sort of changes from a major to a minor sound at that point. This may trip you when sight reading.
Comment: @ghellquist It all sounds like F minor to me, melodic or harmonic in the first bar and natural in the 5th but then again it's just a snippet, there's no context to go by so people may hear it differently. 4 bars is a little far for a courtesy accidental imo but it doesn't hurt. Parentheses would be good in this case though.
Answer: For some reason the top line in written in some kind subbass clef (with a really weird key signature).  So the the third space is a C, but the second line is written in bass clef where the third space is an E (not a C).

The second line has an E-natural because this part is playing in the scale of F harmonic minor.
The last bar has an E-flat which isn't strictly necessary, but is some what useful because it is clearly showing that we have modulated to A-flat major.
It might be more modern/sensible to put this necessary accidental in parentheses (as a courtesy accidental).
Answer: I think it's a coding error in the program that typeset the musical examples.
I wouldn't trust any music typesetting program that let me supply 8/9 as a time signature and then lets me enter bars of 9/8.
Furthermore, the accidentals in the first sample don't agree with the clef. What music program would let you write that?  Here's what Sibelius does with Ab major key signature and the Archaic Sub-bass clef:

So I think it is a coding error that there's a courtesy flat in front of the E in the fifth bar, rather than some little-known rule of music typesetting.
Comment: What rule is that?

Incorrect Placement of an Accidental?


Torus minus a point homeomorphic to sphere with three points?

Question: I was able to show they are both homotopy equivalent to $S^1 \wedge S^1$. I cannot find any reason why they would not be homeomorphic, but I also cannot see any way to construct an explicit map. Any hints would be appreciated.
Comment: A standard way to prove such statements is to use cohomology with compact support: $H^1_c(T^2- p)\cong Z^2$, $H^1_c(S^2-\{p_1,p_2,p_3\})=0$. Cohomology with compact support is a topological invariant but not a homotopy-invariant. (It is only invariant under proper homotopy-equivalence.)
Answer: When you take a loop $\gamma$ which goes once around the torus $\Bbb T^2$ (and doesn't go on the point $p$ which was removed) then the complement of $\gamma$ in $\Bbb T^2-p$ is still connected.
The complement of any loop $\gamma$ in $\Bbb S^2-\{p_1,p_2,p_3\}$ is disconnected (because of Jordan curve theorem basically). Therefore they can't be homeomorphic.
Comment: Has this got something to do with genus?
Comment: @WhySee I don't see a relation between genus and this argument.


RSS 2.0 can't use "&" in  tag

Question: I can't use a & in the  tag of rss feed item, because when I do I always get the error
error on line 1 at column 1337: EntityRef: expecting ';'

but If I don't use & in the  tag then everything is ok.
E.g this doesn't work:
<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">
<channel>
  <title>Borken RSS feed</title>
  <description>Broken RSS Feed is broken.</description>
  <link>http://example.org</link>
  <lastBuildDate>Tue, 21 Jan 2012 19:13:22 +0100</lastBuildDate>
  <pubDate>Tue, 21 Jan 2012 19:13:22 +0100</pubDate>

[...]
    <link>
    https://www.youtube.com/watch?v=pH6rSul-5X8&feature=related
    </link>
    <guid>
    https://www.youtube.com/watch?v=pH6rSul-5X8&feature=related
    </guid>
[...]

Answer: You have to escape all special characters. & and should look like &
Using php, that would look like: htmlspecialchars($text);
Chars that need to be escaped: <, >, ", &, and possibly others...
Comment: @MichealPerr: Those weren't valid RSS feeds - although many readers may be able to cope with them. All valid RSS feeds are XML, and XML requires that ampersands be escaped, and there's no way around it.
Comment: Srsly? Isn't there anything I can add to the header of the rss Feed, because I have already seen valid rss 2.0 feeds which didn't escaped special characters....

RSS 2.0 can't use "&" in  tag


Invariant Violation: Element type is invalid

Question: I am trying to clean up my styles by using a StyleSheet, but I can't seem to get it to work. I believe the error (seen below) is caused when I attempt to create a StyleSheet (const styles =  EStyleSheet.create.
Note I am using react-native-extended-stylesheet  However this is not the problem. This also happens with react-native's stylesheet.
This a picture of the error:
This this my code:
import React, { Component } from "react";

import {
  View,
  Text,
  Button,
  Image,
  StyleSheet,
  TextInput,
  KeyboardAvoidingView,
  TouchableOpacity
} from "react-native";

export default class Login extends Component {
  render() {
    return (
      <View style={styles.wrapper}>
        <Text>Login screen </Text>

        <KeyboardAvoidingView behavior="padding" style={styles.loginContainer}>

          <TextInput
          placeholder="username or email"
          placeholderTextColor='whitesmoke'
          style={styles.input}
          />

          <TextInput
          placeholder="password"
          secureTextEntry
          placeholderTextColor='whitesmoke'
          style={styles.input}
          />

          <TouchableOpacity style={styles.loginbutton} onPress={() => this.props.navigation.navigate("Grades")}>
            <Text style={{
              textAlign: 'center',
              color: "whitesmoke",
              fontWeight: '700',
            }}>
            Login
            </Text>
          </TouchableOpacity>

        </KeyboardAvoidingView>

      </View>
    );
  }
}

const styles = StyleSheet.create({
  loginContainer: {
    paddingHorizontal: 9,
    backgroundColor: "red"
  },

  input: {
      paddingHorizontal: 10,
      marginBottom: 10,
      color: '#f1c40f', //sunflower color
      backgroundColor: '#3498db',
    },

 logo: {
    width: 231,
    height: 231
  },

  wrapper: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center"
  }

});

Here is my app.js.
import React from "react";
import { Font } from "expo";

import { Root } from "./app/router";
import { FontError } from "./app/components/fontError";

export default class App extends React.Component {
  state = {
    fontLoaded: false
  };
  async componentDidMount() {
    await Font.loadAsync({
      Arial: require("./app/resources/Arial.ttf")
    });
    this.setState({ fontLoaded: true });
  }
  render() {
    if (!this.state.fontLoaded) return <FontError/>;
    return <Root />;
  }
  // ...
}

My root component is router.js, I am using react-navigation.
import React, { Component } from "react";
import { createStackNavigator } from "react-navigation";

import {
  Login,
  Grades,
} from "./screens";

export const Root = createStackNavigator({
  Login: {screen: Login},
  Grades: {screen: Grades},

});

Feel free to ask me to append any additional information.
Thanks for your help in advance.
Comment: You are missing a comma after StyleSheet in your import statement. Is it the same in your code or just in your question
Comment: Whoops. That's just in my question
Comment: please add app entering component of the your app e.g. App.js
Comment: Sorry for the wait. I added in my app.js and router.js. (I am using react-navigation)
Answer: To fix my error I just re-cloned the repo and added back in all the code I wrote.
Thankfully I didn't push this error to the master branch.
This fixed the error.
*note in the process I got rid off react-native-extended-stylesheet, so it might have been cause of error.


Rewriting $a= \tan^{-1}\left( \frac{b/c - \cos \gamma}{\sin(\gamma) } \right) - \gamma$ as $\gamma = \cdots$

Question: I have this formula and I want it to be $\gamma = \dots$
$$a= \tan^{-1}\left(  \frac{b/c - \cos \gamma}{\sin(\gamma) } \right) - \gamma$$
while $a$, $b$ and $c$ are constants.
I tried several ideas but none worked, any ideas?
Comment: What about $\gamma=\arctan\left(\frac{b/c-\cos\gamma}{\sin\gamma}\right)-a$?
Comment: I don't understand your comment. Did I or did I not express $\gamma$ as a functions of $a$, $b$, and $c$?
Comment: the thing is I am trying to use it in matlab so I have no information about $\lambda$
Comment: $tan( a+ \gamma) =(  \frac{(b/c - cos(\gamma))}{sin(\gamma) } )$  ??? after that it's simply an equation you play with trigo formulas to simplify ...eexpressing everything in term og tan(\gamma)
Comment: No because I want $\gamma = (not function of \gamma)$ because I know $a$,$b$ and $c$ only
Comment: Where does $\lambda$ com into it? You can write $tan(\gamma +a)$ out using double angle formula. With some messing around I expect you can write it as a polynomial in $sin(\gamma)$
Answer: Let $(*)$ be the initial equation.
$$ (*) \Leftrightarrow \tan(a+\gamma)=\frac{\frac{b}{c}-\cos\gamma}{\sin \gamma}$$
$$ \Leftrightarrow (\sin\gamma)(\tan (a+\gamma))+\cos \gamma=\frac{b}{c}$$
$$\Leftrightarrow \sin \gamma\frac{\tan a +\tan \gamma}{1-\tan a \tan \gamma}+\cos \gamma = \frac{b}{c}$$
Now, I'll use $ u = \tan \frac{\gamma}{2}$
Then,
$$ \cos \gamma = \frac{1-u^2}{1+u^2}, \sin \gamma = \frac{2u}{1+u^2} \text{ and } \tan \gamma = \frac{2u}{1-u^2}$$
The equation becomes ($A=\tan a$ and $R=\frac{b}{c} $)
$$ (*) \Rightarrow \frac{2u}{1+u^2}\frac{A+\frac{2u}{1-u^2}}{1-A\frac{2u}{1-u^2}}+\frac{1-u^2}{1+u^2}= R$$
After simplification, you would get an equation in $u$:
$$ (R+1)u^4+2ARu^3+2u^2+2ARu+(1-R)=0 $$
$$\Leftrightarrow (u^2+1)((R+1)u^2+2ARu+1-R)=0$$
By solving the quadratic equation and using $ u =\tan\frac{\gamma}{2}$ you should obain an expression for $\gamma$.
You'll need to check yourself, but what I got was under favorable conditions is
$$ \gamma = 2\arctan (\frac{-2\frac{b}{c}\tan a+\sqrt{(\frac{b}{c})^2(\tan^2 a+1)-1}}{2(\frac{b}{c})+1})$$
Answer: Not sure I understood correctly what you want to do but here is how I tried... I set $k=\frac{b}{c}$ for simplification.
$$a= \tan^{-1}\left(  \frac{k - \cos(\gamma)}{\sin(\gamma) } \right) - \gamma$$
$$ \tan (\gamma+a)=\frac{k-\cos(\gamma)}{\sin(\gamma)}$$
$$ \frac{\tan(\gamma)+\tan(a)}{1-\tan(a)\tan(\gamma)}=\frac{k - \cos(\gamma)}{\sin(\gamma) }$$
Use the formulas for $\sin$, $\tan$ and $\cos$ in terms of $\tan\left(\frac {\gamma}{2}\right) $
Normally you will get an equation in $\tan\left(\frac{\gamma}{2}\right)$, that's not going to be that simple.
Answer: The arctangent function has range $(-\pi/2,\pi/2)$, so if we begin by rewriting the equation as
$$\gamma+a=\arctan\left(b/c-\cos\gamma\over\sin\gamma \right)$$
we see that any solutions we get require $-\pi/2\lt\gamma+a\lt\pi/2$.  This suggests making a convenient change of variable, $v=\gamma+a$, so that the equation becomes
$$v=\arctan\left(b/c-\cos(v-a)\over\sin(v-a) \right)=\arctan\left(b/c-\cos v\cos a-\sin v\sin a\over\sin v\cos a-\cos v\sin a \right)$$
Taking the tangent on both sides turns this into
$${\sin v\over\cos v}={b/c-\cos v\cos a-\sin v\sin a\over\sin v\cos a-\cos v\sin a}$$
or
$$\sin^2v\cos a-\sin v\cos v\sin a=(b/c)\cos v-\cos^2v\cos a-\cos v\sin v\sin a$$
which simplifies to
$$\cos a=(b/c)\cos v$$
Thus
$$\cos v={c\cos a\over b}$$
The requirement $-\pi/2\lt v\lt\pi/2$ implies $0\lt\cos v\le1$, so we see that we must have $0\lt {c\cos a\over b}\le1$ in order to have any solutions, in which case we get two solutions:
$$\gamma=\pm\arccos\left(c\cos a\over b\right)-a$$


javascript regex search and find

Question: Im trying to check if a string contains [suggestion=mixofnumberandcharacter]
But im not sure how to do that, anynumber will of course be any number or character.
and, how do i after that get the suggestion mixofnumberandcharacter id?
Comment: `/\[suggestion=\d+\]/.test(yourStringVar)`
Comment: @PranavCBalan could you explain how do use it?
Comment: `if(/\[suggestion=\d+\]/.test(yourStringVar)){   }`
Comment: what is the test containing? and string?
Comment: to get the id value...  `yourStringVar.match(/\[suggestion=(\d+)\]/)[1]`
Comment: how do i do it to also allow characters ( with numbers) ? @PranavCBalan
Comment: `yourStringVar.match(/\[suggestion=([\da-zA-Z]+)\]/)[1]`
Comment: dont you mean [0] ?
Comment: the captured value present at index `1` and entire string match at `0`
Answer: What about:
var str = "asd asd asd asd [suggestion=mix0fnumb3r4ndch4racTeR] sd  asd asd sd";
var found = str.match(/\[suggestion=([0-9A-Za-z]*)\]/);
console.log(found);

The console output will be:
Array[2] {
    0        : "[suggestion=mix0fnumb3r4ndch4racTeR]"
    1        : "mix0fnumb3r4ndch4racTeR"
    index    : 16
    input    : "asd asd asd asd [suggestion=mix0fnumb3r4ndch4racTeR] sd  asd asd sd"
    length   : 2
    __proto__:    Array[0]
}

So what you are looking for is found[1] which is matched by the (). Fiddle here.
Comment: I know it is a trivial question/answer but why the -1? It is a starting point for @maria to look into the code, console and fiddle...

javascript regex search and find


error code in WordPress: {"code":0,"url":""}

Question: My WordPress website stopped displaying images in my portfolio. When O logged in to the CP, I see this error {"code":0,"url":""} in many places like: when load official wp feeds, when try to add blocks, when try to add images or edit pages.
Do you have any suggestion?
I did google it without any solution.
Thanks
Answer: You may want to try adding this to the top of your .htaccess file,
I had the same issue and this resolved it:
## EXPIRES CACHING ##

ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 2 days"

## EXPIRES CACHING ##
This should help page load in the future too!
These file types will be cached in order to improve faster loading times in the future.
Hope that helps.
Also if Yahoo is okay leave it be unless you start to get the same error.


How can I predict/interpret results of Poisson regression?

Question: We are working on a project where we want to find the pure premium for which we first want to fit Poisson regression.
Data Used: data(dataCars) from insauranceData package in R
We have an offset term exposure which takes value between 0 and 1
when I fit my model then I am getting rates between 0 and 1
but when I calculate the original rates to compare my prediction, there are values in 365claims/year  (since few observations had claimed within 0.0027 exposure time)
So is my interpretation of no of claims using Poisson GLM incorrect or is it wrong to compare the rates calculated using the model and calculated from the original data ?
What is the right method to go about it? Please Help
Following are the codes attached:

library(insuranceData)
library(forcats)
library(caret)

data(dataCar)
data1 <- dataCar
#Data Cleaning & Pre-processing
data2 <- unique(data1)
data3 <- data2[data2$veh_value > quantile(data2$veh_value, 0.0001),]
data4 <- data3[data3$veh_value < quantile(data3$veh_value, 0.999), ]
#Regrouping vehicle categories
top9 <- c('SEDAN','HBACK','STNWG','UTE','TRUCK','HDTOP','COUPE','PANVN','MIBUS')
data4$veh_body <- fct_other(data4$veh_body, keep = top9, other_level = 'other')
#Converting catagorical variables into factors
names <- c('veh_body' ,'veh_age','gender','area','agecat')
data4[,names] <- lapply(data4[,names] , factor)
str(data4)
##data partition - original data
data <- data4
data_partition <- createDataPartition(data$numclaims, times = 1,p = 0.8,list = FALSE)
str(data_partition)
training <- data[data_partition,]
testing  <- data[-data_partition,]

##data partition - re-sampled data
data <- data4
data_partition <- createDataPartition(data$numclaims, times = 1,p = 0.8,list = FALSE)
str(data_partition)
training <- data[data_partition,]
testing  <- data[-data_partition,]

#Number of Claims(Orignal Data)
table(training$numclaims)
ggplot(training,aes(numclaims))+geom_bar(fill="deepskyblue4")+
  geom_text(aes(label = ..count..), stat = "count", vjust = -0.3, colour = "black")+
  xlab("No of Claims")+
  ylab("Count of Claims")+
  ggtitle("Histogram of Number of Claims(in given exposure)")+
  theme(plot.title = element_text(hjust=0.5))+
  theme_update()

#Poisson model with offset
poissonglm <- glm(numclaims ~veh_value+veh_body+veh_age+gender+ area+ agecat+offset(log(exposure)),data=training, family = "poisson")
summary(poissonglm)

predict(poissonglm,newdata=data,type="response")

Our Models Predicts the Rate but since now the exposure term is taken care of,so the Rates are No of claims per year so Rate=No of Claims (here)?
I want my predictions to be in some range of counts (i.e 0 1 2 4) which I can compare with the number of claims in my original data.
Answer:
"when I fit my model then I am getting rates between 0 and 1 but when I calculate the original rates to compare my prediction, there are values in 365claims/year"

When I try to reproduce your problem, then I find no predicted values above 365. Or maybe you are looking at some different result?

I want my predictions to be in some range of counts (i.e 0 1 2 4) which I can compare with the number of claims in my original data.

The predictions are for the individual means or rates. Based on the rates you can make predictions for the number of counts in a particular bin.
The expected number of counts in a particular bin is equal to the sum of probability over all individuals
$$E[\text{total number of cases } x_i = k] = \sum_{i=1}^n P(x_i = k)$$
code example:
means = predict(poissonglm,newdata=data,type="response")

probs_individual = sapply(0:10, function(x) dpois(x,means))
expected = colSums(probs_individual)
print(round(expected))

This gives the following table
Number of claims   0     1      2     3
Expected counts    62681 4440   228   0

Your original data has more often 3 or more claims than predicted. This might be because the true distribution is not Poisson and can be overdispersed (or the true data is Poisson distributed, but you can't describe the outliers well with your regressors/predictors).
Comment: I am getting it as 365 when I look for rates of original data which is calculated by doing numcalims/exposure. (if I am not wrong)

And also from, where did we end up with that formula (regarding The expected number of counts in a particular bin ), could you refer any book or article about the same.

and actually I want the number of claims of an individual
as in ,how many times would a particular person claim based on the values of predictor variable. or is it something which we cannot find?
Comment: @AniketKanse the Poisson regression models the number of claims as a Poisson distributed random value computes the rate or average of that value.  For instance for the 35729-th person this might be $\hat\lambda_{\text{individual number 35729}} = 0.4$ you can use that value to estimate the distribution for the number of claims that the individual makes. The formula for the distribution is a Poisson distribution. The expectation for the total is the sum of the expectation for the individuals. If these individuals are assumed independent then you can sum it.
Comment: So I can find the distribution but not the number of claims for say 35729-th person right? like cant I say that he would claim Once in 2.5yrs (i.e 1/0.4  since its rate of claiming is 0.4/year)  also I am so sorry but I didn't get the expectation part since in the formulae which you gave had sum of the "probability" that he would claim k  number of time
Comment: It's like rolling a 6 sided dice ten times. You can say that you can get a 'six' for 1/6-th of the time, and in ten rolls on average 1 4/6 sixes. The probability to roll zero sixes is 1-(5/6)^10, and similarly you can compute the probability for one six, two sixes, etc. Then, with those probabilities for the individual, you can compute how often on average a dice that is being rolled ten times will roll a specific number of sixes. That average/frequency/probability can be used to estimate the expectation for the number of times you get a particular outcome.
Comment: Okay This made sense,......Though, So what is the use of Poisson Regression as we cant really "predict" the number of claims of an individual (i.e I cannot firmly say that ith individual is claiming 1 time in a year or etc )
Comment: Also about the rate part in the code. Cant I obtain the original rate of claiming by doing numclaims/exposure  ?  if you could try doing that, you'd find some rates in 365claims/year (Since some of the individuals have 1 claim in 0.0027exposure time)
Comment: @AniketKanse the point of the regression would be to figure out the rate parameter which can be different for different type of people. Counter-question, what is the point of your analysis, what would you like to achieve with it?
Comment: Actually we want the number of claims of an individual per year, and then we predict the cost of claims (severity) and thus further the Pure Premium by the product of two models.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/140856/discussion-between-aniket-kanse-and-sextus-empiricus).
Comment: If you think Sextus Empiricus' post answered your query, please upvote and [accept](https://stats.stackexchange.com/help/accepted-answer) it by clicking the tick symbol alongside it.


Why can't I save a Send HTML Email action?

Question: I have a rule component set up that currently sends an HTML email. I need to change the body of the email to include a new field, but when I do and press Save, it doesn't return to the Rule page, it just goes to the top of the page and loses the changes I've made.
If I overwrite the HTML with a simple piece of text or a small piece of HTML, it works OK.
I'm wondering if there's some validation going on, but there are no error messages displayed or in the logs. I've validated the html through the W3C Validation Service and cleaned it up so there are only a couple of warnings.
My other thought is that maybe there's some limit that I've hit? The HTML is quite long, as it was generated by an online generator.
I can't include an export of the rule as it's too big for this message.
Any help?
I am using Drupal 7.59 and Rules v7.x-2.10; MimeMail v7.x-1.0. Have tried the latest dev version MimeMail too, but made no difference.
Answer: Thanks Pierre for your suggestion. I didn't need to try it, but it makes a lot of sense. Wish I'd have thought of it!
In the end (before I saw your suggestion), I rebuilt the email using a different generator tool, which seemed to produce much smaller and cleaner HTML.
This works OK. It looks like there was either a problem with the HTML or there is some kind of limit on length.
Answer: You could try to add 2 Rules Actions, something like so:

Add a variable of type text
Set a data value for that variable, with value the HTML string.

While doing so, you have the Rules power available to include any relevant conditional logic. And if you then use the "replacement tokens" within the "Message type" you're working with (to make the value of your new variable available as a token in the message you want to create), you should be good to go.
Did I mention there is zero custom code involved?


GDX-SQLite android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1

Question: I work in Android Studio with libgdx and gdx-sqlite. I want a simple query from my database with the following code.
<code> try {
        cursorSettings = dbHandler.rawQuery("SELECT "+COLUMN_SETTING+" FROM "+TABLE_SETTINGS+" WHERE "+COLUMN_SETTINGSID+" =13");
        System.out.println(cursorSettings.getLong(0));
    } catch (SQLiteGdxException e) {
        e.printStackTrace();
    }
</code>
The Desktop-Version works without problems, but in the android version I get the following error:
<code>05-25 10:21:47.341 11978-12232/ch.shuttering.rapporte E/AndroidRuntime: FATAL EXCEPTION: GLThread 82275
    Process: ch.shuttering.rapporte, PID: 11978
    android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
        at android.database.AbstractCursor.checkPosition(AbstractCursor.java:460)
        at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
        at android.database.AbstractWindowedCursor.getLong(AbstractWindowedCursor.java:74)
        at com.badlogic.gdx.sqlite.android.AndroidCursor.getLong(AndroidCursor.java:61)
        at ch.shuttering.rapporte.Manager.SQLiteManager.SaveMangerSQLite.creatSQLiteSettings(SaveMangerSQLite.java:295)
        at ch.shuttering.rapporte.RapporteMain.create(RapporteMain.java:66)
        at com.badlogic.gdx.backends.android.AndroidGraphics.onSurfaceChanged(AndroidGraphics.java:311)
        at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1546)
        at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1262)
</code>
So every time I make a getXXX () query from the cursor I get an error, but if I now use the following code:
<code> try {
        cursorSettings = dbHandler.rawQuery("SELECT * FROM "+TABLE_SETTINGS);
    } catch (SQLiteGdxException e) {
        e.printStackTrace();
    }
    while (cursorSettings.next()) {
        Gdx.app.log("FromDb", String.valueOf(cursorSettings.getString(1)));
    }
</code>
I have a correct output with all data.
Does anyone have an idea what the problem is?
Thank you for your help
Answer: Okay I found the problem by myself, that was the code in the Android class
<code>@Override
        public long getLong (int columnIndex) {
            try {
                return cursor.getLong(columnIndex);
            } catch (SQLiteException e) {
                Gdx.app.log(DatabaseFactory.ERROR_TAG, "There was an error in getting the long", e);
                throw new SQLiteGdxRuntimeException(e);
            }
        }
</code>
The problem is that in android the cursor points to -1 so it must first be set to the correct position, the following code solves the problem
<code>@Override
    public long getLong (int columnIndex) {
        try {
           cursor.moveToFirst();
            return cursor.getLong(columnIndex);
        } catch (SQLiteException e) {
            Gdx.app.log(DatabaseFactory.ERROR_TAG, "There was an error in getting the long", e);
            throw new SQLiteGdxRuntimeException(e);
        }
    }
</code>
You can found this code in the library gdx-sqlite-android.jar in the class AndroidCursor.
I hope the solution helps someone.


Find the average value of $i_1i_2+i_2i_3+........+i_9i_{10}+i_{10}i_1$

Question: Determine the average value of $i_1i_2+i_2i_3+........+i_9i_{10}+i_{10}i_1$ taken over all permutations $i_1,$ $i_2,$ ......$,$$i_{10}$ of $1,$ $2,$.....$,$$10$.
I think there are $9!$ combination of such numbers    $i_1i_2+i_2i_3+........+i_9i_{10}+i_{10}i_1$. But I started it with a huge calculation, but cannot find it out. I know there is a trick which I unable to find out. Please help me to solve this.
Answer: By the "linearity of expectation" principle, the answer is $10$ times
the mean of $i_1i_2$. There are $90$ equally probable values of
$(i_1,i_2)$, so the mean of $i_1i_2$ is
$$\frac1{90}\sum_{i,j=1\atop i\ne j}^{10}ij
=\frac1{90}\left(\sum_{i=1}^{10}\sum_{j=1}^{10}ij-\sum_{i=1}^{10}i^2\right)
=\frac{55^2-385}{90}=\frac{88}3$$
so the original problem has answer $880/3$.


How to brake in rollerblade?

Question: I just began rollerblade, or inline skating. After tried it twice, now I can skate on the pavements in a park nearby (I choose late night to avoid pedestrians). However, I don't know how to brake without using the brake at the heel of the right boot.
I've checked on wikihow, it says:

Learn to brake. Just like driving a car, riding a bike, or even
  running, anticipate where you want to stop. Move one foot forward and
  bend the knee slightly, applying pressure on your heel until you
  slowly come to a complete stop.

This is to use the brake at the heel of the right boot, isn't it?
However, seems all advanced rollerblade skaters take off the brake at the heel of the right boot? At least is what I observe from youtube videos, people stand on one foot, and brake by using another boot's side or tip.
But the skills are a bit too advanced for me. When I try to place the two feet as a "T" shape, I always go sideways. Should I just practice more, or there's some trick?
I'd like to seek some advice. Just to summarize my questions:
Q1: Is it true that advanced rollerblade skaters take off the brake at the heel of the right boot (and brake use other ways)?
Q2: After taking off the brake at the heel of the right book, is there an easy way to brake ? e.g. "T" shape? If so any suggestion to practice?
Q3: After taking off the brake at the heel of the right book, what are the different ways to brake ? e.g. which one is faster, which one is safer...?
Answer: Stopping is a crucial skill in skating.  Inline skates generally come with a removable heel brake on the right skate.  The advice on skating that you quoted from WikiHow does indeed refer to using the heel brake for stopping.
Advanced inline skaters usually remove the brake.  There are a couple of reasons for this.  The brake can often get in the way of tricks.  The primary reason, though, is that stopping with a heel brake is not a very fast way to stop.  There are other ways to stop that are much faster.
The T Stop is one of those ways.  When practicing this stop, it is helpful to start skating from the T position.  Push off of your rear skate, then immediately use the rear skate to stop.  By practicing this, you've eliminated one of the steps of the stop, which is getting your braking skate into position.  After you've practiced starting and stopping while in the T position, you can work on skating normally, then moving your braking skate into position for the T Stop.  When you first get into the T shape, keep your weight on the front skate, and very gently transfer some of your weight to the braking skate.  If you find yourself spinning sideways, perhaps you are putting too much weight on the braking skate too early.
The beginning of this video discusses practicing the T Stop: How To Practice The T-Stop On Rollerblades.
This video discusses what to do if you are spinning while stopping: How to do a T-Stop on inline skates
Some other stops you could learn are the Edge Stop and the Hockey Stop.  This video discusses learning both stops: How to stop on rollerblades using the Hockey Stop.
Using a heel brake is probably the easiest, but slowest, way to stop.  The Hockey Stop is one of the fastest ways to stop.
There are other stops, as well.  For example, here is a video that demonstrates the Plough Stop: How to stop without a brake using the Plough Stop on inline skates or rollerblades.
Which stop is safest?  This is relative.  The safest stop is the one that you have practiced and can do reliably.  For a beginner, using the heel brake is safest, because it is easiest.  However, for an advanced skater that has several stops in his arsenal, using the heel brake would not be the safest, because it is slow.
Comment: Great answer!  I want to throw in one more thing.  Try to learn to do things with both feet.  If you are right handed, you probably want to use your right foot to break.  Once you feel like you are getting the motion, switch and try breaking with your left foot.  Don't worry if it feels completely horrible.  When you get to a hockey stop, do the same thing.  If you naturally want to stop left.  Make sure to try turning right too.
Comment: The hockey stop is extremely difficult on rollerblades; I've only known one roller hockey player who could do it on a prepared rink surface, and it's pretty much impossible in your average parking lot. Ice skate blades are essentially square with two edges, and will naturally skid sideways over the ice when they're close to vertical (just don't catch the outside edge), so turning your ankle in will start shaving ice. Try the same thing with a rollerblade, and falling over the top of the skate is the least of your worries.
Comment: @KeithS the 'hockey stop' in inline skates isn't quite the same as on ice. On ice, it's typically a two-skate stop. On inline, it's more of a one-foot stop (the outside foot doing the 'sliding'). It's also heavily dependent on having the right type of wheel for the surface you are on.
Comment: Great answer, but one thing that needs to be pointed out: heel brakes aren't always the safest option. Older heel brakes that require you to tilt the forward skate back onto one wheel greatly reduce your stability and at higher speeds can cause you go to way off balance. Newer brakes that allow all of the wheels to remain in contact are safer.
Answer: Yes, the wiki is talking about the heel brake. The first thing I would advice is remove the heel brake(s).
Learn to brake without.
Reason being: It can get stuck behind things. If you plan to learn any other discipline like aggressive rollerblading, you really don't want to try dropping in a ramp with that heel break still on your skates. Learn to brake 'properly' from the start.
I made the error skating a long time still with these attached. The moment I removed them, I almost had an accident because I wasn't used to it. I panicked and I wanted to slow down but I forgot I removed it some hours before I went blading.
Brakes ordered by times that I actually use them:
1. T-Stop
One foot behind the other in a 'T' like position. Pros: Easy. Usable at every speed. High controlability. Safe! Cons: Your wheels won't last long if you brake frequently. Don't forget to switch them up from time to time that both sides wear down at the same rate.
You were talking about going sideways when attempting this stop. Bend your knees (always..in every circumstance). Put your hands in front of you. Imagine that you are holding a joy stick. If go sideways to the right, move the 'joystick' / your hands to the left and the other way around.
Also, if you are still having trouble, learn to skate on one foot as long as possible first.
2. Turn Stop
I struggled long to get this one right, it's practically putting one foot in the opposite direction of your other foot and making a u turn, which will slow you down pretty hard. Really hard to explain in words, this is the best video I could find: Turn Stop Pros: Doesn't wear your wheels down. Good for braking at slow speed. It's fun. It's also a nice way to turn at slow speed. Cons: Don't try this at high speed. Hard to learn.
3. Power Slide
This is actually a reverse T Stop. There are two ways, you can do a 180° (jump and land facing backwards) or turn smoothly into a power slide. Tips: Get really low. Practice first while you're not rolling. Just jump into the right position and get that foot really low that you are practically braking on the side of your skate. After a while you can try practicing this when going really slowly. Video: (just look up Power slide on youtube, I can't post more than two links because I have no rep.) Pros: Really good way to stop really fast. Fun. Looks bad-ass. Good at high speed. Cons: Don't try this at too low speed. Hard. Wears both your skates and your wheels down.
4. Cess Slide
This is a trick but also a good way to stop. It's similar to the powerslide but it has a ton of variations. (a lot of grinds in aggressive rollerblading could be, in theory, a cess slide) It's actually grinding, but on the ground or surface which is not a rail or a ledge. Example: Cess Slide Pros: Impressive. A lot of fun on slippery surfaces (or when it's wet!). High speed. Good way to stop quickly. Cons: Don't try this at too low speed. Hard. Wears both your skates and your wheels down.
5. Plough Stop
Opening your legs, going really wide, and then when going back to normal position, push your force outwards but let your feet go like this /. It will make you slow down quite a bit. The wider you go, the more you'll slow down. Also when going downhill for example, holding your legs really wide will make you go slower. That' just plain aerodynamics.
Sources: I do Aggressive Rollerblading for two years now.
Answer: Find some grass.
Obviously this isn't all that useful in a skate park or on a hockey rink, but if you are primarily street/sidewalk skating, one of the safest options is to find a surface that will

slow you down
not give you road rash if you have to bail.

When skating fast on sidewalks, you need to account for pedestrians, pets, obstacles and the issues that your surface is quite narrow meaning you're going to have to depend much more on stopping and controlling your speed as you just don't have the space to turn and maneuver.
At slow-to-moderate speeds you can typically roll off the pavement right into the grass and glide to a fairly quick stop. When doing so, put one foot out in front of you to counter-act the quick change in surface speed (your body will be thrown a bit forward as your feet suddenly become slower).
At high speed, do the same, but be prepared to do a bit of running to slow your momentum down.
Worst case, where you're simply going way too fast, be prepared to tuck and roll. Tucking and rolling on grass always beats doing the same on concrete or running into someone or something.

How to brake in rollerblade?


Proof for planar embeddings

Question: Prove that any planar embedding of a simple connected planar graph contains a vertex of degree at most $3$ or a face of degree at most $3$.
Can someone help me with this please? Thank you!
Comment: It would be better if you post some of your thoughts or your work, that way people would be more willing to help ...
Comment: I am stuck on this problem, and I don't really know what to do :\
Answer: Hint:  If every face has degree $4$ or more, then we can use Euler's polyhedron formula to show that $e \leq 2v - 4$. What does that imply about the degrees in the graph?
Comment: Sorry but I still don't really know how to use that to prove this problem, can you give me some tips on how to do this?
Comment: The handshaking lemma says that the sum of the degrees is twice the number of edges...
Comment: Ah yes, sorry I forgot about that. so that means that the total number of degree is $≤ v − 2$. How will this help me with proving this?
Comment: Oh, can I say something like. since the number of degrees $≤$ vertices - 2, therefore there can't be any vertices of degree 3 or more? Since if there is, then the formula can't be true.
Comment: Nevermind, I think I got it now. Thank you!

Proof for planar embeddings


Legendre symbol $ p ≡ 5 \mod 8$

Question: I need to prove:
If $p$ is a prime number congruent to $5 \mod 8$, and $\left(\frac np\right)= 1$, then
either $ [n^{(p+3)/8}] ^2 ≡  n\bmod p$
or   $ [n^{(p+3)/8}((p-1)/2)! ]^2 ≡  n\bmod p$
I am not really sure how to proceed, although I have tried checking the cases $n= 1$ and $n = -1$, I have also tried various things with the definition of a Legendre symbol.
Answer: You can argue as follows.
We know that $n$ is a quadratic residue.
The question is whether $n$ is a quartic residue or not.

Assume first that $n\equiv a^4\pmod p$ for some $a$ coprime to $p$. By Little Fermat we can deduce that
$$1\equiv a^{p-1}\equiv n^{(p-1)/4}\pmod p.$$
Multiplying this congruence by $n$ gives
$$
n^{(p+3)/4}\equiv n\pmod p.
$$
As $k=(p+3)/8$ is an integer, this means that $(n^k)^2\equiv n$ in line with the first alternative.
If $n$ is a modular square but not a modular fourth power, then I first claim that $-n$ will be a fourth power modulo $p$. This is because $-1$ is known to be a quadratic residue. But as $p\not\equiv 1\pmod 8$ there are no elements of order $8$, and consequently $-1$ cannot be a fourth power. The claim follows from this because the quotient group of quadratic residues modulo quartic residues is cyclic of order two (this holds for all $p\equiv1\pmod4$). The result of the previous bullet thus implies the congruence
$$
(-n)^{(p+3)/4}\equiv -n\pmod p.
$$
Here $(p+3)/4$ is even, so this reads
$$
n^{(p+3)/4}\equiv -n\pmod p.\qquad(*)
$$
Let $u$ be the residue class of $((p-1)/2)!$. Because $p\equiv1\pmod4$ it follows from Wilson's theorem, $(p-1)!\equiv-1\pmod p$, that $u^2\equiv-1\pmod p$. This allows us to rewrite congruence $(*)$ in the form
$$[u n^{(p+3)/8}]^2\equiv n^{(p+3)/4}u^2\equiv (-n)\cdot (-1)=n\pmod p,$$
which is exactly what the second alternative says.
Comment: yes, you are correct about the typo. I am not good with MathJax on here.
Comment: Thanks for notifying me about the fix @user2782067. Don't worry. You'll get the hang of it quickly enough.

Legendre symbol $ p ≡ 5 \mod 8$


Summation $ \sum_{k=-\infty}^n a^k$

Question: Is there any formula that directly gives the result of
this summation:
$$
\sum_{k=-\infty}^n a^k$$
?
Comment: Searching for an answer on the Internet is not "your work."
Comment: its a geometric series plus a finite sum. the result is finite for $|a|>1$.
Comment: If $|a| > 1$:
$$\dfrac{a^{n+1}}{a - 1}$$
Comment: You should show your work when you ask a question.
Comment: i searched the internet but i couldn't find any close answer.
Comment: @Max More concisely it's just a geometric series. (With first term $a^n$ and ratio $a^{-1}$.)
Comment: @arctictern both is correct and leads to the same result, its a matter of taste. i didn't want to make it too complicated since ppl who start getting in contact with math are often not so familar with index changes, splitting a sum into 2 sums is mostly easier to understand.
Comment: I saw exactly this question on this site several days ago. Can't find it now. Where does the problem come from?
Comment: it is in the book of discrete time signal processing written by alan v. oppenheim, question 2.10 a)
Answer: One may write
$$
\sum_{-\infty}^na^k=\sum_{-\infty}^0 a^k+\sum_1^n a^k
$$ then one may use the standard geometric series
$$
\sum_{k=0}^n x^k=\frac{1-x^{n+1}}{1-x}, \,\, x\neq1,\quad \sum_{k=0}^\infty x^k=\frac{1}{1-x},\quad |x|<1.
$$
Finally the sought sum is

$$
\sum_{-\infty}^na^k=\sum_0^{\infty} a^{-k}+\sum_1^n a^k=\frac{1}{1-\frac1a}+\frac{a(1-a^{n})}{1-a}=\frac{a^{n+1}}{a-1},\quad |a|>1.
$$
Comment: If one divides out $a^{n}$ and rewrites the sum as $a^n \sum_{k=0}^\infty a^{-k}$ then the geometric series is directly applicable (no splitting needed).
Comment: @Semiclassical Good catch!
Comment: @Semiclassical Another short way: $\sum_{k=-n}^\infty a^{-k}$ (no need to factor out $a^n$)
Comment: My preferred way (which is quite similar to Yves's answer): $$(a-1)\sum_{k=-\infty}^n a^k=\sum_{k=-\infty}^{n+1} a^k-\sum_{k=-\infty}^{n} a^k=a^{n+1}\implies \sum_{k=-\infty}^n a^k=\frac{a^{n+1}}{a-1}$$
Comment: Yes, but you are proving the formula... Not just applying. But since it is a short proof, I understand your point of view.
Answer: $$
S_{n+1}=\sum_{k=-\infty}^{n+1} a^k=S_n+a^{n+1}$$
and
$$S_{n+1}=\sum_{k=-\infty}^n a^{k+1}=aS_n$$ give
$$S_n=\frac{a^{n+1}}{a-1}.$$
Answer: Hint: separate the sum, from $-\infty$ to $0$, and from $0$ to $n$. Make the change of variables $k\mapsto -k$ in the first one.
Answer: Another aspect to view this from is convolution/deconvolution pair of a discretized differential operator $[-1,1]$ has $\mathcal{Z}$ transform $a-1$. And the integral filter which is $[\cdots,1,0,\cdots]$ would have the given series as it's $\mathcal{Z}$-transform (here $n$ is the position of the last 1). The integral of the derivative is the identity [1] and as composition corresponds to multiplication in the $\mathcal{Z}$ domain we have our correspondence between the three of them.
We can check by a discrete approximation of the convolution in matlab or octave:
<code>a = [1,1,1,1,0,0,0,0]; b = [0,-1,1];
conv(a',b','valid')'
ans =
0   0   0   1   0   0
</code>
a is the integral of the first four values, b is a differential approximation. In theory a would be of infinite length of 1s from $-\infty$ up to position $n$.
Comment: Erm. It may only be me, but regardless of whether it being correct, this answer makes me orders of magnitude more confused about the question than I was before reading it.
Comment: That depends solely on the reader. I can't know the background of everyone who reads questions and answers. One answer can confuse one reader but may help another.
Comment: Well, admittedly. But from your answer: where does $n$ come up in what you write, for instance? (To ask for a specific point.) (Also, sorry for the grammatical mistake I made above.)
Comment: Tried making it a bit more clear with an example in matlab. $n$ is the position of the last $1$ in the integral filter.

Summation $ \sum_{k=-\infty}^n a^k$


how to get forecast error measures in R after outliers detection using tsoutliers

Question: I used the tsoutliers package in R for outlier detection. Thereafter I used the following code to obtain a forecast:
x <- ts(x, frequency=12, start=c(2006,1))
res <- tso(x, types=c("AO","LS","TC"))

# define the variables containing the outliers for
# the observations outside the sample
npred <- 12 # number of periods ahead to forecast
newxreg <- outliers.effects(res$outliers, length(x) + npred)
newxreg <- ts(newxreg[-seq_along(x),], start = c(2012, 1))

# obtain the forecasts
p <- predict(res$fit, n.ahead=npred, newxreg=newxreg)

My question is, how do I obtain forecast measures such as ME, RMSE, MAE, MPE, MASE after using the predict function to obtain forecast as above?
Comment: I'm voting to close this question as off-topic because it is primarily about software implementation.  It also is unclear because it does not explain how outliers were removed.
Answer: You can obtain the measures of accuracy this way:
1)  Retain your model:
model_out <- forecast::auto.arima(x=x, xreg = res$fit$xreg, ic = "bic")

2) Obtain the forecasts using the forecast function:
p <- forecast.Arima(model_out, h =12, xreg= newxreg )

3) ask for the accuracy measures.
accuracy(p)

Hope this help.


How to change the Background of Layout dynamically while dragging layout in android?

Question: I want to change the background of layout dynamically while dragging the layout.
I used the following code for touch listener.
RelativeLayout   rlImages.setOnDragListener(new MyDragListener());
    RelativeLayout   half_left.setOnTouchListener(new MyTouchListener());

private final class MyTouchListener implements OnTouchListener {
    Drawable normalShape = getResources().getDrawable(R.drawable.pinkcircle);

    @SuppressWarnings("deprecation")
    public boolean onTouch(View view, MotionEvent motionEvent) {
        view.setBackgroundResource(R.drawable.pinkcircle);

        if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
            ClipData data = ClipData.newPlainText("", "");
            DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view);
            view.startDrag(data, shadowBuilder, view, 0);
            view.setVisibility(View.INVISIBLE);
            return true;
        } else {

            return false;
        }
    }
}

My dragListener class :
class MyDragListener implements OnDragListener {
    Drawable enterShape = getResources().getDrawable(R.drawable.halfcircle_left);
    Drawable normalShape = getResources().getDrawable(R.drawable.pinkcircle);

    @SuppressWarnings("deprecation")
    @Override
    public boolean onDrag(View v, DragEvent event) {
        int dragAction = event.getAction();
        final View dragView = (View) event.getLocalState();

        dragView.setBackgroundDrawable(normalShape);
        switch (event.getAction()) {
            case DragEvent.ACTION_DRAG_STARTED:
                // dragView.setBackgroundDrawable(normalShape);
                dragView.setBackgroundDrawable(normalShape);
                // Do nothing
                break;
            case DragEvent.ACTION_DRAG_ENTERED:
                dragView.setBackgroundDrawable(normalShape);
                // v.setBackgroundDrawable(enterShape);
                break;
            case DragEvent.ACTION_DRAG_EXITED:
                // v.setBackgroundDrawable(normalShape);
                break;
            case DragEvent.ACTION_DROP:
                // Dropped, reassign View to ViewGroup
                dragView.setBackgroundDrawable(normalShape);
                break;
            case DragEvent.ACTION_DRAG_ENDED:
            default:
                break;
        }
        return true;
    }
}

Comment: I want to change the background of layout while dragging it,but couldnt able to do that in any of DragEvents
Comment: Can you show the code where you set `MyTouchListener` and `MyDragListener` to a View?
Comment: rlImages.setOnDragListener(new MyDragListener());
   half_left.setOnTouchListener(new MyTouchListener());
Comment: I have edited please check
Comment: As soon as you get the `onTouch()` callback, you change the Views visibility: `view.setVisibility(View.INVISIBLE);`. Why?
Comment: It should look like it is dragging with my finger movement
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/40171/discussion-between-jeffrey-klardie-and-user1891910)
Answer: In the onTouchListener you need to change the background before you start the drag, because once you call view.startDrag(), the view gets duplicated. Then, when the drag ends and before it becomes visible again, you need to reset the background to what it was in the beginning (or whatever other background you want).
The following shows how that works:
public class MainActivity extends Activity implements OnTouchListener, OnDragListener {
    private static final String LOGCAT = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // doing view stuff...
    }

    public boolean onTouch(View view, MotionEvent motionEvent) {
        if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
            DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view);
            // set background of dragged view to red
            view.setBackgroundResource(android.R.color.holo_red_dark);
            view.startDrag(null, shadowBuilder, view, 0);
            view.setVisibility(View.INVISIBLE);
            return true;
        } else {
            return false;
        }
    }

    public boolean onDrag(View layoutview, DragEvent dragevent) {
        int action = dragevent.getAction();
        View dragView = (View) dragevent.getLocalState();
        switch (action) {
            case DragEvent.ACTION_DRAG_STARTED:
                Log.d(LOGCAT, "Drag event started");
                break;
            case DragEvent.ACTION_DRAG_ENTERED:
                Log.d(LOGCAT, "Drag event entered into " + layoutview.toString());
                break;
            case DragEvent.ACTION_DRAG_EXITED:
                Log.d(LOGCAT, "Drag event exited from " + layoutview.toString());
                break;
            case DragEvent.ACTION_DROP:
                Log.d(LOGCAT, "Dropped");
                // reset background of dragged view
                dragView.setBackground(null);
                ViewGroup owner = (ViewGroup) dragView.getParent();
                owner.removeView(dragView);
                LinearLayout container = (LinearLayout) layoutview;
                container.addView(dragView);
                dragView.setVisibility(View.VISIBLE);
                break;
            case DragEvent.ACTION_DRAG_ENDED:
                Log.d(LOGCAT, "Drag ended");
                break;
            default:
                break;
        }
        return true;
    }
}


Compare the mean of two independent samples (equal size)

Question: I would like to check whether there are statistically significant difference between women and men in the use of the Internet. I have a data for 144 countries about the use of the Internet by women and the use of the Internet by men (expressed in percentage of total population). Hence, n1 = 144 and n2 = 144. Which test in SPSS is appropriate for this analysis?
Answer: You provide little information about the shape of the data. I will crawl far out onto a speculative limb, trying to imagine what you have. I suppose data consist of 144 pairs of scores. If I'm somewhere near close, maybe you have your answer. If not, you can provide numerical/graphical
data summaries (as part of your Question), explaining any doubts about what I show below, and maybe someone can give a better-informed answer. [Also, I do not use SPSS and will show output from R, but the crucial procedures I show here should be also available in SPSS.]
Sampling and computations in R.
set.seed(2021)
w = 80*rbeta(144, 4,5)
m = w + 45*(rbeta(144, 5,5) - .35)

Numerical summaries:
summary(w)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  8.723  25.027  33.701  33.960  42.380  62.391
summary(m)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  3.325  31.526  41.131  41.281  50.558  76.597

d = m-w
summary(d);  length(d);  sd(d)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
 -8.611   2.760   7.444   7.321  12.523  22.594
[1] 144        # sample size (nr. of differences)
[1] 7.046872   # SD of differences.

A histogram of the differences shows more positive differences than
negative ones. Tick marks below the histogram (made with 'rug') show
the exact values of the 144 differences.
hdr = "144 Countries: Diff in Pct Internet Use"
hist(d, prob=T, br=20, col="skyblue2", main=hdr)
rug(d)

The data are not obviously normal, but a Shapiro-Wilk test does not
reject the possibility that the population of differences may be normal
(P-value well above 5%).
shapiro.test(d)

        Shapiro-Wilk normality test

data:  d
W = 0.99024, p-value = 0.4169

One expects that men and women in the same country may have roughly
the same access to the Internet. Ordinarily, paired data are associated.
We find a positive correlation between vectors m and w.
cor(m, w)
[1] 0.8619649

A scatterplot of m against w shows a strong positive association.
That most of the points lie above the 45-degree line (slope 1 through the origin), indicates most difference d = m-w are positive; more Internet
usage by men in my fake data.
 plot(w, m, pch=20);  abline(0, 1, col="blue")

A one-sample t test on differences (as below) is the same as a paired t
test of the differences. It confirms that the sample mean difference is
significantly above $0.$ (P-value almost $0.)$
t.test(d)

        One Sample t-test

data:  d
t = 12.467, df = 143, p-value < 2.2e-16
alternative hypothesis: true mean is not equal to 0
95 percent confidence interval:
 6.160184 8.481767
sample estimates:
mean of x
 7.320975

Note: If the histogram of the differences had shown marked differences
or far outliers (either positive or negative), then me might have
decided to use a nonparametric Wilcoxon signed rank test to see whether
the sample median of the ds is significantly greater than $0.$ (But is not proper statistical procedure to do both tests and pick the one with the smaller P-value.)
wilcox.test(d)

        Wilcoxon signed rank test with continuity correction

data:  d
V = 9680, p-value < 2.2e-16
alternative hypothesis: true location is not equal to 0


Changing var/www to something else

Question: I've installed Ubuntu on a Oracle VM Virtual box, and installed Apache etc.
How do I change the var/www folder that Apache uses, to something else? Can I simply rename it? I'm, trying to change it to nordy/core, in place of var/www.
Can I create a separate folder called nordy/core and place my html files there? One of the reasons I did not do this it because I noticed that var/ has several other folders that will not be created if I simply create a new folder. So, I'm guessing the site wont work.
I'd like to store my html and php files in a folder nordy/core so Apache can use it from there. Can I simply create a folder nordy/core and point Apache to it in Apache's configuration?
How do I do this?
Answer: You need to change the value of the DocumentRoot directive of your apache2.conf file. You may find this file at /etc/apache2/apache2.conf.
DocumentRoot "/nordy/core"

Then restart your apache process.
sudo service apache2 restart

Comment: So I need to create folders `nordy\core` and change the DocumentRoot, is that all? No need of copying all those files in var/ to the folders  I create?

Changing var/www to something else


Erro no emulador android genymotion (linux): HttpException: Connection closed before full header was received, uri = http://127.0.0.1

Question: Eu tenho o seguinte erro ao executar um projeto android flutter, notei que, se eu deixar meu código sem letras no text class, o código será executado. Um exemplo:
import 'package:flutter/material.dart';
void main(){
  runApp(MaterialApp(
      title: "Count People",
      home: Column(
        children: <Widget>[
          Text(".", style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
          ),
          FlatButton(
              child: Text("ButtonTest", style: TextStyle(color: Colors.white),),
              onPressed: (){}
          ),
        ],
      )
  ));
}

Observei que se eu usar "." (ponto como está no código acima), o programa executa, porém  ao colocar qualquer letra (a, b, c...), o programa até chegar a entrar no processo de implantação, mas dá um erro no emulador.
Exemplo do trecho com caracteres que causam o erro:
children: <Widget>[
          Text("a", style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
          ),

Saída de erro do console:
    Performing hot restart...
    Syncing files to device Flutter...
    Restarted application in 2.687ms.
    F/libc    ( 2131): Fatal signal 4 (SIGILL), code 2, fault addr 0xcee3f908 in tid 2148 (1.gpu)
    *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
    Build fingerprint: 'Android/vbox86p/vbox86p:7.1.1/NMF26Q/392:userdebug/test-keys'
    Revision: '0'
    ABI: 'x86'
    pid: 2131, tid: 2148, name: 1.gpu  >>> br.com.myname.count_people <<<
    signal 4 (SIGILL), code 2 (ILL_ILLOPN), fault addr 0xcee3f908
        eax cdb8e5a8  ebx cf6fdbbc  ecx cdb8d430  edx 00000000
        esi 0000001b  edi 00000002
        xcs 00000023  xds 0000002b  xes 0000002b  xfs 0000006b  xss 0000002b
        eip cee3f909  ebp cdb8d378  esp cdb8d330  flags 00010246
    backtrace:
    ...
    #61 pc 0111accf  /data/app/br.com.myname.count_people-1/lib/x86/libflutter.so (offset 0x10fb000)
        #62 pc 000752b2  /system/lib/libc.so (_ZL15__pthread_startPv+210)
        #63 pc 000202ae  /system/lib/libc.so (__start_thread+30)
    Lost connection to device.

Saída de erro do terminal com o comando flutter run:
Launching lib/main.dart on Flutter in debug mode...
Initializing gradle...                                              1,2s
Resolving dependencies...                                           2,6s
Running Gradle task 'assembleDebug'...
Running Gradle task 'assembleDebug'... Done                        18,0s
Built build/app/outputs/apk/debug/app-debug.apk.
Installing build/app/outputs/apk/app.apk...                         6,6s
I/Choreographer( 2267): Skipped 89 frames!  The application may be doing too much work on its main thread.
Syncing files to device Flutter...                                 F/libc    ( 2267): Fatal signal 4 (SIGILL), code 2, fault addr 0xcef18908 in tid 2284 (1.gpu)
*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
Build fingerprint: 'Android/vbox86p/vbox86p:7.1.1/NMF26Q/392:userdebug/test-keys'
Revision: '0'
ABI: 'x86'
pid: 2267, tid: 2284, name: 1.gpu  >>> br.com.myname.count_people <<<
signal 4 (SIGILL), code 2 (ILL_ILLOPN), fault addr 0xcef18908
    eax cdc5c5a8  ebx cf7d6bbc  ecx cdc5b430  edx 00000000
    esi 0000001b  edi 00000002
    xcs 00000023  xds 0000002b  xes 0000002b  xfs 0000006b  xss 0000002b
    eip cef18909  ebp cdc5b378  esp cdc5b330  flags 00010246
backtrace:
...
#61 pc 0111accf  /data/app/br.com.myname.count_people-2/lib/x86/libflutter.so (offset 0x10fb000)
    #62 pc 000752b2  /system/lib/libc.so (_ZL15__pthread_startPv+210)
    #63 pc 000202ae  /system/lib/libc.so (__start_thread+30)
Lost connection to device.
Could not update files on device: HttpException: Connection closed before full header was received, uri =
http://127.0.0.1:44139/D4BNlRCD8IA=/
Syncing files to device Flutter...

Acho esquisito esse erro e não aceitar letras, fechando a conexão. Pesquisei bastante e vi que algumas pessoas que usam Mac OS parecem ter um erro parecido, não sei se tem haver com a base do kernel do Unix. Lá eles falavam para configurar o no_proxy. Mas realmente não tenho ideia do que seja.
Agradeço quem puder contribuir.
Answer: Experimenta colocar um Scaffold, por que Text depende de theme, você pode implementar o theme colocando algum pre definido por exemplo:
Text(
'Seu texto aqui',
 style: Theme.of(context).primaryTextTheme.headline,
 textAlign: TextAlign.center,
),

ou então colocar um:
Material (
 child: Text(
 'Seu texto aqui',
 style: TextStyle( ...)
 textAlign: TextAlign.center,
),

e a forma indicada:
void main(){
 runApp(MaterialApp(
   title: "Count People",
   home: Scaffold(
     body: Column(
    children: <Widget>[
      Text(".", style: TextStyle(color: Colors.white, fontWeight:
      FontWeight.bold),
      ),
      FlatButton(
          child: Text("ButtonTest", style: TextStyle(color: Colors.white),),
          onPressed: (){}
      ),
    ],
  )
 ));
}


Hook to track commerce product category view

Question: I am creating a drupal commerce module for tracking users. I want to access a hook in drupal commerce on product category page. Went through most of the documentation but was not able to find the hook to listen to for product category page view.
Answer: Well, since you're dealing with Drupal, there's no "product category page"s ... per say ... but there are taxonomy terms that are often used for catalogs and attributes. So, you could, in theory, use hook_entity_view() to tap into when a taxonomy term is being viewed.
https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_entity_view/7
If you're building a module, I could see you building an interface that lets people assign urls and taxonomy terms that would potentially "make" the catalog pages trigger whatever it is you want to trigger.
Ultimately, though, there's no hard and fast rule on how to build a commerce store, so there's nothing for you to hook into.


TYPO3: Add LINK tags to CSS Files in the HEAD tag from within a Typo 3 extension

Question: I have a custom extension in Typo3.
Does anyone know how to add in a template ?
Ive had some success with adding in
call_user_func(
    function($extKey)
    {
       //other init code goes here

       $GLOBALS['TBE_STYLES']['skins'][$extKey] = array();
       $GLOBALS['TBE_STYLES']['skins'][$extKey]['name'] = $extKey;
       $GLOBALS['TBE_STYLES']['skins'][$extKey]['stylesheetDirectories'] = array(
        'structure' => 'EXT:'. $extKey. '/Resources/Public/css/',
        );
    },
    $_EXTKEY
);

Ive looked at typo3 docs but cant get it to work when adding to ext_tables.php
It is a Front End Plug in and I want the reference to be contained within the Extension for ease of installation and management.
Anyone  had success with this ?
Answer: put following in this file your_extension/Configuration/TypoScript/setup.ts
page = PAGE
page {
    # CSS files to be included
    includeCSS {
        yourCss = EXT:your_extension/Resources/Public/Css/yourCss.css
    }
}

and then call it in your ext_tables.php
/***************
 * Include TypoScript
 */
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addStaticFile(
    $_EXTKEY, 'Configuration/TypoScript', 'Your Package'
);

you'll find this voice in your template in the backend so that you can include it ...


AWS Beanstalk: Cannot determine embedded database driver class

Question: I have a spring boot application which runs just fine on my local instance (through Intellij) but while deploying on AWS BEanstalk, the application throws the following error (sorry about the formatting. This is how spring generated the exception):
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfig
uration$JdbcTemplateConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationExcept
ion: Could not autowire field: private javax.sql.DataSource org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$JdbcTemplateConfigur
ation.dataSource; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in cla
ss path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration$NonEmbeddedConfiguration.class]: Bean instantiation via factor
y method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method
'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cann
ot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you
 have database settings to be loaded from a particular profile you may need to active it (the profiles "aws" are currently active).
pom.xml
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>com.amazonaws</groupId>
        <artifactId>aws-java-sdk-dynamodb</artifactId>
        <version>1.10.56</version>
    </dependency>

</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>

        <plugin>
            <artifactId>maven-war-plugin</artifactId>
            <configuration>
                <archive>
                    <manifest>
                        <mainClass>com.my.app.path.MyApplication</mainClass>
                    </manifest>
                </archive>
            </configuration>
        </plugin>
    </plugins>
</build>

application.properties
spring.profiles.active=aws
dynamodb.tablename=my_dynamodb_table

application-aws.properties
spring.profiles.active=aws

The application uses a table in dynamodb. Could this be because I might need to set permissions in AWS to allow beanstalk to talk to dynamodb? If so, please let me know how to do that.
My EC2 instance is tomcat8 type.
Answer: Found the solution to my question on this post. See the answer by @user672009.
Just add this to your pom.
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>1.3.156</version>
</dependency>


Different usage of the term "Bias" in stats/machine learning

Question: I think I've seen about 4 different usages of the word "bias" in stats/ML, and all these usages seem to be non-related.  I just wanted to get clarification that the usages are indeed non-related.
Here are the 4 I've seen:
(1) "Bias"-variance tradeoff: Here, bias is used to characterize the model error due to simplified assumptions of the model, e.g., using linear regression when linear regression is not complex enough to capture the trends of the data.
(2) "Bias" of an estimator: the difference between the expectation of an estimator and its true value.
(3) "Bias" as in the offset term: e.g., in simple linear regression with $y = \hat{\beta}_1x + \hat{\beta}_0$, I sometimes see the offset term, $\hat{\beta}_0$, referred to as the "bias" term. e.g., in Role of the bias term in regression
(4) "Biased" data: I think this might be similar to (1), but here it's referring to the data and not the model. I typically see this in experimental studies where the experiment was conducted in a setting that captures a limited portion of the trend. e.g., you could have some response that's sinusoidal, $e.g., y = \sin(x)$, and the experiment was only performed for $x \in [0, \pi/2]$, which is a monotonically increasing period.
I think these are the 4 usages that I've seen, but if there are others, please do share.
The usage of "bias" in these 4 settings are un-related, correct? It's a little confusing to see the same term show up many times in different settings in the same field.
Comment: 1 and 2 seem related, no?  And related to 4 there's learning of social bias implicit in the data.
Comment: Bravo for the question!
Answer: I will give you a run-down of the terminology used in statistics, which I think is sensible terminology.  Cases (1) and (2) do refer to bias in the usual statistical sense, (4) refers to something closely related, and (3) is just misleading renaming of an object that already has a perfectly sensible name.  Just to quickly dispose of (3), I note that the term $\beta_0$ in regression is called the "intercept" term, not the "bias".  Unless there are good contextual reasons to refer to it as the "bias term", that language is highly misleading.  (The link you give for this usage is just a CV.SE question that was closed for lack of clarity, so not really evidence of widespread usage.  I have never seen this term in the regression referred to as the bias term.)

Estimator bias and the "bias-variance trade-off": When we "fit" a statistical model we are essentially just estimating the unknown parameters in that model.  As you note in case (2), the bias of an estimator is defined as the difference between the expected value of the estimator and the value of the parameter it is estimating:
$$\text{Bias}(\hat{\theta}, \theta) = \mathbb{E}(\hat{\theta}) - \theta. \quad \ $$
When looking at the performance of estimators we often measure this by the mean squared error, which is the expected value of the squared deviation of the estimator from the value it is estimating:
$$\text{MSE}(\hat{\theta}, \theta) = \mathbb{E} \Big( (\hat{\theta}-\theta)^2 \Big).$$
One of the properties of the mean squared error is that it can be decomposed as:
$$\quad \quad \ \ \text{MSE}(\hat{\theta}, \theta) = \mathbb{V}(\hat{\theta}) + \text{Bias}(\hat{\theta}, \theta) ^2.$$
If we examine a model for an observable value $y = f(x, \theta) + \varepsilon$ composed of a regression term and an error term, we likewise have:
$$\mathbb{E} \Big( (y-f(x, \hat{\theta}))^2 \Big) = \mathbb{V}(f(x,\hat{\theta})) + \text{Bias}(f(x,\hat{\theta}), f(x,\theta)) ^2 + \sigma_\varepsilon^2.$$
Now, if we examine the class of estimators with some fixed mean squared error, we can see that there must be a trade-off between the bias and variance in these estimators --- a lower bias corresponds to a higher variance and vice versa.  Often when we have competing methods of estimating parameters (i.e., alternative ways to "fit" the model) we focus on those that have the optimal mean squared error, and within this class we see that there is a choice between methods that have higher bias but lower variance, and methods that have low (or no) bias but have higher variance.
As you point out in your case (1), it is common in discussions of machine-learning to refer to a general "bias-variance trade-off" in the choice of model fitting methods and the use of training data.  While this discussion is often quite broad and esoteric, ultimately it derives from the statistical decomposition shown here.  It is therefore referring to "bias" in the standard statistical sense.  Consequently, cases (1) and (2) both refer to bias in its usual statistical definition.

Informative sampling (so-called "biased" data): In discussions of sampling you might sometimes run across references to "bias" in the data or sampling method.  Statisticians generally do not use this language (except sometimes as shorthand) because they recognise that bias is a property of an estimator, and so it only occurs from the combination of a sampling method and an inference method.  When data gives information in a non-standard way we say that it is an "informative" sampling method and we try to take this into account in our inferences.  If the inference method does not properly take account of this information then this gives us a biased estimator, but the bias comes from the combination of the sampling method and the inference method --- it is not the data per se that is biased.
This area of statistics is quite subtle, so I will describe it through an example.  Suppose you have a small community with ten children, and you want to know the average number of children per family (only for the families with at least one child).  Suppose that of these ten chidren, nine are from the same family (all siblings) and the one is an only child (no siblings), which means that the true average is five.  Suppose you sample all the children and ask each of them how many siblings they have, then use this data to estimate the average number of children per family.  A naive estimator would be to take the average number of siblings per child and then add one to get an estimate of the average number of children per family.  If you use that inference method, you get a substantial overestimate:
$$\hat{\theta} = \tfrac{1}{10} (9 \cdot 9 + 1 \cdot 0) + 1 = 8.1+1 = 9.1.$$
The problem here is that we are sampling over children rather than over families, and so we are more likely to select a child from a larger family; the average over all children gives proportionately more weight to families of larger size.  This is an example of "informative" sampling method where the naive estimator leads to large bias in estimating the true quantity of interest.  (The technical name for this type of sampling is probability proportional to size (PPS) sampling.)  Note here that it is the use of a particular type of (erroneous) estimator that leads to the bias.  If we take account of the fact that we are using PPS sampling, and account for this in our estimator, we can get rid of this bias.
As you can see from this example, it is not quite right to say that the data themselves are biased --- the sampling method is unusual, and it leads us to substantial bias if we treat it as if it were giving us direct information on the quantity of interest, but the bias occurs from our failure to account for the nature of the sampling mechanism in our estimator.  In statistical discussion we use the term "informative sampling" to describe this kind of sampling mechanism, but "bias" remains a property of the estimator.  Consequently, whether or not we have bias is determined by the combination of the sampling method and the estimator.
Answer: They all refer to something being "non-neutral", but, apart from that, I wouldn't say they are related. To my understanding, (2) refers to the computational method, irrespective of the data. For example MLE vs. unbiased estimator of the variance, whether you use $N$ or $(N-1)$ as the denominator. (4), on the other hand, is about the sampling process.
Regarding (3), based on my professional experience and acquaintance with machine learning history, I believe the usage of "bias" with the meaning of "intercept" comes from electronics: The early research on what we today call "machine learning", in the 1950's-60's, often involved building specialised hardware or, later, simulating that hardware in computers. "Bias" in electronics means the intentional shift of the operating voltage away from zero, in order to achieve desired response characteristics (typically: linearity) of a component, like transistor or vacuum tube. This is probably also the reason why the intercept in machine learning is often denoted by $b$ and the predictor coefficients ("weights" in neural network terminology) by $\textbf{w}$.
Comment: Ah ok. That would make sense then. Thanks for sharing!
Answer: (2)
What is bias? As you correctly defined in (2), bias is the difference between the estimator and its true value in expectation.
(4)
This is an application of the definition. Making things a bit explicit here can help. What we want to estimate is:
E[sin(x) | full_period]
But instead we estimated using:
E[sin(x) | quarter_period]
Clearly:
E[sin(x) | full_period] != E[sin(x) | quarter_period]
in general.
Thus our estimator is wrong. It's wrong because we incorrectly sampled on a different set of conditions. But it still fits the definition of bias.
(3) and (1)
(3) is interesting. I am not sure why historically the term of 'bias' originated in linear regression. If I simulated data from a linear regression model with a non-zero intercept and then built a linear regression model from its output data, clearly my non-zero 'bias' term is what we want--so it's not biased according to our definition of bias. This suggests it does indeed reflect a different meaning.
It seems by 'bias' in this context, we are really trying to hint at this idea of how well the model is influenced by data. That is, the larger we make our intercept, the less impact the data has on our predictions. This would also capture this notion .
Research Paper
I also found this research paper while answering this question (have not read it) that attempts to distinguish the bias definitions used in machine clearing:
https://arxiv.org/pdf/2004.00686.pdf
Comment: Is there significance to the nested expectation in E[E[sin(x) | full_period]] or was that a typo? Is E[sin(x) | full_period] a random variable?
Comment: (1) is not too interesting. If $\hat{\beta}$ is an estimator which may be biased, $\hat{Y}$ is also an estimator - a function of $\hat{\beta}$ - which may also be biased. You would simply measure the bias on a different scale. The parameters may be biased on the parameter scale, but the predictions unbiased on the response scale. Hence "bias-variance" tradeoff in the context of MSE.
Comment: @student010101 My intent was emphasize E[sin(x) | full_period] as a random variable (which changes based on what is being conditioned on). But I think that made it more confusing than necessary. I have removed it.
Answer: They all mean a systematic (as opposed to a random) deviation from a target, when repeatedly applying a (sampling and/or estimation) procedure. The target differs in  the mentioned examples:

Target is value of the response in a sample from the target population, that was not part of the training sample.

Target is true value of the estimated quantity. (Also goes for point 1. actually)

Target is zero.

Biased data should read biased sample. Target is the (multivariate) distribution of values in the target population.
Answer: To me this is an excellent question, I would be very proud if I asked it. I will not analyze the bias in bias-variance-trade-off in here just, just the bias function instead.
Bias is often related to any of these:

sampling method
estimator
model
inference method

Sampling method
Both quality and quantity sampling may influence the later bias, but sampling method itself will not produce the bias.
In short the $N$ -- number of elements in your sample or the $n$ -- number of samples represent the quantity part and quality would be either of the techniques:

random sampling
stratified sampling
systematic sampling

It depends on a problem what kind of a sampling we choose, but again sampling method may be a cause for a bias, not the instant creator of the bias, because data is innocent.
Estimator
Estimator and how it relates to a model I don't understand quite, but I will shoot proudly and congruently and check yor comments later:

Estimator is parameter estimator and can show the bias in parameter estimation
Model is what estimates the prediction and can show the bias of a prediction

We can call estimator -- the decision rule for selecting parameters.
I learned that there are biased and unbiased estimators. The bias (or bias function) of an estimator is the difference between this estimator's expected value and the true value of the parameter being estimated. We usually use thetas for general parameters so:
$$ \text{Bias}(\hat{\theta}, \theta) = \mathbb{E}(\hat{\theta}) - \theta. \quad \ $$

Let's say bias can also be measured with respect to the median, rather than the mean (expected value), in which case one distinguishes median-unbiased from the usual mean-unbiasedness property.

An estimator with zero bias is called unbiased. In statistics, "bias" is an objective property of an estimator super related to the term called degrees of freedom. At this moment my understanding is: The more degrees of freedom, the more bias, the more estimation errors we have.
Model
There are many ways you can define what is a model, but in here I will just analyze the models as being able to predict the feature of interest. In that respect the bias will tell us how off from the true value of the prediction we are. I will use this image to save some words.

There is another bias in the model, where we say bias exists because hypothesis functions are biased to a particular kind of solution. In other words, bias is inherent to a model (but I would call this simple as the bias of the estimator).
Inference method
Classical inference method (I will just stick with that) computes probabilities from multiple hypotheses in order to determine their acceptability. This method usually analyses two hypotheses at a time.
This inference provides quantitative information about a sensor observation in the form of a probability. As I see it -- we cannot create bias in here. We may change and adopt to differnt confidence intervals but this will not provide bias or errors.


Solution for backing up/copying from multiple destinations

Question: We have 12 Debian servers that we want to copy a specific directory from to just one server on a weekly basis. This server will act as sort of a backup server.
Any suggestions how to go about this?
Answer: Rsnapshot is the way to go. Rsnapshot is just as easy to setup as your own rsync commands and will add some nice flexibility. http://rsnapshot.org/. Rsnapshot will automatically create versions of your backup, but only a relatively small amount of additional storage (the deltas)
You will need to setup ssh keys to do any kind of copy securely.
Answer: A combination of rsync, ssh and some basic bash scripting is the way to go. It's not complex.
Answer: I'll recommend you to keep in mind that you can have multiple rsnapshot configuration files and then call them from your crontabs or anacrontabs.
rsnapshot -c /etc/your_config_file_for_servers1
rsnapshot -c /etc/your_config_file_for_servers2

For doing it securely over network go through ssh if you need encrypted data, otherwise through nfs.
If you need to backup a workstation or server which is not always up, take a look @ anacron
Answer: Rocknroll is a light alternative.
To use it, first, prepare an archive point on the destination server (one shot). For example :
rocknroll --init 7 daily /var/snapshots
rocknroll --init 4 weeky /var/snapshots

prepare the directory /var/snapshots for a set of 7 series of archives named daily, and a set of 4 series of archives named weekly.
After that, yo can perform daily and weekly backup. To do a weekly backup  :
rocknroll weekly email@example.com:/home /var/snapshots

This perfoms a rsync from remote.my.domain:/home into /var/snapshots/weekly.1/
A second :
rocknroll weekly email@example.com:/home /var/snapshots

rename /var/snapshots/weekly.1/ to /var/snapshots/weekly.2/, and   perfoms a new rsync from remote.my.domain:/home into /var/snapshots/weekly.1/ (with file deduplication between the 2 directories).
4 archives will be kept : /var/snapshots/weekly.1/ to /var/snapshots/weekly.4/.
Comment: Please disclose directly that you are the author of this script.
Comment: It would also be a good idea to provide an example usage, perhaps related to the original question.


Echo token in CMD

Question: What I am trying to do is add quotation marks around the tenth token of a text files so a number would read "55555" instead of 55555. While leaving the other tokens untouched.
What I have as of now which doesn't work is:
FOR /F "skip=1 delims=, tokens=*" %i in (file.txt) do
IF tokens EQU 10
    echo "%i" >> data.txt
ELSE
    echo %i >> data.txt

Answer: FOR /F "skip=1tokens=1-9,10*delims=," %i in (file.txt) do (
 >>data.txt echo(%%i,%%j,%%k,%%l,%%m,%%n,%%o,%%p,%%q,"%%r",%%s
)

should work for you.
Comment: Did this help you, Bob?

Echo token in CMD