Proving piecewise function is not Riemann integrable

Question: How would you prove that $f(x) = \left\{ \begin{array}{l l} \pi, & \text{if $x$ is rational}, \\ 1, & \text{if $x$ is irrational}. \end{array} \right.$
is not Riemann integrable
What I did is look at the Riemann sum when all the $x_i$ in the partitions are rational, and when they are irrational. Is this the correct way of doing this?
Answer: Yes, that is correct. More formally: since $\mathbf{Q}$ is dense in $\mathbf{R}$, we have that $\sup_{x\in[x_i,x_{i+1}]} f(x)=\pi$ and $\inf_{x\in[x_i,x_{i+1}]} f(x)=1$ on any interval $[x_i,x_{i+1}]\subset\mathbf{R}$, therefore the upper and lower sums don't converge to the same limit. Hence $f$ is not Riemann-integrable.

Consider the partition $P=\{a=x_1<\cdots<x_n=b\}$ of an interval $[a,b]$.
For the upper sum, we have $$U(f,P)=\sum_{i=1}^{n-1} \color{blue}{\sup_{x\in[x_i,x_{i+1}]}f(x)}\cdot (x_{i+1}-x_i)=\color{blue} \pi\sum_{i=1}^{n-1} (x_{i+1}-x_i)=\pi(b-a),$$
while the lower sum evaluates to
$$L(f,P)=\sum_{i=1}^{n-1} \color{blue}{\inf_{x\in[x_i,x_{i+1}]}f(x)}\cdot (x_{i+1}-x_i)=\color{blue} 1\cdot\sum_{i=1}^{n-1} (x_{i+1}-x_i)=b-a.$$
Since $\pi(b-a)\neq b-a$, we conclude that $U(f)\neq L(f)$ therefore $f$ is not (Riemann-)integrable (on any interval $[a,b]$).
Comment: To rae306: +1. To OP: Note that rae306 is using a characterization of Riemann integrability called Darboux condition.
Comment: When I did the Reimann sums for the irrationals I got $\sum_{i=1}^\infty \frac{1}{n}$ and for the rationals i got $\pi \sum_{i=1}^\infty \frac{1}{n}$ is it enough to say that these limits are not the same considering that they are harmonic sums?
Comment: @Skrrrrrtttt I added some new information
Comment: the thing is we have not yet learned Darboux Integration so I wouldn't be able to apply it
Answer: hint
Each subinterval $F_i=[x_i,x_{i+1}] $ of a subdivision $\sigma $ of $[a,b] $, contains a lot of rationals and irrational reals.
thus
$$\sup_{x\in F_i}\{f (x)\} (x_{i+1}-x_i)=\pi (x_{i+1}-x_i) $$
and
$$U(f,\sigma)=\pi (b-a) $$


Show external mysql database data in webform field

Question: External database. - I want to allow drupal webform users to choose data from an external mysql database table. They would have the option to choose a region and an associated locality when completing the webform. What is the best way to expose this data in webform?
I have created a view using the entity reference but can't seem to expose this in the form field?
What is the simplest
Answer: It seems you need Webform Views Select module.
But it works for D7 only.


React-redux component is not re-rendering after state change

Question: One of my react-redux components is not re-rendering after state change. I want the select to become enabled after the checkbox is checked. But that doesn't happen. Only if I click somewhere else on the page on another component that triggers re-rendering, everything becomes as I expected. What am I doing wrong? I would be grateful for any help.
class Select extends React.Component {
    constructor(props) {
        super(props);
    }

render() {
    return (

            <input type="checkbox" onClick={this.props.toggleSelect}/>
            <select disabled={ !Object.keys(this.props.syncObjects).includes("select") }>
            // some options
            </select>

    )
}
}

const mapDispatchToProps = {
    toggleSelect
}

const mapStateToProps = state => {
    return {
        syncObjects: state.json.objects
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Select);

// reducer file
const initialState = {
    objects: {}
}

export const myReducer = (state = initialState, action) => {
    switch (action.type) {
        case TOGGLE_SELECT:
            if (Object.keys(state.objects).includes("select")){
                const new_state = {...state}
                delete new_state.objects["select"]
                return new_state
            }
            else {
                return {
                    ...state,
                    objects: {
                        ...state.objects,
                        'select': ''
                    }
                }
            }

        default:
            return state
    }
}

// actions.js
export function toggleSelect() {
    return {
        type: TOGGLE_SELECT
    }
}

Comment: The problem is that your reducer is mutating the state, which you should never do and leads to exactly this problem. Your `new_state` is just a shallow copy, and you then mutate one of its sub-objects.
Comment: @Helen : than your problem is, obviously, caused by using `delete` operator
Comment: First off, you don't seem to be ***dispatching*** anything from within your `mapDispatchToProps()`, next, you use `delete` operator to mutate your store which is done silently for Redux, thus React doesn't trigger re-renders. Consider using immutable techniques to filter out properties from the object, instead.
Comment: I was about to start an answer to show how to fix that, but then I noticed something else is strange: your `mapStateToProps` references `state.json.objects` and the `render` method cares whether that contains a `select` key or not, yet your reducer only manipulates that key within `state.objects`. Which is correct?
Comment: @yevgengorbunkov I believe defining `mapDispatchToProps` as an object will automatically dispatch the relevant actions, so that part looks fine. You are of course correct about the mutation.
Comment: @Robin Zigmond I wanted to make sure that when changing checkbox, if the key is already there, delete it. And if not, add it. But I also wanted it to work with it vice versa. So that, when I change the state (for example, loading data about components from a file), the page was re-rendered.
Comment: @RobinZigmond : when shorthand object form of `mapDispatchToProps` is used, you need to have action creator (`toggleSelect()`), which I don't see in the code, that's why I assumed there may be a mistake over there
Comment: @YevgenGorbunkov Yes, I have action creator in my code. I've omitted it here so it was more concise, but I'll update the post and add it now.
Answer: Best to not mutate state.updates, you can do the following:
const objects = { ...state.objects };
if (objects.select) {
  delete objects.select;
} else {
  objects.select = true; //set it truthy
}
return {
  ...state,
  objects,
};

Working example:

const { Provider, connect } = ReactRedux;
const { createStore, applyMiddleware, compose } = Redux;
const initialState = {
  objects: {},
};
//action types
const TOGGLE_SELECT = 'TOGGLE_SELECT';
// actions.js
function toggleSelect() {
  return {
    type: TOGGLE_SELECT,
  };
}

const reducer = (state = initialState, action) => {
  switch (action.type) {
    case TOGGLE_SELECT:
      const objects = { ...state.objects };
      if (objects.select) {
        delete objects.select;
      } else {
        objects.select = true; //set it truthy
      }
      return {
        ...state,
        objects,
      };
    default:
      return state;
  }
};

//creating store with redux dev tools
const composeEnhancers =
  window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(
  reducer,
  initialState,
  composeEnhancers(
    applyMiddleware(() => (next) => (action) =>
      next(action)
    )
  )
);

class Select extends React.Component {
  render() {
    return (

        <input
          type="checkbox"
          onClick={this.props.toggleSelect}
          checked={Object.keys(
            this.props.syncObjects
          ).includes('select')}
        />

          select enabled:
          {String(
            Object.keys(this.props.syncObjects).includes(
              'select'
            )
          )}

          select enabled (simpler example):
          {String(Boolean(this.props.syncObjects.select))}

    );
  }
}

const mapDispatchToProps = {
  toggleSelect,
};

const mapStateToProps = (state) => {
  return {
    syncObjects: state.objects,
  };
};

const App = connect(
  mapStateToProps,
  mapDispatchToProps
)(Select);

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);


Why does differencing once remove not only linear but also nonlinear trends?

Question: Applying first differences to a time series removes linear trends. See e.g. Can I detrend and difference to make a series stationary? I can understand the motivation. And also, why you would need to difference twice to remove quadratic trends.
But for a simple quadratic, differencing only once already completely removes the trend.
xx <- seq(-2,2, by = 0.01)
yy.quadratic <- 3*xx^2 + rnorm(length(xx))
d.yy.quadratic <- diff(yy.quadratic)

par(mfrow = c(1,2))
plot(xx,yy.quadratic)
plot(d.yy.quadratic)

And it also works for non-linear trends.
yy.complicated <- 2*sinpi(xx) + 4*exp(xx) + rnorm(length(xx))
d.yy.complicated <- diff(yy.complicated)
plot(xx,yy.complicated)
plot(d.yy.complicated)

Why does this work?
Comment: you should put xx on the horizontal axis in the rhs graphs. Then you'd see the top differencing graph go from mostly negative differences for small xx (near -2), to mostly positive differences for large xx (near 2)
Comment: I tried it out, but it makes no difference, as xx is already sorted increasingly.
Comment: True, I hadn't noticed that.
Comment: The trend is small but present; it's just swamped by the amount of noise
Comment: OK so basically this is the issue of noise-to-trend-ratio? If you have high noise, first differences will show more of the noise, no matter if the true underlying trend was linear or not. Maybe this is why differencing once or twice are usually said to be enough.
Answer: In your example, there is a lot of data for a small interval, hence the trend is swamped out. If you lower the number of data points to 41, you see the trend is definitely there:

nrpoints=40
start=-2
end=2
xx <- seq(start,end, by = (end-start)/nrpoints)
yy.quadratic <- 3*xx^2 + rnorm(length(xx))
d.yy.quadratic <- diff(yy.quadratic)
par(mfrow = c(1,2))
plot(xx,yy.quadratic)
xx1<- head(xx,-1)
plot(head(xx,-1),d.yy.quadratic)
abline(  coef(    lm(d.yy.quadratic~xx1))  )

If you increase the number of points to 401, the trend line becomes more horizontal. Increasing the range with 401 data points to [-20, 20] will also keep a visible trend.
Comment: I haven't thought of that. So it depends on the ratio of y(t) - y(t-1) / x(t) - x(t-1). This makes things more clear. Thanks!
Comment: Yes, in fact you had a very dense cloud of data, and 1st differences are usually used with a constant $x(t)-x(t-1)= 1$ in x-values. Here your noise crowded out the trend.
Answer: The accepted answer is great.  But, it didn't answer the secondary question:

And also, why you would need to difference twice to remove quadratic trends.

The principle is based on the Method of Differences.
If you'll forgive some Python:
>>> import numpy as np
x>>> xs = np.arange(5)
>>> xs
array([0, 1, 2, 3, 4])
>>> ys_constant = 0.0 * xs + 1
>>> ys_constant
array([1., 1., 1., 1., 1.])
>>> np.diff(ys_constant)
array([0., 0., 0., 0.])
>>> ys_linear = 2.0 * xs + 1
>>> ys_linear
array([1., 3., 5., 7., 9.])
>>> np.diff(ys_linear)
array([2., 2., 2., 2.])
>>> ys_quad = xs**2 + 2.0*xs + 1
>>> ys_quad
array([ 1.,  4.,  9., 16., 25.])
>>> np.diff(ys_quad)
array([3., 5., 7., 9.])
# need the second difference to get constant behavior
>>> np.diff(np.diff(ys_quad))
array([2., 2., 2.])
>>> np.diff(ys_quad, n=2)
array([2., 2., 2.])

Now, that shows that the method works.  But how/why?  Consider the differences as simple approximations to a derivative $\frac{f(x)-f(x+\Delta)}{\Delta}$ where the $\Delta$ values is fixed at $1$ (so it disappears from the denominator and is use a "fixed increment" to the next input in the sequence -- $x=2 \rightarrow x=3$ -- in the numerator).  Then, repeated differencing is like taking higher order derivatives.  The first order derivative of a line (aka the slope of a line) is always constant.  So, we only need a first order difference to remove a linear trend.  The second order derivative of a quadratic likewise gets us to a constant (in $y=ax^2 + bx + c$ we throw away the $b,c$ and are left with $a$).
Comment: It might be difficult to find this answer maybe you could add a question with this answer to make it easier to find.
Comment: lovely, but actually, the OP claims to understand that part, so that wasnt a question :-)
Comment: Indeed: if the "I can understand ..." applies to the "And also, why ..." -- which isn't how I interpreted it when I first read it.  But upon rereading, I could certainly see that interpretation.  Either way, I hope my answer is useful for someone!


