How does differential equations in the space of operator valued functions work?

Question: In my Quantum Mechanics class, we talked about Schrödinger Equation for the time evolution operator $\hat U(t)$,
$$i\hbar\frac{d\, \hat U(t)}{dt} = \hat H(t)\hat{U}(t),\qquad \hat U(0)=\mathrm{id},$$
with $\hat H(t)$ being some self adjoint operator on a Hilbert space $\mathcal H$, with the solution $\hat U(t)$ being some unitary operators.
And if $\hat H$ is independent of time, then we are given the solution
$$\hat U(t) = e^{-i\hat H t/\hbar}.$$
We were told to just plug in and check that this is a solution, and were given no further explanation.
I'm just basically not sure how most of this works. More specifically, I have the following questions.

How is the derivative defined? My guess is that, we are using the operator norm for the operator, and define the derivative the normal way?
If there's an integral, how is it defined? I've only seen lebesgue integral for real and complex valued function, and I couldn't think of a way it could work for operators.
How do we know that the solution $\hat U (t)$ will remain unitary, provided the only thing we know is $\hat H(t)$ is self adjoint and $\hat U(0) = \mathrm{id}$.
If $\hat H(t_1)$ commutes with $\hat H(t_2)$, is it true that the solution is $\hat U(t) = e^{-i\int \hat H(t) \,dt /\hbar}$? My intuition says this should be true, as $\hat U(t)$ should always commute with $\hat H(t)$ in this case.
How much does the theory of normal differential equation carries over? Do we know that the solution exist? Is it unique? etc. The most general differential equation I've seen is for smooth functions on manifolds, and the one here is obviously very different (the functions aren't even commutative).
What are some good references for these (if there are any)?

Note: I'm an undergraduate student double majoring in math and physics, and I have taken several graduate courses. So don't expect me to know any of the advanced results, but I'd love to learn about them :)
Comment: You are overwhelmingly wrong that I don't understand the questions.  In addition, you would be overwhelmingly wrong to believe that I don't understand the correct ladder of abstractions to take someone asking your questions to this level of abstraction.  These questions are targeted to understand exactly where on that ladder you are since your questions indicate that you are confused about several of the rungs prior to the ones at the level of your class.
Comment: Have you read, and do you understand, the material in the Definition section of the [Schroedinger equation](https://en.wikipedia.org/wiki/Schr%C3%B6dinger_equation) Wikipedia page?  (That section has three subsections: Preliminaries, Time-dependent equation, and Time-independent equation.)  Do you understand that the unitarity of $\hat{U}$ encodes that it is a probability amplitude (a.k.a. wave) function on the Hilbert space?  Can you solve the equation for a *function* $\hat{U}(t)$? so that you have a formal solution?
Comment: Finally, do you see that complex phase is the only thing changing in that formal solution, so unitarity is preserved?
Comment: @EricTowers Please don't give suggestion when you don't even understand the questions. Here, $\hat U$ and $\hat H$ are the operators, not the wave functions.
Comment: I agree with @Eric that you are overthinking it. For a constant Hamiltonian, you are instructed to consider seat-of-the-pants "matrix" exponentials, and formally solve the OD.  The operator extension of the mature theory of [matrix exponential](https://en.wikipedia.org/wiki/Matrix_exponential)s and [matrix differential equation](https://en.wikipedia.org/wiki/Matrix_differential_equation)s is is normally *assumed* to generalize to QM operators, with some common sense.
Comment: @CosmasZachos That's why I posted it on math SE instead of physics SE. Thanks anyways :)
Comment: @CosmasZachos The biggest issue is that the Hilbert space is infinite dimensional. Are there any references on the operator extensions of the theory? I'd love to see them.
Comment: Most physicists stay away from these things with extreme prejudice. I have no doubt there are such things, but you got to take a Reed-Simon-style course on functional analysis, not spatchcock books and questions together... I thought you just wanted to follow the course involved.
Answer: I've found some relevant information in the text One-Parameter Semigroups for Linear Evolution Equations. I think it's only relevant for the case when $\hat H(t)$ is independent of time.
With some more reading, I believe the answer for question 1 and 2 is the Fréchet derivative and Bochner integral with the norm being the operator norm.
I wasn't able to find relevant information for time dependent $\hat H(t)$ though, and would love to see if anyone else can find anything.


Solve a quadratic for a unique solution.

Question: If $ax^2-5x+2=0$ then find the value of $a$ that makes the quadratic have a unique root.
Answer: If $a=0$ it's a linear equation and therefore has exactly one solution: $x=\frac{2}{5}$
If $a\neq 0$ you can solve it as a quadratic equation:
$$x = \frac{5\pm \sqrt{25-8a}}{2a}$$
this has exactly one solution iff
$$\sqrt{25-8a} = 0 \Leftrightarrow 25-8a = 0 \Leftrightarrow a=\frac{25}{8}$$
Now the only solution is
$$x = \frac{5}{2*\frac{25}{8}}=\frac{4}{5}$$
Comment: Thank you so much sir
Answer: Hint: Write $$a=\frac{5x+2}{x^2}$$


Adult learning to play popular songs on piano

Question: OK, similar questions may have been asked over and over again, but I would like to know how much time it takes to learn the piano. I am almost 34 (male), and have never taken any piano lessons before and I almost forgot everything I learned from music classes in my elementary school through high school.
I am not interested in playing classical or jazz, and I do not want to be a musician. I just want to play some popular songs I like for my own amusement. For example, these are the songs I would like to play.

I did some Google search and the first article told me that to learn to play the piano, I have to practice 4 hours a day, 5 days a week, for the next 15 years. The article said not to worry because if even one starts at one's 40, one would be fluent at 55, and could enjoy 20 or more years of one's life playing the piano.
I do not know what level of fluency that estimation targets. Can I actually be fluent in piano in some years on my age?
Comment: You say you've never taken any piano lessons BEFORE. I would hope this indicates that you ARE going to take lessons. A teacher will short-circuit the amount of time quoted here. Obviously, one can learn anything, given enough time (and application), but a teacher is worth many, many books/web lessons/etc.
Comment: Thank you, Tim. There are not many piano academy (forgive me, if this is a wrong term) for adults where I live, most of them are for kids. I am considering possibilities.
Comment: The idea of "fluency" is very arbitrary.  You will never be entirely satisfied with your playing, which is part of the attraction of learning.  The other part of the attraction is that the more you work at it, the better you get.
Comment: No, I originally did not ask about fluency. My question was modified by the moderator. I asked how much time it would take to be able to play songs like in the videos.
Comment: I only started seriously playing piano about 4 years ago. For 2 years I took lessons from a classical teacher, which had a serious deficiency - we covered was "how you play the notes on the page", not chords or theory at all. In the past 2 years I've taken rock lessons and played with a band. Since I'm forced to improvise over chord charts vs. written music, I've studied theory, which has enabled me to pick up songs much more quickly, especially pop and rock. If you want to learn quickly, make sure to study theory just as much as what note on the page is what note on the keyboard!
Comment: A tutor who teaches kids should be able to teach you too - at least some basics.
Answer: Yeah, the numbers listed above are way off. If you just want to play a handful of popular songs you should be able to do it in a year or so, depending on how much time you dedicate and how well you get along with your piano!
As aforementioned, you might want to conduct a search and see if there are any tutorial videos for any of the songs that you want to learn. If you're not a musician, this is a great way to see what you need to play. If there are no videos then you're going to have to work a lot harder. You will then need to either know how to read music or know music theory if you plan on using your ear to figure the song out.
If you can practice 30 minutes a day, or at least 2-3 hours a week, you should be able to learn the 3 songs in less than a year. The thing is how long it takes to learn to play popular songs on piano as an adult isn't really quantifiable. It really boils down to how much you want to play it, and how fast you learn.
Comment: Thank you Mr Bard. You think people like me (I have described my state in my question) could play that kind of song in 1 year just by practicing 1 hour a day? That seems quite fast to me.
Comment: I absolutely think so. None of the songs above seem particularly difficult. There are obviously a lot of easier first songs to learn, but an important thing about music or learning to just play a piece of music is that you have to like what you're playing. You can get boggled down learning beginner piano music, but if you don't like it, you won't get very far. If these songs are songs that you love and have the desire and means to learn them, then 365 hours is plenty of time, even for a beginner. Again, you just have to figure out how to tackle the learning process, if you have to learn how to
Comment: read music or play by ear, then that's going to slow you down. You mentioned you don't want to be a musician and you just want to play these songs, so my suggestion would be to see if you can find some sort of tutorial video for the songs on youtube. If you can, then you'll be on your merry way to learning the songs in a relatively short while. If you have to learn how to read music, then I still think that a year is plenty of time, but that will boil down to how fast of a learner you are, and most importantly your willpower and determination to play these songs.
Comment: I second MrTheBard here.  I would add this: suppose you put in the time and then let us know how you do? :)
Answer: I know a 70+ year old man who is still learning to play the piano. The fact that you express a desire to play indicates you have a real interest, at least ostensibly. This is important, as that would be your impetus to play the piano as an adult learner. It is not necessary to explain why being young is extremely advantageous to acquiring any musical ability through training. However, musicality is subjective and an older person can appreciate many things that a younger person cant. Don't be intimidated and have a dedicated goal in your mind. Then, consider a piano teacher as an aid. Many adult learners find being 'back in school' under the tutelage of a piano teacher truthfully unpleasant. This is because they expect to be taught which of course is not productive for an adult. In reality, one must go to the core of musicianship, which is mastery. The faster you can do this, with or without help, the better you are.
Answer: If your goal is only play a handful of songs on piano it will take nowhere near 20 years to play them. The hardest part for you would be understanding the notation for the songs, but if you can find more videos like the ones above where you can see what notes are being played instead of trying to read the score it shouldn't take that long. Most people who start playing piano rely more on memorization than actually reading the score because especially at first it is the equivalence  of a foreign language.
If you can make enough time to learn even 5 just seconds of the song a day by just watching and mimicking what you see it will take you about a month and a half per song.
I would also get the scores for the songs so you can use them as a guideline when you just listen to the songs. Even if you don't know how to read music notion pop songs tend to repeat themselves and you should be able to see the repeated parts without knowing how to read the and start learning the basics of how music is notated. There are also many online resources including this site that can help you if you need help.
I know many people who know how to play a few of their favorite song on the piano, but can't read any piano sheet music. It is not required if you are just want to learn a few songs and as long as you are determined enough you should be able to learn them in a timely manner.
Comment: So basically there are two parts in learning piano; reading the notes and playing. What you mean is I can save some time by reducing the time for learning how to read the notes, if I am only interested in a fixed number of songs, right?
Answer: After learning the basics of playing the piano, you can do a shortcut since you are basically only interested in playing popular songs.  On udemy.com there are several courses on harmony and improvisation.  You learn a standard set of harmonies for the left hand which can be played for any melody.
It is simple to learn.  You might check out the "Learn Piano" series by Rosa Suen.
Answer: You can become an expert in pretty much anything with 10,000 hours practice. To become professional standard pianist, if you practice for 4 hours a day you should get there in well under 10 years, not 15. However, to play those kinds of songs, you do not need to be anywhere near that kind of standard.
As a reasonable lower bound, I am good at music and could already play another instrument to a good standard when I began teaching myself the piano, and I reached the standard where I could play those kind of songs in well under 1 hour a day practice, for 3 years.
As a reasonable upper bound, if you are not innately very musical, but you practice persistently, then I would say you should be able to reach that standard in about 2500 hours, or 1 hour a day for 7 years.
Comment: OK, 1 hour a day for 7 years, if I am not good at music.
Comment: @SinJeong-hun At maximum, likely quite a lot less. You could probably play one or two specific songs in a year with 1 hour a day.
Answer: I think one could learn a song such as you post in a much shorter time. It would involve someone showing you exactly what to do, in sequence.It will not make you a pianist, but it will allow you to play tunes, parrot-fashion.
I don't necessarily advocate this , but, from memory, there was a comedian who could 'play' many instruments, but - apparently, learnt only one tune on each, to use in his act. If anyone knows his name, please tell me.
Answer: Enthusiasm will be your carrier :-)
Every day of playing will make a marked difference in your skill, and if you're playing for your own amusement then you can be your own judge about how you're doing. Lessons always help to iron out bad habits and start you off with good technique of course, but ultimately it's up to you how long you take to get to whichever point you end up at. For that reason I think putting an amount of time on it is a bit arbitrary - the end goal (fluency) isn't that well defined in that your idea of fluent might be different to someone else's, and your learning rate depends on so many things.
So as I say .. enthusiasm will carey you through.
I hope you enjoy it ! I can't explain the satisfacition I still get from learning new songs - which brings me to my next point ..
Amount of time to practice daily: Can I suggest you practice when you WANT to? If that's 4 hours a day (or more), great- but don't drag it out so it feels like a chore. In my experience this is an effective way of kirbing enthusiasm.
Keep it fresh and enjoy ! :-D


