How do I programmatically update a UUID?

Question: Reason: Receiving uid does not exist error. Upon investigating, this error appears only when we edit or save the preexisting columns paragraph. If we create new columns paragraph, the error doesn't appear as the uuid is different for the newly created columns paragraph.
This is the reason to update the uuid for a paragraph that is referenced on that page. In my custom module I have loaded all nodes using entity query below and loaded the referenced paragraph.
<code>$nids = \Drupal::entityQuery('node')
  ->condition('type', 'page')
  ->execute();
$nodes = \Drupal\node\Entity\Node::loadMultiple($nids);

  foreach ($nodes as $n) {
   //Relevant apragraph for the content type
   $para = $n->get('field_page_content')->getValue();
   $para_2 = $n->get('field_banner_image')->getValue();

   foreach($para as $e){
     $p = \Drupal\paragraphs\Entity\Paragraph::load($e['target_id']);

    if($p->bundle() == "columns"){
      kint($p,'Paragraph Entity');
      kint($p->uuid(),'Paragraph UUID');

       $uuid = 'd12da227-890b-4eb7-86b1-93937e7d6d91';

       //save paragraph
       //$p->save();

    }
  }
}
</code>
How can I get this updated without recreating the columns paragraph as there are quite a few.
Comment: The UUID of the paragraph will be the unique identifier of the paragraph, not the owner of the paragraph. The UID of the paragraph will be the User ID of the owner of the paragraph. It's not clear from your post which one you actually want.
Comment: @Jaypan updates : Updated the question, I wan to update the UUID of the paragraph. How do I do this
Comment: Sorry, I don't have the answer to that. I just wanted to help you clarify your question as it was confusing. You may also want to state your end goal, as changing the UUID may not be the best way to go about it.
Comment: @Jaypan Thanks for notifying that. will add the reason for this issue soon
Answer: This is the route to go if you must add the uuid in this manner.
<code>$uuid = 'd12da227-890b-4eb7-86b1-93937e7d6d91';
$p->set('uuid',$uuid);
$p->save();
</code>
Comment: Hi Matt thanks, great that worked. +1 for this.


Error when calling a user-defined function within a while loop, but not when called directly

Question: When I call the user defined function sRGB_to_CAM16UCS in the console, it displays the result as intended. But when I try to call it within a while loop it throws an error. Can somebody help me understand the error?
library(purrr)
library(tibble)
library(tidyr)

sRGB_to_CAM16UCS <- function(R255, G255, B255){
  # Convert sRGB to 1931 CIE XYZ [IEC 61966-2–1:2003(E)]
  ## Convert to the range of 0 to 1
  R1 <- R255 / 255
  G1 <- G255 / 255
  B1 <- B255 / 255
  ## Gamma Expansion of sRGB values
  gamma_inverse <- function(RGB1){
    if (RGB1 < -0.04045 | RGB1 > 0.04045){
      ((RGB1 + 0.055)/1.055)^2.4
    } else {
      RGB1/12.92
    }
  }
  R_li <- gamma_inverse(R1)
  G_li <- gamma_inverse(G1)
  B_li <- gamma_inverse(B1)
  # Convert linear RGB values to CIE XYZ
  X <- 41.24 * R_li + 35.76 * G_li + 18.05 * B_li
  Y <- 21.26 * R_li + 71.52 * G_li + 07.22 * B_li
  Z <- 01.93 * R_li + 11.92 * G_li + 95.05 * B_li
  # Convert XYZ to CAM16
  ## User defined Parameters
  X_w <- 96.4212
  Y_w <- 100
  Z_w <- 82.5188
  L_A <- 40
  Y_b <- 20
  surround <- 2
  discounting <- FALSE
  ## Predefined functions and constants
  ### M16
  M16 <- matrix(c(0.401288,-0.250268,-0.002079,
                  0.650173, 1.204414, 0.048952,
                 -0.051461, 0.045854, 0.953127), nrow = 3, ncol=3)
  ### lerp
  lerp <- function(a,b,c){
    (1 - c) * a + c * b
  }
  ### Crop
  crop <- function(a,b,c){
    pmin(pmax(c, a), b)
  }
  ### Define adapt
  adapt <- function(component){
    con <- (F_L * abs(component) * 0.01)^0.42
    sign(component) * 400 * con / (con + 27.13)
  }
  ### Define unadapt
  unadapt <- function(component){
    sign(component) * 100 / F_L * ((27.13* abs(component))/(400-abs(component)))^2.38095238095
  }
  # Calculations
  ## Calculate "c"
  if (surround >=1){
    c <- lerp(0.59, 0.69, surround-1)
  }else{
    c <- lerp(0.525, 0.59, surround)
  }
  ## Calculate "F" and "N_c"
  if (c >= 0.59){
    N_c <- lerp(0.9, 1.0, (c - 0.59)/.1)
  } else {
    N_c <- lerp(0.8, 0.9, (c - 0.525)/0.065)
  }
  ## Calculate "k"
  k <- 1/(5*L_A + 1)
  ## Calculate F_L
  F_L <- k^4 * L_A + 0.1 * (1-k^4)^2 * (5 * L_A)^0.33333333333
  ## Calculate n
  n <- Y_b / Y_w
  ## Calculate z
  z <- 1.48 + sqrt(n)
  ## Calculate N_bb
  N_bb <- 0.725 * n^-0.2
  ## Calculate D
  if (discounting == FALSE){
    D <- crop(0,1,N_c* (1 - 1/3.6 * exp((-L_A - 42)/92)))
  }else {
    D <- 1
  }
  ## Calculate the "RGB_w"
  RGB_w <- matrix(c(M16[1,1] * X_w + M16[1,2] * Y_w + M16[1,3] * Z_w,
                      M16[2,1] * X_w + M16[2,2] * Y_w + M16[2,3] * Z_w,
                    M16[3,1] * X_w + M16[3,2] * Y_w + M16[3,3] * Z_w), nrow = 3, ncol=1)
  # Calculate the "D_RGB"
  D_RGB <- apply(RGB_w, c(1, 2), function(x)((1 - D) * 1 + D * Y_w/x))
  # Calculate the "D_RGB_inv"
  D_RGB_inv <- apply(D_RGB,c(1, 2),function(x)1/x)
  # Calculate the "RGB_cw"
  RGB_cw <- RGB_w*D_RGB
  # Calculate RGB_aw
  RGB_aw <- apply(RGB_cw, c(1,2), adapt)
  # Calculate A_w
  A_w <- N_bb * ( 2 * RGB_aw[1,1] + RGB_aw[2,1] + 0.05 * RGB_aw[3,1])
  # Calculate RGB_a
  R_a <- adapt((M16[1,1] * X + M16[1,2] * Y + M16[1,3] * Z) * D_RGB[1,1])
  B_a <- adapt((M16[2,1] * X + M16[2,2] * Y + M16[2,3] * Z) * D_RGB[2,1])
  G_a <- adapt((M16[3,1] * X + M16[3,2] * Y + M16[3,3] * Z) * D_RGB[3,1])

  # Calculate Hue
  a <-  R_a + (-12 * G_a + B_a) / 11
  b <- (R_a + G_a - 2 * B_a) / 9
  h_rad <- atan2(b, a)
  h_ucs <- h_rad*(180.0/pi)

  # Calculate Lightness (J)
  e_t <- 0.25 * (cos(h_rad + 2) + 3.8)
  A <-  N_bb * (2*R_a + G_a + 0.05*B_a)
  J <- 100 * ((A / A_w)^(c*z))
  J_ucs <- 1.7 * J / (1 + 0.007 * J)

  # Calculate brightness (Q)
  Q <- 4/c * sqrt(J/100) * (A_w + 4) * (F_L^0.25)

  # Calculate chroma (C)
  t <- (5000 / 13 * N_c * N_bb * e_t * sqrt(a*a + b*b)) / (R_a + G_a + 1.05 * B_a + 0.305)
  alpha <- t^0.9*(1.64 - 0.29^n)^0.73
  C <- alpha * sqrt(J/100)

  # Calculate colorfulness (M)
  M <- C * F_L^0.25
  M_ucs <- log(1 + 0.0228 * M) / 0.0228

  # Calculate redness-greenness(a)
  a_ucs <- M * cos(h_rad)

  # Calculate yellowness-blueness(b)
  b_ucs <- M * sin(h_rad)

  # Calculate Saturation (s)
  s <- 50 * sqrt(alpha*c /(A_w + 4))

  return(tibble(R255, G255, B255, h_ucs, J_ucs ,M_ucs ,a_ucs, b_ucs))
}

nc <- 5
rgb_vals <- tibble(r1 = rdunif(nc, b=255, a=0), g1 = rdunif(nc, b=255, a=0), b1 = rdunif(nc, b=255, a=0))

test <- 1
test_df <- tibble(h_ucs = numeric(), J_ucs = numeric(), M_ucs = numeric(), a_ucs = numeric(), b_ucs = numeric())

while(test <= nrow(rgb_vals)){
  test_r <- sRGB_to_CAM16UCS(rgb_vals[test, 1],rgb_vals[test, 2],rgb_vals[test, 3])
  test_df <- rbind(test_df, test_r)
  test <- test + 1
}

output <- cbind(rgb_vals, test_df)
print(output)
openxlsx::write.xlsx(output, "rgb2camucs.xlsx")

threw an error as following
Error in atan2(b, a) : non-numeric argument to mathematical function
>
> output <- cbind(rgb_vals, test_df)
Error in data.frame(..., check.names = FALSE) :
  arguments imply differing number of rows: 5, 0
> print(output)
Error in print(output) : object 'output' not found

UPDATE: If I wrap the a and b with as.numeric() function, it throws the following error message:
Error:
! Column names `r1`, `r1`, `r1`, `r1`, `r1`, and 1 more must not be duplicated.
Use .name_repair to specify repair.
Caused by error in `repaired_names()`:
! Names must be unique.
x These names are duplicated:
  * "r1" at locations 1, 2, 3, 5, 6, etc.
Run `rlang::last_error()` to see where the error occurred.
>

Comment: print the `test` for every iteration. you will get the iteration at which your loop breaks. then you can look at the data to recreate the problem manually. i'm sure you will find the problem.
Comment: @D.J, I have tried, I also tried to print the class of a and b variables. The code throws an error even before running the first iteration.
Comment: what happens when you run the while loop for only 1 iteration but save `rgb_vals` and `test_df` as different list entries (without `c()`)? the loop only breaks when trying to cocatenate those two
Comment: @D.J You mean if drop `output <- cbind (rgb_vals, test_df)`? I still get the error. Since I wrapped the a and b values with `as.numeric()`, the error message is elaborate, but it still doesn't make any sense to me. You can see the new error message in the original post, as update.
Answer: This is because b and a are indeed non-numeric arguments. They are data.frames.

Replacing that line with h_rad <- atan2(b$r1, a$r1) makes it work as class(b$r1) results in numeric. Note that the last line of code where output is exported to an XLSX does not work.

You can also "unpack" your 1x1 data.frame using double brackets before calling your method, i.e., say test_r <- sRGB_to_CAM16UCS(rgb_vals[[test, 1]],rgb_vals[[test, 2]],rgb_vals[[test, 3]])   instead of test_r <- sRGB_to_CAM16UCS(rgb_vals[test, 1],rgb_vals[test, 2],rgb_vals[test, 3])  near the end of your code. This way you are passing the plain numbers to your function. This way, also the export to XLSX works.

I found this using RStudio's debugger, setting a breakpoint to that line and then entering class(b) into the console on the bottom.


Does $a_n = \sin (\tfrac{\pi}{2}n + \tfrac{\pi}{3})\sqrt{n}$ converge?

Question: The question sounds like:

Let $a_n = \sin (\frac{\pi}{2}n + \frac{\pi}{3})n^{0.5}$ for $n = 1, 2, 3,...$
Check if $\{a_n\}$ from $n = 1$ to infinity is convergent or divergent.