Correct position of D7 chord

Question: I am preparing "Whirling Dervishes" for my Trinity Grade 1 Keyboard exam. In that piece D7 chord is present. As I figured out online, it's D-F#-A-C. Which of the following 2 pictures shows the correct position of D7 chord.
Picture 1:

Picture 2:

Keyboard layout:

Sheet Music:
Comment: They are both correct, containing D, F#, A, C. The second picture simply shows the chord played an octave higher than the first, but you can play a D7 chord in any octave. Is this exam not based on sheet music that will show you exactly the notes to play?
Comment: That sheet music only shows the melody line, and does not show a chord part. If you weren't doing this for an exam, I would say "play whatever sounds good" - but as you are doing this for an exam, you need to find out what's specified in the exam syllabus. https://www.trinityrock.com/instruments/keyboards/grade1 states that some of the songs are supposed to be played to a backing track. Is that the exam you are doing? Perhaps those chords simply indicate what's being played on the backing track, so perhaps *you* aren't supposed to play them at all..?
Comment: @topomorto added sheet music and keyboard layout. Can you please answer?
Answer: Unfortunately, this question is impossible to answer without the sheet music (not to mention the layout of your entire keyboard).
The two D7 chords that you show are both perfectly legitimate, so really it's up to the composer/arranger of the work to decide which of those D7 chords is actually intended.
As you work to figure this out, consider relating the D7 chord to Middle C. Middle C is the C written on the first ledger line above the bass clef, and it's equivalent to the first ledger line below the tremble clef. Find Middle C on your keyboard, and then use that as a reference point to identify which D7 chord your sheet music is showing.
Comment: Hi @Richard, added sheet music and keyboard layout. Can you please answer?
Answer: Are you using the auto-accompaniment feature of the keyboard, where you hold down a chord and it creates a rhythmic backing?   If so, both positions are correct, and will  trigger the same accompaniment, IF they both fall below the split point where the melody sound starts.  I suspect the higher position may JUST fit under this point!  It's safer to make a habit of choosing the lowest practical position.
Answer: Assuming that you should be playing that chord at all (doesn't the backing track have it?), it's entirely up to you and your sense of musicality not only in what octave you play it, but also in what inversion, and whether you want to play it as an arpeggio - and then what arpeggio, because it doesn't just have to be D-F#-A-C in that order. You could play it, for example, as (1/4)D-F#-A-C, or (1/4)D-F#-(1/8)A-C-D-F#, or (1/4)D-F#-(1/8)-A-C-A-C etc. Whatever sounds good and doesn't detract from the melody should work.
Remember that this is music, and you'll be judged by musicians: a reasonable, musically appropriate creative effort goes some way towards demonstrating your ability. Whatever own interpretative element you apply must be musically sound, i.e. must harmonize with the melody without overwhelming it, be separated from the melody appropriately, etc. You should be able to write some ideas down and play them for your teacher and ask for feedback!
Answer: Either of these will work.

The red square is on Middle C. The orange is the lowest part of that melody thing that's in the sheet music, so you'll probably want our chord to be lower than the melody. The green represents the higher root position D7 available, the blue represents the lower. You could also play a combination of the green and blue keys for an inversion of D7.

With no specified voicings, the only guideline I could give you would be to keep the melody above the chords.

Correct position of D7 chord


What is the area of the region enclosed by Ox, the curve $ y=\ln(x) $ and its tangent?

Question: First of all I determined the tangent. Let $d1$ be $y=\ln(x)$ and its tangent $dtan$. $dtan$ passes through $ (0,0) $ so it should be tangent to $d1$ in $ (a,b) $. I used the formula $y-\ln(a)=\frac{1}{a}\left(x-a\right)$ and replaced $x$ and $y$ with $0$. Like this, I determined that $a=e$ and $b=1$. Now, $dtan: y=\frac{x}{e}$. $\space\ln(x)$ and $\frac{x}{e}$ are both continuous so they can be integrated. Since $\ln(x)\lt\frac{x}{e}$, the area should be $\int _0^e\:\frac{x}{e}-\ln\left(x\right)dx$ which is $\frac{e}{2}$. The problem is that this is not the answer. It should be $\frac{e}{2} -1$. Have I missed something important?
Answer: All calculations are correct except the integral limits. If you plot the curves, you'll see that you have to split the integral in two parts as the region is limited by three curves. The integral has to be from $0$ to $1$ only for $x/e$ and from $1$ to $e$ for the one you wrote with $x/e-\ln x$. The way you've stated the limits, you are integrating the logarithm for all its negative values.


Error when executing SQL

Question: I get the following error when I try and execute the code down below.  I have added the SQL string I pass as well.  What am I missing?
Error:

Syntax error (missing operator) in query expression 'TOURID =
  25e5eed3-ea84-4c30-a660-2c880253da60'

My query,
DELETE * FROM TOURS WHERE TOURID = 25e5eed3-ea84-4c30-a660-2c880253da60;

My code,
Dim connectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\_Development\Data\filename.accdb;Persist Security Info=False;"
Dim DBConnection As New System.Data.OleDb.OleDbConnection(connectionString)
Try
    DBConnection .Open()
    Dim cmd As New System.Data.OleDb.OleDbCommand(sql, DBConnection )
    Dim sqlAdapterTOURS As New System.Data.OleDb.OleDbDataAdapter(cmd)
    cmd.CommandType = CommandType.Text
    cmd.ExecuteNonQuery()
Catch ex As Exception
    MessageBox.Show(ex.Message)
Finally
    DBConnection .Close()
End Try

Answer: You need to quote when working with GUIDS like this:
DELETE *
FROM TOURS
WHERE TOURID = '25e5eed3-ea84-4c30-a660-2c880253da60';

Answer: Your value should be surrounded by single quotes, like this:
DELETE * FROM TOURS WHERE TOURID = '25e5eed3-ea84-4c30-a660-2c880253da60';

Answer: Guess: your GUID-type entry should be quoted, maybe?:
DELETE FROM TOURS WHERE TOURID = '25e5eed3-ea84-4c30-a660-2c880253da60'

Answer: Access/Jet/ACE is not very GUID-friendly. Michael Kaplan wrote about this many years ago:
Replication and GUIDs, the Good, the Bad, and the Ugly
Depending on the context, you may need to use the VBA functions for working with GUIDs, i.e., StringFromGUID() and GUIDFromString(). I'm not sure exactly what you have to do in a SQL context, though. I do know you can't do a join between two GUID fields (you have to use implicit joins, i.e., using a WHERE clause instead).

Error when executing SQL


PHP: How to delete a page after 24 hours?

Question: We'd like to have PHP automatically delete a page from our website 24 hours after a specified date and time. The purpose is to offer promotional coupons to certain customers that last only 24 hours. How can we do this? (I'm ultra novice so please answer by example  code rather than explanation. Thank you.)
What we have so far:
<code><?php
$filename = "myfile.txt";
sleep (86400);
unlink($filename);
?>
</code>
This doesn't make sense though because I think the page has to be open for a full 24 hours (86,400 seconds) for it to execute, yes? Also, the 24 hours countdown should start at a specified date and time. What code would do this?
Thank you so much!
Answer: Don't delete it... just don't show it.  I'd avoid using PHP via web to delete stuff on local system.  Basically, wrap the code in an include where if with the date range show, otherwise don't.
Better yet, store the offer details in a CSV file, XML doc, or database with start & finish date/times and use that for your check.
Comment: +1:  Agreed.  Also, the 24 hour timer would have to be started at the right time, and could not be interrupted until expiration, like rebooting for maintenance.
Answer: If you want things to happen at scheduled times as opposed to responses to user events, use they scheduling system built into the operating system. On Linux/Unix, that would be cron.
It is too detailed to explain here but it isn't terrible complicated. Just BE CAREFUL if you are deleting files.
Wikipedia has a good overview of cron here: http://en.wikipedia.org/wiki/Cron
Of course, using cron usually requires that you have terminal access to the server.


Some JQuery Mobile touch events not firing

Question: I have the following code, and it seems clear that JQuery is working, but some JQuery Mobile events are not firing at all:
<!DOCTYPE html>

        <title>JQuery Mobile Test</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <link rel="stylesheet" href="css/jquery.mobile.custom.complete.theme.min.css"/>
        <link rel="stylesheet" href="css/jquery.mobile.custom.complete.structure.min.css"/>

-

-

-

-

-

-

-

I'm trying it out on Chrome on an Android. Of the above events, these don't work: tap, taphold and swipe. I have triple checked the file URLs.
The versions of JQuery above: JQuery: compressed, production 3.1.1,  and the latest JQuery Mobile: 1.4.5, custom with all options, minified.
Annoyingly it works as expected when I replace the link and script tags with a (random) earlier version, hosted by JQuery:
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.css" />

And it doesn't work when I use the latest JQuery-hosted versions:
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />

But I need to host the files myself and I would like to have the latest versions. What am I doing wrong? Are there differences in the API? Or is it a JQuery bug?
Comment: It doesn't work with jQuery v3. Use older version of jQuery. Additionally, I don't recommend using a custom version of jQM; create your own touch events.
Answer: To expand on Omar's comment above...
jQuery Mobile isn't compatible right now with the latest version of jQuery. If you look at the jquerymobile homepage, you will see under the download buttons (top-right) what versions of jQuery you can use. Currently for jQM v.1.4.5 you need:

jQuery 1.8 - 1.11 / 2.1


Como inserir rand no C?

Question: Em portugol:
Algoritmo "semnome"
    // Linguagem e Lógica de Programação
    // Lu e Gustavo
    // Descrição   : Aqui você descreve o que o programa faz! (função)
    // Autor(a)    : Nome do(a) aluno(a)
    // Data atual  : 27/09/2020
    Var
       // Seção de Declarações das variáveis
       Joken, Joken_at: Inteiro