underline the clicked text element

Question: I have a list of text elements that I want to underline when clicked. If I add the text decoration to the tabText then obviously it is applied to all items. How can I make sure that the when I click on another tab, the underline from the previous tab gets removed?
Is there any way I can add or remove items from the style element upon clicking on an item?
//onPress={() => {}}>
const tabs = [
  {
    id: 1,
    text: 'Alle List',
  },
  {
    id: 2,
    text: 'Second',
  },
];
export const Tab: React.FunctionComponent = () => {
  return (
    <View style={styles.tabView}>
      {tabs.map((item: any) => (
        <View>
          <Text style={styles.tabText}>{item.text}</Text>
        </View>
      ))}
    </View>
  );
};

const styles = StyleSheet.create({
  tabView: {
    paddingTop: moderateScale(15),
    paddingLeft: moderateScale(20),
    paddingRight: moderateScale(20),
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  tabText: {
    color: 'white',
    paddingBottom: moderateScale(10),
    //textDecorationLine: 'underline'
  },
});

Codesandbox (with tabText items as an array too):
https://snack.expo.io/@nhammad/shallow-watermelon
Answer: You can add different styles for your tab depending on active route
<Text style={[(this.props.activeRouteName == route.routeName) ? styles.tabActiveText: styles.tabText]}>{item.text}</Text>

And then in the styles

tabActiveText: {
    color: 'white',
    paddingBottom: moderateScale(10),
    textDecorationLine: 'underline'
}

Comment: Thanks for your input. There's no 'activeRoute' right now. This is just plain text. And there's no this. property here either since I am not using classes
Answer: You can use useState to save the selected index and then apply another style based on the selected index. Here is a quick modification to your script and the snack link is at the end.
import * as React from 'react';
import { Text, View, StyleSheet, TouchableOpacity } from 'react-native';

const tabs = [
  {
    id: 1,
    text: 'All Friends',
  },
  {
    id: 2,
    text: 'Second',
  },
  {
    id: 3,
    text: 'Third',
  },
];
export default function App() {
  const [selected, setSelected] = React.useState(null)
  return (
    <View style={styles.container}>
      <View style={styles.tabView}>
        {tabs.map((item: any, index) => (
          <TouchableOpacity onPress={()=>setSelected(index)}>
          <View>
            <Text style={[styles.tabText,selected===index?styles.selected:null]}>{item.text}</Text>
          </View>
          </TouchableOpacity>
        ))}
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  tabView: {
    paddingTop: 15,
    paddingLeft: 20,
    paddingRight: 20,
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  tabText: {
    color: 'black',
    paddingBottom: 10,
  },
  selected: {
    textDecorationLine: 'underline'
  },
});

https://snack.expo.io/@saachitech/da6280
Comment: Is it possible to style the underline too? For instance, I added a color to it but I want to increase it's height or maybe increase the distance between the underline and the text. ```textDecorationColor: 'green```,
Comment: perhaps use ```textUnderlinePosition: 'under'```, here is more info https://css-tricks.com/almanac/properties/t/text-underline-position/
Comment: Updated Snack with border-bottom styles

underline the clicked text element


Flag module: Do not allow users to flag own content

Question: I am using Flag 7.x-3.0 to enable users to flag file entities. I only want users to be able to flag files that other users have uploaded. However, I am missing the checkbox option "allow users to flag own content" that I remember having been a part of earlier versions of Flag module.
Has this feature been removed?
Answer: This is a specific use-case so it may be better to approach this using the Flag API. Specifically, try hook_flag_access and add this to your custom module (or create one). This function takes the following parameters:
hook_flag_access($flag, $entity_id, $action, $account)

and what you are specifically interested in is the following:
$entity_id: The id of the entity in question.

$account: The user on whose behalf to test the flagging action.

The $entity_id will allow you to determine what user id created the entity and the account object will already contain the account of the current user so this function will block flag display if they are the same:
function YOUR_MODULE_flag_access($flag, $entity_id, $action, $account) {

  //load data for the entity
  $entity = entity_load($entity_type, array($entity_id));

  // if the account that created the entity is the same as the user attempting to flag it then block access
  if ($entity[$entity_id]->uid == $account->uid) {
    return false;
  }

}

Comment: The line `if ($entity[$entity_id]->uid == $account->uid) {` causes an error, "Notice: Undefined variable: entity" and "Notice: Trying to get property of non-object". What is the correct way to load the file entity and the file entity's author id?
Comment: I used `$author_id = db_query("SELECT uid FROM {file_managed} WHERE fid = :fid", array(':fid' => $entity_id))->fetchField();` and then `if ($author_id == $account->uid) {` instead, which works like a charm. Can anyone tell me if this would be a lightweight solution?
Comment: Right - again, forgetting that you're using a managed file field here this query would work better for you. This query is about as preformant as you can get, especially since you're no longer using the entity_load function above.
Answer: That feature is still in there. Edit your flag and you will see it about midway through the settings
Comment: I do see it for flags of flag type "Nodes" but not for flags of flag type "File". Is File Entity Module causing issues so that the flag access settings don't appear for "File" flags? Or are flag access settings just not provided for "File" flags?
Comment: Ah that must be it. Files are their own entities and most likely do not have the same author property as nodes. You'll probably have to put in a feature request, do something in code as schnippy shows below or you could do it with rules.


How to interpret multiple interactions in lm

Question: I'm wondering how to interpret the summary(lm) output in the context of multiple interactions. Here's some toy data with 2,000 observations, one dependent variable, two conditions (control + treatment), and some further covariates:
set.seed(101)
n <- 2000
dv <- rnorm(n)
condition <- sample(c("control","treat"),n,rep=TRUE)
age <- sample(18:85,n,rep=TRUE)
gender <- sample(c("male","female"),n,rep=TRUE)
education <- sample(c("less_than_undergrad","undergrad","post_grad"),n,rep=TRUE)

df <- cbind.data.frame(dv,
                       condition,
                       age,
                       gender,
                       education)

Say we think that the treatment effect on dv will be different for different levels of education. So we fit the following:
summary(lm(dv ~ condition +
             age +
             gender +
             education +
             condition:education,
           data = df))

Call:
lm(formula = dv ~ condition + age + gender + education + condition:education,
    data = df)

Residuals:
    Min      1Q  Median      3Q     Max
-3.2715 -0.6805  0.0090  0.6786  3.2264

Coefficients:
                                    Estimate Std. Error t value Pr(>|t|)
(Intercept)                        0.0116217  0.0843061   0.138    0.890
conditiontreat                    -0.0661622  0.0775752  -0.853    0.394
age                                0.0003638  0.0011395   0.319    0.750
gendermale                        -0.0417308  0.0448992  -0.929    0.353
educationpost_grad                -0.0516772  0.0769658  -0.671    0.502
educationundergrad                -0.0381631  0.0786148  -0.485    0.627
conditiontreat:educationpost_grad  0.1508896  0.1089535   1.385    0.166
conditiontreat:educationundergrad  0.0192628  0.1106549   0.174    0.862

Residual standard error: 1.002 on 1992 degrees of freedom
Multiple R-squared:  0.00212,   Adjusted R-squared:  -0.001386
F-statistic: 0.6047 on 7 and 1992 DF,  p-value: 0.7525

Here, I believe we would say that, for someone with no undergraduate degree (the reference category), being treated is associated with a decrease in dv of 0.0662, holding the other covariates constant. For someone with a postgraduate degree, as opposed to no undergraduate degree, being treated is associated with an increase in dv of 0.0847 (-0.0662 + 0.1509), holding the other covariates constant.
But what happens when we include another interaction? Let's say we think that the treatment also interacts with age:
summary(lm(dv ~ condition +
             age +
             gender +
             education +
             condition:education +
             condition:age,
           data = df))

Call:
lm(formula = dv ~ condition + age + gender + education + condition:education +
    condition:age, data = df)

Residuals:
    Min      1Q  Median      3Q     Max
-3.2345 -0.6733  0.0034  0.6782  3.2327

Coefficients:
                                   Estimate Std. Error t value Pr(>|t|)
(Intercept)                        0.096527   0.103572   0.932   0.3515
conditiontreat                    -0.232409   0.141088  -1.647   0.0997 .
age                               -0.001272   0.001625  -0.782   0.4342
gendermale                        -0.042656   0.044893  -0.950   0.3421
educationpost_grad                -0.052710   0.076950  -0.685   0.4934
educationundergrad                -0.036852   0.078601  -0.469   0.6392
conditiontreat:educationpost_grad  0.150504   0.108927   1.382   0.1672
conditiontreat:educationundergrad  0.019220   0.110627   0.174   0.8621
conditiontreat:age                 0.003212   0.002277   1.411   0.1585
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 1.001 on 1991 degrees of freedom
Multiple R-squared:  0.003117,  Adjusted R-squared:  -0.000889
F-statistic: 0.7781 on 8 and 1991 DF,  p-value: 0.6221

Here's how I think we should interpret this: For someone with no undergraduate degree, being treated is associated with a decrease of 0.2324 in dv plus an increase of 0.0032 for every year. So, for someone who is 30 years old, the effect would be -0.2324 + 0.0032 * 30 = -0.1364. Having an undergraduate degree as opposed to no undergraduate degree, by contrast, would be associated with an effect of -0.2324 + 0.0192 = -0.2132, plus 0.0032 for every year. So, for a 30-year-old, the effect would be -0.1172.
Am I interpreting that correctly?
Answer: Original Model
The linear regression model you fitted to your data looks like this:
$dv = \beta_0 + \beta_1conditiontreat +  \beta_2age + \beta_3gendermale +  \beta_4educationpostgrad +  \beta_5educationundergrad +  \beta_6conditiontreat:educationpostgrad +
 \beta_7conditiontreat:educationundergrad + \beta_8conditiontreat:age + \epsilon$.
The effect of condition in this model can be determined by re-arranging the model so that it takes the form $dv = intercept + slope * conditiontreat + \epsilon$, in which case the effect of $condition$ will be captured by the $slope$.
Re-Arranged Model
The re-arranged model is given by:
$dv = (\beta_0 +  \beta_2age +  \beta_3gendermale + \beta_4educationpostgrad +  \beta_5educationundergrad) +  (\beta_1 + \beta_6 educationpostgrad +
 \beta_7educationundergrad +  \beta_8 age)conditiontreat
  + \epsilon$.
In the re-arranged model, the $intercept$ gathers together all terms in the original model which DO NOT depend on the dummy variable $conditiontreat$, while the $slope$ gathers together all terms which DEPEND on $conditiontreat$. This dummy variable is used to capture the effect of $condition$ on the dependent variable $dv$.
Effects of condition
From the re-arranged model, it is clear that the effect of $condition$ on $dv$ depends on both education status and age.
For those with no undergraduate degree, the effect of $condition$ is given by $\beta_1 + \beta_8age$.  This effect represents the difference among the mean value of $dv$ between treated and untreated subjects in the target population having the same gender and no undergraduate degree. You can evaluate the effect of 3 different values of age, such as mean(age) - sd(age), mean(age), mean (age) + sd(age) if the distribution of age is approximately bell-shaped. Here, mean() and sd() stand for the sample mean and sample standard deviation.
For those with a post-graduate degree, the effect of $condition$ is given by $\beta_1 + \beta_6 + \beta_8age$.  This effect represents the difference among the mean value of $dv$ between treated and untreated subjects in the target population having the same gender and a post-graduate degree. This effect can be evaluated for meaningfully chosen values of age, as per above.
For those with an undergraduate degree, the effect of $condition$ is given by $\beta_1 + \beta_7 + \beta_8age$.  This effect represents the difference among the mean value of $dv$ between treated and untreated subjects in the target population having the same gender and an undergraduate degree. This effect can be evaluated for meaningfully chosen values of age, as per above.
Of course, once you fit your model to the data, you can replace the true values of the parameters with their estimated values in the above.  For example, $beta_1$ is estimated by -0.232409, etc.


SwiftUI: ObservableObject with a computed property

Question: I have a simple View with a custom month selector. Each time you click chevron left or right,
Inside DateView I had two private vars: startDateOfMonth2: Date and endDateOfMonth2: Date. But they were only available inside DateView.
QUESTION
How to make those two variables available in other views?
I have tried to add them as @Published vars, but I am getting an error:

Property wrapper cannot be applied to a computed property

I have found just a few similar questions, but I cannot manage to use answers from them with my code.
import SwiftUI

class SelectedDate: ObservableObject {
    @Published var selectedMonth: Date = Date()

    @Published var startDateOfMonth2: Date {
        let components = Calendar.current.dateComponents([.year, .month], from: selectedMonth)
        let startOfMonth = Calendar.current.date(from: components)!
        return startOfMonth
    }

    @Published var endDateOfMonth2: Date {
        var components = Calendar.current.dateComponents([.year, .month], from: selectedMonth)
        components.month = (components.month ?? 0) + 1
        let endOfMonth = Calendar.current.date(from: components)!
        return endOfMonth
    }
}

struct DateView: View {
    @EnvironmentObject var selectedDate: SelectedDate

    static let dateFormat: DateFormatter = {
        let formatter = DateFormatter()
        formatter.setLocalizedDateFormatFromTemplate("yyyy MMMM")
        return formatter
    }()

    var body: some View {

        HStack {

            Image(systemName: "chevron.left")
                .frame(width: 50, height: 50)
                .contentShape(Rectangle())
                .onTapGesture {
                    self.changeMonthBy(-1)
            }

            Spacer()

            Text("\(selectedDate.selectedMonth, formatter: Self.dateFormat)")

            Spacer()

            Image(systemName: "chevron.right")
                .frame(width: 50, height: 50)
                .contentShape(Rectangle())
                .onTapGesture {
                    self.changeMonthBy(1)
            }

        }
        .padding(EdgeInsets(top: 5, leading: 5, bottom: 5, trailing: 5))
        .background(Color.yellow)
    }

    func changeMonthBy(_ months: Int) {
        if let selectedMonth = Calendar.current.date(byAdding: .month, value: months, to: selectedDate.selectedMonth) {
            self.selectedDate.selectedMonth = selectedMonth
        }
    }
}

Answer: No need to declare your computed values as Published, as they are depending on a Published value. When the published value changed, they get recalculated.
class SelectedDate: ObservableObject {
    @Published var selectedMonth: Date = Date()

    var startDateOfMonth2: Date {
        let components = Calendar.current.dateComponents([.year, .month], from: self.selectedMonth)
        let startOfMonth = Calendar.current.date(from: components)!

        print(startOfMonth)
        return startOfMonth
    }

    var endDateOfMonth2: Date {
        var components = Calendar.current.dateComponents([.year, .month], from: self.selectedMonth)
        components.month = (components.month ?? 0) + 1
        let endOfMonth = Calendar.current.date(from: components)!

        print(endOfMonth)
        return endOfMonth
    }
}

When you print endDateOfMonth2 on click, you will see that it is changing.
Comment: Worked for me with print(selectedDate.endDateOfMonth2)
Comment: You can not change computed values itself. It is always computed. So the question is, when do you need to compute it again? It will computed if the Published value changes inside the class. As the computed value depends on that Published value, it will recalculated when the Published changes. So basically, the Published will change, the computed will recalculate and hence the Published changed, your view will reload and both values will be updated.
Comment: Cool. Thank you very much for this further explanation. In my case I only need the computed values to update based on the Published value.  So it works perfectly with your solution :)
Comment: Thank you, but I think that this way I still cannot access endDateOfMonth2 outside of class. I have just added `print("\(startDateOfMonth2)")` to .onTapGesture in my code and I am getting an error: `Use of unresolved identifier 'startDateOfMonth2'`
Comment: Oh! Great. print(selectedDate.endDateOfMonth2) works and I can access it in another view. Thank you! :) So as far as I am using vars that depend on a @Published var there is no need to declare new published vars? I guess it makes the app use less memory, right? As in my case, I just need to store 1 published var in memory, not 3. Am I correct?


Data Atual VBA com mês

Question: Bom dia,
Tenho um formulário no qual no campo textbox este recebe a data do dia e em que noutro textbox ele extrai o mês da data.

Neste caso, hoje é dia 10/02/2022 mas ele assume que é dia 02/10/2022, terá a ver com o modo em inglês? Como posso fazer para ficar com a hora em PT, neste caso 10/02/2022.
O código que estou a usar é o seguinte
 txt_datarececao = Date
Obrigado desde já pela ajuda.
Answer: Boa tarde,
Para informar que já consegui resolver o problema.
Neste caso criei uma variável e esta assume a data com o formato que desejo.
Fica abaixo caso seja útil para alguém.
Dim data As String

data = Format(Date, "dd/mm/yyyy")
txt_datarececao = data

Data Atual VBA com mês


How to set PageOptions in TuesPechkin

Question: I'm using TuesPechkin (the C# wrapper of wkhtmltopdf) and have it generating PDF files from HTML.
However, I would like to set the --disable-smart-shrinking option, which is listed in the wkhtmltopdf documentation as a PageOption
How can I do that?
public sealed class PdfConverter
{
    static readonly PdfConverter instance = new PdfConverter();
    private IConverter converter;

    static PdfConverter()
    {
    }

    PdfConverter()
    {
        // Keep the converter somewhere static, or as a singleton instance! Do NOT run this code more than once in the application lifecycle!
        this.converter = new ThreadSafeConverter( new RemotingToolset<PdfToolset>( new Win32EmbeddedDeployment( new TempFolderDeployment())));
    }

    public static PdfConverter Instance
    {
        get { return instance; }
    }

    public byte[] ConvertHtmlToPdf(string html)
    {
        var document = new HtmlToPdfDocument
        {
            Objects = { new ObjectSettings { HtmlText = html } }

            // Where are PageOptions?  Thats where --disable-smart-shrinking is
        };

        return converter.Convert(document);
    }
}

Answer: The --disable-smart-shrinking option does not exist in the API -- well, it kind of does, but in the form of it's opposite sibling: --enable-smart-shrinking.
That property is available in the TuesPechkin API as WebSettings.EnableIntelligentShrinking as seen in the TuesPechkin source code. It was named that way in TuesPechkin because that is how it is named in wkhtmltopdf's API as seen in the wkhtmltopdf source code.
You can also see there that the default value is true (from wkhtmltopdf), so if you set WebSettings.EnableIntelligentShrinking to false you should get the result you're aiming for.
Answer: It seems this functionality hasn't been implemented in Tuespechkin. I can't find it here, where most of the page options are located.
I guess he forgot to implement the option, so probably best to request the feature here. Or you can also add the feature yourself. :)

How to set PageOptions in TuesPechkin


"Adding one dimension" to an infinite dimensional topological vector space

Question: Let $V$ be an infinite-dimensional Hausdorff topological vector space over $\mathbb{R}$. Is it true that $V\oplus\mathbb{R}$ is isomorphic (as a TVS) to $V$ itself? (How about $V\oplus V$?) If yes, I also wonder whether for every $v \ne 0$ in $V$ there exists an isomorphism $f : V \cong V \oplus \mathbb{R}$ such that the projection of $f(v)$ to $\mathbb{R}$ is nonzero.
If no:

What is the simplest counterexample?

What are some minimal conditions (complete/locally convex/normed/inner product etc.) that guarantee the existence of such isomorphisms? (If $V$ is a Hilbert space, desired isomorphisms exist in all three cases above.)

I looked briefly into Schaefer and Wolff's Topological Vector Spaces but did not find any clue.
Comment: [Reposting my deleted first comment which was kind of fubar] For $V\oplus \mathbb R \cong V$, I suspect the answer is no in general, based on the wikipedia claim (https://en.wikipedia.org/wiki/Complemented_subspace#Indecomposable_Banach_spaces) that the answer is yes specifically for Banach spaces. For the general $V\oplus V\cong V$ case, the answer certainly seems to be no from same wiki article (https://en.wikipedia.org/wiki/Complemented_subspace#The_Method_of_Decomposition) as $V\oplus V\cong V$ is listed as a nontrivial requirement for a decomposition result.
Comment: I will say, though, that in any Locally convex space such that $V\cong V\oplus \mathbb R$, the proof of this result (https://math.stackexchange.com/a/1169419/1210477), along with Hahn Banach for locally convex spaces, seems to indicate that your followup question is true, since by Hahn Banach any $v\in V$ is complementary to a codimension one closed subspace (namely, kernel under Hahn banach functional).
Comment: @MW Thanks but Gowers's counterexample shows the Wikipedia claim is problematic; for details see my answer.
Answer: Since this is a question in Functional Analysis, I will assume that isomorphism means "bicontinuous bijective linear map".
The answer is no in both cases. Not sure what the "simplest example is". The category "topological vector space", without further qualifications, allows for fairly nasty things to happen.
Let $V=L^p[0,1]$, with $0<p<1$. The "$p$-norm" in this case is not a norm, but $V$ is a complete metric topological vector space with the metric
$$
d(f,g)=\int_0^1 |f-g|^p.
$$
It turns out that $V^*=\{0\}$, that is $V$ has no nonzero continuous linear functionals. But $V\oplus\mathbb R$ (you are not saying what topology you consider there, but I will assume that it is the product topology) clearly has the continuous functional $\varphi(f,t)=t$, so its dual is nontrivial. So $V$ and $V\oplus\mathbb R$ cannot be isomorphic as topological vector spaces.
As for Banach spaces $V$ such that $V\not\simeq V\oplus V$, these exist but you will not find them among the classical examples of Banach spaces. Easiest examples (bear in mind that I'm not an expert) seem to be of the form infinite $\ell^2$-sums of spaces $\ell^{n_j}_{p_j}$ (this would be $\mathbb R^{n_j}$ with the $p_j$-norm). There even exists a Banach space that is not isomorphic to any square of any Banach space. The keyword to search for all this stuff is "Banach spaces nonisomorphic to their squares" (this is almost verbatim the title of a paper that has several references).
As far as I can tell, there is no characterization of Banach spaces isomorphic to their squares.
Comment: Thanks for the answer! The trivial dual examples are pretty easy to find, but evaded me when I asked the question. You almost fully answer my questions, but did not yet eliminate the hope that $V \cong V \otimes \mathbb{R}$ might hold for all locally convex $V$, since they have enough continuous linear functionals, and the question is whether the (some?) kernels are isomorphic to $V$.
Comment: This (and the followup question) was motivated by the question whether the projectivization (the space of lines through the origin) of a TVS $V$ is a "manifold" modelled by $V$ itself, and there still seems to be hope that it's true for locally convex $V$. (We're trying to formalize the manifold structure in Lean: https://leanprover.zulipchat.com/#narrow/stream/287929-mathlib4/topic/Projective.20space/near/392194024 )
Comment: Any Banach space with a Schauder basis (which are all that you will find in "real life") have a Schauder basis, and then they trivially satisfy $V\simeq V\oplus \mathbb R$. A counterexample can only occur if $V$ does not have a Schauder basis. These spaces are rare and none of them is "natural", if I'm not wrong.
Comment: Hmm I don't see why the existence of a Schauder basis implies $V \cong V \oplus \mathbb{R}$ and apparently Gowers's counterexample admits a Schauder basis https://outofthenormmaths.files.wordpress.com/2012/04/gowers_hyperplane_counterexample.pdf You may be proposing that the map $\sum_{i=1}^\infty a_i e_i \mapsto \sum_{i=1}^\infty a_{i+1} e_i$ is continuous, but it's not even clear to me that the RHS always converges if the LHS converges.
Comment: Yes, you are right. I'm too biased by Hilbert spaces. My bad.
Answer: Sophie Morel on Zulip found this counterexample (by Gowers) to $V \cong V \oplus \mathbb{R}$ with $V$ a Banach space: A Solution to Banach's Hyperplane Problem, and there's a nice blog post about it; it turns out Banach asked both questions (about $V \oplus \mathbb{R}$ and $V \oplus V$) for Banach spaces.
The claim on Wikipedia that "a finite-codimensional subspace of a Banach space $X$ is always isomorphic to $X$" is apparently problematic, and Antoine Chambert-Loir offered an explanation how the mistake could have been made.
For the followup question, the answer should be true if $V^*$ (the continuous linear functionals) separates points in $V$ (which is true in any locally convex space by Hahn-Banach): from $V \cong V \oplus \mathbb{R}$ we know at least one closed hyperplane in $V$ is isomorphic to $V$, but all closed hyperplanes are isomorphic (I believe the proof works in any Hausdorff TVS, and so does this stronger result), so for any nonzero continuous linear functional $f \in V^*$ we get a decomposition $V \cong \text{ker }f \oplus \mathbb{R} \cong V \oplus \mathbb{R}$.


why my emails are going into spam folder

Question: I have a domain name hosted at godaddy and if I send an email from gmail to a friend with a link to my domain or a subdomain of it in the content, the email is sent to the spam folder.
I never sent batch emails. I use that domain name just for some personal tests. Why yahoo, gmail or other email services consider the emails with my personal domain as a spam email?
Comment: If you don't insert the URL with your domain, it doesn't go to the spam folder?
Comment: only if I add a link to that domain, my emails are sent to the spam folder of my friends
Comment: possible duplicate of [How to send emails and avoid them being classified as spam](http://serverfault.com/questions/48428/how-to-send-emails-and-avoid-them-being-classified-as-spam)
Answer: The most likely cause is that you're sending email through a shared ip address at GoDaddy which has a bad reputation. This is one of the risks with shared hosting, just because you're doing everything right, it doesn't mean that everyone using the same shared resource is.
You can check the IP your email is coming from against multiple black lists at sites like this. If your not sure of the ip, look at the headers in the email that blocked as spam in Google and look for the `Received: header with the connection from GoDaddy to Google.
It's very possible that the IP won't appear in any public RBL, but will be on internal RBLs used by Google and Yahoo.
Comment: You can also check the domain name you mentioned against the same lists.
Answer: First something general: You can see in the source code of the email why it was tagged as spam. Most spam filters set some information in there. it will look something like this:
<code>X-Spam-Checker-Version: SpamAssassin 3.3.1 (2010-03-16) on server.domain.com
X-Spam-Level:
X-Spam-Status: No, score=-0.8 required=5.0 tests=BAYES_00,DC_IMAGE_SPAM_HTML,
DC_IMAGE_SPAM_TEXT,DC_PNG_UNO_LARGO,RCVD_IN_DNSWL_NONE autolearn=no
version=3.3.1
</code>
With some googling you will find out what everything means.
And now regarding your question: It could be that your domain name has some string in it that is related to porn. A friend of mine had once a similar problem. The administrator within his company decided that "boys" somewhere in a domain name is not work related and potential porn. So he started to block it. The problem was now that my friend had to be in contact with "boyscouts" (in domain names often written together like this) because they were sending fund-raising requests to him.
So my recommendation is to check the email source code. Maybe your domain name is not your only problem. So if you can fix the other things then you can still send emails with your domain name in it.


open cover to approach a set

Question: Suppose $A$ is a given set in $\mathbb R^d$,  and $O_n$ is the open set
$$O_n = \left\{x\in \mathbb R^d, d(x,A)< \frac{1}{n}\right\}.$$
show that:

If $A$ is bounded, then $\lim_{n\to\infty}\lambda(O_n)=\lambda(\bar A).$ Where $\lambda$ is the Lebesgue measure and $\bar A$ is the closure of $A$.
Give an example of an unbounded and closed set $A$ such that the inequality in (1) is not true.

Here is my thinking:
For 1, since $O_i$'s are decreasing in sense of inclusion, and $O_1$ has finite measure. So I have
$\lim_{n\to\infty}\lambda(O_n)=\lambda(\lim_{n\to\infty}O_n).$ I only need to show that $\lim O_n = \bar A$ (or maybe differ from a set of measure $0$?) How can I prove this part?
For 3, I don't have any idea how to find this counterexample. Any thoughts?
Answer: For 1, your conclusion should be $\lim_{n\to\infty} \lambda(O_n) = \lambda(\bigcap_n O_n)$. What's left is to show that $\bigcap_n O_n = \overline{A}$. Notice that if $x \in \bigcap_n O_n$, then $d(x, A) = 0$.
For 2, consider a line in $\mathbb R^2$. The measure of the line is $0$, but the measure of each $O_n$ is $\infty$.
Answer: Let $C_n = \{x\in \mathbb R^d, d(x,A) \le \frac{1}{n}\}$, note $C_n$ is closed and $A \subset C_{n+1} \subset O_n \subset C_n$. Hence $C= \cap_n C_n$ is closed, and $A \subset C$.
Furthermore, $C = \{x\in \mathbb R^d, d(x,A) =0\} = \overline{A}$. Since $A$ is bounded, $\lambda O_1 < \infty$, and so $\lim_n \lambda O_n = \lim_n \lambda C_n = \lambda C = \lambda \overline{A}$.
For a counterexample, take $A= \mathbb{Z}$. Then $\lambda O_n = \infty$, but $\lambda A = 0$.
In fact, any unbounded set of measure zero will do.
Comment: Why do you construct the family $C_n$? The same argument can be done via $O_n$.
Comment: @AymanHourieh: To be sure, to be sure :-). My initial thought was that it would be easier to show the intersection of the $C_n$ was the closure, but as you have pointed out, it was entirely unnecessary.

open cover to approach a set


A ''significant variable'' that does not improve out-of-sample predictions - how to interpret?

Question: I have a question that I think will be quite basic to a lot of users.
Im using linear regression models to (i) investigate the relationship of several explanatory variables and my response variable and (ii) predict my response variable using the explanatory variables.
One particular explanatory variable X appears to signficantly impact my response variable. In order to test the added value of this explanatory variable X for the purpose of the out-of-sample predictions of my response variable I used two models: model (a) which used all explanatory variables and model (b) which used all variables except variable X. For both models I solely report the out-of-sample performance. It appears that both models perform almost identically as good. In other words, adding the explanatory variable X does not improve out-of-sample predictions. Note that I also used model (a), i.e. the model with all explanatory variables, to find that explanatory variable X does significantly impact my response variable.
My question now is: how to inpret this finding? The straightforward conclusion is that, even though the variable X appears to significantly influence my response variable using inferential models, it does not improve the out-of-sample predictions. However, I have trouble further explaining this finding. How can this be possible and what are some explanations for this finding?
Thanks in advance!
Extra information: with 'significantly influence' I mean that 0 is not included in the highest 95% posterior density interval of the parameter estimate (im using a Bayesian approach). In frequentist terms this roughly corresponds to having a p-value lower than 0.05. I am using only diffuse (uninformative) priors for all my models parameters. My data has a longitudinal structure and contains around 7000 observations in total. For the out-of-sample predictions I used 90% of the data to fit my models and 10% of the data to evaluate the models using multiple replications. That is, I performed the train-test split multiple times and eventually report the average performance metrics.
Comment: Because you are using a Bayesian approach, your results depend as much on your prior as on the data.  Because the dependence on the prior decreases with increasing amounts of data and increases to the extent the data and prior disagree, it would be useful for you to supply information both about the prior distribution, the amount of data, and how closely the *data alone* conform to the prior distribution.
Comment: @whuber I forgot to mention that I am only using diffuse (uninformative) priors. Therefore, I do not feel like my prior specification has anything to do with my findings. I'm pretty sure that fitting frequentist linear regression models will result in the exact same findings.
Comment: Are you refitting the models to the held out data or using the models you fit to your original data? In either case one possible problem is that you are making a Type II error on the held out data; perhaps the variable is relevant but you were underpowered originally (in which case you are probably overestimating the effect which could make predictions worse). Or the variable was irrelevant and you made a Type I error. There are lots of reasons this type of thing might happen.
Comment: I have used several metrics: RSME, MAE and AUC (Im also trying to predict whether my depedent variable, which is continous, is below a certain threshold).
Comment: @EdM sorry just saw your comment. I am selecting 10% of the individuals in my data to be included in the test set and 90% of the individuals to be included in the train set. For bot sets of individuals I use all observations (either for training the model or for estimating the out-of-sample error).
Comment: Thanks--that helps rule out several possible explanations.
Comment: Im not sure what you mean exactly. For inferential purposes (from which I found my variable X has significant influence on my response variable) I use all data. For the out-of-sample predictions I fit my models using 90% of the data and then evaluate the performance of the models using the 10% hold-out data (I do this multiple times and analyze average performance).
Comment: What is your performance metric for the prediction?
Comment: I don't have an answer for you but this seems quite related to a question I asked recently where I wonder whether coefficients/p-values can you be used to infer variable importance for a predictive context.  Question is here: https://stats.stackexchange.com/questions/363797/regression-as-a-way-to-determine-variable-importance
Comment: Could you say more about how you did the repeated 90/10 splits for estimating out-of-sample prediction error on these longitudinal data? I wonder if this might be facing issues similar to those of attempting to [cross-validate time series data](https://stats.stackexchange.com/q/14099/28500).
Answer: When a particular predictor is statistically significant doesn't really mean that it also considerably improves the predictive performance of a model. Predictive performance is more related to the effect size. As an example, the function below simulates data from a linear regression model with two predictors x1 and x2, and fits two models, one with both x1 and x2, and one with x1 alone. In the function you can change the effect size for x2. The function reports the confidence intervals for the coefficients of x1 and x2, and the $R^2$ values of the two models as a measure of predictive performance.
The function is:
sim_ES <- function (effect_size = 1, sd = 2, n = 200) {
    # simulate some data
    DF <- data.frame(x1 = runif(n, -3, 3), x2 = runif(n, -3, 3))
    DF$y <- 2 + 5 * DF$x1 + (effect_size * sd) * DF$x2 + rnorm(n, sd = sd)

    # fit the models with and without x2
    fm1 <- lm(y ~ x1 + x2, data = DF)
    fm2 <- lm(y ~ x1, data = DF)

    # results
    list("95% CIs" = confint(fm1),
         "R2_X1_X2" = summary(fm1)$r.squared,
         "R2_only_X1" = summary(fm2)$r.squared)
}

As an exampple, for the default values we get,
$`95% CIs`
               2.5 %   97.5 %
(Intercept) 1.769235 2.349051
x1          4.857439 5.196503
x2          1.759917 2.094877

$R2_X1_X2
[1] 0.9512757

$R2_only_X1
[1] 0.8238826

So x2 is significant, and not including it in the model has a big impact on the $R^2$.
But if we set the effect size to 0.3, we get:
> sim_ES(effect_size = 0.3)
$`95% CIs`
                2.5 %    97.5 %
(Intercept) 1.9888073 2.5563233
x1          4.9383698 5.2547929
x2          0.3512024 0.6717464

$R2_X1_X2
[1] 0.9542341

$R2_only_X1
[1] 0.9450327

The coefficient is still significant but the improvement in the $R^2$ is very small.
Comment: The vague dichotomy between *statistical significance* vs *predictive performance* is the bane of my analytics life in more ways than one. (+1 - and a general welcome to CV Prof.!)
Answer: This is a fairly normal thing to happen in multiple regression. The most common reason is that your predictors are related to one another. In other words, you can infer X from the values of the other predictors. Therefore, while it's useful for predictions if it's the only predictor you have, once you have all the other predictors it doesn't provide much extra information. You can check whether this is the case by regressing X on the other predictors. I would also refer to the chapter on linear regression in the free online textbook, Elements of Statistical Learning.
Comment: I read the question as meaning that $X$ is significant *in the context of a multiple regression.*  This seems pretty clear from the references to "several explanatory variables."  I am concerned that your answer might be confusing the OP.
Comment: You seem to be describing a non-significant explanatory variable rather than addressing the specific circumstances described in the question.
Comment: Yes whuber, you understood it correctly. This is what I mean. I hopefully clarified this well enough in my question.
Comment: I'm describing an explanatory variable which is significantly related to the response on its own (i.e. in a simple regression), which is what I presume the question means by "X appears to signficantly impact my response variable".
Comment: But in that case I would not have found that my explanatory variable X significantly impacts my response variable right? Maybe I did not make it clear in my question initially, but I used a model with all explanatory variables to find that explanatory variable X has a significant influence on my response variable.
Comment: Right, as I said I took you to be referring to a simple regression on X.


Show that the special unitary group $SU(n)$ is a compact topological group

Question: What I know:
$SU(n)=${$A \in U(n): detA=1$}
where
$U(n)=${$n \times n$   matrices $A: AA^*=I=A^*A$} with elements in $\mathbb{C}$ and $A^*$ is the complex transpose of $A$
A topological group is a Hausdorff topological space with a continuous group operation with continuous inverse
My idea is to first show that $U(n)$ is compact, which would then imply the compactness of $SU(n)$ since any closed subset of a compact space is itself compact.
Heine Borel criterion of compactness: A subset $V \subset \mathbb{R^n}$ is compact $\iff$ V is closed and bounded
So how can I show that $U(n)$ is closed and bounded?
Perhaps we can find a function whose preimage is closed and is $U(n)$
Would very much appreciate your help. Thanks
Comment: The columns of a unitary matrix are orthonormal. In particular they have norm $1$.
Comment: Does this prove it is closed? How so?
Comment: No, that proves it's bounded.
Comment: oh yes, with upper limit $1$. So if the elements in a matrix are bounded, the matrix as a whole is bounded? And then I guess I can use the fact that $U(n)$ is a closed set from the below answer
Answer: You just defined $SU(n)$ as the preimage of 1 under $\det$, so it is necessarily closed.
You also defined $U(n)$ as the preimage of $I$ under the continuous function $A \mapsto A^*A$.
Also, the operator norm of an unitary matrix is always 1, so $U(n)$ is bounded.

Additional information:
By definition of continuity, the preimage of a closed set is closed. Also, points are closed in $\mathbb{C}$ and $\mathbb{C}^{n\times n}$.
The operator norm of a matrix is defined by $\max_{x \neq 0}\frac{|Ax|}{|x|}$. It is easy to see that it is a norm and that it equals 1 for unitary operators.
In any case, whatever norm you use, it should not be hard to see that $U(n)$ is bounded: All the entries in an unitary matrix have absolute value at most one.
Comment: @QGravity Correct. Indeed, it is precisely for finite $n$ that "closed and bounded" implies "compact".
Comment: Can I just ask for some more information? Why is the pre-image of 1 necessarily closed? Also, what is the operator norm of an unitary matrix? Thanks
Comment: The inverse image of a singleton set $\{1\}$ (which is also closed) under a continuous map is closed.
Comment: By definition of operator norm, $||U|| = \text{sup}\{ ||U(x)||: ||x|| =1\}$. But $||U(x)||^2= \langle U(x), U(x)\rangle= \langle x, x\rangle = ||x||^2.$ Therefore, $||U||= 1$.
Comment: @filipos this holds for finite $n$, right? if we take $n\to\infty$ limit, then $U(n)$ becomes non compact, right?


Configure apache to listen on port other than 80

Question: I want to configure apache to listen on port 8079
I added LISTEN 8079 directive in httpd.conf
I opened 8079 port in iptables / restarted iptables etc. I even stopped iptables service.
"netstat -nal | grep 8079" shows "tcp 0 0 :::8079 :::* LISTEN"
Now, if I try to access localhost:8079 or myserver.com:8079 from that machine, I can access that page
BUT from any other machine I am not able to access the site on any port other than 80. On port 80, it works. On port 8079 it does not.
what else do I need to configure???? Please help.
If it matters, I use centOS server. You can see my httpd.conf file here  fileuploading.net/860467
I am not using any third party software - compiled apache, tomcat and jk connector from source.
Thanks
UPDATE::::::::
It was a firewall issue. There was a hardware firewall that was blocking access to almost all ports. (Turning off software firewall / SELinux bla bla had no effect)
Then I scanned the open ports and used the port that was open. (came to know about this command many days later)
If you are facing the same problem, Run the following command
sudo nmap -T Aggressive -A -v 127.0.0.1 -p 1-65000
It will scan for all the open ports on your system. Any port that is open can be accessed from outside.
Ref.: http://www.go2linux.org/which_service_or_program_is_listening_on_port
Comment: You've got firewall issues, this has nothing to do with Apache.
Comment: Can you amplify how it doesn't work? Presumably you are getting "connection refused" or similar? What do nmap or wget from other computer say?
Comment: Could not connect to server through browser
wget says connection refused.
Comment: yeah chris, it is a firewall issue and I am supposed to solve it ;)
Answer: You disabled firewall from Centos? execute setup command, then go to "Firewall configuration" and on "Security Level" mark Disabled option.. I also had problem with that.
Neto
Answer: Do you perhaps have a hardware firewall or similar device between the other machines and this webserver? If so, the firewall might be port forwarding connections incoming on port 80 on the firewall from the test machines to go to port 8079 on the webserver instead, and you will need to modify the firewall's configuration.
Comment: yeah, your aswer is almost correct. I had to get information about hardware firewall from someone else. And you proved right :-) Anyway, there's a simpler way i.e. of port scanning. Check my answer.


Three treatment groups vs one control group - only interested in comparing each treatment group separately to control - best test/follow-up test?

Question: I have an analysis in which I have three treatment groups each assigned to a (different) experimental condition, and one group assigned to a control condition. I am interested in whether any/each of the treatment groups differ on the DV from the control group. I'm not interested in whether the treatment groups differ from each other. I'm wondering what the best test is here?
My professor has suggested a one-way ANOVA, without getting into what tests (planned contrasts or post-hoc tests) I should use to follow up the omnibus test.
If I use planned contrasts, I don't think I can compare each treatment group separately to the control group? AFAIK I would have to do something like compare the three treatment groups simultaneously/as a chunk to the control, and then compare them to each other, which is not what I'm interested in. Is that right?
If I use post-hoc tests, my understanding is that all groups will be compared to all other groups (I think seven comparisons), and the necessary adjustments for multiple comparisons will weaken my power more than is necessary, given that I'm only interested in three comparisons.
Can I follow up the ANOVA with t-tests just for the comparisons I'm interested in, and apply a Bonferroni correction for the multiple comparisons? Or do I even need the ANOVA/omnibus at all if I'm doing this?
Or is there something else I should be doing?
Thanks for any help for what I realise is a very basic question.
EDIT: Thanks for the responses, Dunnett's test is exactly what I need!
Comment: Does this answer your question? [1 control group vs. 2 treatments: one ANOVA or two t-tests?](https://stats.stackexchange.com/questions/78324/1-control-group-vs-2-treatments-one-anova-or-two-t-tests) I think that covers your situation, as Dunnett's test is for handling multiple comparisons in the general case of multiple treatments against a single control. See the discussion on that page for whether prior ANOVA is necessary. It isn't technically, but reviewers might nevertheless object if you omit the preliminary ANOVA.
Answer: Dunnett's test does exactly what you want. It is usually available in stats software as a follow-up to one-way ANOVA, but the results stand alone. The results can be interpreted without reference to the overall ANOVA results.


How to configure hosts to show host name in ibnetdiscover (infiniband)?

Question: Windows machines with the OFED stack installed show the host names in ibnetdiscover.
Under Ubuntu Linux all I see is "MT25408 ConnectX Mellanox Technologies".
Is there a way of configuring the driver to show the hostname or some other text instead?

EDIT:  After haggai_e's answer below I added the following to my init scripts in ubuntu.  Now ibnetdiscover etc will show more useful information.
# Add node description to sysfs
IBSYSDIR="/sys/class/infiniband"
hca_id=1
if [ -d ${IBSYSDIR} ]; then
  for hca in ${IBSYSDIR}/*; do
    if [ -e ${hca}/node_desc ]; then
      echo -n "$(hostname -s) HCA-${hca_id}" >> ${hca}/node_desc
    fi
    hca_id=$((hca_id+1))
  done
fi

Which in ibnetdiscover shows the host names as
e.g.
node1 HCA-1
node2 HCA-2

For my nodes
Answer: ibnetdiscover prints the NodeDescription field of the InfiniBand node in quotes. You can set this by writing to /sys/class/infiniband/<device name>/node_desc. OFED contains an init script called openibd that will set this to show the host name during startup.


In Laravel 8, how do I get the url of a request when unit testing?

Question: I want to write a unit test in Laravel 8 to test a POST request that creates a new entity. In that request, a job_id is created and the url has that job_id appended. I wish to retrieve that job_id. How do I do that?
For example,
$route = route( 'job.store', $payload );
$response = $this->followingRedirects()->post( $route );

The $response should redirect to something like http://localhost:9080/sales/job/J00561. I want to get the url so I can get job_id, being J00561.
How do I do that?
Comment: I don't have `Location` in my headers. I have `content-type`, `cache-control`, `date`, and `set-cookie`.
Comment: try `$response->headers->get('Location')`
Comment: It's because you use followRedirects - and your response is NOT redirect
Comment: @Raza could you add more details as it is not clear how do you do this ? Can you add the controller method so I can create a test for you ?
Answer: For this case, because it is not an API and you cannot get a created job ID from the response, I suggest the following:
// create
$createResponse = $this->post(route('job.store', $payload))
    ->assertSuccessful();

// get created job by params
$job = Job::where($payload)->find();

// check creation
$this->assertNotNull($job);

// assert redirect
$createResponse->assertRedirect($showRoute = route('job.show', $jobId));
$this->get($showRoute)->assertSuccessful();

Here is another way: parse the header's Location for jobId, but in my opinion it's a wrong way:
$response = $this->post(route('job.store', $payload))
   ->assertSucceful();

$params = explode('/', parse_url($response->headers->get('Location'))['path']);

$jobId = array_pop($params);
$response->assertRedirect($showRoute = route('job.show', $jobId));
$this->get($showRoute)->assertSuccessful();

Comment: Please add some explanations instead of a code-only answer.
Comment: @endo64 What i can explain here? Pls suggest your edit, i really cannot imagine what i can write about this code.
Comment: I don't have the `$jobId` variable, I need the redirected url to get the jobId in the uri.


Start up values for the Kalman filter

Question: I am trying to understand how the start up values (initialisation) are calculated in the Kalman filter. As an example, I simulated the MA(2) model below.
y <- arima.sim(n = 120, model = list(order = c(0,0,2), ma = c(0.6,0.4)))
fit <- arima(y, order = c(0,0,2), include.mean = FALSE)

Extracted matrices needed for the Kalman Filter.
sigma2 <- fit$sigma2
T <- fit$model$T
R <- c(1,fit$coef)
Z <- t(fit$model$Z)
I <- diag(9)

And calculated start up values for predicted state vector a_pred1 and variance P_pred1 as below,
A <- solve(I-kronecker(T, T))
vecc <- A%*%vec(R%*%t(R))
P_pred1 <- as.matrix(cbind(vecc[1:3],vec[4:6],vec[7:9]))
a_pred1 <- c(0,0,0)

But I do not get the same start up values as produced by KalmanRun.
F <- as.numeric(Z%*%P_pred1%*%t(Z))
v <- as.numeric(y[i]-Z%*%a_pred1)
a_filt1 <- a_pred1 + P_pred1%*%t(Z)*(F^-1)*v
kfrun <- KalmanRun(y, fit$model)
cbind(kfrun$states[1,],a_filt1)
          [,1]      [,2]
[1,] 1.1964116 1.1964116
[2,] 0.7583928 0.6427514
[3,] 0.5353670 0.2493952

Can any one explain what I am doing wrong in my calculations?
Comment: What is the package of the `vec()` function and is this function really needed? Cannot we simply use `c()`? The value of `i` in the expression of `v` is not defined in the code.
Answer: The initialisation is done by makeARIMA and sets the initial state vector equal to zeros. Do not get confuse with fit$mod$a, which returns the contemporaneous state vector at the last iteration, not the first one.
It seems that you are obtaining the prediction error, v, before
running the prediction step, a_filt1.

The Kalman filter recursions that reproduce the output from KalmanRun can be implemented as follows (based on source code of KalmanRun and package KFKSDS).
set.seed(123)
y <- arima.sim(n = 120, model = list(order = c(0,0,2), ma = c(0.6,0.4)))
fit <- arima(y, order = c(0,0,2), include.mean = FALSE)
# matrices of the state space representation of the model
ss <- fit$model
# storage for the contemporaneous state estimates and residuals
a.upd <- matrix(nrow = length(y), ncol = length(ss$a))
v <- rep(NA, length(y))
# initial state vector and corresponding covariance matrix
a.upd <- rbind(rep(0, length(ss$a)), a.upd)
P.upd <- ss$P
# Kalman filter recursions
for (i in seq_along(y))
{
  # prediction
  a.pred <- ss$T %*% a.upd[i,]
  P.pred <- ss$T %*% P.upd %*% t(ss$T) + ss$V
  # prediction error
  v[i] <- y[i] - ss$Z %*% a.pred
  # variance of prediction error, 'f'
  M <- crossprod(P.pred, ss$Z)
  f <- drop(ss$Z %*% M + ss$h)
  # update of state vector and its covariance matrix
  a.upd[i+1,] <- a.pred + M * v[i] / f
  P.upd <- P.pred - tcrossprod(M) / f
}
# remove the initial state vector containing zeros
a.upd <- a.upd[-1,]

Now compare with KalmanRun (remember setting the initial state vector to zeros):
ss$a <- rep(0, length(ss$a))
kf <- KalmanRun(y, ss)
head(cbind(kf$states[1,], a.upd[1,]))
#           [,1]      [,2]
# [1,] 1.1964116 1.1964116
# [2,] 0.7150462 0.7150462
# [3,] 0.3612108 0.3612108
all.equal(kf$states, a.upd)
# [1] TRUE

The residuals also match those returned by KalmanRun:
all.equal(kf$resid, v)
# [1] TRUE

However, this does not match the residuals from the fitted model:
head(cbind(residuals(fit), v))
# [1,]      0.9941325  1.1964116
# [2,]      0.2668942  0.1986161
# [3,]      0.3804713  0.3151606
# [4,]      1.5094031  1.5725179
# [5,]      0.5247281  0.5066900
# [6,]     -1.0697975 -1.0800751

Some further details remain to be checked to fully reproduce the fitted model, but I think this will help you to reproduce KalmanRun.

For completeness I show the equations of the Kalman filter discussed above (Durbin and Koopman, 2001 Time Series Analysis by State Space Methods Section 4.2):
\begin{eqnarray}
\begin{array}{lll}
a_{t+1} = T a_{t|t} &
P_{t+1} = T P_{t|t} T^\top + V \\
v_t = y_t - Z  a_t &
M_t = P_t Z^\top &
f_t = Z M_t + H \\
a_{t|t} = a_t + M_t v_t / f_t &
P_{t|t} = P_t - M_t M_t^\top / f_t \\
t = 1,2,\dots,n.
\end{array}
\end{eqnarray}
Answer: I would have added this answer as a comment to javlacalle's excellent answer above but I do not have enough reputation.
javlacalle's answer is mostly correct, however, there are a few details that are missing.
The reason why the residuals from R's arima fit and javalacalle's fit do not match is because the residuals R uses are, from Durbin & Koopman, 2012, 2.12.1, equation 2.65, "standardised one-step ahead forecast errors"
$$e_{t} = \frac{v_{t}}{\sqrt{F_{t}}},\qquad t = 1,\dots,n$$
The unscaled first residual, $v_{1}$, is always equal to $y_{1}$ since $a_{1}$ is always set equal to a vector of zeros, $Z$ is nothing more than a selection vector containing a one in the first position and zeros everywhere else, and, as javalacalle points out, $v_{1} = y_{1} - Za_{1}$.
Further, in the R code provided lines 5 and 11 should be replaced with,
ss <- makeARIMA(phi = numeric(), theta = c(0.6, 0.4), Delta = numeric())
...
P.upd <- ss$Pn

respectively, and,
v[1] <- v[1] / sqrt(f)

should be inserted after line 22. The reason for the first change is that R uses ss\$Pn from a call to makeARIMA to calculate f while fit\$model represents the final state as opposed to the initial state of the model.
For additional information, the scaling of the residuals by $F_{t}$ can be seen on line 719 (as of July 2016) of arima.c located here, while the construction of the ARIMA state space model can be found here.

Start up values for the Kalman filter


For last 3 years, your investment returned: {+35%, +35%, -70%}. Which measure of central tendency would best describe your annual return?

Question: Arithmetic Mean, Geometric Mean, Median or Standard Variance?
Say I started with $100.
1st Year = $135
2nd Year = $182.25
3rd Year = 54.675
100-54.675 = 45.325 = loss / 3 = roughly 15 = annual loss.
Arthemtic Mean is 0 so thats no good.
Median is 35 so thats no good.
Standard Variance doesn't measure central tendency.
Geometric Mean yields 44 so where am I going wrong?
Comment: You seem to be treating a *loss* of 70% as if it were a gain of 70%!  (I wish I could do that with my investments ...)
Comment: I obtain -18% for the geometric mean return ($100(1 - (1.35\times1.35\times0.30)^{1/3})$).  How do you obtain 44?
Comment: Hey thanks for helping. Isn't the formula (35 * 35 * 70)^(1/3)? I thought I had to multiply all the numbers and n root it
Comment: Oh i c now..wow thanks for ur help.
Comment: Just to make sure, I can't measure central tendency with standard variance, correct?
Comment: Standard variance isn't a thing. Do you mean variance or standard deviation?
Comment: Sorry I meant Variance.
Comment: Variance is not a measure of central tendency.
Comment: Right ty for clarifying.
Answer: Take the geometric mean not of 35% and 35% and -70% but rather of (1+.35),(1+.35) and (1-.70) which works out to be the cube root of .54675 which is 0.8177..... This is a per annum loss of 18.23%. So, over three years, thinking that the annual loss just adds up, end up with a three-year loss of 54.69% instead of the actual loss of 45.325% (close enough to 54,69% for gummint purposes).  I remind those who are horrified by the cavalier addition of the annual losses to get the three-year loss that many newbies to the stock market (and many seasoned shills too) are quite happy to believe (or aver to the newbie) that a 50% gain one year followed by a 50% loss means that at the end of two years, the investment has not lost any value.


Proving that if $A^n = 0$, then $I - A$ is invertible and $(I - A)^{-1} = I + A + \cdots + A^{n-1}$

Question:
Let $A$ be a squared matrix, and suppose there exists an $n\in \Bbb N$ in a way that $A^n=0$. Show that $I-A$ is invertible and that $(I-A)^{-1}=I+A+\cdots+A^{n-1}$

I don't have a clue where to start from.
Comment: Of course this has nothing to do with matrices, it holds in every ring.
Comment: related question http://math.stackexchange.com/questions/336869/expanding-ia-1/
Comment: duplicate question
Comment: Why the downvote?
Comment: There are several related questions. Just google "nilpotent matrix invertible". (Note that $A^n = O$ for some $n$ is equivalent to $A$ being nilpotent.)
Comment: @MartinBrandenburg my proof doesn't use matrices at all and juliens only a bit.
Answer: Set $B:=I+A+\ldots+A^{n-1}$ and compute $(I-A)B$ by expanding the product:
$$
(I-A)B=(I-A)(I+A+\ldots+A^{n-1})=I+A+\ldots+A^{n-1}-A(I+A+\ldots+A^{n-1})
$$
$$
=I+A+\ldots+A^{n-1}-A-A^2-\ldots-A^{n-1}-A^n=\;?
$$
Observe the cancellations: you are left with $I$. This suffices to show that $I-A$ is invertible with inverse $B$. This is by the rank-nullity theorem: a square matrix is right invertible if and only if it is invertible. Or you can observe that $B$ and $I-A$ commute, so $(I-A)B=I$ yields also $B(I-A)=I$.
Comment: finally we got totally different ways :)
Comment: @DominicMichaelis I actually refrained from doing the quasinilpotent generalization in a unital Banach algebra...That would have been closer to your answer.
Answer: How do you check a matrix $B$ is the inverse of matrix $A$? You multiply them together and see if you get the identity matrix. This is just the definition of inverse matrix.
You have a matrix $I-A$ and you want to check that its inverse is $1+A+A^2+...+A^{n-1}$ given that $A^n=0$.
So multiply together and after doing lots of cancellations etc you get $I - A^n = I$, which is what we were after!
Comment: I didn't read any of the answers a priori...I just typed my own. However now I have read his answer I feel that Julian's is a bit more technically phrased (the question does not need to go into the rank-nullity theorem and the abstractness of quasinilpotents in unitary Banach algebras, I doubt the person asking the question wants this either). I decided to take a down to earth approach by first explaining what we were trying to do in a simple manner. Of course the maths is the same but on a question like this surely 99% of answers will be! I guess it is up to the person asking the question...
Comment: that totally looks like juliens answer
Comment: I think my answer is very down to earth. I mentioned the rank-nullity theorem just because it is a good opportunity to recall that left invertible is enough with square matrices. (You omitted to mention that the product had to be $I$ in both directions). Then if you read, I mention that the two matrices commute, so it is not needed. And finally, I only mentioned quasinilpotents in comments. This being said, I upvoted your answer.
Answer: Well wenn $A^n=0$ then we konw that every eigenvalue of $A$ is zero, taking jordannormalform one sees that $I-A$ is invertible cause it is similar to a triangular matrix with every value 1 on the diagonal.
Afterwards you make something like the geommetric series
$$\frac{1}{1-x}= 1+x+x^2+\dots$$
now we have matrices but it is essentially the same it give syou
$$(I-A)^{-1}=1+ A +A^2 + \dots+ A^{n-1} + \underbrace{A^n}_{=0}+\dots$$
But as every $A^k$ for $k\geq n$ is zero it is finite.
As Git mentioned it is unneccessary to go to infty
We can even take the finite geometric series which says that
$$\sum_{i=0}^{n-1} x^i = \frac{x^n -1}{x-1}=\frac{1-x^n}{1-x}$$
We have $$(I-A)^{-1}= (I-A^n) \cdot (I-A)^{-1} = \sum_{i=0}^{n-1} A^i = I + A + A^2 + \dots + A^{n-1}$$
Comment: @GitGud added the finite way thanks for pointing it out
Comment: Under which conditions for the matrix $A$ is this formula $(I-A)^{-1} = I + A + A^2 + ...$ valid ?


If statement for user input on time

Question: I am trying to create a if statement where the user must select a time between 7am and 16pm. I have searched on Stack, WESchools, MDN and written the if statement in a multiple of ways and still can not get it to work correctly.
Either the alert pops up, no matter the time inputted and the code wont run, or the code will run no matter the time put in by the user.
Here is the code:

    <button class="confirm">Confirm</button>
    <button class="reset" type="reset">Reset</button>

    Registration
    Name
    Current Miles Range
    Miles needed for next trip
    Hours to charge for next trip
    Time Leaving

    <input class="reg question" id="car-1-reg" type="text" value="" placeholder="Enter Registration"></input>

    <input id="car-1-cmr" class="cmr question" type="text" value="" placeholder="Enter Miles Left"></input>
    <input id="car-1-mtnc" class="mtnc question" type="text" value="" placeholder="Enter Miles needed"></input>

    <input class="time" type="time" min="07:00:00" max="16:00:00" required></input>

   <button id="generate-time-table" class="generate">Generate Schedule</button>

$(".confirm").click(function() {
  var _times = document.getElementsByClassName("time");
  if ((_times > 7) && (_times < 16)) {
    $("#table_id tbody tr").each(function() {
      if ($(this).find(".reg").val() == "") {
      $(this).find(".name").text("Please enter valid Registration");
  }
  var cmra = $(this).find(".cmr").val();
  var mtnc = $(this).find(".mtnc").val();
  if ((cmra != null && cmra != "") && (mtnc != null && mtnc != "")) {
    var miles = Math.ceil((parseInt(mtnc - cmra)) / 44);
    $(this).find(".charge").text(miles);
  } else if (cmra == null || cmra == "") {
    $(this).find(".charge").text("Please enter the current miles left");
  } else if (mtnc == null || mtnc == "") {
    $(this).find(".charge").text("Please enter the mtnc  left");
  }
})
} else {
  alert("Please enter a time between 7:00am and 16:00pm");
}
});

Here is the fiddle: https://jsfiddle.net/Coxy/bv5jct7n/20/
Any pointers would be really appreciated, I just can't figure out what's wrong no matter which way I write it.
Comment: Hi you need to validate that thing inside your `$("input[type='time']").change(function() {..` when user select any time validate it before putting value in `span` tag .
Comment: Please reduce the linked demo to the minimum ("*[mcve]*") code necessary to reproduce the problem you're experiencing. Unless the cars or solar chargers are relevant to your problem we don't need to see it. Reduce the cruft, expose the problem. Once that's done please include the entirety of that reduced - again: ***minimal*** *complete verifiable example* code - in your question, don't just link to it elsewhere.
Comment: Thanks for your reply David, I think I have done what you asked, if there is something still wrong with it let me know and I will try again. I out the snippet on Stack that I am having trouble with, then the full code on Fiddle in case someone wants or needs a bigger clearer picture. Thank you for correcting me on how it should be, I will take not going forward.
Comment: Thank you Swati, amazing reply! I will have  a go at that now! Thank you :D
Comment: Hi, I think the problem is that you are trying to get the values using here `var _times = document.getElementsByClassName("time");` directly, `getElementsByClassName` returns an [array](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName), and an time input, without any extra configuration, will return the time in format 'HH:MM' as you can see [here](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/time)
Comment: Thank you h3nr1ke, That helps, I have moved the code to Swati's suggestion and still not running properly, I will have a look at the links and try again thank you .
Comment: Simply use `$(this).val().split(":")[0]` to get hrs and then simply use if statement to check if the value which is entered by user is `greater than 7` and `less than 16` .Here is working [fiddle](https://jsfiddle.net/Swati911/zg5ot6n1/4/)
Comment: So this is what I was trying: // $("input[type='time']").change(function() {

//   if (($("input[type='time']")> 7) && ($("input[type='time']") < 16)) {
// $(this).closest('td').find("span").show().text($(this).val());

// $(this).hide();
//   } else {
//     alert("Please enter a time between 7:00am and 16:00pm");
//   }
// });

But I had a duplicate at the bottom of the page, making the alert pop up every time.lol I have amended my code to match thank you again Swati, I can't up vote a comment to solve the question I'm afraid but if you do post an answer i'd like to up vote it:)
Answer: You can simply get hh part from time input and then compare it with hours i.e : if the hh is >= 7 and <= 16 depending on this show error message .
Demo Code :

$("input[type='time']").change(function() {
  var time = $(this).val().split(":")[0]; //get hrs
  console.log($(this).val().split(":")[0]);
  //check hrs if grater then or lss then or not
  if ((time >= 7) && (time <= 16)) {
    //show value in span
    $(this).closest('td').find("span").show().text($(this).val());
    $(this).hide(); //hide that input

  } else {
    //show error
    $(this).closest('td').find("span").show().text("please enter time below 16:00 and greater the 07:00")

  }

});

$(".reset").click(function() {
  $(".answer").html("");
  $("input").show();
});

      <button class="confirm">Confirm</button>
      <button class="reset" type="reset">Reset</button>

            Registration
            Name
            Current Miles Range
            Miles needed for next trip
            Hours to charge for next trip
            Time Leaving

            <input class="reg question" id="car-1-reg" type="text" value="" placeholder="Enter Registration"></input>

            <input id="car-1-cmr" class="cmr question" type="text" value="" placeholder="Enter Miles Left">

            <input id="car-1-mtnc" class="mtnc question" type="text" value="" placeholder="Enter Miles needed">

            <input class="time" type="time" min="07:00:00" max="16:00:00" required>

If statement for user input on time


Sufficient condition for convergence of multivariate complex power series

Question: At a lecture a professor stated us the following

Proposition. Consider the multivariate complex power series
$$
f(z)=\sum_{\nu \in \mathbb{N}_0^n} a_\nu z^\nu
$$
(where $z^\nu:=z_1^{\nu_1}\cdots z_n^{\nu_n}$ and $\mathbb{N}_0=\{0,1,2,\dots\}$). Suppose that there exists $S\in [0,+\infty)$ and $z^0\in\mathbb{C}^n$ with $z_j^0\neq 0$ for all $j$ such that $|a_\nu(z^0)^\nu|\leq S$ for all $\nu\in\mathbb{N}^n_0$. Then the series converges uniformly on compacts inside $D_{z^0}(0):=D_{|z_1^0|}(0)\times\cdots\times D_{|z_n^0|}(0)$, the complex open $n$-polydisk of polyradius $(|z_1^0|,\dots,|z_n^0|)$, centered at the origin.

As indication of the proof he only said that "we should compare with the geometric series." I'm not an analysis guy and I'm not used to comparisons tests techniques; I don't know exactly what does he mean by this. My guess is that I should somehow use the ratio comparison test, or the limit comparison test, with the expressions $S/|(z^0)^\nu|$ (since $z^0_j\neq 0$). But I'm not sure how to apply it.
Any comments are appreciated :)
Answer: Okay, the trick I wasn't seeing is just doing
$$
|a_\nu z^\nu|=|a_\nu(z^0)^\nu|\left|\frac{z^\nu}{(z^0)^\nu}\right|
\leq S\left|\frac{z^\nu}{(z^0)^\nu}\right|.
$$


is it possible to move hard disks in raid 5 to pc without raid controller for accessing the information Temporarily?

Question: I want to rebuild my array (RAID 5) for expansion. In the current configuration, I have 3x320GB hard disks giving me about 600 GB usable. I want to replace these hard disks with 3x1TB hard disks giving me about 2TB usable.
What I want to know, is there a way to  move hard disks in the hardware RAID5 from the server to my PC without raid controller and access the information on it temporarily?
Also, I want to know if I get an image of my current system, is it possible to restore the image to the same server with the updated RAID configuration?
Please respond to my Two above questions... help me on this issue.
Answer:
Is there a way to move hard disks in hardware raid 5 from a server to my pc without raid controller for accessing the information on it, Temporarily?

No - this will not be possible.

if I get an image of my total current system with such as raid configuration and then restore on that same server with the raid configuration of 3 hard disks with the size of 1 TB of each one.is it possible?

Usually, yes.


Python - Networkx: Neighbours with certain weight

Question: This question setting is python 2.7 using the package networkx: https://networkx.github.io/documentation/stable/reference/classes/generated/networkx.Graph.neighbors.html
I'm looking for a way to use the function "networkx.Graph.neighbors" which returns me all the neighbors with a certain weight value (or higher/lower than a certain value).
Any suggestions how I could make this possible?
Thanks in advance :).
Tim
Comment: quick comment - make sure you're aware that the two answers you got make different assumptions about what weights you're after (is it the weight of the edge, or the node weight of the neighbor).
Comment: Yep I know. I was looking for edge weight. Sorry for the bad explanation. Thank you however for showing me it also works for nodes :).
Answer: Lets assume that you want to filter 'c' node neighbors according to the weight.Creating the following graph:
    G = nx.Graph()
    G.add_edge('a', 'b', weight=0.6)
    G.add_edge('a', 'c', weight=0.2)
    G.add_edge('c', 'd', weight=0.1)
    G.add_edge('c', 'e', weight=0.7)
    G.add_edge('c', 'f', weight=0.9)
    G.add_edge('a', 'd', weight=0.3)

    list_neighbors=G.neighbors('c')
    for i in list_neighbors:
        if G.edges[('c',i)]['weight']>0.5:
            print (G.edges[('c',i)])

Gives:
{'weight': 0.7}
{'weight': 0.9}
Hope this answers your question.
Refer to the link if you need more info on how to work with weights.
https://networkx.github.io/documentation/stable/auto_examples/drawing/plot_weighted_graph.html
Comment: Thank you, quick and easy! I'm quite unfamiliar with python or networkx :).
Answer: I'm going to assume that "all the neighbors with a certain weight value" refers to node weights.  I'll do the example finding neighbors of weight greater than a particular value.
import networkx as nx
import random

G = nx.Graph()

#now create nodes with random weights.  If this notation is
#unfamiliar, read up on list comprehensions.  They make life much easier.
nodes = [(node, {'weight':random.random()}) for node in range(10)]
G.add_nodes_from(nodes)

#now G has the nodes and they each have a random weight.
G.nodes(data=True)
> [(0, {'weight': 0.42719462610483916}),
 (1, {'weight': 0.13985473528922154}),
 (2, {'weight': 0.06889096983404697}),
 (3, {'weight': 0.10772762947744585}),
 (4, {'weight': 0.24497933676194383}),
 (5, {'weight': 0.18527691296273396}),
 (6, {'weight': 0.16379510964497113}),
 (7, {'weight': 0.5481883941716088}),
 (8, {'weight': 0.3782931298078134}),
 (9, {'weight': 0.5902126428368549})]

#now create edges from 0 to all other nodes
zero_edges = [(0,u) for u in range(1,10)]
G.add_edges_from(zero_edges)

#now find all neighbors of 0 with weight > 0.5
heavy_neighbors = [nbr for nbr in G.neighbors(0) if G.node[nbr]['weight']>0.5]
heavy_neighbors
>[7,9]

If you wanted to, you could also make heavy_neighbors be a generator by replacing the outer [ and ]  with ( and ).
Comment: Thank you for reponse Joel! It certainly helped me :).


Explaining a certain result with Matrix Method of Simplex Method

Question: I have been learning Linear Programming, and at the moment, the Simplex Method. I have been looking at this resource.
I understand all the steps up until the last statement (page 5), where we find the max $x_1$ and $x_2$. I understand why $Z = 90$ and $x_2 = 30$ but it bewilders me why $x_1 = 0$ instead of $20$.
Any ideas or pointers are super helpful. Thanks!!
Comment: $x_1$ is not basic
Comment: @MarcelloSammarra is that because it is not in $x_B$?
Comment: yes, the basic variables are $S_2$ and $x_2$
Answer: Disclaimer: I too am learning the Simplex algorithm.
According to Page 4, Step 4, the new basis set is $\{S_1, x_2\}$.  If you understand the derivation of ${\bf{}X}_b$ on Page 5, Step 2, you can see that $S_1 = 20$ and $x_2 = 30$.
Let's back up:  The basis set ${\bf{}X}_b$ on Page 4 began as $\{S_1, S_2\}$.  Steps 3 and 2, respectively, determined that $S_2$ would be leaving the basis set, while $x_2$ would be entering.  That brought us to ${\bf{}X}_b$ = $\{S_1, x_2\}$.
If a variable does not appear in the basis set, its value is $0$ (necessarily, I think).  Since $x_1$ is not in the basis set, its value must be $0$.
To verify that $x_1 = 0$, consider from the augmented form $x_1 + x_2 + S_1 = 50$ at the top of Page 4 that $x_1 = 50 - x_2 - S_1$, so $x_1 = 50 - 30 - 20 = 0$.


How to build the table that will be suitable for big data Query process by using Mysql

Question: I want to build the table for 30 lakhs (= 3 million) records. Currently I am working on one PHP project.
For that I need to create a table for 30 lakhs of record.
Based on my project that table will only be used for select statements. There is no insert,update and delete process.
I want to improve my project process speed, efficiency, etc.
For that, based on which criteria do I want to create table.
The table columns are, *country varchar(20),state varchar(20),city varchar(20),
           created by timestamp,updated by timestamp,zipid int(11) auto_increment.*
I am working on Mysql 5.1.
According to my Mysql Knowledge there are 3 Way's to do like,

Create the INDEX for columns.
Split the table into no of table and create the view for that.
Create the table with partitions.

Can anyone please suggest me the best solution for my problem based on the 3 points above or anything new criteria for my problem.
Answer: if tables would be partitioned, the query will first have to join them
thus it will take time
I would suggest using stored procedure, and the columns that are used most
in the query should be indexed
Comment: thank you for your suggestion sir and can u explain with small example.
Comment: Stored prcoedures make the query execution faster look here

http://dev.mysql.com/doc/refman/5.0/en/create-procedure.html
http://www.mysqltutorial.org/mysql-stored-procedure-tutorial.aspx

for indexing use PhpMyAdmin or other DB interface to set columns as indexed
Comment: i had gone through website which you have suggested me, in that i could understand stored procedure can make it and column must be indexed but i'm having one doubt in some websites giving some information about index like if you use index for large data table the index file also grows up with the data file in disk and there may be a chance to reach the OS max file size that will decrease the performance, is it correct?
Comment: Yes it is
Specially when there are more update commands (insert, delete, update)
then select commands from the applications

u are responsible to take into the account for all the trade offs
and devise a better plan, u can use only stored procedures with
no indexing, some columns indexing (that are most used in various queries) etc, or all columns indexing


Vue.js - Firebase Auth cannot check correctly error message on Reset Password

Question: I am sending a password reset email to a user; when the number of request exceed a certain level, Firebase raise an error RESET_PASSWORD_EXCEED_LIMIT
I am trying to capture this message to alert the user ( account unavailable for a period of time ... cannot find how long..) but I cannot correctly grab the message ..
auth.sendPasswordResetEmail(this.email)
  .catch((error) => {
    console.log('ERROR: ', ...

console.log('ERROR: ', error.message)
  ERROR: {"error":{"code":400,"message":"RESET_PASSWORD_EXCEED_LIMIT","errors":[{"message":"RESET_PASSWORD_EXCEED_LIMIT","domain":"global","reason":"invalid"}]}}

console.log('ERROR: ', error.message.error.message)
ERROR:  undefined
console.log('ERROR: ', error.message['"error"'])
ERROR:  undefined
console.log('ERROR: ', error.message['"error"'])
ERROR:  undefined

It is a very strange error object format
Answer: I believe the error message is stringified. You should use JSON.parse.


Solution for showing a specific start and end time of a long video file. using react js or node js?

Question: Imagine this scenario:
There is a blank page with only two input fields that users can input timestamps like this:
<code>start: 00:20:21.330
end: 00:22:31.330
</code>
There is also a start button, and when the user clicks it, a video that has now been trimmed based on the input values appears.
the original video file length is 2 hours or so, but the user just wants to see their selected time frame.
I googled and suppose the crop process should be done with node js and FFmpeg library but Is this a rational and optimal solution?? I assume it takes a very long time to shorten, store, and then play a video.
is there any better idea?
Comment: Please check this: https://video-react.js.org/components/player/
Comment: Didn't find anything useful bro
Answer: fluent-ffmpeg seems to be the way to go to accomplish this. Currently working through a very similar problem but a lot of researching the topic for doing this in React or Javascript in general seem to point to this library https://github.com/fluent-ffmpeg/node-fluent-ffmpeg


Netsuite quote form not showing all subsidiaries

Question: We recently are trying to implement Netsuite on my company, but after setting up all the Subsidiaries I encounter an issue that I'm not being able to resolve.
So here is the steps that I performed so far, I created a new Customer and on the "Subsidiaries" sub-list at the bottom of the form I added both subsidiaries to it.
After that I went to the Transaction -> Sales -> Create Prepare Quotation to start creating my quote.
First step on the quote is pick the newly created customer, right after that is choose from the "Subsidiary" drop-down list which one I want it to use, unfortunately only the main company is showing there.
Where this data for the Quote subsidiary drop-down list is coming from?
If I went to Setup -> Company -> Subsidiaries, I do have both entities showing there.
Anyway any help is appreciated, thanks.
Answer: I think the subsidiary field in the quote (estimate) record is sourcing from the subsidiary which is set on the customer record level. This is why the subsidiary field is populated only upon selecting a customer for the quote.
Answer: I found that if you've opened a transaction and discover at that point that the subsidiary needs to be added (to the sub list on the customer record), you will need to make that change on the customer record, log out, clear your browser cache, and log back in for that subsidiary selection to be available on the transaction.  You can also use a different browser or machine.
If you have the appropriate subs added on the customer record before you open a transaction, you don't have to jump through the hoops.


Views profile2 views

Question: I hope it's okay to ask a why question here. I've got a profile named Expert Information and a Skills field in that profile. I've got 9 users with the Expert role. Now my problem is: When I make a user type of view and make a relationship to profile, I get all 9 users but nothing shows under Skills; however when I make a profile type of view and make a relationship to user, I get results under Skills but this time I get 4 users. Why is that happening and what is the correct way to fulfill both?
Thanks,
K.
Comment: You are right, there is an issue. If you filter your view by profile type 'main profile', then it shows the 'expert' profile as well. In the database 'profile' table has 'type' set to main, when it must be expert. And 'profile_type' table is correct, however the sql query never joins on that table. It just filters on the join between users table and profile table on the profile.type, which as I mentioned is set to 'main' instead of 'expert. Please file a bug report about this.
Comment: Is the skills field empty for any of the users? Reason I am asking is that AFAIK the profile 2 entity is only created when you actually add content to it. It is created on demand in a lazy load manner.
Comment: No, most of them have the skills field filled.
Answer: It was my bad, the person who originally made the view did not make the relationship properly. But the weird thing is, it worked properly on a Drupal 7.30 installation and broke on 7.34.

Views profile2 views