So far, I have the following:
$$\{a_n\} = \sin \left(n\frac{\pi}{2} + \frac{\pi}{3}\right)\sqrt{n}$$
$$= \lim\limits_{n\to \infty} \sin \left(n\frac{\pi}{2}\right)\cdot\lim\limits_ {n\to \infty} \left(\frac{\pi}{3}\right) \sqrt{n}$$
I know that the limit of $\sin$ is bounded between $-1$ and $1$. Am I on the right path?
Comment: What you've done so far does not make much sense unfortunately. $\{a_n\}$ denotes the sequence, $\sin(n\frac{\pi}{2} + \frac{\pi}{3}n^{0.5}$ is a single term of the sequence, so they can't be equal. Also, where do the $\lim$'s in the second step suddenly come from? And to do something about the sum within the $\sin$, you probably need some kind of trigonometric identity.
Comment: Hello and welcome to math.stackexchange. You should have a look at the [editing help](http://math.stackexchange.com/editing-help) to learn how to make your math look nicer. You can then edit your question, although someone will have probably done it for you by then (still: look at what they did to learn).
Answer: I assume your sequence is $\{a_n\}$ where $a_n = \sin(\frac{\pi n}{2} + \frac{\pi}{3}) \cdot \sqrt{n}$, for $n = 1, 2, 3, ...$.
Using the angle sum formula, we see that
$\sin(\frac{\pi n}{2} + \frac{\pi}{3}) = \cos(\frac{\pi n}{2}) \; \sin(\frac{\pi}{3}) + \sin(\frac{\pi n}{2})\; \cos(\frac{\pi}{3}) = $
$\frac{\sqrt{3}}{2}$ for $n = 4k$,
$ \frac{-\sqrt{3}}{2}$ for $n = 4k + 2$,
$ \frac{1}{2}$ for $n = 4k + 1$, and
$\frac{-1}{2}$ for $n = 4k + 3$.
We have
$\lim_{k\to \infty} a_{4k} = \lim_{k \to \infty} a_{4k + 1} = \frac{\sqrt{3}}{2} \cdot(\lim_{k \to \infty} \sqrt{4k}) = \frac{1}{2} \cdot(\lim_{k \to \infty} \sqrt{4k+1}) = \infty$,
and
$\lim_{k \to \infty} a_{4k+2} = \lim_{k \to \infty} a_{4k + 3} = -\frac{\sqrt{3}}{2} \cdot(\lim_{k \to \infty} \sqrt{4k+2}) = -\frac{1}{2} \cdot (\lim_{k \to \infty} \sqrt{4k + 3}) = - \infty$.
So the limits of different index sequences are different. I believe we say that the limit does not exist.


If I flip $1$ of $3$ modified coins $3$ times, what's the probability that I will get tails?

Question:
We have $3$ modified coins: $M_1$ which has tails on the both sides, $M_2$ which has heads on the both sides and $M_3$ which is a fair coin. We extract a coin from the urn and we flip it $3$ times.

What is the probability that if I flip the coin $3$ times I will get all tails?
If I got all tails at all $3$ flips what is the probability that the extracted coin is $M_3$?

My attempt:

I have tried this way: There is a $\frac{1}{3}$ chance to get $M_1$ or $M_2$ or $M_3$. If we get $M_1$ the probability to get tails is $1$, for $M_2$ is $0$ and for $M_3$ is $\frac{1}{2}$. Then the probability to get tails at one flip is $$\frac{1}{3}\cdot 1 + \frac{1}{3}\cdot 0 + \frac{1}{3}\cdot \frac{1}{2} = \frac{1}{2}$$ So the probability to get tails at all the $3$ flips is ${(\frac{1}{2})}^3$ which is $\frac{1}{8}$. Is this right?
The probability seems to be intuitively $\frac{1}{3}$, but I don't know how to formally prove it.
Answer: By Bayes' theorem \begin{align}P(M_3\mid TTT)=\frac{P(TTT\mid M_3)P(M_3)}{P(TTT)}=\frac{\left(\frac12\right)^3\cdot\frac13}{\frac38}=\frac19\end{align}

Note: The denominator was calculated using the Law of total probability as is common when applying the Bayes rule. You did this in part 1. but not correctly. To see this write \begin{align}P(TTT)&=P(TTT\mid M_1)P(M_1)+P(TTT\mid M_2)P(M_2)+P(TTT\mid M_3)P(M_3)\\[0.2cm]&=1\cdot\frac13+0\cdot\frac13+\left(\frac12\right)^3\frac13\\[0.2cm]&=\frac13\left(1+\frac18\right)=\frac38\end{align}
Comment: $P(TTT\mid M_3)=\left(\frac12\right)^3$ You roll a fair coin three times and you want three times tails, so $\frac12\cdot\frac12\cdot\frac12$.
Comment: Why $(\frac{1}{2})^3$. Where did this come frome? So for each coin you computed the probability that we will get tails and for that probability the probability to get 3 tails in a row?
Comment: Yes, exactly as you say it.
Answer: Paint the double-head coin yellow on one side and red on the other.
Paint the double-tail coin blue and green.
There are 24 possible outcomes.  One of the outcomes is:

Pick double-head, toss yellow,yellow,yellow

Run through the 24 outcomes, how many of them give you three tails?
Of those outcomes, how many were with the fair coin, how many were with the double-tail coin?
Answer: I will extend my comment: remember that $\text{probability of A}=\frac{\text{number of A cases}}{\text{all possible cases}}$.
Then, how many ways we can get (tail, tail, tail)? If we take the fair coin with this coin we only can take (tail, tail, tail) i.e. only exist one way we can take the desired result.
But if we took the double-tail coin we take (tail, tail, tail) any time i.e. the full 8 ways that a coin can show when it is tossed three times.
And when we get the double-head coin we cant take (tail, tail, tail).
Then the total amount of ways we can take (tail, tail, tail) is just $1+8$, and the cases for the fair coin is just $1$ so the probability that you want is $1/9$.
This is a visual way to see the problem but the formal way to solve it is the answer of @JimmyR i.e. using the basic definitions and theorems of probability theory.
Answer: There are some correct answers here. Many use Bayes' rule, which is correct and elegant but takes getting used to. Let me try instead to help you think through this particular example, to train your intuition.
In your answer to #1 you correctly compute that the probability of one $T$ is 1/2. But that doesn't mean the probability of $TTT$ is 1/8 unless you put the coin back and choose independently again for each of the next two tosses. The way the problem is stated, you use the same coin all three times. Then the right way to compute the weighted average is
$$
\frac{1}{3}⋅1+ \frac{1}{3}⋅0+ \frac{1}{3}⋅\frac{1}{8}= \frac{3}{8}.
$$
For the second question, you know that you don't have the middle coin, so you need the probability of the first compared to the last. If you imagine that you can tell the two sides of the two-tailed coin apart, there are 8 ways to do three flips, all of which are all tails. For the fair coin, only one triple is all tails. So when you see all tails the probability that you had the all-tail coin is 8/9.


is there a modulation in boogie-woogie?

Question: Consider the standard boogie-woogie bass such as this one. The C, F and G phrases are each in its own mixolydian. Is that a modulation from C to F and G?
If no, why?
Answer: No. The F and G are heard as the subdominant and dominant of the home key.  When listening you have the sense of being away from the C chord and wanting to return to it.  A modulation sets up a new home key.  It can be temporary (like a vacation home) or permanent (like moving to a new home, for instance the modulation just before the last chorus of "Grandma Got Run Over By A Reindeer").
Comment: You get a vote up for reminding me about them being heard as D and S. I see wikipedia article on modulation refers to [Tonicization](http://en.wikipedia.org/wiki/Tonicization) as a kind of "smaller" modulation, where the original tonic is still present. Is it a tonicization then?
Comment: I don't think so, because you don't get the sense that you want to rest on F or G. Using an arrow -> to indicate that a chord "pushes" toward another one and a comma to indicate a restful chord, the blues is heard as C, F -> C, G -> C or C, F -> C, F -> G -> C. Tonicization would be C, D7 -> G, G7 -> C. Modulation: C -> F -> G7 -> C, F -> G7 -> C, G -> A7 -> D. (That's a "truck driver's gear change"; see www.gearchange.org.)
Answer: I suppose you could consider it a modulation; but it's normally considered part of the "changes".
It's as if C-mixolydian, F-mixolydian and G-mixolydian were all superposed together to create a C-"blues" scale. C-D-Eb-E-F-G-A-Bb-B-C. The notes that belong to the "superscale" but not the "current" scale are the blue notes.
But the "full" blues scale is constructed by using the dorian scales: C-dorian, F-dorian and G-dorian, giving: C-D-Eb-E-F-F#-G-Ab-A-Bb-B-C. This gives you more blue notes against the mixolydian harmony.
Comment: You get a vote up for explaining the merge of scales. Somehow your and Mark's answers together give almost the complete picture. Except I think I need a reference to an explanation of mode progressions in the super-scales as opposed to chord progressions in the scales. Could it be explained in the books on *jazz* harmony?
Comment: It would *have to* be in a book on Jazz harmony; although I've never read one. Historically, I think, Jazz developed out of Blues; like a creole language from a pidgin language.
Comment: Now that you mention it, the dorian construction is probably a Jazz *revision*; the origin of the blues scale was probably based on minor pentatonic.
Comment: Rats! That doesn't work either! **I don't know where the F#/Gb comes from!** Ascending Melodic Minor?   it just kinda *shows up.*

is there a modulation in boogie-woogie?


A Pythonic approach to a list comparison/generation script

Question: Consider I've got a list of 2-tuples named listuple and another simple list named list0. I want to generate a list of 1s and -1s based on comparing my two given lists.
def Vectomparison (listuple, list0):
    result = []
    for EachElement in listuple:
        if EachElement [0] in list0:
            result.append (1)
        else:
            result.append (-1)
    return result

But I really think that this not a Pythonic approach. Any idea for making this Pythonically more compressed?
Answer: A direct rewrite using a list comprehesion, and ternary operator:
def Vectomparison (listuple, list0):
  return [1 if item[0] in list0 else -1 for item in listuple]

Note that item[0] in list0 uses a linear search if list0 is a list. That makes the algorithms time complexity O(N*M) where N = len(listuple), M = len(list0)
You can make it faster:
def Vectomparison (listuple, list0):
  set0 = set(list0)
  return [1 if item[0] in set0 else -1 for item in listuple]

This version has a time complexity of O(N+M)
Comment: Please, how do you estimate/formulate time complexity in such problems?
Comment: A linear search on a list takes `O(N)` steps. Doing it `M` times yields in a `O(N*M)` algorithm. In the second example building the set takes `O(M)` time (as inserting a new element is `O(1)`), and building the final list is `O(N)`, so overall `O(N+M)`
Comment: @MerlotLatterian also i suggest you to use lowercase function names


dplyr left join error when create dataframe for superheat heatmap

Question: I'm trying to prepare data for making a heatmap using the superheat package in R.
I aim to use the left_join() to join two dataframes, one containing abundance data and one containing a column with corresponding site names. The superheat function does not accept my column with site names to be a factor. I hoped left_join() would work around this problem. So far my code des not work. I would be grateful for your help!
fishdiet <- read.csv("Capis_otu_superheat3_small.csv", header=TRUE, row.names = 1)
Sites <- read.csv("Sites.csv", header=TRUE)

# choose only columns with numeric values
mynumbers <- fishdiet[,c(2:15)]

# left join the 2 data frames
joined.data <- left_join(data.frame(Sites = rownames(mynumbers)),
                           Sites,
                           by = "Site")
 # or try
joined.data <- left_join(Sites, mynumbers, by = "Site")

output: dput(head(fishdiet))
structure(list(Site = structure(c(3L, 6L, 5L, 3L, 4L, 7L), .Label = c("MLALR",
"MLCCR", "MLPBL", "MLPPR", "MLPST", "MLRNW", "MLROL", "MLSCR",
"MLSIS"), class = "factor"), A1 = c(0L, 0L, 0L, 0L, 0L, 0L),
A2 = c(0L, 0L, 0L, 0L, 0L, 0L), A3 = c(0L, 0L, 2L, 0L, 0L,
0L), A4 = c(3L, 0L, 5L, 0L, 52L, 9L), A5 = c(0L, 0L, 0L,
0L, 0L, 0L), A6 = c(0L, 0L, 0L, 0L, 0L, 0L), A7 = c(0L, 0L,
0L, 0L, 0L, 0L), A8 = c(0L, 0L, 0L, 0L, 0L, 0L), A9 = c(0L,
0L, 0L, 0L, 0L, 0L), A10 = c(0L, 0L, 0L, 0L, 0L, 0L), A11 = c(0L,
1757L, 0L, 0L, 0L, 716L), A12 = c(0L, 0L, 0L, 0L, 0L, 0L),
A13 = c(24499L, 8785L, 7267L, 19885L, 69L, 12L), A14 = c(19L,
0L, 0L, 0L, 0L, 0L)), row.names = c("BCS19-10-1_ML1926",
"BCS19-10-2_ML1950", "BCS19-10-3_ML1974", "BCS19-10-4_ML1998",
"BCS19-10-5_ML2022", "BCS19-10-6_ML2046"), class = "data.frame")

output: dput(head(Sites))
structure(list(Site = structure(c(3L, 6L, 5L, 3L, 4L, 7L), .Label = c("MLALR",
"MLCCR", "MLPBL", "MLPPR", "MLPST", "MLRNW", "MLROL", "MLSCR",
"MLSIS"), class = "factor")), row.names = c(NA, 6L), class = "data.frame")

Comment: Can you please post the output of `dput(head(fishdiet))` and `dput(head(Sites))`? This will show the first few rows of each data frame and give people an idea of what they look like, so then can then help you.
Comment: Many thanks for your quick reply! Please see the output for dput(head(fishdiet)) and dput(head(Sites)). Frederica
Comment: Hi. Please read & act on [mcve]. That includes example input & desired output & a clear specification of how desired output is a function of input. Nothing in this post explains what you want.
Answer: It's a little unclear what you are aiming to achieve. Both your attempts
left_join(data.frame(Sites = rownames(mynumbers)), Sites, by = "Site")

and
left_join(Sites, mynumbers, by = "Site")

fail because mynumbers does not contain a column "Site" (which is what you are trying to join on). If your goal is to simply get rid of the factors you can just do
fishdiet <- fishdiet %>%
    rownames_to_column() %>%  # necessary only if you want to preserve rownames
    mutate(fishdiet, Site = as.character(Site))

Then try to call your heatmap function on fishdiet. If it doesn't work, feel free to post your heatmap code and desired output, it will be easier to help you this way.


Validação para evitar registro duplicados em um formulário PHP

Question: Estou com um site aonde o usuário insere: -Código Produto codProd , Descrição Produto descProd e Unidade de Medida unidMed. Nesse caso queria colocar um tipo de mensagem printada na tela, se o usuário digitasse um Código de Produto que já estivesse cadastrado (pra ajudar coloquei codProd como chave primária no banco).
<form action="produto.php" id='cadastroRegistro' method = "POST">

Código do Produto:

              <input id='nome' data-ls-module="charCounter" maxlength="16" name = 'codProd'/>

Descrição do Produto:

              <input type='text' id='fone' data-ls-module="charCounter" maxlength="50" name = 'descProd'/>

Unidade de Medida:

            <select name="select_unidMed" required>
                    <option value="" disabled selected hidden>Selecione</option>
                    <?php
                        $select_unidMed2 = "SELECT * FROM UnidMed";
                        $select_unidMed2 = mysqli_query($conexao, $select_unidMed2);
                        while($row_unidMed = mysqli_fetch_assoc($select_unidMed2)){ ?>
                            <option value="<?php echo $row_unidMed['codUnidMed']; ?>" <?php
                     if($select_unidMed == $row_unidMed['codUnidMed']){
                         echo 'selected';
                     }
                     ?>
              >

              <?php echo $row_unidMed['codUnidMed']; ?></option> <?php
                        }
                    ?>
                </select>

Parte PHP do formulário
<?php

include_once('config.php');

if(isset($_POST['submit'])){
  $idProd = $_POST['idProd'];
  $codProd = $_POST['codProd'];
  $descProd = $_POST['descProd'];
  $select_unidMed = $_POST['select_unidMed'];

  $result = mysqli_query($conexao, "INSERT INTO Produto(idProd,codProd,descProd,codUnidMed) VALUES('$idProd', '$codProd', '$descProd', '$select_unidMed')");

}

$validacao = "SELECT codProd FROM Produto where codProd = '$codProd'";

$duperaw = mysqli_query($conexao, $validacao);

if (mysqli_num_rows($duperaw) > 0) {
  echo $validacao;

}

else {
// continui //
}

Comment: Você precisa realizar a validação antes de fazer a inserção.
Answer: Dá para você usar o $_SESSION para mostrar essa mensagem de duplicidade.
Exemplo PHP
$validacao = "SELECT codProd FROM Produto WHERE codProd = '$codProd'"
$duperaw = mysqli_query($conexao, $validacao);

if(mysqli_num_rows($duperaw) > 0){
    $_SESSION['duplicado'] = true;
    echo "";
    exit();
}

Página HTML
No lugar que você desejar mostrar a mensagem de erro você verifica a sessão.
<?php
if(isset($_SESSION['duplicado'])){
?>

   Mensagem de erro

<?php
}
unset($_SESSION['duplicado'])
?>

Não esqueça de dar um session_start(); no começo dos dois arquivos, ou irá dar erros pois nenhuma sessão foi iniciada.
Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


xlpagertabstrip some labels not fully displayed

Question: am using XLpagertabstrip in my application .. but i have a problem that the text is bigger than the width and it got cut from both sides .. like image below:

as you can see last tab which is المواجهات المباشرة is not displayed fully..
this is my code:
override func viewDidLoad() {
    super.viewDidLoad()

    containerView.isScrollEnabled = false
    containerView.delegate = self

    self.settings.style.buttonBarBackgroundColor = UIColor.clear
    self.settings.style.buttonBarItemBackgroundColor = UIColor.clear
    self.settings.style.selectedBarBackgroundColor = UIColor.clear
    self.settings.style.buttonBarItemFont = .boldSystemFont(ofSize: 7)
    self.settings.style.selectedBarHeight = 1.0
    self.settings.style.buttonBarMinimumLineSpacing = 0.1
    self.settings.style.buttonBarItemTitleColor = UIColor.white
    self.settings.style.buttonBarItemsShouldFillAvailableWidth = true
    self.settings.style.buttonBarLeftContentInset = 0
    self.settings.style.buttonBarRightContentInset = 0
    self.settings.style.selectedBarHeight = 1.0

    changeCurrentIndexProgressive = { [weak self] (oldCell: ButtonBarViewCell?, newCell: ButtonBarViewCell?, progressPercentage: CGFloat, changeCurrentIndex: Bool, animated: Bool) -> Void in
        guard changeCurrentIndex == true else { return }
        //oldCell?.label.adjustsFontSizeToFitWidth = true
        //newCell?.label.adjustsFontSizeToFitWidth = true
        oldCell?.label.textColor = UIColor.white
        newCell?.label.textColor = UIColor.white
        oldCell?.label.font = UIFont(name: "AJannatLT", size: 14)!
        newCell?.label.font = UIFont(name: "AJannatLT", size: 14)
        newCell?.label.lineBreakMode = .byCharWrapping
        oldCell?.label.lineBreakMode = .byCharWrapping
        self?.buttonBarView.selectedBar.backgroundColor = UIColor.white
    }

    getMatchInfo()

    self.navigationController?.navigationBar.topItem?.title = " "

    // Do any additional setup after loading the view.
}

but this will only change it's font size if i tabbed it ...
how to solve this? i want it from the start to be fully displayed and fit cell's width ..
Comment: how are you creating cell  ? is it custom cell with its own class ?
Comment: @Tobi its created by xlpagertabstrip.. i didn't create it or customized it .. am using the library's default
Comment: oh alright, great.
Comment: try setting the label.numberOfLines = 0
Comment: @George did not work :(
Comment: keeping the numberOfLines = 0 increase the label height. If that did not work try reducing the font size to lower values and see if the full text appears. Just to make sure that text is there.
Comment: Did it work for you?
Comment: @George it did not work with me sadly
Comment: then you need to check the library you are using I suspect that the library is overriding the numberOfLines property
Answer:
but i have a problem that the text is bigger than the width and it got cut from both side

You can try lineBreakMode
label.lineBreakMode = .ByCharWrapping

Read more about LineBreakMode.
Comment: sadly got the same result as my posted screenshot :(
Comment: try to move super.viewDidLoad to the bottom of the method, sounds weird but could work
Comment: sadly it did not :(


What type of regression analyses can I use on non-normally distributed data?

Question: I have a set of data that are non-normally distributed. I am trying to find which independent variable predicts the dependent variable. This is why I want to use regression. But since I am not familiar with statistical tests involving non-normally distributed data, I am asking for some help regarding this matter. Please tell me the name of the test that is most appropriate for use in this case.
Update: The dependent variable is always positive. It consists of scores calculated on questionnaires.
I checked the errors using the Shapiro test, and they are not normally distributed.
Update 2: Scores are summed, and they range from 0 to 100. So, technically, they have an upper bound. Same for all the independent variables. All are scores that have an upper bound and are all positive.
Comment: A normal distribution of the response variable is not a standard assumption of OLS. The common normality assumption that let's us do parameter inference is a normality distributed error term. These are very different assumptions. Run your regression and then check the residuals. If they look about normal, then you probably have an error that is about normal. (Related, you definitely don't need normal distributions for your predictor variables!)
Comment: If linear regression isn't a good idea for your data on other grounds, which is entirely possible, we can't advise on good practice, including a good model (which is the main question, not which test to use), without knowing more about the data. Perhaps you can post the dataset if it is not small or at least show us some graphs to get a better idea. For example, you don't say anything about the dependent variable. Is it counted? measured? Always positive? Ever zero? Ever negative? etc.
Comment: Scores calculated on questionnaires is helpful, but not enough to advise. Do you mean scores 1 to 5 or some sum with an upper bound?
Comment: @NickCox Can you please look at update 2 and advise me, please? Thank you!
Comment: Could be a logit on proportions, but still to advise well.
Comment: ... still hard ...
Answer: For ordinary least squares regression, distributional assumptions apply to the residuals, not to the variables themselves. The predictor variables are entirely excluded from distributional assumptions.
Comment: Distributional assumptions are weak, and do not require normality of residuals even for OLS
Comment: @Ed The usual (iid Gaussian) dIstributional assumptions apply to the errors, not the residuals, and are only really needed when using something that assumes those errors are Gaussian (such as the usual tests and intervals) -- unless you want reasonably efficient estimates of the coeffcients, in which case you do need something not too far from those assumptions (with the usual estimator)


Using Processing-3.2.2 from shell

Question: guys, I am working on audio visualization and made a successful running file in pde. The code takes an "input.mp3" then export the .mp4 file. Can it be possible that we can use it through the terminal(.sh)? I mean with writing some command it executes the program. like:
processing-3.2.2 filename.pde input.mp3

And it produces the video of that input.mp3. Here's my code:
import ddf.minim.*;
import ddf.minim.analysis.*;
import com.hamoid.*;

Minim minim;
AudioPlayer player;
AudioMetaData meta;
BeatDetect beat;
VideoExport videoExport;
int  r = 200;
float rad = 70;
void setup()
{
  size(600, 600);
  //size(600, 400);
  minim = new Minim(this);
  player = minim.loadFile("son_final.mp3");
  meta = player.getMetaData();
  beat = new BeatDetect();
  videoExport = new VideoExport(this, "basic.mp4");
  player.loop();
  //player.play();
  background(-1);
  noCursor();
}

void draw()
{
  float t = map(mouseX, 0, width, 0, 1);
  beat.detect(player.mix);
  fill(#1A1F18, 20);
  noStroke();
  rect(0, 0, width, height);
  translate(width/2, height/2);
  noFill();
  fill(-1, 10);
  if (beat.isOnset()) rad = rad*0.9;
  else rad = 70;
  ellipse(0, 0, 2*rad, 2*rad);
  stroke(-1, 50);
  int bsize = player.bufferSize();
  for (int i = 0; i < bsize - 1; i+=5)
  {
    float x = (r)*cos(i*2*PI/bsize);
    float y = (r)*sin(i*2*PI/bsize);
    float x2 = (r + player.left.get(i)*100)*cos(i*2*PI/bsize);
    float y2 = (r + player.left.get(i)*100)*sin(i*2*PI/bsize);
    line(x, y, x2, y2);
  }
  beginShape();
  noFill();
  stroke(-1, 50);
  for (int i = 0; i < bsize; i+=30)
  {
    float x2 = (r + player.left.get(i)*100)*cos(i*2*PI/bsize);
    float y2 = (r + player.left.get(i)*100)*sin(i*2*PI/bsize);
    vertex(x2, y2);
    pushStyle();
    stroke(-1);
    strokeWeight(2);
    point(x2, y2);
    popStyle();
  }
  endShape();
   if (flag) showMeta();
   videoExport.saveFrame();
 }

void showMeta() {
  int time =  meta.length();
  textSize(50);
  textAlign(CENTER);
  text( (int)(time/1000-millis()/1000)/60 + ":"+ (time/1000-millis()/1000)%60, -7, 21);
}

boolean flag =false;
void mousePressed() {
  if (dist(mouseX, mouseY, width/2, height/2)<150) flag =!flag;
}

void keyPressed() {
  if(key==' ')exit();
  if(key=='s')saveFrame("###.jpeg");
}

Answer: You can't run a .pde file from the command line or from a script.
But you can convert the .pde file into a Java application, and then run that Java application just like you'd run any other Java application.
As a first step, from your Processing editor, go to File > Export Application... which brings up the Export Options window. Set your options there (might play around a bit to see what each option does) and then click the Export button.
That will export the application to your sketch directory. That application gives you various .java and .jar files that you can use as a Java application.
From there it's just a matter of running the .jar files exactly like you'd run any other .jar file.
Comment: Hey @KevinWorkman I tried that export option and it does export the files. But I am getting too many files. How can I know which file to run in the script?
Comment: @PradhvanBisht You need all of the files. You'd run the `.jar` or `.java` file that has the name of your sketch, and you'd add the rest to your classpath. From a script that's the `-cp` option.

Using Processing-3.2.2 from shell


HttpContext.Current.User.Identity.IsAuthenticated is false in Login control LoggedIn event

Question: I am getting mad regarding why would HttpContext.Current.User.Identity.IsAuthenticated return false in LoggedIn event in Login control?
I type the correct username and password and hence I am in loggedin event but yet the IsAuthenticated is false!
Comment: How is your iis setup? How about the web.config? Are you using FormsAuthentication? How about some code?
Answer: This is because the page hasn't been posted back since the user logged in.  The entire User object is not filled out yet, this is a known behavior.
See this very informative blog post:
http://forums.asp.net/t/982749.aspx
Also credit for the above link goes to this related SO QA:
Get UserID from ASP.Net Login control LoggedIn event
Answer: Application_AuthenticateRequest happens very early staging of the page life cycle.
If you are in LoggedIn event, you can assume that the user is already authenticated.
If you want a logged-in user's username, you can get it like this -
protected void LoginUser_LoggedIn(object sender, EventArgs e)
{
    var usernameTextBox = (TextBox)LoginUser.FindControl("UserName");
    string username = usernameTextBox.Text;

    MembershipUser user = Membership.GetUser(username);
    Guid userId = (Guid)user.ProviderUserKey;
}


creating an list of occurence dataframes (two sided matrix) in R

Question: My original Dataframe looks like
A <- data.frame(Actor1 = c("A1", "B2", "C3", "D4"),
           Actor2 = c("A1", "C4", "F2", "B2"),
           Dates = as.Date(c('1999/01/01', "1999/02/05", "1999/05/06", "2000/03/06")),
           Case = c(4, 6, 8, 10))
Actor <- unique(c(A$Actor1,  A$Actor2))

I wish to transform this actor-event-based Dataframe to convert it to an occurence list of dataframes, where every dataframe representing a extra day, and the row and column names of each Dataframe are the actorsname of the original Dataframe. If they interact in one day, it should be a 1 on the dataframe of this day.
At the end it should be look like but for all days given in a certain timespan.:
Jan_01_99 <- data.frame(matrix(ncol = 6, nrow = 6))
colnames(Jan_01_99) <- Actor
rownames(Jan_01_99) <- Actor
Jan_01_99[1,1] <- 1
Jan_02_99 <- data.frame(matrix(ncol = 6, nrow = 6))
colnames(Jan_02_99) <- Actor
rownames(Jan_02_99) <- Actor

Feb_05_99 <- data.frame(matrix(ncol = 6, nrow = 6))
colnames(Feb_05_99) <- Actor
rownames(Feb_05_99) <- Actor
Feb_05_99[2,5] <- 1
complete_List <- list(Jan_01_99, Jan_02_99, Feb_05_99)

Anyone have an approach how to do this? Thanks
Comment: Your second chunk of code does not work. Actor is not defined.
Comment: I'm sorry. I skpit this coping form my Testscript, but just added it. Actor <- unique(c(A$Actor1,  A$Actor2))
Comment: The Problem on the solution down for me is, that I have sometimes several observations in one day. In the new list, they shall be stored in one Dataframe. So there is a dataframe in the list for each day.
Answer: Here's a way:
library(tidyverse)
A %>%
  mutate(across(c(Actor1, Actor2), factor, levels = Actor)) %>%
  split(seq(nrow(.))) %>%
  map(~ table(.[1:2]))

output
$`1`
      Actor2
Actor1 A1 B2 C3 D4 C4 F2
    A1  1  0  0  0  0  0
    B2  0  0  0  0  0  0
    C3  0  0  0  0  0  0
    D4  0  0  0  0  0  0
    C4  0  0  0  0  0  0
    F2  0  0  0  0  0  0

$`2`
      Actor2
Actor1 A1 B2 C3 D4 C4 F2
    A1  0  0  0  0  0  0
    B2  0  0  0  0  1  0
    C3  0  0  0  0  0  0
    D4  0  0  0  0  0  0
    C4  0  0  0  0  0  0
    F2  0  0  0  0  0  0

$`3`
      Actor2
Actor1 A1 B2 C3 D4 C4 F2
    A1  0  0  0  0  0  0
    B2  0  0  0  0  0  0
    C3  0  0  0  0  0  1
    D4  0  0  0  0  0  0
    C4  0  0  0  0  0  0
    F2  0  0  0  0  0  0

$`4`
      Actor2
Actor1 A1 B2 C3 D4 C4 F2
    A1  0  0  0  0  0  0
    B2  0  0  0  0  0  0
    C3  0  0  0  0  0  0
    D4  0  1  0  0  0  0
    C4  0  0  0  0  0  0
    F2  0  0  0  0  0  0


Understanding Intuition for ETS Damping Selection via AIC/BIC

Question: I'm trying to understand how ETS selects whether to use a damped model via information criteria (I'm not sure which of AIC, AICc or BIC are used).
I have a time series and I'm comparing two ETS models, one that sets damped = TRUE and the other that sets damped = FALSE. Visually, the model with damped = FALSE provides a better fit by capturing the trend.
Undamped:

Damped:

Yet by AIC, AICc and BIC, damped provides a much better fit. Why do these penalized likelihoods prefer the damped model instead of the undamped model?
Undamped:
ETS(M,A,N)

Call:
 ets(y = daily_max, damped = FALSE)

  Smoothing parameters:
    alpha = 0.1162
    beta  = 0.0025

  Initial states:
    l = 3.703
    b = 0.4918

  sigma:  0.2977

     AIC     AICc      BIC
7703.744 7703.829 7726.542

Damped:
ETS(M,Ad,N)

Call:
 ets(y = daily_max, damped = TRUE)

  Smoothing parameters:
    alpha = 0.088
    beta  = 1e-04
    phi   = 0.8773

  Initial states:
    l = 0.4713
    b = 2.8166

  sigma:  0.3013

     AIC     AICc      BIC
7680.163 7680.283 7707.521

Answer: The AIC and AICc are optimal for one-step forecasting. Over the course of your historical data, the damped model would do reasonably well, with the local trend sometimes heading up and sometimes heading down. If you think the trend near the end of the series will continue into the forecast period, then just set damped=FALSE.
Comment: Can you explain why "The AIC and AICc are optimal for one-step forecasting?" Does this imply that some other criterion is more appropriate for a longer horizon?
Comment: Asymptotically, minimizing the AIC is equivalent to minimizing the cross-validated one-step forecast MSE (Stone JRSSB 1977 http://www.jstor.org/stable/2984877). It is this property that makes the AIC so useful in model selection when the purpose is prediction.
Comment: It seems to me that the choice of damped TRUE/FALSE and the fitting of phi would benefit from longer-horizon test data.  Perhaps through cross validation.  There is a fundamental difference between phi and the other model parameters in this regard.  Am I going down the right path with this?
Comment: Yes, you're right. The likelihood is quite flat in the phi dimension as one-step-ahead is not really enough to see the effect of damping.


Theory of integration with respect to a function, continuous martingales

Question: I am currently doing courses in Financial Derivatives and in Continuous Martingales and Stochastic calculus, the former being not very rigorous in comparison with the latter, so this is going to be a question on how the stochastic calculus is developed.
For me it's not very clear how things work at the moment so I'm going to share with you what I know and what I'd like to understand.
We define the variation of a function $a$ over $[0,T]$ to be
$$V(a)_T=\sup_\pi \sum_{i=1}^{N(\pi)-1}|a_{t_{i+1}}-a_{t_i}|$$
where $\pi$ is a partition of $[0,T]$ consisting of the points $a_{t_i}$
Then my lecture notes say that we can define measures $\mu_+$ and $\mu_-$ such that
$$\mu_+((0,t])=\frac{V(a)_t+a(t)}{2}, \mu_-((0,t])=\frac{V(a)_t-a(t)}{2}$$
and say that
$$\int_0^tf(s)da(s)=\int_0^tf(s)\mu_+(ds)-\int_0^tf(s)\mu_-(ds)$$
provided we have
$$\int_0^t|f(s)|(\mu_+(ds)+\mu_-(ds))<\infty$$
The definition I have in the less formal course for integration against a Brownian motion $W_t$ is the following:
$$\int_0^tf(Wu,u)dW_u=\lim_{\pi \rightarrow 0}\sum f(W_k, t_k)(W_{k+1}-W_k)$$
I have the following problems:
$1:$ Shouldn't there be a limit as the mesh of the partition goes to $0$ in the definition of the variance of the function $a$?
$2:$ In the definition of the $2$ measures, we have only information about intervals of the form $(0,t]$. What happens otherwise?
$3:$ Finally, if I am supposed to calculate the Stratonovich integral for example, it involves a limit as the mesh goes to $0$ which we are not given in the rigorous definition.
Sorry if those questions are way too obvious, I just can't get the concept.
Thanks in advance!
Comment: I don't quite follow what you mean in 3. Are you trying to calculate some specific Stratonovich integral or are you confused about some aspect of the definition? (In the former case it might help if you give an example of the thing you'd like to calculate and in the latter it might help if you give the definition and clarify exactly what you are confused about)
Comment: Well, first of all I'm confused about the definition of the $2$ measures. Secondly, the difference of the definition is what I can't explain. Lastly, I've already established (in the non-rigorous course) that if we calculate the Stratonovich integral of the BM with respect to itself on $[0,t]$ we get $\frac{B_t^2}{2}$. I can't use the formal course's definitions to get the same answer though
Comment: Sorry, I only meant to ask for clarification of the 3rd point! What is the definition of the Stratonovich integral given in the Continuous Martingales course?
Comment: It's defined as $\lim_{\delta \rightarrow 0} \sum_{j=0}^{N(\pi)-1} \frac{1}{2}(B_{t_{j+1}}+B_{t_j})(B_{t_{j+1}}-B_{t_j})$
Answer: $1$: You are confusing the concepts of $p$-variation (in the case $p=1$) and total variation. The object you have defined is the latter and shouldn't include the limit as the mesh size goes to $0$.
$2$: Notice that the sets of the form $(0,t]$ are enough to define the measure since, by finite additivity, they are enough to specify what happens on sets of the form $(s,t]$ and sets of this form are a $\pi$-system generating the Borel $\sigma$-algebra.
$3$: To compute the Stratonovich integral of B.M. against itself according to your definition note that
\begin{align*}
\lim_{\delta \to 0} \sum_{j=0}^{N(\pi)-1} \frac{1}{2}(B_{t_{j+1}}+B_{t_j})(B_{t_{j+1}}-B_{t_j}) = \lim_{\delta \to 0} \bigg \{ \sum_{j=0}^{N(\pi)-1} \frac{1}{2} (B_{t_{j+1}}-B_{t_j})^2 + \sum_{j=0}^{N(\pi)-1} B_{t_j}(B_{t_{j+1}}-B_{t_j}) \bigg \}
\end{align*}
where the first sum converges to half of the quadratic variation of Brownian motion and the second to the Ito integral of B.M. against itself. To calculate the latter, you could  for example apply Ito's formula to $B_t^2$. Here both limits are in probability and follow from fairly standard results for both objects.
Comment: @asdf I think I recognise the course you're taking and you might want to try looking at theorem 6.14 and proposition 7.15 in your notes for the results I reference in the third point.


a very basic question on finding the discriminant for $x^2+2(a-3)x-3a-7=0$

Question: Sorry for asking such a basic question.
In the following quadratic equation
$$x^2+2(a-3)x-3a-7=0$$
by my calculations,
$$D=\left(\frac{b}{2}\right)^2-ac=(a-3)^2-1(-3a-7)=a^2-6a+9+3a+7=a^2-3a+16$$
But in a PDF article that describes a solution to a problem concerning this equation the discriminant is calculated as
$$a^2-3a+2$$
Is there any error in my calculation?
Comment: @CopperKettle. Your result is correct. One more typo in a book !
Comment: change $-7$ for $+7$ and see what happens...
Comment: Your calculation seems correct - must be a typo somewhere.
Comment: @DietrichBurde - thanks! Could be that. I change my books but keep finding typos. Must be a good sign. (0:
Comment: @Math-fun - indeed! Thank you. I've notified the author of the article (which is a great guide on quadratics in all respects)
Answer: Notice, compare the given equation: $x^2+2(a-3)x-3a-7=0$ with $Ax^2+Bx+C=0$, we get $$A=1, \ B=2(a-3), \ C=-3a-7$$
Hence,
discriminant is calculated as follows $$D=B^2-4AC=\left(2(a-3)\right)^2-4(1)(-(3a+7))$$ $$=4a^2-24a+36+12a+28$$ $$=4a^2-12a+64$$
Comment: Oh, yes you are right. Thanks
Comment: OK, so $D=4(a^2-3a+16)$, which is what the OP did.
Comment: Which is the OP result !


Operadores AND e OR

Question: Comecei a usar recentemente a Criteria API, pois preciso fazer consultas que seriam muito complexas com HQL.
Como eu uso os operadores AND e OR nas queries com Criteria API?
Comment: Bem vindo ao Stack Overflow, Roger! Por favor visite a [Central de ajuda](http://pt.stackoverflow.com/help) para entender melhor como o site funciona, e faça o [tour](http://pt.stackoverflow.com/tour)! (Vale uma medalha...)
Comment: O que você procura pode está aqui: http://docs.oracle.com/javaee/6/tutorial/doc/gjivm.html, na seção
Expression Methods in the CriteriaBuilder Interface
Answer: Seria esse o exemplo de sintaxe que você procura?
CriteriaQuery<Pet> cq = cb.createQuery(Pet.class);
Root<Pet> pet = cq.from(Pet.class);
cq.where(cb.equal(pet.get(Pet_.name), "Fido")
    .and(cb.equal(pet.get(Pet_.color), "brown")));

Answer: CriteriaQuery criteriaQuery = criteriaBuilder.createQuery();
Root employee = criteriaQuery.from(Employee.class);
criteriaQuery.where(criteriaBuilder.and(
                    criteriaBuilder.greaterThan(employee.get("salary"), 100000),
                    criteriaBuilder.lessThan(employee.get("salary"), 200000)));
Query query = entityManager.createQuery(criteriaQuery);
List<Employee> result = query.getResultList();

Essa query retorna empregados com salarios entre 100000 e 200000.
Basicamente os operadores AND e OR vem primeiro e dentro deles, separado por virgulas, vem as condições.
AND(condicao1,condicao2,condicao3...)
Tu também podes colocar um dentro do outro:
AND(OR(condicao1,condica2),condicao3)
Segue referencia:
https://en.wikibooks.org/wiki/Java_Persistence/Criteria#Where

Operadores AND e OR


How can I detect if backspace is pressed on the site?

Question: I am currently making a simple online text editor site. And I cannot detect backspace being pressed.
Here is the code:
HTML
<!DOCTYPE html>

    <link rel="stylesheet" href="cssfile/style.css">
    <title> Code Editor </title>

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

js:
This is my main code:
document.addEventListener("keypress", function (event) {
    console.log(event.key)
    if (event.key == "Enter") {
        document.getElementById("board").innerText += '\n'
    } else {
        document.getElementById("board").innerText += event.key
    }
});

This is my code and I tried
if(event.key == "Backspace")

But that didn't work.
Comment: when you press backspace what gets logged by your `console.log` line?
Comment: Is it useful?

https://stackoverflow.com/questions/2353550/how-to-capture-a-backspace-on-the-onkeydown-event
Comment: @Jamiec no i tried that it didnt work. That made me confused
Comment: @AntonyNg Hi i also tried those methods but none of them work.
Answer: You are close.
You are using keypress when you should be using keyup (or keydown if you want to know before the key press is complete).
KeyPress event is invoked only for character (printable) keys, KeyUp and KeyDown events is raised for all including non-printable such as Control, Shift, Alt, BackSpace, etc.
Try this:
document.addEventListener("keyup", function(event) {
  console.log(event.key);
  if (event.key === "Backspace") {
    document.getElementById("board").innerText += '\n'
  } else {
    document.getElementById("board").innerText += event.key
  }
});

Comment: Yes i figured it out now, thanks for your help
Comment: Any time! Don't forget to accept if this answer helped!
Comment: Accepted this answer
Answer: keypress event has been deprecated and there's a change your browser doesn't support it. Use keydown instead.
document.addEventListener("keydown", function (event) {
    console.log(event.key)
    if (event.key == "Backspace") {
        document.getElementById("board").innerText += '\n'
    } else {
        document.getElementById("board").innerText += event.key
    }
});

Comment: Yes i did and upvoted the answer
Answer: The keypress event is deprecated and triggers only when a key press produces a character value. Thus, it is not triggered with the backspace in your case.
You should use the keydown event.
Answer: 2021 Update: Use keyup & event.key
❌ Bad

keydown lets you know when the key is pressed down, but this fires before any action takes place.
event.keyCode is both difficult to interpret (numbers representing letters and all), and deprecated

✅ Good

keyup fires after the backspace event has happened (i.e. a character was deleted), just like keypress
event.key is both universally supported and not deprecated

<form>
  Foo:
    <input name="foobar" placeholder="ex: foobar" />

</form>

document.querySelector('input[name="foobar"]').addEventListener('keyup', function (ev) {
  console.log(ev.key);
  if ("Backspace" == ev.key) {
    console.log("It's a backspace!!");
  }
})

Answer: You can use event.keyCode == 8.

document.addEventListener("keydown", function(event) {
  console.log(event.keyCode);
  if (event.keyCode == 8) {
    document.getElementById("board").innerText += '\n'
  } else {
    document.getElementById("board").innerText += event.key
  }
});

KeyCode Docs:
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode#constants_for_keycode_value
Comment: 32 is the keyCode for Space bar. 8 is for backspace..
Comment: I figured it out i had to use keydown not keypress but still thanks for the help


Problemas com operadores de comparação

Question: Estou desenvolvendo um site, e nele possui níveis de acesso por login, sendo "1" == "Aluno", "2" == "Professor" e assim vai...
Tentei fazer um sistema para que se o usuário não estiver com email e senha logados, ele não entra na página, porém quero fazer com que ele verifique também se o tipo do usuário é compativel com a página que ele está entrando.
<?php
  session_start();
  if(!isset($_SESSION["email"]) || !isset($_SESSION["senha"])) {
    if($_SESSION["tipo"] != '1'){
      // Usuário não logado! Redireciona para a página de login
      header("Location: index.php?login");
      exit;
    }
  }
?>

Porém ele não está verificando:
if($_SESSION["tipo"] != '1'){

Como posso fazer para que o operador funcione?
OBS: Este operador tem que ser verificado na tabela do mysql.
Comment: Chegou a verificar se tipo está setada, exibir o valor dela no console, algo assim?
Comment: O console é seu melhor amigo! :D
Comment: Já tentou depurar e ver o conteúdo, utilizar um var_dump na ```$_SESSION["tipo"]```?
Comment: Ainda não tentei, como que posso fazer com var_dump?
Comment: https://www.php.net/manual/pt_BR/function.var-dump.php
Comment: Deve ter vários exemplos aqui no site, pesquisa assim: https://pt.stackoverflow.com/search?q=var_dump+%5Bphp%5D
Comment: Fiz desta forma mas deu erro:         $teste = if($_SESSION["tipo"] != '1'){
        var_dump($teste);
Comment: vai na minha dica, se não souber debugar aprenda que isso vai te poupar muitas horas de dor de cabeça, mesmo assim se não quiser aprender ou não tiver tempo, vai printando tudo no console.
Comment: é que utilizei método if, por isso não funcionou..
Comment: Um exemplo: https://repl.it/repls/WindingMediumorchidPhysics
Comment: O mais estranho é que passando para o meu aqui, não aparece nada no console, e a aplicação não funciona...
Answer: if((empty($_SESSION['email'])) || (empty($_SESSION['senha'])) || (empty($_SESSION['tipo']))){
  header("Location: index.php");
}else{
  if($_SESSION['tipo'] != "1"){
      header("Location: index.php");
  }
}

Para resolver tive que fazer da seguinte forma acima:

Problemas com operadores de comparação


Chef's knife ec2 plugin create server inside VPC with public IP

Question: So I'm using knife ec2 plugin to create a server, inside a VPC, and then provision it with chef-solo.
Here is my basic command:
    knife ec2 server create -S private-key -I ami-1234 --flavor=m1.medium --subnet xyz

The server is spun up properly, and has the proper VPC IP address. My problem is, I also need a public IP address. When I spin up an instance through the ec2 web console, it simply has an option for this Automatically assign a public IP address to your instances
I simply am unable to figure out how to do this via the knife command.
Answer: Here is one solution I have used, although note that it requires a manual step and knowledge of your free elastic IP pool:

Create one or more elastic IPs on the EC2 webconsole
On the end of your knife ec2 create server command add --associate-eip <free elastic ip address>
Comment: Thanks for this correct answer. Additionally for those that might end up on this page, if you don't want to use an 'EIP' but just an auto-generated public IP you can include "--associate-public-ip" Then if you want to connect via the private IP and not the public (usually for security related concerns) use "--server-connect-attribute private_ip_address"


How can I compare the 2 variables in JavaScript to see if the dates are the same?

Question: I have 2 variables. How can I compare the 2 variables in JavaScript to see if the dates are the same? I don't want to conevert the 2 dates with time. i just want to convert them into yyyy/dd/mm format.
var DateReported = "20/04/2011";
var StartDate = "16/04/2011";

I have to do something if StartDate < DateReported and something else if StartDate > DateReported
Thanks
Comment: Why do you need to convert them to check equality?
Answer: If you have your dates stored as strings in the same date format, there's no reason why you can't you string comparison to check if they're equal:
var DateReported = "20/04/2011";
var StartDate = "16/04/2011";

return DateReported == StartDate;  // returns false;

Update: if you actually need to compare the dates to determine which is the most recent, I'd recommend making use of a library - e.g. the jQuery UI module contains date handling code, so you can easily parse date strings:
var dReported = $.datepicker.formatDate('d/mm/yy', DateReported);
var dStarted = $.datepicker.formatDate('d/mm/yy', StartDate);

if (dReported > dStarted) { ... }

Comment: but I have to do something if StartDate < DateReported and something else if StartDate > DateReported
Comment: that's not actually what you asked!
Comment: @Asif then you should clarify your question because it asks how to find if "the dates are the same?"
Answer: by == operator
if(DateReported == StartDate)
return true;

else create the date object and convert them to millisecond and then compare for > / <
DateReported = new Date(2011,4,20);
StartDate= new Date(2011,4,16);

if (DateReported .getTime()<StartDate.getTime()) {
  alert('DateReported is less than StartDate');
}

Answer: If you don't want to use conversion to date, try this(I assume the months and days are always 0 padded):
var DateReported = "20/04/2011";
var StartDate = "16/04/2011";
var regExp = /(\d{2})\/(\d{2})\/(\d{4})/;
if
(
    StartDate.replace(regExp, "$3$2$1") < DateReported.replace(regExp, "$3$2$1")
)
{
    alert("Lesser");
}
else
{
    alert("Greater");
}

Working Example: http://jsfiddle.net/GE83j/
Answer: Try this:
var DateReported = "20/04/2011";
var StartDate = "16/04/2011";
DateReported = new Date(DateReported).format("yyyy/dd/MM");
StartDate = new Date(StartDate).format("yyyy/dd/MM");
if (DateReported > StartDate) {
     alert("Date Reported Greater");
}
else {
     alert("Start Date Greater");
}


itextsharp tutorials for vb.net express 2008?

Question: anyone know if these are available?
Comment: I've no idea, but if no one has an answer, you'll be able to find out on the iText mailing list. https://lists.sourceforge.net/lists/listinfo/itext-questions
Answer: I think that this:
iText.NET VB Examples
is the closest you're likely to find in VB.NET.
There's also this:
using iTextSharp. NET Form in PDF output
which isn't a complete tutorial, but does give an overview of using iTextSharp in VB.NET, although I'm not sure how useful that link will be to you since the site is originally in Japanese.  (The link I've provided uses Google Translate to translate most of the text to English).


como filtrar um loop ngRepeat de acordo com o valor de um dos conteudos de um array

Question: Bem, o conteúdo de uma página do meu site é gerado a partir do seguinte modelo de JSON:
[
  {
    "company":{
      "name":"Nome do Cliente",
      "url":"#"
    },
    "client":{
      "name":"Projeto",
      "url":"#"
    },
    "tags":[
      "tag1",
      "tag2",
      "tag3"
    ],
    "description":"Lorem Ipsum",
    "image":"#"
  }
]

E então é exibido da seguinte forma:

{{project.company.name}}/{{project.client.name}}

                {{tag}}

{{project.description}}

Porém, eu gostaria de poder filtrar o conteúdo exibido de acordo com a tag selecionada.
Tentei usar o atributo filter:tag, mas o angular não me retorna resultado. ('tag' foi defendia com uma variável de escopo no controller com um dos valores do array 'tags' do JSON)
Comment: cara, você provavelmente precisa fazer um **Filter** do *Angular* customizado pra filtrar esse array aí, dá uma olhada: [https://docs.angularjs.org/guide/filter](https://docs.angularjs.org/guide/filter)
Answer: Bem, com base na resposta do @Pedro Luz e nesta reposta, cheguei ao seguinte código que solucionou o meu problema:
.filter('filterBySelectedTag', function() {
    return function(projects, selectedTag){
        if(selectedTag == null){
            var filtered = projects;
        }else{
            var filtered = [];
            angular.forEach(projects, function(project) {
                angular.forEach(project.tags, function(tag){
                    if( tag == selectedTag )
                        filtered.push(project);
                });
            });
        }
        return filtered;
    }
});

Comment: Marque a sua resposta como solução. Ela vai ficar no topo independente de votação.
Comment: Só posso marcar minha resposta como solução amanhã... =/
Answer: Como o @Pedro Luz respondeu, a ideia está certa, indo no uso de filtros do Angular, mas eles são usados de outra forma.
Por exemplo, eu quero alterar o jeito que uma data é exibida?
Eu uso o seguinte binding do Angular:
{{ date | (filtro aqui) }}

Exemplificando:
{{ date | dd }}

Que retornaria o dia em formato numérico (17, como hoje é 17 de Dezembro).
Answer: Mateus, não sei se é exatamente o que você precisa... mas em um dos meus projetos eu possuo um ng-repeat num JSON e monto alguns filtros a partir de valores digitados no <input>. Exemplo abaixo:

      #

        <input type="text" ng-model="search.contactName">
        Nome do contato

        [[ $index + 1 ]]

      [[ item.contactName ]]

Answer: Cara, eu aconselharia você a não reescrever a roda, porque depois a manutenção seria horrível.
No seu caso específico, basta você fazer o seguinte

Fica muito mais limpo e organizado sem precisar declarar filtros nenhum.
Nesse caso, eu passei um objeto para o filter, e não somente um valor
Exemplo: Imagina uma div onde vc queria filtrar os itens ativos, nesse caso seria

      {{ item.qualquer_coisa }}

Comment: creio que não entendestes o que eu quero fazer. Seguindo seu código eu filtraria apenas o loop de tags, sendo que a minha necessidade era filtrar o conteúdo a partir das tags. Além do mais, fiz um teste e seu código não funcionou. Abraço


Convert Raw 14 bit Two's Complement to Signed 16 bit Integer

Question: I am doing some work in embedded C with an accelerometer that returns data as a 14 bit 2's complement number. I am storing this result directly into a uint16_t. Later in my code I am trying to convert this "raw" form of the data into a signed integer to represent / work with in the rest of my code.
I am having trouble getting the compiler to understand what I am trying to do. In the following code I'm checking if the 14th bit is set (meaning the number is negative) and then I want to invert the bits and add 1 to get the magnitude of the number.
int16_t fxls8471qr1_convert_raw_accel_to_mag(uint16_t raw, enum fxls8471qr1_fs_range range) {
  int16_t raw_signed;
  if(raw & _14BIT_SIGN_MASK) {
    // Convert 14 bit 2's complement to 16 bit 2's complement
    raw |= (1 << 15) | (1 << 14); // 2's complement extension
    raw_signed = -(~raw + 1);
  }
  else {
    raw_signed = raw;
  }
  uint16_t divisor;
  if(range == FXLS8471QR1_FS_RANGE_2G) {
    divisor = FS_DIV_2G;
  }
  else if(range == FXLS8471QR1_FS_RANGE_4G) {
    divisor = FS_DIV_4G;
  }
  else {
    divisor = FS_DIV_8G;
  }

  return ((int32_t)raw_signed * RAW_SCALE_FACTOR) / divisor;
}

This code unfortunately doesn't work. The disassembly shows me that for some reason the compiler is optimizing out my statement raw_signed = -(~raw + 1); How do I acheive the result I desire?
The math works out on paper, but I feel like for some reason the compiler is fighting with me :(.
Comment: If you turn up all the compiler warnings, do you get any relevant diagnostics?  If you compile with optimization turned off does the program work as intended?
Comment: And "my code doesn't work is not a **specific** problem statement. Unless you provide proof, the compiler is likely right optimising your code as it does. Use a debugger and debugging-friendly optimisations, e.g. gcc `-Og`.
Comment: @WeatherVane Yes, but the current C standard declares that any operation that directly manipulates the sign bit is undefined behavior, since it won't work on a one's complement machine, or a sign-magnitude machine.
Comment: @JohnBollinger Yes, but the other branch of the `if` also does the same assignment, and the rest of the code only uses `raw_signed`, so the optimized assembly will not contain an explicit assignment.
Comment: @JohnBollinger: It will likely use the same register for both, not needing a move. Anyway, `1<<15` is already UB for 16 bit `int` (note the tags). No need to do further research what else could have gone wrong.
Comment: You could try `if(raw & _14BIT_SIGN_MASK) raw_signed = (int16_t)(raw | 0xC000);`
Comment: There is no language "embedded C". And left shifting a signed value that cannot be represented in the variable is undefined behaviour.
Comment: @Olaf I was trying to make it clear that I was working with an embedded system so I have certain constraints / limitations John and Weather; ill give it a try
Comment: The "embedded" tag makes that clear already. Yet that does not imply any specific restrictions per se. And for the question as given, it does not matter anyway. Note that it is not the compiler fighting, but you likely have a problem with integer promotion and/or implementation defined and undefined behaviour.
Comment: The statement `raw_signed = -(~raw + 1)` is equivalent to `raw_signed = raw`. That's why the compiler optimizes it out.
Comment: You could try `-(int16_t)((~raw + 1) & 0x3fff)`.  That is, perform a *14-bit* sign inversion, convert the (positive) result to `int16_t`, and negate it.  Alternatively, casting your existing expression to `int16_t` before negating might also help.
Comment: Doesn't any 2's complement number only need a sign bit extension?
Comment: @user3386109, the compiler is can perhaps perform `raw_signed = raw` instead of `raw_signed = -(~raw + 1)`, but that doesn't mean it can omit the assignment altogether.
Comment: @user3386109 my example was not manipulating the sign bit, it was unsigned and manipulated before casting to signed.
Comment: Why so complicated and not just `raw_signed = raw; if ( raw & (1U << 13)) raw_signed |= 0xC000;`?
Comment: @Olaf, because that produces undefined behavior, as it boils down to assigning an out-of-range value to a signed integer.
Comment: @JohnBollinger that code worked! Thanks alot, do you want to put that into an answer I can accept? I'm trying to understand exactly why my code didnt work. If I wanted to do in the exact form that I had originally I would have needed to cast to a `int32_t` prior to performing the negation?
Comment: @JohnBollinger how can any 14-bit signed or unsigned value be out of range of a 16-bit value?
Comment: @JohnBollinger: Please elaborate. IIRC, it is implementation defined, but will work on AVR.
Comment: @WeatherVane && Olaf, I find I must amend and qualify my remark.  `raw_signed |= 0xC000`, produces *implementation-defined* behavior when `int` is 16 bits wide, because then `raw_unsigned | 0xc000` has type `unsigned int` and value outside the range of `int`.  I acknowledge that I am making a logical leap by assuming 16-bit `int` in the target environment, but that seems a clean way to explain the observed compiler behavior.
Comment: @WeatherVane  I was wrong, it's **implementation defined behavior**, not **undefined behavior**. The relevant section is 22.214.171.124 which says: *"When a value with integer type is converted to another integer type [...], if the value can be represented by the new type, it is unchanged. [...] Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised."* The unsigned value `raw | 0xC000` is too big for a 16-bit signed int, so the cast to `int16_t` is implementation defined.
Comment: To be clear: When code reaches `return ((int32_t)raw_signed`, do you expect `raw_signed` to have a value in the range `[-8192 ... +8191]`?
Answer: Converting the 14 bit 2's complement value to 16 bit signed, while maintaining the value is simply a metter of:
int16_t accel = (int16_t)(raw << 2) / 4 ;

The left-shift pushes the sign bit into the 16 bit sign bit position, the divide by four restores the magnitude but maintains its sign.  The divide avoids the implementation defined behaviour of an right-shift, but will normally result in a single arithmetic-shift-right on instruction sets that allow.  The cast is necessary because raw << 2 is an int expression, and unless int is 16 bit, the divide will simply restore the original value.
It would be simpler however to just shift the accelerometer data left by two bits and treat it as if the sensor was 16 bit in the first place. Normalising everything to 16 bit has the benefit that the code needs no change if you use a sensor with any number of bits up-to 16.  The magnitude will simply be four times greater, and the least significant two bits will be zero - no information is gained or lost, and the scaling is arbitrary in any case.
int16_t accel = raw << 2 ;

In both cases, if you want the unsigned magnitude then that is simply:
int32_t mag = (int32_t)labs( (int)accel ) ;

Comment: @chux : Thanks - fixed.  Your two-step solution may be better for clarity.  Personally I really wouldn't bother restoring to 14-bit magnitude scaling; it is an unnecessary step.
Comment: Before the UB police pipe up, I realise that strictly this is not guaranteed to work where 2's complement is not the signed encoding, but in the real world it works.  In embedded systems you would expect to know how your hardware behaves and performance is often more critical than portability to some hypothetical machine.
Comment: @Lundin : To ensure it is arithmetic, simply divide by 4.  The compiler will almost certainly generate an arithmetic-shift operation if the instruction set allows.  Edited accordingly.
Comment: @Lundin: `intX_t` are **guaranteed** to be 2s complement by the standard.
Comment: A disadvantage of "... shift the accelerometer data left by two bits and treat it as if the sensor was 16 bit in the first place. "  is with `int16_t mag = abs( accel ) ;` that may try to do `abs(0x8000)`
Comment: @chux : Thanks for the spot, changed to use `labs()` and `int32_t`, though `abs()` would still work on a 32 bit target.
Comment: There's no need to call the UB police. However, here comes the implementation-defined behavior police (IDBP). Since `raw` is unsigned, the left shift is well-defined, no UB. And the conversion to `int16_t` is well-defined, given that both systems use two's complement with same endianess. The right shift of a negative number after that is not UB but implementation-defined: it could translate either to logical shift or arithmetic shift. This will cause problems in case of arithmetic shift! You'll have to dodge this somehow, like for example masking the final result with `& 0xBFFF`.
Comment: @Lundin : An *arithmetc shift* is precisely what is required here; it is a logical shift that would cause a problem.  Good point though, and strengthens the argument to left align the data to 16 bit in any case.  Many hardware devices and ADC peripherals do this an an option in hardware in any case.  If you have a high sample rate and real-time deadlines, the less unnecessary manipulation of the the data the better.
Comment: @Clifford Ah yeah, the other way around :) Anyway, it shows that the shifts are problematic. One solution could be to do something semi-obscure like this: `int16_t left = (int16_t)(raw << 2);
if(left < 0)
{
  result = -(int16_t) ((uint16_t)-left >> 2)
}
else
{
  result = left >> 2;
}`
Answer: I would do simple arithmetic instead. The result is 14-bit signed, which is represented as a number from 0 to 2^14 - 1. Test if the number is 2^13 or above (signifying a negative) and then subtract 2^14.
int16_t fxls8471qr1_convert_raw_accel_to_mag(uint16_t raw, enum fxls8471qr1_fs_range range)
{
  int16_t raw_signed = raw;
  if(raw_signed >= 1 << 13) {
    raw_signed -= 1 << 14;
  }

  uint16_t divisor;
  if(range == FXLS8471QR1_FS_RANGE_2G) {
    divisor = FS_DIV_2G;
  }
  else if(range == FXLS8471QR1_FS_RANGE_4G) {
    divisor = FS_DIV_4G;
  }
  else {
    divisor = FS_DIV_8G;
  }

  return ((int32_t)raw_signed * RAW_SCALE_FACTOR) / divisor;
}

Please check my arithmetic. (Do I have 13 and 14 correct?)
Comment: Well, `politically optimal`.
Comment: This answer is optimal, as it does not depend on the native signed type being 2's compliment, nor does it depend on `raw_signed` being exactly 16 bit.
Comment: Thanks for this code, your arithmetic was correct. Just for the exercise I ended up using the code John provided above to understand the necessary manipulations / casts but this code was valid too (and produced much less head scratching)!
Comment: @secretformula Most programming time is spent maintaining and debugging code. Over the long run, it always pays off to avoid "head-scratching" type code!
Comment: @dbush : It is "portable" not "optimal".  *Optimal* usually implies highest possible performance, and code that accommodates hypothetical hardware  rather then being tailored to the actual hardware is sub-optimal.  This question is tagged *embedded*, so will be full of code specific to the target, so optimising this to the target would make sense.  Moreover, where are these one's complement or sign+magnitude machines?  For an optimal *and* portable solution, conditional compilation would be a better approach.
Answer: Supposing that int in your particular C implementation is 16 bits wide, the expression (1 << 15), which you use in mangling raw, produces undefined behavior.  In that case, the compiler is free to generate code to do pretty much anything -- or nothing -- if the branch of the conditional is taken wherein that expression is evaluated.
Also if int is 16 bits wide, then the expression -(~raw + 1) and all intermediate values will have type unsigned int == uint16_t.  This is a result of "the usual arithmetic conversions", given that (16-bit) int cannot represent all values of type uint16_t.  The result will have the high bit set and therefore be outside the range representable by type int, so assigning it to an lvalue of type int produces implementation-defined behavior.  You'd have to consult your documentation to determine whether the behavior it defines is what you expected and wanted.
If you instead perform a 14-bit sign conversion, forcing the higher-order bits off ((~raw + 1) & 0x3fff) then the result -- the inverse of the desired negative value -- is representable by a 16-bit signed int, so an explicit conversion to int16_t is well-defined and preserves the (positive) value.  The result you want is the inverse of that, which you can obtain simply by negating it.  Overall:
raw_signed = -(int16_t)((~raw + 1) & 0x3fff);

Of course, if int were wider than 16 bits in your environment then I see no reason why your original code would not work as expected.  That would not invalidate the expression above, however, which produces consistently-defined behavior regardless of the size of default int.
Comment: Thanks for helping me understand my error. I ended up going with Cliffords answer because it was more concise. Thank you again!
Comment: Disagree with "Also if int is 16 bits wide...." paragraph.  The `-(~raw + 1)` will all be done with 16-bit unsigned math.  The result will be in the range of `int`, so no problem for not all 16-bit combinations are present in `raw`, just 2^14 of them.
Answer: Assuming when code reaches return ((int32_t)raw_signed ..., it has a value in the [-8192 ... +8191] range:
If RAW_SCALE_FACTOR is a multiple of 4 then a little savings can be had.
So rather than
int16_t raw_signed = raw << 2;
raw_signed >>= 2;

instead
int16_t fxls8471qr1_convert_raw_accel_to_mag(uint16_t raw,enum fxls8471qr1_fs_range range){
  int16_t raw_signed = raw << 2;
  uint16_t divisor;
  ...
  // return ((int32_t)raw_signed * RAW_SCALE_FACTOR) / divisor;
  return ((int32_t)raw_signed * (RAW_SCALE_FACTOR/4)) / divisor;
}

Answer: To convert the 14-bit two's-complement into a signed value, you can flip the sign bit and subtract the offset:
int16_t raw_signed = (raw ^ 1 << 13) - (1 << 13);


How to prove $I-BA$ is invertible

Question: Show that $I-BA$ is invertible if $I-AB$ is invertible. And also, we have to prove that eigenvalues are same for $AB$ and $BA$
Till now, I used the equation $(I-AB)(I-AB)^{-1}=I$ which gives $(I-AB)AB(I-AB)^{-1}=AB$ but I don't know how to proceed further.
Any hint would be sufficient !
Comment: Also, http://math.stackexchange.com/questions/237779/i-m-ab-is-invertible-if-and-only-if-i-n-ba-is-invertible.
Answer: Suppose $I - AB$ is invertible.
Suppose $(I - BA)x = 0$.
Then :
$$BAx = x$$
so
$$ABAx = Ax$$
or, what is the same,
$$(I - AB)Ax = 0$$
Since $I - AB$ is invertible, this last equality implies
$$Ax = 0$$
Hence $x = BAx = 0$. Thus the only solution of $(I - BA)x = 0$ is $x = 0$, so $I - BA$ is invertible.
Comment: Thank you for your answer. But i have one doubt, Is it correct to assume $(I-BA)x=0$. Is it necessary that a matrix $x$ exists such that $(I-BA)x=0$ ?
Comment: @VineetMangal I don't think $\;x\;$ is a matrix but **a vector**, and what the above shows is that $\;\ker (I-BA)=\{0\}\implies I-BA\;$ is invertible.
Comment: Now i got it. Thank you very much. But I am unaware of $ker(A)$. What is this ?
Comment: The null space of $\;A\;$ ...
Answer: Let's show that $AB$ and $BA$ have the same eigenvalues.
First, let $\lambda$ be a nonzero eigenvalue of $AB$; then $ABv=\lambda v$, for some $v\ne0$. Therefore $BA(Bv)=B(\lambda v)=\lambda(Bv)$ and so $\lambda$ is an eigenvalue of $BA$ (because $Bv\ne0$).
If $0$ is an eigenvalue of $AB$, at least one of $A$ and $B$ is not invertible. Thus also $BA$ is not invertible and has the eigenvalue $0$.

Now, the eigenvalues of $C$ are the (complex) numbers that make $C-\lambda I$ not invertible. Saying that $AB-I$ is invertible is the same as saying that $1$ is not an eigenvalue of $AB$; thus it is not an eigenvalue of $BA$ either.
Answer: Question 1: Let $A$ and $B$ be square matrices of the same order. Prove that $I-AB$ is invertible if and only if $I-BA$ is invertible.
Proof: Let $C$ be the inverse of $I-AB$. Then
$$I-BA=I-BIA=I-BC(I-AB)A=I-BCA(I-BA),$$
which gives us
$$(I-BA)(I+BCA)=I.$$
Thus $I-BA$ is invertible with the inverse $I+BCA$.
Question 2: Let $A$ be an $m\times n$ and $B$ be an $n\times m$ matrix with $m\le n$. Prove that $AB$ and $BA$ have the same nonzero eigenvalues, counting multiplicities, with $BA$ having an additional $n-m$ eigenvalues equal to $0$.
Proof: (It's a proof by C. R. Johnson and E. Schreiner published in American Mathematical Monthly 103 (1996), 578-582)
First notice that the $(m+n)\times (m+n)$ partitioned matrices
$$\left[
\begin{array}{cc}
AB & 0\\
B & 0
\end{array}
\right]
\qquad \text{and} \qquad
\left[
\begin{array}{cc}
0 & 0\\
B & BA
\end{array}
\right]$$
are similar to each other via the partitioned block calculation:
$$\left[
\begin{array}{cc}
AB & 0\\
B & 0
\end{array}
\right]
\left[
\begin{array}{cc}
I_m & A\\
0 & I_n
\end{array}
\right]=
\left[
\begin{array}{cc}
AB & ABA\\
B & BA
\end{array}
\right]=
\left[
\begin{array}{cc}
I_m & A\\
0 & I_n
\end{array}
\right]
\left[
\begin{array}{cc}
0 & 0\\
B & BA
\end{array}
\right].
$$
Since
$$\left[
\begin{array}{cc}
I_m & A\\
0 & I_n
\end{array}
\right]
$$
is invertible, it provides the similarity. Beacause
$$\left[
\begin{array}{cc}
AB & 0\\
B & 0
\end{array}
\right]
$$
is block triangular, its eigenvalues are those of the two diagonal blocks, $AB$ and the $n\times n$ zero matrix (See eigenvalues of a block matrix or the-eigenvalues-of-a-block-matrix). Similarly, the eigenvalues of
$$
\left[
\begin{array}{cc}
0 & 0\\
B & BA
\end{array}
\right]
$$
are the eigenvalues of $BA$, together with $m$ zeroes. Because the two partitioned matrices are similar and similar matrices have the same eigenvalues (see similar matrices have the same eigenvalues), $AB$ and $BA$ must have the same nonzero eigenvalues (counting multiplicities) and the additional $n-m$ eigenvalues of $BA$ must all be $0$.

Alternate Proof: (It's a proof from the book Matrix Analysis (Roger A. Horn, Charles R. Johnson) suggested in Exercise 9, page 55.)
(a) First, suppose that $A,B\in M_n$ and that at least one of them is invertible, Show that $AB$ is similar to $BA$ and hence the characteristic polynomials of $AB$ and $BA$ are the same. Hint: If $A$ is invertible, $BA=A^{-1}(AB)A$.
(b) Show that if $A,B\in M_n$ are both singular, $AB$ and $BA$ have the same eigenvalues, counting  multiplicities. $Hint:$ Consider the following analytic argument. For all sufficiently  small $\varepsilon>0$, $A_{\varepsilon}:=A+\varepsilon I$ is invertible; thus $A_{\varepsilon}B$ and $BA_{\varepsilon}$ are similar and hence the characteristic polynomials of $A_{\varepsilon}B$ and $BA_{\varepsilon}$ are the same. If we now let $\varepsilon \to 0$, similarity may fail in the limit, but equality of the characteristic polynomials continues to hold since $p_{A_{\varepsilon}B}(t)=\det{(tI-A_{\varepsilon}B)}$ depends continuously on $\varepsilon$. Thus, $AB$ and $BA$ have the same characteristic polynomials and therefore the same eigenvalues, counting multiplicities.
(Far now parts (a) and (b) are the same as the answer of @A.G.)
(c) Finally, if $A\in M_{m, n}$ and $B\in M_{n, m}$, with $m<n$,show that $AB$ and $BA$ have the same eigenvalues, counting multiplicities, except that $BA$ has an additional $n-m$ eigenvalues equal to $0$; equivalently, $p_{BA}(t)=t^{n-m}p_{AB}(t)$. Hint: Make $n$ by $n$ matrices out of both $A$ (by appending $0$ rows) and $B$ (by appending $0$ columns), apply the last result, and compare the two new products (appropriately partitioned) to the old ones.
Comment: Wonderful proof of part 1. But I am bit confused in proof of part 2. Do you have another simple way to prove this ?
Comment: I added an alternate proof.
Answer: Hint: prove that
$$
\det(\lambda I-AB)=\det(\lambda I-BA).
$$
P.S. Matrices has to be square otherwise the statement about eigenvalues is not correct.
Edit:
There is a nice proof of this fact:

If $A$ is invertible then
$$
AB=ABAA^{-1}=A(BA)A^{-1},
$$
and, hence, $AB$ and $BA$ are similar. Similar matrices have the same characteristic polynomial.
If $A$ is singular then it can be disturbed to a nonsingular $A_\epsilon$ such that $A_\epsilon\to A$ when $\epsilon\to 0$ (for example,$A_\epsilon=A+\epsilon I$). By the first item
$$
\det(\lambda I-A_\epsilon B)=\det(\lambda I-BA_\epsilon).
$$
Now take the limit when $\epsilon\to 0$ and use the continuous dependence of determinants on matrix components.
Comment: I forgot to add this information. Both A and B are square matrices.
Comment: But how you will show that determinant are equal ???
Comment: I have added the proof.
Comment: If we are over a commutative ring with 1, then the result is still true, but would this argument still work?  If we are over an arbitrary commutative ring, can we define a topology on the field of fractions?

How to prove $I-BA$ is invertible


How to cancel already fired non-repeating NSTimer?

Question: What I want:
1) 4 puzzle images in UIImageViews, which I can move around
2) after solving puzzle I want to show 2 images instead puzzles: first one just after puzzles are solved, second one 2 seconds after the first image...
What I have:
1) if you're solving really fast one puzzle after another you may fall into NSTimer interval, which will swap these 2 images too fast, like after 0.1 sec not 2.0
Is there any way to solve NSTimer, to not interfere with already fired one?
Solution(?): I was thinking about blocking interaction, so the second image will appear, but it seems like a poor workaround.
Comment: Why would you want to cancel an already fired non-repeating NSTimer? It's done its job already??
Answer: You should keep a reference to this timer (as a property or as an iVar).
Then simply call [myTimer invalidate]; myTimer = nil; when you want to cancel it.
EDIT:
If you are not keeping reference to your timer (if you're creating it from scratch inside code block) there's always a danger of creating multiple instances...
Comment: isn't that nonrepeating timers are self-invalidating after firing them ?
Comment: It's hard to say more without seeing the code. But your original idea (blocking user interaction) is not a poor workaround - although it might be annoying for users.
Comment: well I returned to invalidating and keeping it in ivar, it's debugging, but I have to test if new/old timers are not interferring with eachother
Comment: It should work. But again - it's hard to say where the exact problem is without seeing the code :)
Answer: Write setter method, Like this. Whenever you need to cancel timer
self.myTimer = nil;

- (void)setMyTimer:(NSTimer *)inTimer
{
   if (inTimer != mMyTimer)
  {
    [mMyTimer invalidate];
    [mMyTimer release];
    mMyTimer = [inTimer retain];
  }
}

Hope this might work for you.


Swift: Notifying a ViewController from another using completion handler

Question: I have 2 ViewControllers in my app. One of them named vcA is using a method (here viewDidLoad) to talk to my networking layer (a class in my app). After finishing the networking job (which will be inferred by a completion handler) I want to notify class vcB to call a method to get some data which is provided by networking layer.
Please take a look at below sudo code :
class Networking {

   static var PublicValue : SomeKindOfClass? = nil

   static func test(completionHandler : (successful : Bool) -> Void) -> Void {
      //Do some networking in background
      Network.BackgroundNetworking() {
         if result = true {
            PublicValue = SomeValue
            completionHandler(successful : true)
         }
         else {
            completionHandler(successful : false)
         }
    }
}

class vcA : UIViewController {

   override func viewDidLoad() {
      super.viewDidLoad()

      // Do any additional setup after loading the view.
      Networking.test(completionHandler : { (successful) in
         if successful == true {
            //Here I want to notify class vcB to call printPublicValue method
         }
      })
   }
}

class vcB : UIViewController {

  func printPublicValue() {

      print(Networking.PublicValue)
   }
}

Comment: Use NSNotifications
Comment: Thanks. I read about that here but I can't understand what's difference B/W NSNotifications & NSNotificationCenter & performSelector & KVO and which one is the best for my case ?
Answer: I agree with @Paulw11 you should consider using NSNotifications. They are easy to set up and use and would work great in this situation. To do this, in one of your view controllers put the following code:
NSNotificationCenter.defaultCenter().postNotificationName("nameOfNotification", object: nil)

In your second view controller (the one that will be receiving the notification) put:
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(NameOfViewController.nameOfFunction(_:)), name: "nameOfNotification", object: nil)

Then you can create a function like so:
func nameOfFunction(notif: NSNotification) {
      //Insert code here
}

There is a great tutorial here if you want to go more in depth:
https://www.andrewcbancroft.com/2014/10/08/fundamentals-of-nsnotificationcenter-in-swift/
EDIT: Swift 3 implementation of this.
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "nameOfNotification"), object: nil)

In your second view controller (the one that will be receiving the notification) put:
NotificationCenter.default.addObserver(self, selector: #selector(self.nameOfFunction), name: NSNotification.Name(rawValue: "nameOfNotification"), object: nil)

Then you can create a function like so:
func nameOfFunction(notif: NSNotification) {
      //Insert code here
}

Swift 4 implementation of this.
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "nameOfNotification"), object: nil)

In your second view controller (the one that will be receiving the notification) put:
NotificationCenter.default.addObserver(self, selector: #selector(self.nameOfFunction), name: NSNotification.Name(rawValue: "nameOfNotification"), object: nil)

Then you can create a function like so:
@ objc func nameOfFunction(notif: NSNotification) {
      //Insert code here
}

Comment: You should never call a view controller's `viewDidLoad` directly.  If you have a reference to an instance of B then you can set the object as the observer (the first argument to `addObserver`) but generally a class should manage its own observations.  Since you say that you want to call `viewDidLoad` it is actually that you should trigger a segue from A to B (or present B) when the data is retrieved, in which case you don't need NSNotifications
Comment: Thanks for your answer. That worked for me. But what would happen if I want to add observer B from class A ? What I actually want to do is to invoke method `viewDidLoad` of class B when class A finished the job through completion handler.
Comment: I have a UITabBarViewController, so I want it to ask networking layer to fetch all data for me. After this process I want to notify each of it's tabs that their data is ready to use. But as you know it's only the first tab's ViewController which added as an observer (other tabs did not even load yet !). Is there a way to handle this or I am completely on a wrong road ?!
Comment: You can add observers to the other view controllers too.
Answer: In latest swift version NotificationCenter.default.post(name: NSNotification.Name(rawValue: "Name"), object: notification) and


Question about the nlme setup/syntax R for nested repeated observations regression R

Question: I'm looking to perform a nonlinear mixed effects regression.
Sample data:
data.frame("id" = 1:2,
           "intervention" = c(rep("a",9),rep("b", 9)),
           "area" = 1:3,
           "dv" = sample(18, replace=TRUE))

In the sample data there were 3 observations per area and per intervention but the actually data isn't balanced like that.
DV is continuous data
2 subjects with repeated observations

I know from R Companion that I can use the following code to nest 1 level
library(nlme)

model = lme(dv ~ intervention, random=~1|id,
            data=Data,
            method="REML")

How do I nest a second level to also account for area?
Answer:
lme fits linear mixed models, not non-linear ones. For certain types of non-linear mixed models, you can use nlme.

If area is nested in the levels of id, you can use the code

model = lme(dv ~ intervention, random=~1|id/area,
            data=Data,
            method="REML")

to fit the nested mixed effects model.
Edits:
If you just specify random = ~ 1|id, you fit the single-level mixed model, which corresponds to the regression equation
$$
\textrm{dv}_{ik} =  \beta_0 + \beta_1 \textbf{1}_{\textrm{intervention}} + b_i + \epsilon_{ik} \\
b_i \sim \textrm{Normal} (0, \sigma_b^2) \\
\epsilon_{ik} \sim \textrm{Normal} (0, \sigma^2),
$$
where $b_i$ are the random effects due to differences among patients.
Nesting further with random = ~1 | id/area, then the effect of the intervention is further conditional on the random area effects that vary within patients (id's). This is basically the same as conditioning effects on the interaction of area and id. The regression equation in the nested model is
$$
\textrm{dv}_{ijk} =  \beta_0 + \beta_1 \textbf{1}_{\textrm{intervention}} + b_i + b_{ij} + \epsilon_{ijk} \\
b_i \sim \textrm{Normal} (0, \sigma_b^2) \\
b_{ij} \sim \textrm{Normal} (0, \sigma_c^2) \\
\epsilon_{ijk} \sim \textrm{Normal} (0, \sigma^2),
$$
where $b_i$ is the same as above, but now we additionally have $b_{ij}$, which are random effects due to areas within patient. (Some may prefer to use the notation $b_{i(j)}$ to make it clear that the effects are not crossed).
If there is further nesting, then (I think) the syntax extends the way you would expect it to: random = ~ 1 | id/area/subarea, but we are now pushing the limits of my experience with nlme.
Comment: The intervention is applied multiple times within an area for a given subject. The intervention is applied across multiple areas. What's the logic behind the id/area? What if I wanted to take it a level deeper and there's a subarea? Thanks!
Comment: @myfatson check my edits and report back.
Comment: Beautifully explained! What do you use to perform post-hoc testing on a double-nested model like this?
Comment: What would you like to know, post-hoc? The library `emmeans` has a lot of post-hoc testing capabilities, so does `survival::yates`.


Forward plain-text emails to TLS enabled SMTP server?

Question: I am running old applications that are not supporting any encryption/authentication  protocol on outgoing e-mails.
Is it possible to send plain-text emails to a local "relay" server that forward it to a TLS enabled SMTP server?
Comment: This is entirely practical and configured "out the box" by most "general purpose" SMTP servers work.
Answer: This is perfectly possible. And it is not even a strange scenario.
In fact, SMTP is not an end to end connection between mail client and final server but the mail client usually submits the mail to some local SMTP server which then delivers the mail to the next server etc. And this can take multiple hops. The connection between these hops might be encrypted with TLS or might be not. There might be authentication between the hops but usually there is none.
In other words: this setup fits well into the architecture of SMTP. This means it is supported by many mail servers, among them Postfix.


Error Build next js, Type error: 'carData' is possibly 'undefined'

Question: I have a problem with this component in next js, if I do the npm run dev it works, the problem is when I try to generate the next js build, it returns this error
./pages/marcas/[marca].tsx:66:30
Type error: 'carData' is possibly 'undefined'.
> 66 |                             {carData.cars && carData.cars.length > 0 ? (
     |                              ^

The code of the component is this
import React, { useEffect, useState } from 'react';
import { useRouter } from 'next/router';
import Header from '@/app/components/template/Header';
import Footer from '@/app/components/template/Footer';
import Content from '@/app/components/template/Content';
import '../../app/styles/globals.css';
import Link from 'next/link';
import { CarData } from '@/app/types/types';

const capitalizeWords = (str: string) => {
    return str.replace(/\b\w/g, (char) => char.toUpperCase());
};

const MarcaDetailPage = () => {
    const router = useRouter();
    const { marca } = router.query;
    const [carData, setCarData] = useState<CarData>();
    const [isLoading, setIsLoading] = useState(true);

    useEffect(() => {
        const fetchCarData = async () => {
            try {
                const response = await fetch(
                    `http://localhost:8000/api/cars/brand/${marca}`
                );
                const data = await response.json();
                setCarData(data);
                setIsLoading(false);
            } catch (error) {
                console.error('Error fetching car data:', error);
                setIsLoading(false);
            }
        };

        if (marca) {
            fetchCarData();
        }
    }, [marca]);

    return (
        <>

            <Content>
                {isLoading ? (

Loading...

                ) : (

Cars {brand}

                            {carData.cars && carData.cars.length > 0 ? (
                                carData.cars.map((car) => (

                                            Modelo: {car.model}

                                ))
                            ) : (

Error

                            )}

                )}
            </Content>

        </>
    );
};

export default MarcaDetailPage;

I'm trying to use the carData interface to obtain an array of objects from the API and display them one by one. I think the error is in the map when I try to use the carData interface but I can't solve it
CarData Interface

export interface CarData {
    id: number;
    model: string;
    battery_kw: number;
    brand: {
        name: string;
        slug: string;
    };
    year_ini: number;
    year_end: number | null;
    power: number;
    sku_vehicle: string;
    initial_price: number;
    car_images: { id: number; ruta_imagen: string }[];
}

I have searched for help in google, stackoverflow, even chatGPT but I can't see the solution
Answer: In useState() code you are not setting an initial state for carData, so it is undefined until fetch() resolves - hence the error during the build.
You can change the code to carData?.cars to specify that carData could be undefined (and cars array could not exists too).
Comment: Resolved, thxs !!!
Answer: const [carData, setCarData] = useState<CarData>();

This () means that the initial value of carData is undefined. You can either initialize it with a value (in case the data was an array) or you can use optional chaining carData?.cars
{carData?.cars && carData?.cars.length > 0 ? (
  carData.cars.map((car) => (

              Modelo: {car.model}

  ))
) : (

Error

)}

Comment: Resolved, thxs !!!