Inicio
      // Seção de Comandos, procedimento, funções, operadores, etc...
      Escreval("Neste jogo você ira jogar JoKenPo contra a maquina")
      Escreval("Digite [1] para pedra")
      Escreval("Digite [2] para papel")
      Escreval("Digite [3] para tesoura")
      Leia(Joken)
      Enquanto (Joken<=0) ou (Joken>=4) faça
               Escreval("Opção inválida")
               Escreva("Digite novamente: ")
               Leia (Joken)
      Fimenquanto
      Escolha Joken
             Caso 1
                  Escreval("Você é pedra")
             Caso 2
                  Escreval("Você é papel")
             Caso 3
                  Escreval("Você é tesoura")
      Fimescolha
      Aleatorio 1, 3
      Leia(Joken_at)
      Aleatorio off
      Escolha Joken_at
             Caso 1
                  Escreval("O computador é pedra")
             Caso 2
                  Escreval("O computador é papel")
             Caso 3
                  Escreval("O computador é tesoura")
      Fimescolha
      Enquanto (Joken=Joken_at) Faça
               Escreval("O jogo empatou")
               Escreval("Para parar de jogar aperte esc")
               Escreval("Se quiser jogar novamente aperte [1] para pedra , [2] para papel ou [3] para tesoura")
               Leia(Joken)
               Enquanto (Joken<=0) ou (Joken>=4) Faça
                        Escreval ("Opção invalida")
                        Escreva ("Digite novamente: ")
                        Leia(Joken)
               Fimenquanto
               Escolha Joken
                       Caso 1
                            Escreval("Você é pedra")
                       Caso 2
                            Escreval("Você é papel")
                       Caso 3
                            Escreval("Você é tesoura")
               Fimescolha
               Aleatorio 1, 3
               Leia(Joken_at)
               Aleatorio off
               Escolha Joken_at
                       Caso 1
                            Escreval("O computador é pedra")
                       Caso 2
                            Escreval("O computador é papel")
                       Caso 3
                            Escreval("O computador é tesoura")
               Fimescolha
      Fimenquanto
      Se (((Joken=1) e (Joken_at=3)) OU ((Joken=2) e (Joken_at=1)) ou ((Joken=3) e (Joken_at=2))) Então
         Escreva("Você é o vitorioso")
      senão
      Escreva("Você perdeu")
      Fimse
Fimalgoritmo

Em C:
#include <stdio.h>
#include <locale.h>
int main (){
    setlocale(LC_ALL,"Portuguese");
    int J, Ja;
    printf("Neste jogo você ira jogar JoKenPo contra a maquina \n");
    printf("Digite [1] para pedra \n");
    printf("Digite [2] para papel \n");
    printf("Digite [3] para tesoura \n");
    scanf("%d",&J);
    while ((J<=0)||(J>=4)){
        printf("Opção invalida \n");
        printf("Digite novamente: ");
        scanf("%d",&J);
    }
    switch(J){
        case 1: printf("Você é pedra");break;
        case 2: printf("Você é papel");break;
        case 3: printf("Você é tesoura");break;
    }
    //Aleatório
    switch(Ja){
        case 1: printf("O computador é pedra");break;
        case 2: printf("O computador é papel");break;
        case 3: printf("O computador é tesoura");break;
    }
    while (J==Ja){
        printf("O jogo empatou\n");
        printf("Para jogar novamente aperte [1] para pedra , [2] para papel ou [3] para tesoura");
        scanf("%d",&J);
        while((J<=0)||(J>=4)){
            printf("Opção inválida\n");
            printf("Digite novamente: ");
            scanf("%d",&J);
        }
        switch(J){
            case 1: printf("Você é pedra");break;
            case 2: printf("Você é papel");break;
            case 3: printf("Você é tesoura");break;
        }
        //Aleatório
    }
    if(((J==1) && (Ja==3)) || ((J==2) && (Ja==1)) || ((J==3) && (Ja==2)))
        printf("Você é o vitorioso");
    else
        ("Você é o perdedor");
    getch ();
    return 0;
}

A pergunta é: como eu faço pra botar o //aleatório em C, como está no portugol?
Comment: Antes de fazer outras perguntas, leia [isto](https://pt.stackoverflow.com/help/how-to-ask)
Comment: Veja um exemplo aqui: https://www.cplusplus.com/reference/cstdlib/rand/
Comment: Se uma das respostas abaixo resolveu o seu problema e não restou nenhuma dúvida, escolha a que você mais gostou e marque-a como correta/aceita ao clicar no "✅" que está ao lado dela, o que também marca a sua pergunta como resolvida. Se ainda te resta alguma dúvida ou gostaria de maiores esclarecimentos, fique a vontade para comentar.
Answer: Assumindo que "Aleatório 1, 3" significa gerar um número aleatório entre 1 e 3, pode ser programado em C assim:
#include <stdlib.h>
...
Ja = rand() % 3 + 1;

Answer: Existe várias maneiras de você gerar números aleatorios no C.
Primeiro adicione no seu código as libs:
#include <stdlib.h>
#include<time.h>

Em seguida no começo do código adicione essa linha:
srand(time(NULL));

Isso vai fazer com que os números aleatórios sejam diferentes.
quando quiser gerar um número aleatório use: rand() % max + 1
Onde max será o valor máximo que você quer gerar, no seu caso, max = 3;
Caso você queira saber melhor sobre o rand() e o srand() acesse esse link.
Caso queira ver a documentação, acesse este.

Como inserir rand no C?


Subring of a UFD need not be a UFD

Question: Let $R$ be a UFD with $1$, are the following two statements true?

If $S$ is a subring of $R$, then $S$ is also a UFD;
if $S$ is a subring of $R$, and $1\in S$, then $S$ is UFD.
Comment: @J.W.Tanner: It depends on the text. Some don't require rings to have a unit, so (for example) $\{2n:n\in\Bbb Z\}$ is a ring with the usual integer operations.
Comment: Doesn't subring automatically have $1$?
Answer: Not in general. For example, note that $R=\Bbb C$ is a field, so trivially a UFD. However, consider $S=\Bbb Z[2i]:=\{x+2iy:x,y\in\Bbb Z\}.$ One can show fairly easily that $S$ is a subring of $R$ with unity. However, while $2$ is irreducible in $S,$ it is not prime in $S$. Hence, while $S$ is an integral domain (as a subring with unity of an integral domain), it is not a UFD. See here for more information on how we might go about proving this (and feel free to ask me questions if you're stuck).
Answer: Pick any quadratic number ring UFD $\,R = \Bbb Z[\sqrt n]\,$ and let $\,S =  \Bbb Z[2\sqrt n]\subset R.\,$ Notice that $\,w = (2\sqrt{n})/2 = \sqrt{n}\,$ is a fraction over $S$ and $\,w\not\in S\,$ but $w$ is a root of the monic polynomial $\,x^2 - n, \,$ contra the Rational Root Test (which is valid in any UFD). So $S$ is not a UFD.
Comment: @J.W.Tanner Yes, typos now fixed, thanks.
Comment: Did you switch $R$ and $S$?
Answer: Generalizing the examples given by Bill Dubuque and Cameron Buie, we can use the fact that a UFD is normal (that is, it is integrally closed in its field of fractions) to give us a strategy for finding counterexamples.
Namely, take some UFD $R$, consider its field of fractions $K$, and then find a (unital) subring $S\subseteq R$ such that the field of fractions of $S$ is still $K$, and $S$ is not integrally closed, i.e., there is $\omega\in K\setminus S$ which satisfies a monic polynomial over $S$.
This gives us the counterexamples from both of the other examples. Cameron Buie's has $R=\Bbb{Z}[i]$, $S=\Bbb{Z}[2i]$, $\omega=i$. Bill Dubuque's has $R=\Bbb{Z}[\sqrt{n}]$, $S=\Bbb{Z}[2\sqrt{n}]$, and $\omega = \sqrt{n}$.
Both of these examples are of rings of integers, however, we can also find a subring of a polynomial ring that is not a UFD via this strategy. Consider $R=k[t]$, $S=k[t^2,t^3]$, $\omega = t$. We have $\omega^2-t^2=0$, so $\omega$ is integral over $S$. Note that $t$ is in the fraction field of $S$, since $t=\frac{t^3}{t^2}$.
Comment: In case it was not obvious I chose the Rational Root form of integral closure since many beginners are not familiar with the more general ring-theoretic notion of integral closure (which is not really any more general *here*).
Comment: @Bill Dubuque, I upvoted both your answer and Cameron Buie's, I wrote this answer because I felt that it wasn't necessarily clear how those examples were arrived at. It's possible that this answer will be less useful to the OP, but I did think that it might be useful to someone. :)
Comment: No doubt. I didn't elaborate since it's already been done in many prior answers (and the CRUDE folks will soon be deleting this thread due to the "quality" of the question)

Subring of a UFD need not be a UFD


Getting java.net.ConnectException: Connection refused (Connection refused) while creating object using fake-gcs-server image

Question: I am getting java.net.ConnectException:connection refused error while trying to write junit for creating object in gcs using fake-gcs-server image. Please find the below code. Bucket name is test and consider, it is already created.
@TempDir
private static File         directory;

private static final GenericContainer<?> GCS_CONTAINER = new GenericContainer<>(DockerImageName.parse("fsouza/fake-gcs-server:1.33.1"))
        .withExposedPorts(4443).withCreateContainerCmdModifier(cmd -> cmd.withEntrypoint(
                "/bin/fake-gcs-server",
                "-scheme", "http"
        ));

String fakeGcsExternalUrl = "http://" + GCS_CONTAINER.getContainerIpAddress() + ":" + GCS_CONTAINER.getFirstMappedPort();

private static final Storage storage = new Storage.Builder(getTransport(), GsonFactory.getDefaultInstance(), null).setRootUrl(fakeGcsExternalUrl).setApplicationName("test").build();

void test() {

    final File localFile1 = new File(directory.getAbsolutePath() + File.separator + "testFile.txt");
    localFile1.createNewFile();

    try (final FileWriter fileWriter = new FileWriter(localFile1.getPath())) {
        fileWriter.write("Test gs file content");
    }

    final InputStream stream = FileUtils.openInputStream(localFile1);

    Path path = localFile1.toPath();
    String contentType = Files.probeContentType(path);
  uploadFile("test", "/sampleFiles/newFile.txt", contentType, stream, null);
}

public String uploadFile(final Storage storage, final String bucketName, final String filePath,
                         final String contentType, final InputStream inputStream, final Map<String, String> metadata)
        throws IOException {
    final InputStreamContent contentStream = new InputStreamContent(contentType, inputStream);
    final StorageObject objectMetadata = new StorageObject().setName(filePath);
    objectMetadata.setMetadata(GoogleLabels.manageLabels(metadata));
    final Storage.Objects.Insert insertRequest = storage.objects().insert(bucketName, objectMetadata,
            contentStream);
    return insertRequest.execute().getName();
}

Comment: Nothing was listening at the IP:port you tried to connect to.
Answer: This problem might be related to you omitting to set the fake-gcs-server's external URL property to the container's address. Make sure you follow guide in the official repo https://github.com/fsouza/fake-gcs-server/blob/cf3fcb083e19553636419818e29f84825bd1e13c/examples/java/README.md, particularly, that you execute the following code:
private static void updateExternalUrlWithContainerUrl(String fakeGcsExternalUrl) throws Exception {
  String modifyExternalUrlRequestUri = fakeGcsExternalUrl + "/_internal/config";
  String updateExternalUrlJson = "{"
      + "\"externalUrl\": \"" + fakeGcsExternalUrl + "\""
      + "}";

  HttpRequest req = HttpRequest.newBuilder()
      .uri(URI.create(modifyExternalUrlRequestUri))
      .header("Content-Type", "application/json")
      .PUT(BodyPublishers.ofString(updateExternalUrlJson))
      .build();
  HttpResponse<Void> response = HttpClient.newBuilder().build()
      .send(req, BodyHandlers.discarding());

  if (response.statusCode() != 200) {
      throw new RuntimeException(
          "error updating fake-gcs-server with external url, response status code " + response.statusCode() + " != 200");
  }
}

before using the container.


Is a DAO Only Meant to Access Databases?

Question: I have been brushing up on my design patterns and came across a thought that I could not find a good answer for anywhere. So maybe someone with more experience can help me out.
Is the DAO pattern only meant to be used to access data in a database?
Most the answers I found imply yes; in fact most that talk or write on the DAO pattern tend to automatically assume that you are working with some kind of database.
I disagree though. I could have a DAO like follows:
public interface CountryData {
    public List<Country> getByCriteria(Criteria criteria);
}

public final class SQLCountryData implements CountryData {
    public List<Country> getByCriteria(Criteria criteria) {
        // Get From SQL Database.
    }
}

public final class GraphCountryData implements CountryData {
    public List<Country> getByCriteria(Criteria criteria) {
        // Get From an Injected In-Memory Graph Data Structure.
    }
}

Here I have a DAO interface and 2 implementations, one that works with an SQL database and one that works with say an in-memory graph data structure. Is this correct? Or is the graph implementation meant to be created in some other kind of layer?
And if it is correct, what is the best way to abstract implementation specific details that are required by each DAO implementation?
For example, take the Criteria Class I reference above. Suppose it is like this:
public final class Criteria {
    private String countryName;

    public String getCountryName() {
        return this.countryName;
    }

    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }
}

For the SQLCountryData, it needs to somehow map the countryName property to an SQL identifier so that it can generate the proper SQL. For the GraphCountryData, perhaps some sort of Predicate Object against the countryName property needs to be created to filter out vertices from the graph that fail.
What's the best way to abstract details like this without coupling client code working against the abstract CountryData with implementation specific details like this?
Any thoughts?
EDIT:
The example I included of the Criteria Class is simple enough, but consider if I want to allow the client to construct complex criterias, where they should not only specify the property to filter on, but also the equality operator, logical operators for compound criterias, and the value.
Comment: I, for one, do not use DAO just for database access.  In my design, I often have a DAO that reads data, just like the name says, from some source. Sometimes, it's a database, other times it might be a file, a particular stream, an encryption device, hardware random number generator, you name it. As long as it supplies me data, and I don't care where the data comes from, I'm comfortable following the DAO pattern.  It also makes it easy to refactor code later, what was a SQL database might become some other storage mechanism, with no effect on my application other than on the DAO implementation.
Answer: DAO's are part of the DAL (Data Access Layer) and you can have data backed by any kind of implementation (XML, RDBMS etc.). You just need to ensure that the project instance is injected/used at runtime. DI frameworks like Spring/Guice shine in this case. Also, your Criteria interface/implementation should be generic enough so that only business details are captured (i.e country name criteria) and the actual mapping is again handled by the implementation class.
For SQL, in your case, either you can hand generate SQL, generate it using a helper library like Spring or use a full fledged framework like MyBatis. In our project, Spring XML configuration files were used to decouple the client and the implementation; it might vary in your case.
EDIT: I see that you have raised a similar concern in the previous question. The answer still remains the same. You can add as much flexibility as you want in your interface; you just need to ensure that the implementation is smart enough to make sense of all the arguments it receives and maps them appropriately to the underlying source. In our case, we retrieved the value object from the business layer and converted it to a map in the SQL implementation layer which can be used by MyBatis. Again, this process was pretty much transparent and the only way for the service layer to communicate with DAO was via the interface defined value objects.
Comment: Small thought, what if you wanted the client to specfiy a property to order on for example. How would the Criteria object accomdate that so that you can translate it to say a map to pass to MyBatis? Sorry if this seems like a similair question so my last one; I'll admit they are kind of similiar
Comment: I'd pass along with the criteria (e.g. country name) and a ordering value (object having field name and type of ordering `ASC` or `DESC`). MyBatis is [capable of creating dynamic queries](http://ibatis.apache.org/docs/dotnet/datamapper/ch03s09.html) based on the passed in "value object" or "map" which should take care of the query created.
Comment: I am assuming you mean you would pass along the field name in the database? Or do you mean the "property" name on the value model that you want to order on and in your SQL Map, you would translate it to the appropiate dtabase field name? If the latter, won't there be tons of conditional logic if there as a lot of "properties" in the model?
Comment: I meant database column name which can be used in dynamic query along with direction (`ASC`, `DESC`). In your SQL DAO implementation, you will read these values and create a map which will be something along the lines; `map.put("sortColumn", ordering.column); map.put("sortOrder", ordering.order); map.put("countryName", myCountryName);`. This map will then be passed to MyBatis and the MyBatis XML will use the map "keys" are propeties when creating queries.
Comment: Right, but that's exactly my point. If the client code is working with an injected instance of your DAO, it is working against the interface not the concrete implementation. So in essense, it has no idea what kind of implementation it is working against. It could be the SQL or Graph as in my examples. So if you force the caller to set an order criteria using the database field name when they are invoking the DAO method, there is an implicit coupling there and the entire idea of the interface is useless. See what I am saying?
Comment: ... Ran out of characters. Thanks for your detailed answers and for sticking in there with me. I enjoy getting insight from experienced people like yourself.
Comment: I understand your concern, but it's a non-issue IMO. For the SQL implementation, it is the RDMBS table's column name. For XML based solution, it might be the attribute/element name. After all, when you are "ordering" something, it makes perfect sense to know *what* you are ordering on. It really isn't RMDBS specific but a data store related concept really.
Comment: I agree that it makes sense to know _what_ you are ordering on but I think its a **huge** concern. If one day I decide to change the injected implementation to something else, which is not uncommon, then there would be a ton of refactoring that needs to be done because the new implementation would not necessarily know the it is being passed a database field name. Perhaps some other layer in the middle needs to be introduced? I guess I'll have to think about it some more. Thanks again for your detailed comments, much appreciated.
Comment: You are of course welcome. BTW, I have been there, done that. It just works. Also, too much thinking is counter productive. If I were you, I would have whipped out a simple working implementation/POC, tried changing underlying datastore and see how it turns out. Unless you "actually" interact with the API you are designing, any more design thought would be nothing more than over engineering. I'm more into a good lightweight initial design and then aggressive refactoring rather than thinking all combinations/design upfront. Of course, YMMV. :)
Answer: No, I don't believe it's tied to only databases. The acronym is for Data Access Object, not "Database Access Object" so it can be usable with any type of data source.
The whole point of it is to separate the application from the backing data store so that the store can be modified at will, provided it still follows the same rules.
That doesn't just mean turfing Oracle and putting in DB2. It could also mean switching to a totally non-DBMS-based solution.
Answer: ok this is a bit philosophical question, so I'll tell what I'm thinking about it.
DAO usually stands for Data Access Object. Here the source of data is not always Data Base, although in real world, implementations are usually come to this.
It can be XML, text file, some remote system, or, like you stated in-memory graph of objects.
From what I've seen in real-world project, yes, you right, you should provide different DAO implementations for accessing the data in  different ways.
In this case one dao goes to DB, and another dao implementation goes to object graph.
The interface of DAO has to be designed very carefully. Your 'Criteria' has to be generic enough to encapsulate the way you're going to get the data from.
How to achieve this level of decoupling? The answer can vary depending on your system, by in general, I would say, the answer would be "as usual, by adding an another level of indirection" :)
You can also think about your criteria object as a data object where you supply only the data needed for the query. In this case you won't even need to support different Criteria.
Each particular implementation of DAO will take this data and treat it in its own different way: one will construct query for the graph, another will bind this to your SQL.
To minimize hassling with maintenance I would suggest you to use Dependency Management frameworks (like Spring, for example). Usually these frameworks are suited well to instantiate your DAO objects and play good together.
Good Luck!
Comment: Interesting. Would you mind giving a small explanation what you mean by "another level of indirection"? I am trying to think of a way to design a Criteria object like you said, where client code can specify which a property to filter on, it's operator (=, >, etc.) and value in a generic decoupled manner and have each DAO implemenetation can interpect it however it likes. But I can't seem to figure it out. EDIT: Thanks for the great detailed answer BTW.
Answer: No, DAO for databases only is a common misconception.
DAO is a "Data Access Object", not a "Database Access Object". Hence anywhere you need to CRUD data to/from ( e.g. file, memory, database, etc.. ), you can use DAO.
In Domain Driven Design there is a Repository pattern. While Repository as a word is far better than three random letters (DAO), the concept is the same.
The purpose of the DAO/Repository pattern is to abstract a backing data store, which can be anything that can hold a state.


Looping in R to create calculated delta columns

Question: I have a dataframe with baseline variables and the same variables after a period of time.
I'm trying to loop in order to calculate delta columns.
delta <- function(df, lenght) {
half<-lenght/2
for (i in df[,(half+1):(lenght)])
{   df[,i]- df[,i-half]
df }
}

Unfortunatelly, it still doesn't work; plus i'm not able to give a name to the new column.
Thanks in advance,
A
Comment: I'm not sure if I understand your question. If you're just trying to calculate the delta between 2 columns you can just do `column1-column2` since R is a vector language
Comment: Could you please provide data to make this reproducible?
Comment: You may be interested in the function `diff()`.
Comment: @CephBirk Diff is for lagged/iterated differences within a vector. He's taking the delta between columns, I believe
Comment: @Hack-R yes, you're right
Comment: @Hack-R transpose then diff?
Answer: I'm not sure what you're trying to do without more information about your columns and your goal with the logic you have in your question but this is how you calculate the delta between 2 columns within a data frame in R:
df = data.frame(v1 = c(1,2,3,4,5),v2 = c(5,4,3,2,1))

v3 = df$v1-df$v2

#-4 -2  0  2  4


Why doesn't drupal_render work, but render does?

Question: I've a piece of code what is rendering a custom table (see var_dump below) what is shown on for specific states of the node. The data of the table is for both states the same.
array(1) {
  [0]=>
  array(5) {
    ["#theme"]=>
    string(5) "table"
    ["#header"]=>
    array(2) {
      [0]=>
      string(4) "test"
      [1]=>
      string(9) "geen test"
    }
    ["#rows"]=>
    array(2) {
      [0]=>
      array(2) {
        [1]=>
        string(6) "e1a1r1"
        [2]=>
        string(6) "e1a2r1"
      }
      [1]=>
      array(2) {
        [1]=>
        string(6) "e1a1r2"
        [2]=>
        string(6) "e1a2r2"
      }
    }
    ["#prefix"]=>
    string(38) "
Table
"
    ["#attributes"]=>
    array(1) {
      ["class"]=>
      array(1) {
        [0]=>
        string(15) "previous-scheme"
      }
    }
  }
}

The custom states of the node are determined by a condition what prints one of the following gathered variables.
For the variable at the line below works with both drupal_render and render.
$kickoff_deadline .= '
Between kickoff and deadline
'.drupal_render($table);

For the variable at the line below only works with render, without it wont show anything.
$after_deadline .= '
After the deadline
'.render($table);

So what is happening? Why doesn't drupal_render work for a similar printed variable what does work?
Answer: Once you've done this:
$kickoff_deadline .= '
Between kickoff and deadline
'.drupal_render($table);

The render array is marked as #printed, and won't be rendered again. So this
$after_deadline .= '
After the deadline
' . drupal_render($table);

Will do nothing.
If you take a look at the code for render():
function render(&$element) {
  if (is_array($element)) {
    show($element);
    return drupal_render($element);
  }
  else {
    // Safe-guard for inappropriate use of render() on flat variables: return
    // the variable as-is.
    return $element;
  }
}

You can see it runs show($element);, making it available for rendering again. Which is why this works:
$after_deadline .= '
After the deadline
'.render($table);

Comment: So performance related it would be the best solution to use one of the two function, right? This is how that can be done with drupal_render. By storing the render action into a variable `$rendered_table=drupal_render($table);` and than.. `$kickoff_deadline='...'.$rendered_table; `$after_deadline='...'.$rendered_table;`
Comment: Correct @Fleuv - you'll save processing time and a bit of memory by caching the result in a local var
Answer: If you look at the documentation for those functions there are hints to this.
drupal_render() will only render the element if it has not already been printed and has not been hidden using hide().
render() on the other hand will always render the element because it calls show() on the element before then calling drupal_render() on it.


Use variable as object key

Question: I wish to insert variables into an object key structure but I just get the variable name rather than the variable value.
var winnerId = 10;
var loserId = 11;

newMessage.setMessageData({
  winnerId : {
    "status" : "win",
    "choice" : playerData[winnerId]["currentChoice"],
    "newScore" : playerData[winnerId]["score"]
  },
  loserId : {
    "status" : "lost",
    "choice" : playerData[loserId]["currentChoice"],
    "newScore" : playerData[loserId]["score"]
  }
});

Comment: I feel like a broken record a bit, but it always feels useful to point out that what you're describing has nothing to do with JSON. It's just a plain old *object*. JSON is a `string` that *represents* an object.
Comment: good to know thanks. I am sure it has been said many times :-)
Answer: You should use computed-property-names:
newMessage.setMessageData({
    [winnerId]: {
        "status": "win",
        "choice": playerData[winnerId]["currentChoice"],
        "newScore": playerData[winnerId]["score"]
    },
    [loserId]: {
        "status": "lost",
        "choice": playerData[loserId]["currentChoice"],
        "newScore": playerData[loserId]["score"]
    }
});

Comment: @KeithPower it should work, can you post more detail of your code?
Comment: I am getting  invalid property id (#114) error

Use variable as object key


Autenticação com duas tabelas diferentes

Question: Eu preciso fazer duas autenticações, uma para clientes outra para administradores, então tenho que ter duas instância de auth; como fazer isso no Laravel, sendo que eu tenho uma tabela de cliente e outra de administradores?
Comment: porque é que tem 2 tabelas?
Comment: uma de clientes e outra de administradores.
Comment: Acredito que o ideal é você criar uma tabela específica para login, a qual será "linkada" ou com  clientes ou com administradores (especialização).

Assim fica melhor até de trabalhar, pois imagine que em uma tabela o nome do usuario o campo correspondente é 'nome', e em outra 'nome_completo', você terá que encher o seu sistema de if (ou então criar acessors, mas mesmo assim).
Answer: O método mais prático é configurar a autenticação na rota onde se fizer necessário:
Config::set('auth.model', 'Admin');

ou ainda, setar para um padrão de URI's
if ($request->is('admin*'))
{
    Config::set('auth.model', 'Admin');
}

Desse modo, o Model Admin será responsável pela autenticação.
Answer: Acredito que seja o caso de se criar uma nova classe do Auth Illuminate\Auth\Guard e algumas Facades, pra replicar o componente Auth. Aí você faria, por exemplo, uma autenticação usando Auth::attempt() e outra usando a sua autenticação, MeuAuth::attempt().


Heteroscedasticity in Fixed Effects model

Question: I've found heteroscedasticity in my panel data. However, Gujarati (2009) says in a footnote to the chapter "The fixed-effect within group estimator" that Stata provides heteroscedasticity-corrected standard errors in panel data regression models. Does this mean that I can ignore the heteroscedasticity found?
Answer: The option vce(robust) for regress, xtreg etc... produces heteroskedasticity consistent standard errors. Note also that heteroskedasticity robust standard errors in a regression with fixed effects is produced in Stata by clustering on the panel's grouping variable.
Theoretically, heteroskedasticity robust standard errors will produce consistent estimates in the presence of heteroskedasticity (as your sample size goes to infinity), but of course, all bets are off for too small a sample.
Comment: @MatthewGunn right, this is true.  Stata doesn't let you make the wrong choice, apparently.
Comment: Thanks for your quick response.I'd just like to know when the feasible generalized least squares (xtgls); should be used instead of the robust fixed effect model.
Comment: So vce(robust) option with fixed effects just fixes up your standard errors taking into account how your various observations may be correlated. GLS will take into account *in the estimation phase* some estimate of the covariance in your error terms. If the covariance structure is accurate, that can seriously improve efficiency. On the other hand, if the covariance structure/estimate is junk, it can introduce serious error. Basically, instead of weighting each observation equally, you're assigning more weight to less noisy observations, but if they're not less noisy, shit may hit the fan.
Comment: That's my extremely loose, high level take anyway. I'm not familiar with the all the particulars of 'xtgls' in Stata.
Comment: Is it true that the sandwich estimator is equivalent to the cluster-sandwich estimator? I think not. Or maybe you're referring to a state default?
Comment: @generic_user From the Stata [technical notes for xtreg](http://www.stata.com/manuals13/xtxtreg.pdf) on page 25, "As discussed
by Wooldridge (2013), Stock and Watson (2008), and Arellano (2003), specifying vce(robust) is equivalent to specifying vce(cluster panelvar), where panelvar is the variable that identifies the panels."
Comment: @MatthewGunn OK, I assume that under-the-hood stata knows the difference between $(X'X)^{-1}X'\hat{\epsilon}\hat{\epsilon}'X(X'X)^{-1}$ and $(X'X)^{-1}\displaystyle\sum_j \left(X_j'\hat{\epsilon_j}\hat{\epsilon_j}'X_j\right)(X'X)^{-1}$
Comment: @generic_user For fixed $T$ in panel data, the usual heteroskedastic-robust standard-errors are inconsistent. See [Stock and Watson (2008)](https://www.princeton.edu/~mwatson/papers/ecta6489.pdf). Stata changed how it calculates vce(robust) in [I think version 10 or so](http://www.stata.com/statalist/archive/2010-07/msg00899.html)? I changed my language to reflect this approach may be Stata specific.


DateTime Format

Question: Currently I am using below code to get March 06.  What do I do to get 06 March?
Text='<%# Bind("ToDate","{0:m}")%>'

Answer: Either use a custom format string or use a different locale.  If I'm reading the code right, here's a format string to give you the right string:
Text='<%# Bind("ToDate", "{0:dd MMMM}") %>'

I'm not sure how you'd use a different locale however.  Someone else might have the answer to that.
Answer: Text='<%# Bind("ToDate","{0:dd MMM}")%>'

Answer: see http://msdn.microsoft.com/en-us/library/hzz3aycd(v=vs.71).aspx

DateTime Format


Como concatenar colunas identificadas pelo apelido?

Question: Tenho a seguinte consulta:
select case when datediff(...) > 0 then month(tblData.data1)
            when day(tblData.data2) > 10 then month(tblData.data2)
            when month(tblData.data2) = 1 then 12
            else month(tblData.data2) - 1 end as Mês,

    case when datediff(...) > 0 then year(tblData.data1)
    when day(tblData.data2) > 10 then year(tblData.data2)
    when month(tblData.data2) = 1 then year(tblData.data2) - 1
    else year(tblData.data2) end as Ano,

    concat(Ano, Mês) as AnoMes -- Como fazer essa linha aqui funcionar??

...
from where order by

Eu preciso que a terceira coluna concatene os valores das duas anteriores. Porém, se eu colocar essa função tomo um erro de nome de coluna não definido, visto que Anoe Mês são apenas apelidos.

Como posso concatenar esses valores evitando a repetição desses case when???

obs: as partes omitidas em nada interferem com a questão!
Comment: não é possível referenciar um alias na mesma query, porque isso é processado ao final, e no momento da execução "Mês" não existe, só vai ser ao final da query. A solução pra isso é transformar o primeiro case num subselect
Answer: Não é possível dessa forma. Mesmo que suas colunas com apelido venham antes, não é assim que as coisas funcionam...
Esse trecho de código por exemplo:
case when datediff(...) > 0 then month(tblData.data1)
            when day(tblData.data2) > 10 then month(tblData.data2)
            when month(tblData.data2) = 1 then 12
            else month(tblData.data2) - 1 end as Mês

Ainda não foi processado no contexto da sua consulta, logo esse apelido "Mês" não existe ainda. Não é tão simples como um excel por exemplo, pra acessar essa informação ela precisa ser processada primeiro.
Para não repetir esse processamento, você pode fazer um SELECT ao redor da sua consulta, transformando a consulta principal em uma SUB-QUERY.
Exemplo:
SELECT mês
  FROM (SELECT CASE
                 WHEN datediff(.. .) > 0 THEN MONTH(tbldata.data1)
                 WHEN DAY(tbldata.data2) > 10 THEN MONTH(tbldata.data2)
                 WHEN MONTH(tbldata.data2) = 1 THEN 12
                 ELSE MONTH(tbldata.data2) - 1
               END AS mês
          FROM tblData)

Assim a coluna mês já foi processada na sua sub consulta e você poderá fazer o que quiser com ela na consulta principal sem repetir o processamento.
Você poderia ainda criar uma visão para sua tabela, retornando esses campos formatados e utiliza-la na sua consulta... As formas de se fazer isso são várias...


Algorithm for generating hyperexponential distribution

Question: I need to generate a hyperexponential distribution for my project. I have already implemented a poisson generating algorithm given by Donald Knuth, but I couldn't find an algorithm for generating a hyper exponential random variable.
I am provided with the mean and variance required of the distribution and I need an algorithm which can generate a random variable from this distribution when I execute it.
Comment: @Anirudh just having a mean and variance is not sufficient to determine a hyperexponential. Even a two-component exponential has 3 parameters ($\lambda_1,\lambda_2, p_1$,) while specifying mean and variance will only fix two parameters. [Once you've chosen your $p$ and $\lambda$ vectors, it's very easy to generate. e.g. it's a single line in R: `rexp(n,lambda[sample(p,n,TRUE,p)])`  generates n values from the hyperexponential if you've already specified `p`, `lambda` and `n`. ]
Comment: Hi and welcome to the site, @Anirudh Vemula. [This book](http://goo.gl/Jp7T4) contains an algorithm for generating RVs from a hyperexponential distribution (page 107). [This site](http://www.iro.umontreal.ca/~vazquez/SimSpiders/GenerRV/Methods/composition.html) also seems to offer some guidance. [Here](http://www.csee.usf.edu/~christen/tools/genhyp2.c) is an algorithm implemented in C.
Comment: Thanks a lot! There is an alias method which is used in the algorithm(in book) to select lambda, do you have any idea what that is?
Comment: Unfortunately, I don't know what the alias method is. But a quick Google search reveiled several interesting documents (especially the third): [first](http://en.wikipedia.org/wiki/Alias_method), [second](http://web.eecs.utk.edu/~vose/Publications/random.pdf), [third](http://luc.devroye.org/chapter_three.pdf), [fourth](http://stackoverflow.com/a/5033445).
Comment: The alias method is just [a method](https://en.wikipedia.org/wiki/Alias_method) for generating discrete random variates; since the hyperexponential is a finite mixture of exponentials you need to choose which exponential component to generate first. The alias method is particularly convenient if the discrete variable has a finite range (as here). I describe the basic approach [here](https://stats.stackexchange.com/a/68041/805) along with some other methods.
Answer: If you have a Hyperexponential-2 (H2), then with probability $p$ you sample from $F_1$ and with $1-p$ sample from $F_2$.  Obviously $p$ must be on the interval $[0,1]$, $F_1$ ~ Exponential($\lambda_1$), and $F_2$ ~ Exponential($\lambda_2$).
You can mix a larger number of exponentials by extending this idea.
If you have a target mean and variance, select $p,\lambda_1,\lambda_2$ so that the resulting hyperexponential will have the target mean and variance.
To choose the parameters, solve the equations for the mean and variance.  If $X$ ~ $H2(p,\lambda_1,\lambda_2)$ then $\text{E}[X] = p/\lambda_1 + (1-p)/\lambda_2$.
$\text{Var}[X] = \text{E}[X^2]-\text{E}[X]^2 = 2p/\lambda_1 ^2 + 2(1-p)/\lambda_2^2 - \text{E}[X]^2$
Set these equal to your targets and solve for $p,\lambda_1,\lambda_2$; it will be underdetermined so a number of hyperexponentials will have your target mean and variance. Just pick one solution.
MATLAB Code to generate from $H2(p,\lambda_1,\lambda_2)$:
function [ X ] = h2rnd( p,Rates,N )
%H2RAND Samples from specified Hyperexponential distrbution
%   [ X ] = h2rnd(p,Rates,N)
%   INPUTS
%        p: mixing probability
%    Rates: rates for the two exponential distributions (2 x 1 vector)
%        N: number of samples to generate
%  OUTPUTS
%        X ~ H2(p,Rates(1),Rates(2))
% %%%%%%%%%%%%% BEGIN ERROR CHECKING %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if p < 0 | p > 1, error('p must be on interval [0,1]'), end
if min(Rates)<=0, error('Rates must be positive'), end
% %%%%%%%%%%%%% END ERROR CHECKING %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
X = zeros(N,1);
P = rand(N,1);
X(P<=p)= -log(1-rand(sum(P<=p),1))/Rates(1);
X(P>p)= -log(1-rand(sum(P>p),1))/Rates(2);
end

Update:
Adding another exponential to have $Y\sim H3(p_1,p_2,\lambda_1,\lambda_2,\lambda_3)$ allows one to match more moments but increases the complexity as well.
Reference:
Wiki for Hyperexponential Distribution
Answer: Composition method is used in @SecretAgentMan's answer.
Instead, inverse transformation is used in the following Python function.
import random as rd
import math
from scipy.optimize import fsolve

def sim_exp_hyper(pmf:list, expects:list, n:int, whi_seed:int=123) -> list:
    """Simulate realisation of hyper-exponentially distributed random
    variables using inverse transformation method.

    Keyword Arguments
    =================
    pmf: probability mass function
    expects: expectation of each individual exponential distribution
    n: number of realisations
    whi_seed: seed
    """

    if len(pmf) != len(expects):
        raise ValueError("len(pmf) != len(expects).")
    elif sum([i < 0 for i in pmf]) > 0:
        raise ValueError(f"There are negative values in the probablity mass "
            f"function {pmf}.")

    def get_eq(u, x):
        eq = 1 - sum(pmf[i] * math.exp(- x / expects[i]) for i in range(len(pmf))) - u
        return eq

    rd.seed(whi_seed)
    us = [rd.random() for i in range(n)]
    xs = [fsolve(lambda x: get_eq(u, x), 0.1)[0] for u in us]
    return xs, us

This method is inefficient because a nonlinear equation is solved to generate one realisation. There is no way to express the inverse of CDF of hyper-exponential distributions. So we can only obtain $x$ by solving:
$$ F(x)=1-\sum_{i=1}^{m} p_{i} e^{-\lambda_{i} x}=\sum_{i=1}^{m} p_{i}\left(1-e^{-\lambda_{i} x}\right) = u $$
where $u$ is a simulated random number from uniform distribution over $[0, 1]$.
However, one random number (instead of two in composition method) is used for every realisation, which is essential in common random number method for variance reduction.


wp_nav_menu add  tags inside  tags that is parent

Question: I found examples adding a class to top level items, so we can display an arrow in menu items with sub-items, but is seems terrible to cope with the already built in WordPress classes, can't display the arrow with current and CSS hover, it just ruins all states.
The current nav menu is like this
Text

Is there someway to add a  within the parent  tags instead?!
Add -> "" -> inside  tags
Thus ->
Text
 that is parent.
the current code Adds the  tags outside the  tags
class My_Walker_Nav_Menu extends Walker_Nav_Menu {
    function start_lvl(&$output, $depth, $args) {
        $indent = str_repeat("\t", $depth);
        if('primary' == $args->theme_location && $depth ==0){
            $output .='';
        }
        $output .= "\n$indent
\n";
    }
}

Comment: would you like to consider jquery?
Answer: You are overwriting the incorrect method. You need the start_el instead. Here is the code for it:
class add_span_walker extends Walker_Nav_Menu {
    function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
        global $wp_query;
        $indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';

        $class_names = '';

        $classes = empty( $item->classes ) ? array() : (array) $item->classes;
        $classes[] = 'menu-item-' . $item->ID;

        $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args ) );
        $class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : '';

        $id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args );
        $id = $id ? ' id="' . esc_attr( $id ) . '"' : '';

        $output .= $indent . '
';

        $attributes  = ! empty( $item->attr_title ) ? ' title="'  . esc_attr( $item->attr_title ) .'"' : '';
        $attributes .= ! empty( $item->target )     ? ' target="' . esc_attr( $item->target     ) .'"' : '';
        $attributes .= ! empty( $item->xfn )        ? ' rel="'    . esc_attr( $item->xfn        ) .'"' : '';
        $attributes .= ! empty( $item->url )        ? ' href="'   . esc_attr( $item->url        ) .'"' : '';

        $item_output = $args->before;
        $item_output .= '';
        $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;

        if ( 'primary' == $args->theme_location ) {
            $submenus = 0 == $depth || 1 == $depth ? get_posts( array( 'post_type' => 'nav_menu_item', 'numberposts' => 1, 'meta_query' => array( array( 'key' => '_menu_item_menu_item_parent', 'value' => $item->ID, 'fields' => 'ids' ) ) ) ) : false;
            $item_output .= ! empty( $submenus ) ? ( 0 == $depth ? '' : '' ) : '';
        }
        $item_output .= '';
        $item_output .= $args->after;

        $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
    }
}

This code will add a  to top-level menu items from the menu selected for the primary theme location in case that this menu item has any child items.
Comment: hey thanks nikola, I totally need it to be like is has parent then $item_output the following, can it be done please???? :)
Comment: Sorry, I couldn't really understand what you meant :) I thought that you initially wanted to just add `` inside of the `a` tag. Can you try to explain(with an example would be best) again what you want :)
Comment: if has parent or if has sub-menu then it outputs the following code, what would i add, what do you suggest?
Comment: would i add this at the top?    **if($depth > 0)
           return parent::end_lvl(&$output, $depth);**
Comment: Okay, I edited the code from my answer - it tries to pull a child menu of the current menu item and will add the spam only if: 1) this menu is the "primary" theme location menu AND 2) this is a top-level menu item AND 3) there are sub-menu items for this item. Please try the code and see if it works. If it doesn't I'll be able to reply tomorrow though, since I'm going to bed now :) Hope it works.
Comment: and it would be even awesomer if you can add another output if it sub-menu li has a sub-menu :)
Comment: Sure, do you want to have the same span in second-level menus? Maybe we can just make it to have a span as long as it has a sub-menu, regardless of the depth of the item. This way you won't have to worry about if you decide to add another level of sub-menus :)
Comment: Can you try again? This time a top-level item with sub-menus will get a span with class `arrow` and a second-level item with sub-menus will get a span with class `sub-arrow`.


Proving $\Bbb{H\otimes_R C }\cong M_2(\Bbb{C})$ versus proving $\Bbb{H\otimes_R C }\cong_{\mathbb R} M_2(\Bbb{C}).$

Question: 1- Is there a difference between saying  I want to prove this $\Bbb{H\otimes_R C }\cong M_2(\Bbb{C})$ and I want to prove this $\Bbb{H\otimes_R C }\cong_{\mathbb R} M_2(\Bbb{C})$?
I see the OP in the question titled " Why is $\mathbb{H} \otimes \mathbb{C} \cong \text{End}_{\mathbb{C}} (\mathbb{H})$ " here on this site just asked about  $\mathbb{H} \otimes \mathbb{C} \cong \text{End}_{\mathbb{C}} (\mathbb{H})$ without specifying the isomorphism he required is of $\mathbb R-$algebras or $\mathbb C-$algebras and he got an isomorphism as complex algebras of $\Bbb{H\otimes_R C }\cong M_2(\Bbb{C})$ .
My second question is there a different isomorphism as $\mathbb R-$ algebras of $\Bbb{H\otimes_R C }\cong M_2(\Bbb{C})$ or can I consider the same isomorphism?
Answer: Those two statements are technically different, and the second (an iso as $\mathbb{R}$ algebras) implies the first, so we might expect it to be harder to prove.
However in this instance, any isomorphism you think of will be an isomorphism of $\mathbb{R}$ algebras. It can be helpful to instead think of this kind of thing as:

Find an isomorphism between your structures, preserving as little as possible.
Find out what extra properties your isomorphism preserves.

In this case, once you do step 1, you just need to check whether the complex vector space structure is preserved.
One can give isomorphisms of algebras that dont respect all the potential choices of "underlying scalars" however, eg, consider pointwise complex conjugation on $2\times 2$ complex matrices. This is a morphism of $\mathbb{R}$ algebras, but not of $\mathbb{C}$ algebras.
Comment: Yep, being an isomorphism as $\mathbb{R}$ algebras is asking for the map to respect multiplication by real number scalars, so since it respects complex number scalars, it will certainly respect real ones (since $\mathbb{R}$ is contained in $\mathbb{C}$).
Comment: This is the linear map from $2\times 2$ complex matrices to itself that just conjugates each entry, so for instance the digaonal matrix with values $1+i $ goes to the diagonal matrix with values $1-i $.
Comment: So the isomorphism given to the OP in the accepted answer can be considered as an isomorphism as $\mathbb R-$ algebras?
Comment: can you please write the pointwise complex conjugation on $2 \times 2$ complex matrices explicitly to me?
Comment: Thanks for your very lucid answer :)


Visual studio save development state

Question: Is there any Visual Studio addin/thing that will save the current set of open windows, bookmarks, and breakpoints, etc? Whenever I return to an issue, it takes a while to find reopen the appropriate classes, reset breakpoints, etc. Something that could load previously saved states for each issue would save a lot of time on issues that need to be readdressed several times in response to feedback.
Comment: Oops, sorry, I meant saving states for different items, then being able to load them when you need to return.
Comment: As far as I know, it already does that, saving these details in the `.user` and `.suo` files. See this: http://stackoverflow.com/questions/72298/should-i-add-the-visual-studio-suo-and-user-files-to-source-control
Answer: As stated on visualstudio.uservoice such a feature kinda exists. You can group breakpoints by labeling them in the breakpoints window and then perform actions on group level. Those actions include enable/disable and even import/export. As the msdn link on that uservoice spage is already down, you should check the archived page.
Answer: Oded hinted at the answer here.  Save off those files, particularly the .suo file (for your breakpoints and windows) at the moment you need that snapshot.  Restore it (Open/Close solution as required) when you want those windows and breakpoints set as they were at the time of the file save.
Comment: Although this works it has other implications and the user experience sucks - a typical workaround, but only a workaround. A "debug session state" incl. all breakpoints nice integrated in the UI shure makes sense. Sounds like a job for uservoice...

Visual studio save development state


What is the difference between HTML tags and elements?

Question: I notice that most people use the words HTML tags and HTML elements interchangeably.
But what is the difference between them?
The way I see it is that tags are in the source code and elements are processed tags (by the browser) in the DOM. Am I wrong?
Comment: valid question even in 2020 and will remain in 2040 as well :)
Answer: HTML tag is just opening or closing entity. For example:

 and
  are called HTML tags
HTML element encompasses opening tag, closing tag, content (optional for content-less tags)
Eg:

This is the content
 : This complete thing is called a HTML element
Comment: This is a great answer because one expects something esoteric or even a little complicated, but instead it's just a really useful specialization of vocabulary for good granularity when speaking about HTML.  Does anyone know if these terms also apply to XML?
Comment: @YuvrajPatil it's both. It's a tag without content, and it's an element too
Comment: then what about  ? Is it a html tag or html element ?
Comment: @YuvrajPatil Also known as a ["empty element"](https://developer.mozilla.org/en-US/docs/Glossary/empty_element). I believe in the past they were also referred to as "void" or "self-closing" tags.
Comment: @JuanMarco This is speculating, but one would assume that the empty element / self-closing tag distinction maps over the above element/tag distinction, right? That is, an empty element *is defined by* a self-closing tag.
Answer:
HTML tags vs. elements vs. attributes
HTML elements
An element in HTML represents some kind of structure or semantics and generally consists of a start tag, content, and an end tag. The following is a paragraph element:

This is the content of the paragraph element.

HTML tags
Tags are used to mark up the start and end of an HTML element.

HTML attributes
An attribute defines a property for an element, consists of an attribute/value pair, and appears within the element's start tag. An element's start tag may contain any number of space separated attribute/value pairs.
The most popular misuse of the term "tag" is referring to alt attributes as "alt tags". There is no such thing in HTML. Alt is an attribute, not a tag.

Source: 456bereastreet.com: HTML tags vs. elements vs. attributes
Answer: lets put this in a simple term. An element is a set of opening and closing tags in use.
Element

...

Tag
H1 opening tag

H1 closing tag

Comment: just curious, is html class considered a form of html element?
Comment: My answer is yes. like  i said, above an "opening tag, its content and the closing tag" is called an element.
content... So yes html is a tag but put together with opening and closing tag it becomes and element.
Answer: HTML Elements
An HTML element usually consists of a start tag and end tag, with the content inserted in between:
<tagname>Content goes here...</tagname>

The HTML element is everything from the start tag to the end tag.
Source
HTML Attributes
An attribute is used to define the characteristics of an HTML element and is placed inside the element's opening tag. All attributes are made up of two parts: a name and a value.

All HTML elements can have attributes
Attributes provide additional information about an element
Attributes are always specified in the start tag
Attributes usually come in name/value pairs like: name="value"
Source

HTML Tag vs Element
"Elements" and "tags" are terms that are widely confused. HTML documents contain tags, but do not contain the elements. The elements are only generated after the parsing step, from these tags.
Source: wikipedia > HTML_element
An HTML element is defined by a starting tag. If the element contains other content, it ends with a closing tag.
For example
 is starting tag of a paragraph and
 is closing tag of the same paragraph but
This is paragraph
 is a paragraph element.
Source:tutorialspoint > html_elements
Answer: Html Elements:
An Html Element consists of an opening and closing tag with the content inserted in between:
For Example:

HTML Element

Html tag:
The HTML tag is just an opening or closing entity.
For Example:

 and
 are called Html tags.
Answer: http://html.net/tutorials/html/lesson3.php

Tags are labels you use to mark up the begining and end of an element.
All tags have the same format: they begin with a less-than sign "<" and end with a greater-than sign ">".
Generally speaking, there are two kinds of tags - opening tags:  and closing tags: . The only difference between an opening tag and a closing tag is the forward slash "/". You label content by putting it between an opening tag and a closing tag.
HTML is all about elements. To learn HTML is to learn and use different tags.

For example:

Where as elements are something that consists of start tag and end tag as shown:

Heading

Answer: Tags and Elements are not the same.
Elements

They are the pieces themselves, i.e. a paragraph is an element, or a header is an element, even the body is an element.  Most elements can contain other elements, as the body element would contain header elements, paragraph elements, in fact pretty much all of the visible elements of the DOM.
Eg:

This is the Home page

Tags

Tags are not the elements themselves, rather they're the bits of text you use to tell the computer where an element begins and ends.  When you 'mark up' a document, you generally don't want those extra notes that are not really part of the text to be presented to the reader. HTML borrows a technique from another language, SGML, to provide an easy way for a computer to determine which parts are "MarkUp" and which parts are the content. By using '<' and '>' as a kind of parentheses, HTML can indicate the beginning and end of a tag, i.e. the presence of '<' tells the browser 'this next bit is markup, pay attention'.
The browser sees the letters '' and decides 'A new paragraph is starting, I'd better start a new line and maybe indent it'. Then when it sees '' it knows that the paragraph it was working on is finished, so it should break the line there before going on to whatever is next.
 - Opening tag.
 - Closing tag
Answer: This visualization can help us to find out difference between concept of element and tag (each indent means contain):
- element

        - content:

            - text

            - other elements

            - or empty

        - and its markup

            - tags (start or end tag)

                - element name

                - angle brackets < >

                - or attributes (just for start tag)

                - or slash /

Answer:
Here is a quote from WWF's website:
.

In this part
 is a tag.

facebook is the world's largest socialsite..

in this part
 is an element.
Comment: This doesn't really seem to answer the question.


Change part of excel formula with a constant value

Question: I have an excel formula across a column for which the base changes every "x" number of rows. Note this "x" is not constant and keeps changing. e.g.
=D1/SUM(D$1:D$4)
=D2/SUM(D$1:D$4)
=D3/SUM(D$1:D$4)
=D4/SUM(D$1:D$4)
=D5/SUM(D$5:D$9)
=D6/SUM(D$5:D$9)
=D7/SUM(D$5:D$9)
=D8/SUM(D$5:D$9)
=D9/SUM(D$5:D$9)

I am trying to change the first part of the formulas without changing the second and vice versa. e.g. changing the numerator by 10 cells.
=D11/SUM(D$1:D$4)
=D12/SUM(D$1:D$4)
=D13/SUM(D$1:D$4)
=D14/SUM(D$1:D$4)
=D15/SUM(D$5:D$9)
=D16/SUM(D$5:D$9)
=D17/SUM(D$5:D$9)
=D18/SUM(D$5:D$9)
=D19/SUM(D$5:D$9)

or, changing the base by 100. e.g.
=D1/SUM(D$100:D$104)
=D2/SUM(D$100:D$104)
=D3/SUM(D$100:D$104)
=D4/SUM(D$100:D$104)
=D5/SUM(D$105:D$109)
=D6/SUM(D$105:D$109)
=D7/SUM(D$105:D$109)
=D8/SUM(D$105:D$109)
=D9/SUM(D$105:D$109)

Sometimes, both. Any guidance on how this can be possible?
Thank you.
Comment: One time, but it is such a long list of formulas that i dont want to change every cell by a constant value manually
Comment: Do you want to do it one time? or is it supposed to change like once a week?
Comment: how many distinct ranges (denominators) are there?
Comment: @Jon, 3 segments, each having 10. So 30 in total.
Answer: the first part of this problem seems easy unless I am missing something?
Part 1:
Since the denominator is already in $x form, you can select and COPY the whole range of formulas and PASTE them 10 rows down and then CUT and paste it back into position.  The COPY will update the numerators appropriately and when you CUT and PASTE it back into position they will now be just as you want?  The second question will be a bit more of a challenge!
Part 2:
OK without VBA I can only think of a really long-winded way to change your demoninators, but I just checked that it does work:
To change the bottom.

Search and replace = with '=

Now you can edit the formulas more freely.

Search and replace D with D%
Search and replace D%$ with D
Search and replace D% with D$
get rid of the '= by using the Data>text to columns option
Now use the copy and paste, cut paste trick from part 1.

Then if you still need your $s back as they were you essentially repeat 1 to 5 again.
Sorry, this looks really long-winded, but if you are desperate and back up before you start it should work.
Answer: An excel formula can't replace another cells excel formula... One approach is to make the formula into text and then transform it by other formulas. When transformation is done, you could paste the formula back.
So for changing the D1 -> D11, I would build a dummy series (column K) then write a formula (cell L1). Then I can copy the formula and paste it into the correct column.
Replaceing the "=", with a special character and then you can transform the formulas.
(Column F).
In Column I, the formula used is: =RIGHT(F1,LEN(F1)-FIND("/",F1))

For changing D$1 -> D$100, I think I just would copy and replace it by searching in "Formulas".

This approach can be feasible for acouple of hundred cells. If the list is very long, I would recommend some VBA solution, where you can grab a cells formula with .Range("A1").Formula


Multi-Class Logistic Regression

Question: Considering:
$z=Wx$
$y=softmax(z)$
$L_{CE}(t,y)=-t^{-T}\log y = \sum_{k=1}^{K} t_k \log y_k$
Where the output $t$ is a one-hot encoding of the output.
I am trying to figure out a way to compute $\frac{\partial y_k}{\partial z_{k^\prime}}$ for any $k,k^\prime = 1,...,K$ where $k$ and $k^\prime$ may or may not be the same.
I know that $k$-th component of $y$ is: $y_k = softmax(z_1,...,z_K)_k = \frac{exp(z_k)}{\sum_{k^{\prime}=1}^{K} exp(z_{k^\prime})}$ but I am not quite sure how to proceed.
Additionally, what would be $\frac{\partial L_{CE}(t,y(x;W))}{\partial w_k}$?
Answer: If I understand your problem correctly, we have two cases:
If $k=k'$, then
\begin{equation*}
\frac{\partial y_k}{\partial z_{k'}} = \frac{\partial}{\partial z_{k'}} \frac{e^{z_{k'}}}{\sum_{j=1}^K e^{z_j}} = \frac{e^{z_{k'}}}{\sum_{j=1}^K e^{z_j}} - \frac{e^{z_{k'}}}{\left(\sum_{j=1}^K e^{z_j}\right)^2}e^{z_{k'}} = y_k - y_k^2.
\end{equation*}
If $k\ne k'$, then
\begin{equation*}
\frac{\partial y_k}{\partial z_{k'}} = \frac{\partial}{\partial z_{k'}} \frac{e^{z_{k}}}{\sum_{j=1}^K e^{z_j}} = -\frac{e^{z_k}}{\left( \sum_{j=1}^K e^{z_j} \right)^2}e^{z_{k'}} = -y_k y_{k'}.
\end{equation*}
Comment: gotcha: then what would $\frac{\partial L_{CE}(t,y(x;W))}{\partial w_k}$ be?

Multi-Class Logistic Regression


For loop stop when number is reached

Question: car_names = driver.find_elements_by_xpath('//h2[@class="vehicle-item__title"]')
carnamelist = []
for cars in car_names:
    # print(len(cars))
    carnamelist.append(cars.text)
    # print((len(car_names)))

car_names are now 50, but I would like to stop when it reaches 17
How can I achieve that?
Answer: One approach would be to zip with a range of 17 (zip stops automatically when either input is exhausted):
for cars, _ in zip(car_names, range(17)):
    carnamelist.append(cars.text)

Another would be to break in your loop:
for cars in car_names:
    carnamelist.append(cars.text)
    if len(carnamelist) >= 17:
        break

My approach would be to use zip and make it a list a comprehension:
carnamelist = [cars.text for cars, _ in zip(car_names, range(17))]

If car_names is a list (or anything else that supports slicing) you can do this much more simply with a slice:
carnamelist = [cars.text for cars in car_names[:17]]

Comment: Ok thx a lot for these tips. I forgot to mention that this number 17 is dynamic. It changes every other scrape run.

For loop stop when number is reached


EF Core resursive model - order alphabetically on the same level

Question: We are using .NET Core 3.1 and Microsoft.EntityFrameworkCore 3.1.9. We have the following recursive database model:
[Table("category", Schema = "test")]
public partial class Category
{
    public Category()
    {
        InverseIdParentNavigation = new HashSet<Category>();
    }

    [Key]
    [Column("id")]
    public int Id { get; set; }

    [Column("id_parent")]
    public int? IdParent { get; set; }

    [Required]
    [Column("name")]
    [StringLength(128)]
    public string Name { get; set; }

    [ForeignKey(nameof(IdParent))]
    [InverseProperty(nameof(Category.InverseIdParentNavigation))]
    public virtual Category IdParentNavigation { get; set; }

    [InverseProperty(nameof(Category.IdParentNavigation))]
    public virtual ICollection<Category> InverseIdParentNavigation { get; set; }
}

How can we order categories alphabetically by Name at the same level (inside InverseIdParentNavigation)? Example of result:
Root_1
    j
    k
    l
Root_2
    a
    b
        a
        b
    c

Categories at the same level are ordered alphabetically:

Level 0: Root_1 < Root_2
Level 1: j < k < l and a < b < c
Level 2: a < b

How can we achieve this?
Answer: I haven't tested it, but it might be something like the following
public void RecursiveOrder(IEnumerable<Category> categories)
{
    var children = categories.OrderBy(x => x.Name);
    children.ForEach(u => RecursiveOrder(u.Child);
}


How do I override a single JavaScript file used in a library?

Question: I am trying to override the Search API autocomplete JavaScript file.
In mytheme.libraries, I added the following lines.
mytheme_autocomplete:
  js:
    'assets/js/autocomplete.js': { }

In mytheme.info, I added the following lines.
libraries-override:
  search_api_autocomplete/search_api_autocomplete:
    js:
      component:
        js/search_api_autocomplete.js: mytheme_autocomplete

When I visit the site, js/search_api_autocomplete.js is still loaded, while assets/js/autocomplete.js isn't loaded.
How do I override a single JavaScript file used in a library?
Answer: If you're overriding a single js file, you need to specify a file, not a library:
libraries-override:
  search_api_autocomplete/search_api_autocomplete:
    js:
      js/search_api_autocomplete.js: assets/js/autocomplete.js

However, specify your theme's library if you intend to override an entire library:
libraries-override:
  search_api_autocomplete/search_api_autocomplete: mytheme/mytheme_autocomplete

See the Overriding and extending libraries documentation on d.o
Comment: Thanks, I was able to override the whole library using your 2nd example, but could not override the single JS file in your first example/
Comment: I believe you may have added the extra "component" layer in the overrides definition. That should not be there as the search_api_autocomplete library does not specific the javascript that way. I updated the example with something that should work with that file.
Comment: Incidentally, I believe the component / theme / base, etc weights only apply to css files, not js files, i.e. js would never have component in its definition hierarchy. See https://www.drupal.org/node/2274843#library


how to prove that the curvature of sin x is greatest at its extremum?

Question: how to prove that the curvature of sin x is greatest at its extremum?  I've done several approaches but couldn't see a concrete solution that proves it well.
Comment: The curvature is measured by the second derivative.
Comment: @Arthur According to http://en.wikipedia.org/wiki/Curvature that is actually an approximation used when the slope is "small compared to unity"
Answer: The curvature $\kappa(x)$ of a curve $y=f(x)$ is given by
$$\kappa(x)={|f''(x)|\over(1+f'^2(x)\bigr)^{3/2}}\ .$$
When $y=\sin x$ one immediately gets the estimate
$$\kappa(x)\leq1$$
with equality iff $|\sin''(x)|=|\sin x|=1$ and $\sin'(x)=\cos x=0$.
Answer: It's easier to understand curvature ($\kappa$) by defining it as the multiplicative inverse of the radius of curvature ($1/\kappa$).
Take a point on a function (x, f(x)) and draw a line normal (i.e. perpendicular to the line tangent at that point) at that point; do the same for the point (x+h, f(x+h)) and calculate the point where they intersect (the point of intersection will approach the center of curvature as $h\to 0$). Now find the distance between the center of curvature and (x, f(x)). It may be productive to review the "trick" used in proving the product rule for derivatives (https://www.math.hmc.edu/calculus/tutorials/prodrule/proof.html).
You should end up with the formula on this page http://en.wikipedia.org/wiki/Radius_of_curvature_(mathematics)
I used the following diagram to help me the first time I tried it.

That being done, it's just a simple matter of optimizing the curvature function ($\kappa(x)$) for the sine function.


Are my data paired or not paired for a t-test?

Question: I am analyzing data where my experimental design is as follows:
DNA and RNA samples were taken from 3 mesocosms at seven time points across the duration of the study to see DNA and RNA decay across time.
For example:
At time point 1, 1 DNA and 1 RNA sample was taken from each mesocosm (total 3 samples of DNA, 3 samples RNA for each time point).
My understanding is that when I do a pairwise t-test for DNA and RNA at each time point, I say that DNA and RNA are NOT paired:
data.type = DNA or RNA
count = copies of DNA or RNA recovered
dataset %>%
  group_by(timepoint) %>%
  pairwise_t_test(
    count ~ data.type, paired = FALSE,
    p.adjust.method = "BH")

However, since I am doing repeated measures in the same mesocosms over time, when I do pairwise comparisons of DNA/RNA counts over time, my samples are paired:
dataset %>%
  group_by(data.type) %>%
  pairwise_t_test(
    count ~ timepoint, paired = TRUE,
    p.adjust.method = "BH")

I just want to make sure I am doing this correctly and not specifying if something is paired when it's not and vice versa.
Thanks!!
Answer: Each time period $t$ of measurement during the experiment can be considered  as an experimental unit. Given this, and the fact that each test unit (mesocosms) has two associated measurements (DNA and RNA), then this would make DNA and RNA a paired t-test.
Disclaimer: I do not have a applied professional experience in experimental study designs. Rather, just what I have learned through textbooks / papers.
Comment: Criticism to my thinking here is appreciated—thanks


Object doesnt support this property or method

Question: Why is it when i am looking at tutorials, or examples, when i just essentially do a cut and past onto my HTML page, i get the "Object doesnt support this property or method" on my page, but the site that i copied the script from does not give this error?
is my jQuery library old?
not sure what to do...
here is what i am working on...it is a multiple overlay page.
<map name="Map" id="Map">
  <area shape="poly" coords="90,63,128,110,150,95,177,80" href="#" class="bmhoverlay"  rel="#mies1"/>
  <Area shape="poly" coords="255,5,257,64,276,68,301,73" href="#" class="bhmoverlay"  rel="#mies2" />
</map>

Here is the CSS:
/* the overlayed element */
.simple_overlay {
  /* must be initially hidden */
  display:none;
  /* place overlay on top of other elements */
  z-index:10000;
  /* styling */
  background-color:#333;
  width:675px;
  min-height:200px;
  border:1px solid #666;
  /* CSS3 styling for latest browsers */
  -moz-box-shadow:0 0 90px 5px #000;
  -webkit-box-shadow: 0 0 90px #000;
}
/* close button positioned on upper right corner */
.simple_overlay .close {
  background-image:url(../img/overlay/close.png);
  position:absolute;
  right:-15px;
  top:-15px;
  cursor:pointer;
  height:35px;
  width:35px;
}

/* styling for elements inside overlay */
.details {
  position:absolute;
  top:15px;
  right:15px;
  font-size:11px;
  color:#fff;
  width:150px;
}
.details h3 {
  color:#aba;
  font-size:15px;
  margin:0 0 -10px 0;
}

And calling the script to the page:

but every time i generate this page, i get the "object doesnt support this property or method"..???
anyone?
i am using jquery library 1.3.2
Comment: If you get an answer you like, be sure to "accept" it!
Answer: jQuery doesn't have a .overlay() function.  Are you sure you have included the same plug-ins that the site you're basing it off of does?
here's one such overlay plugin:
jQuery Tools Overlay
Comment: Thats the same site i am using the script from.  I thought i was calling the plugin correctly in my  tag:

is that not the proper way?
Comment: Ok, just tested again, and it works in FF but not in IE8... but keep in mind, when i visit the jQuery Tools Overlay site with IE8, it works fine.  i am confused.
Comment: Problem Solved.  I had to essentially put the .js plugin file on my server.  IE8 was creating a https error, and when i would click "yes" it would throw the error.
Comment: What a nasty bug.. This happend to me as well
Answer: jQuery doesn't include an overlay() function by default. You'll need a plugin for that, like one of the ones here.