How Can I Replicate The Sound Of An Instrument?

Question: I have experience of basic music theory, guitar and piano. My current project involves creating a computer program that can replicate the sounds of any given instrument (starting with piano).
I can quite easily play the correct notes and chords, but am not sure how to make it sound right.
By this I mean, 440Hz is an A but it does not sound like playing an A on a piano... it sounds fake.
So what other things do I need to look into so that my chords sound like they are being played on a real instrument?
Comment: Getting it to *really* sound like a real instrument will be extremely difficult, and piano is probably one of the most difficult instruments to imitate given its complexity. Search for "software sound synthesis" to get a general idea of what's involved in it.
Comment: software synthesis is a big topic.  I'd recommend looking at http://sourceforge.net/apps/trac/fluidsynth  The math is weird for software synthesis.  And usually you write a softsynth in c++.  Good luck to ya.
Comment: After the piano, try replicating say [Elisabeth Schwarzkopf](http://www.youtube.com/watch?v=gJV_nY2CoqQ)'s voice when she things an A. Parameters could be age, 3D-model of her upper body, whether she enjoyed her breakfast that day, (whether the listener enjoyed his breakfast that day) ... You see: perhaps can't be done (plus leave some room for magic :)
Answer: This is an extremely broad topic, so I'm going to try to distill it down to just a handful of points:
There are (basically) two ways of generating sounds electronically: sampling and synthesis. Confusingly, we tend to call all of this sound generation "synthesis", as you are generally working with a "synthesizer".
You will want to read Wikipedia - Synthesizer, but here are some cliff notes:
Sampling is when you literally record the sound of the instrument you want to play into a digital waveform (how all audio is stored digitally), and your software plays back the waveform (or sample), but tweaks it according to how you want it to be played back, either with pitch shifting, looping, or modulation. You can have as few as one sample for an entire digital instrument, or as many as multiple samples for every single note on the keyboard for different dynamic levels or qualities of attack. Nearly all digital pianos use high-quality samples to generate sound, and there are very expensive libraries of orchestral samples that one can purchase if they need to synthesize a full orchestra.
Synthesis: Sampling is technically one type of synthesis. Other types (rather than play back recordings of a particular sound) generate basic waveforms like a sine wave, square wave, and sawtooth wave, often at different frequencies, and add them together while passing them through various filters and other effects to result in a distinct waveform that represents a timbre, or quality of sound. When you are trying to replicate acoustic instruments this way, you call it "imitative synthesis". Usually, though, one would use this kind of synthesis to generate sounds that cannot be generated by an acoustic instrument. Sampling technology is far more effective at replicating acoustic sounds than imitative synthesis.
Based on your question, it sounds like you are trying to achieve imitative synthesis. I'm not sure what you mean by your A sounding "fake" -- if it's at 440Hz, it's just as real of an A as any other A, but chances are it just sounds like a sine wave.
For an extremely simple exercise for the reader, try synthesizing an "organ" sound by playing your 1 amplitude 440Hz sine wave and a .2 amplitude 660Hz sine wave at the same time. It's a long way from there to a piano. You'll want to look at the waveform for a single acoustic piano note (using a waveform editor like Audacity), compare it to what you're generating with your software, and then figure out how to best tweak your software to approach the acoustic piano waveform.
It would also be a good idea to become familiar with some real audio synthesis software first, like Reason, Csound, Max/MSP, or Pure Data. You'll also want to read up on the harmonic series.
Comment: Also http://music.stackexchange.com/questions/7141/math-formulae-for-organs
Comment: Also relevant software in this case is [Pianoteq](http://www.pianoteq.com/)
Comment: That is a great answer, thank you. I am not making this for any commercial usage or anything, just as a demo and to learn from, so realism is not completely required.

I just want to improve the sound, so think I will start by doing the organ synthesis that you mentioned as that looks simple.

Does an electronic keyboard use sampling or synthesis?
Comment: "Electronic Keyboard" is a bit ambiguous. As I say in my answer, digital pianos (fully weighted, 88-key keyboards) use sampling. Lower-end keyboards of various kinds will use less complicated sampling. High-end virtual analog synth workstations (like a Nord keyboard) would have a library of sampled sounds, plus a suite of features to synthesize other timbres. Pure analog synths (like the miniMoog) do not have any samples.
Comment: There are other types of non-sampling synthesis besides additive and subtractive (FM is widely used and granular is technically something different), plus there's modeling synthesis which is like a hybrid of pure samplying and pure synthesis, but great answer overall.
Answer: You need to reproduce the full spectrum for each note and model the way the amplitude (and harmonic mix) varies over time.
See Analysis and Parametric Synthesis of the Piano Sound
For accurate reproduction you also need to take into account complex effects such as induced vibrations in other undamped strings.
Answer: This is a complicated topic. Julius Smith has a book about physical audio synthesis. The section on piano hammers has some decently heavy math. In order to make the chords sound like they are being played on a piano, you have some options:

Correctly model all aspects of a piano (hammer, string, other strings, soundboard, etc.). This is hard.
Record what you want and play it back. Somewhat easier.
Model only a few physical effects and get something pretty close.
Answer: In case actual sound synthesis is not what you are aiming for, but rather your program is about controlling potentially existing sounds, then perhaps what you want to do is to program using some MIDI API. This way you don't have to create the sounds yourself - instead you can control the sounds available of a software, or of a physical, synthesizer.
If this is the case you'll ikely also want to take advantage of the General MIDI scheme which includes a standardized specification of standard sounds (such as piano, violin, guitar, trumpet...) controllable through MIDI.


Hausdorff Dimension Infinity

Question: What are some examples of non-trivial metric spaces that have Hausdorff Dimension of infinity?
I could only think of $\mathbb{R}$ with the discrete metric.
Comment: [This frequent Mathematics Stack Exchange user's](https://math.stackexchange.com/users/21361/mark-mcclure) [Ph.D. dissertation](https://www.marksmath.org/scholarship/dissertation.pdf) is a good place to look. (Hope he doesn't mind my pointing this out!)
Comment: @DaveL.Renfro No problem!
Answer: Take the separable Hilbert space of infinite dimension
$$
\ell^2=\{(a_n)_{n\in\mathbb{N}}\subseteq \mathbb{R}:\sum_{n\in\mathbb{N}}a_n^2<\infty\}
$$
Comment: +1 Did you know that the subset of $\ell^2$ with all rational coordinates has Hausdorff dimension 1? One of my [favorite results of Erdos](https://users.renyi.hu/~p_erdos/1940-11.pdf).
Comment: No, I never studied the Hausdorff measure in depth. It's an interesting result, thanks for share it!

Hausdorff Dimension Infinity


In Table Tennis, does a 7-0 lead mean that set is won?

Question: Suppose we are playing a match/set for 11 points with 2 serves each. If one team get a lead of 7-0, does that mean that the team won that match/set?
What is the case for a match/set for 21 points? 11-0?
Answer: Nothing happens (officially).
According to the ITTF Rules:

2.11 A Game
A game shall be won by the player or pair first scoring 11 points
unless both players  or  pairs  score  10  points,  when  the  game
shall  be  won  by  the  first player or pair subsequently gaining a
lead of 2 points.

In unofficial matches there may be a so-called mercy rule (or skunk rule), which may end a game after a 7-0 lead or other standings. Since no official rule about this exists any longer the requirements may vary.
The USATT also has some extra basement rules (they're not real rules!) which still include a skunk rule:

12.1 Scores of 7-0, 11-1, 15-2, and 21-3 are game winning "skunks". As if being "skunked" isn't bad enough, the skunkee may also be
required to perform push ups or drink two beers.
12.2 The loser of a game is required to drink a beer. In the event of a "skunk" the loser must drink two beers.


Year string in Javascript

Question: I am totally new to javascript and I have a very easy to answer question: How do I use a current year string?
Should I look like this?
var currentyear = now.getYear();

And then I want to use that string in the following code snippet (The string should always replace the 2011)
drawDayEvents('2011-12-27', '#day1');
drawDayEvents('2011-12-28', '#day2');
drawDayEvents('2011-12-29', '#day3');
drawDayEvents('2011-12-30', '#day4');

...

var start = new Date(2011, 12-1, 27);
var end = new Date(2011, 12-1, 31);
if((time < start) || (time > end)) {
time.setYear(2011);

Does it has to be like this?
var currentyear = now.getYear();

drawDayEvents('$currentyear-12-27', '#day1');
drawDayEvents('$currentyear-12-28', '#day2');
drawDayEvents('$currentyear-12-29', '#day3');
drawDayEvents('$currentyear-12-30', '#day4');

...

var start = new Date($currentyear, 12-1, 27);
var end = new Date($currentyear, 12-1, 31);
if((time < start) || (time > end)) {
time.setYear($currentyear);

Answer: You can get the year like this:
var yr = new Date().getFullYear();

then use the + (string concatenation) operator to join it to another string:
drawDayEvents(yr + "-12-27", "#day1");

Answer: You should use getFullYear() instead because getYear() will return the year minus 1900.
var currentyear = now.getFullYear();

In this line:
drawDayEvents('$currentyear-12-27', '#day1');

JavaScript can't interpolate variables like PHP can.  You need to concat the strings.
drawDayEvents(currentyear+'-12-27', '#day1');

Variables in JavaScript don't need to be prefixed with $ (they can contain a $ if you want).
var start = new Date(currentyear, 12-1, 27);
var end = new Date(currentyear, 12-1, 31);
if((time < start) || (time > end)) {
  time.setYear(currentyear);
}

Docs for JavaScript Date: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
Comment: var currentyear = now.getFullYear(); ? is $currentyear right or not?
Comment: `now` isn't a keyword either.
Comment: `time` is not declared, either. Suppose that and `now` should be clarified.
Comment: @MichealPerr: No, `$currentyear` is not right.  It's just `currentyear`, you don't need the `$`.
Comment: @JaredFarrish: I'm assuming that `time` and `now` were declared earler.
Comment: @JamesMontagne: I'm assuming he declared `now` earlier.
Comment: How do I found out the current year then when time and now isn't a keyword at all? No they weren't dclared earler I have no idea what I am doing :D
Comment: @MichealPerr: I figured you declared `now` earlier, if not do `var now = new Date;`.
Comment: @AdamRackis: There are different methods you can use to get the parts of the date you want.  Take a look at the docs: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date#Methods_2
Comment: @AdamRackis: `Date.now()` returns you the current [UNIX Timestamp](http://en.wikipedia.org/wiki/Unix_time).  You can add and subtract this to Date objects.  So, `var time = Date.now()` will get the current time.
Comment: @MichealPerr: Yeah, the JavaScript Date object is confusing.  That's why I suggest using a library, like [Datejs](http://www.datejs.com/).
Comment: No I know - I just now saw your comment saying you're assuming now was declared earlier.
Comment: @MichealPerr - See a working example: http://jsfiddle.net/RDzZC/ Note, you'll need Firebug or Chrome console open to see the output.
Comment: @JaredFarrish: You should log `time.toString()`.

Year string in Javascript


Post (or put) request with uri parameter not working when calling with HttpClient

Question: In trying to make a Web API in c# and consume it via c# HttpClient, I've already written some controllers and client calls and is working fine, but now I need to call a Post method with two parameters, one simple value (long) directly in the URL[FromURI], and the another one is a complex type passed in body.
I think I can simplify the answer, suppose I just want to call a post or put with one simple parameter passed in the URL.
First of all, lets see my web server mapping config:
HttpConfiguration config = new HttpConfiguration(); config.Routes.MapHttpRoute(
                    name: "DefaultWebApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional });

And thats my Put controller:
 [HttpPut]
 public IHttpActionResult PutComandas([FromUri] long ticket)
 {
 ...
 }

I can call this without problem using PostMan and URL like localhost:8200/api/Comandas?ticket=9, but I can't find a way to do that call with HttpClient, also, it's strange to me that I can not simply call (in PostMan) to localhost:8200/api/Comandas/9 as I can do with get requests... is like the routing configuration is working for gets, but not for puts/posts...  Anyway, the real problem is: I can't find the way to do a correct put call with HttpClient. I'm trying:
HttpClient client = new HttpClient();
var response = client.PutAsync("localhost:8200/api/Comandas?ticket=9", null).Result;

but I receive a Not Found response.
Note: I can call Put/Post with complex body parameters without problems.
Comment: do not use `.Result` for stability reasons [see here...](https://josefottosson.se/you-are-probably-still-using-httpclient-wrong-and-it-is-destabilizing-your-software/) and [here](https://github.com/davidfowl/AspNetCoreDiagnosticScenarios/blob/master/AsyncGuidance.md)
Comment: You might want to do `client.PutAsync("http://localhost:8200/api/Comandas?ticket=9", null);`
Comment: Yes, i'm a newbie but i read something about don't use .Result, anyway, it does not work
Answer: A cleaner way would be to use a Dictionary and pass as FormUrlEncodedContent
var url = "localhost:8200/api/Comandas";
var parameters = new Dictionary<string, string> { { "ticket", "9" } };
var encodedContent = new FormUrlEncodedContent(parameters);

var response = await client.PutAsync(url, encodedContent);

Also as a side note, HttpClient should only be instantiated once and then re-used: https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.7.1#Remarks
EDIT: User has now clarified they are looking for both a Uri param and a Body param. Following on from code above:
AddQueryString is available through
Microsoft.Owin.Infrastructure.WebUtilities.AddQueryString()

or if using .NET Core
Microsoft.AspNetCore.WebUtilities.QueryHelpers.AddQueryString()

var url = "localhost:8200/api/";
// Query string parameters
var parameters = new Dictionary<string, string>(){ { "ticket", "9" } };

// Create json for body
var content = new JObject(yourBodyObject);

// SetupHttpClient
client.BaseAddress = new Uri(url);

// This is the important bit
var requestUri = QueryHelpers.AddQueryString("Comandas", parameters);

var request = new HttpRequestMessage(HttpMethod.Put, requestUri);
// Setup headers for Content-Type
request.Headers.Add("Accept", "application/json");
// Add body content
request.Content = new StringContent(
    content.ToString(),
    Encoding.UTF8,
    "application/json"
);

// Send the request
client.SendAsync(request);

Comment: but your solution uses body content encoded like url content. My goal is to be able to call something like: Post([FromUri] long ticket, [FromBody] ComplexType details)... i can do this calling the api with PostMan


How can I emit events to connected sockets using socket.io from within my Express 4 routes?

Question: This is a question other people have asked, but I can't manage to benefit from the answers they've been given, due to the different Express setup I have.
I've got socket.io implemented and working in a simple way on my server. This is how it works:
In bin/www:
#!/usr/bin/env node
var debug = require('debug')('gokibitz');
var app = require('../../server');

app.set('port', process.env.PORT || 3000);

var server = app.listen(app.get('port'), function() {
    debug('Express server listening on port ' + server.address().port);
});

var io = require('socket.io').listen(server);

io.on('connection', require('../routes/socket.js'));

All my routes and other Express setup is in ../../server.js.
var routes = require('./server/routes/index');
var user = require('./server/routes/user');
...

app.use('/', routes);
app.use('/api/user/', user);
...
app.use('*', routes);

Then in ../routes/socket.js, I've got this boilerplate:
module.exports = function (socket) {
    socket.emit('send:news', { hello: 'world' });

    setInterval(function () {
        socket.emit('send:time', {
            time: (new Date()).toString()
        });
    }, 1000);

    return socket;
};

This is working beautifully, I might add. But now I want to be able to emit events from the various routes in my quite-ordinary Express app, and I can't for the life of me figure out the right way to get a reference to the socket object I need.
Example: when a user makes a comment, I'd like to emit an event to all connected users notifying them of the new comment. From my routes file (./server/routes/user.js), how can I get access to the object I need to emit events?
Here's a skeleton of the relevant bits from a route file:
var express = require('express');
var router = express.Router();

router.post('/', function (req, res) {
  ...
});

module.exports = router;

The only place I can access it is in the ../routes/socket.js file, which is useless.
All of the routes are set in a app.js before there's any io or socket object to pass in.
Should I be able to require('socket.io') and use it somehow to emit to all connected sockets?
Is there a sensible way to store the connected sockets on ../routes/socket.js so it can be required and emitted to from other routes?
Can anyone steer me in the right direction?
Comment: From a route, are you trying to broadcast a message to all connected users?  Or send only to the user that made the request on the route?  Who are you trying to send to from your route?  `io.emit(msg, data)` will send to all connected clients.  If you are doing this from another module, you will have to share the `io` variable to that other module.
Comment: I'm trying to broadcast a message to all connected users from a route. Example: a user adds a comment to a post. I'd like to broadcast a (namespaced) event to all users so that anyone viewing that post can listen for updates and have their page refresh with the new comment.

I know I need to share the io object, but I'm struggling to find the right way to do that with my setup.
Comment: In this last case, you need create a singleton returning the object or making this globally.
Answer: I was able to ultimately get things working using this example:
https://github.com/expressjs/generator/issues/45#issuecomment-53719435
I created a new file called server/io.js:
var io = require('socket.io')();

io.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

module.exports = io;

Then I updated server/bin/www to this:
#!/usr/bin/env node
var debug = require('debug')('gokibitz');
var app = require('../../server');
var io = require('../io');

app.set('port', process.env.PORT || 3000);

var server = app.listen(app.get('port'), function() {
    debug('Express server listening on port ' + server.address().port);
});

io.attach(server);

Then, in my route, I use this:
var io = require('../io');
...
io.emit(...);

The missing piece for me, at least, was the ability to create the io object separately, return the correct object, then use io.attach(server) inside bin/www to start it up at the right point.
Hopefully this will help someone else following in my footsteps.
Answer: I think you are confused with the concepts. The socket.io lib uses or emulate a websocket (bidirectional socket) with the client, and have not relation with routes.
You can send a notification to all sockets using the io object:
io.emit('message_to_all', true);

You have to an array on io.sockets, with all sockets.
You can uses namespaces or rooms to, I recomend you learn the documentation:
http://socket.io/docs/rooms-and-namespaces/#
Add something:
If you want to send a message to all people in the same route, you can join to a channel with the same name of the path.
For example, in the client:
var socket = io(window.location.href); // Or route..

And the server:
var nsp = io.of('/the/specific/route');
nsp.on('connection', function(socket){
  // ...
});
nsp.emit('message_to_all_in_route', data);

About the last question editing:
You can send the io object in request or response object to routes, using the Express midleware API:
For example:
#!/usr/bin/env node
var debug = require('debug')('gokibitz');
var app = require('../../server');

app.set('port', process.env.PORT || 3000);

var server = app.listen(app.get('port'), function() {
    debug('Express server listening on port ' + server.address().port);
});

var io = require('socket.io').listen(server);

app.use(function (req, res, next) {
  res.io = io;
  next();
});

io.on('connection', require('../routes/socket.js'));

And in the route:
route.post('/post/:id/comments', function (req, res) {

   // Do your logic

  var postio = res.io.of('/post/' + req.params.id);
  postio.emit('new_comment', commentData);

});

Comment: Using the `io` object seems straightforward, but I don't know how to properly share the `io` object so that my routes in separate files can use it.
Comment: With the namespaces (like the example added in my response) you can define this routes with the io.of method.
Comment: I think we're talking past each other. I've updated my question to clarify how I'm struggling to get access to the object I need to emit events.
Comment: Your edit about using middleware looks like exactly what I need: let me make sure I can get it working.
Comment: It doesn't seem like the middleware is being called when it's added to `app` at that point: are you sure that it should work when added after the routes and after `app.listen`? Maybe I'm missing something.
Comment: Yeah, my routes get called *before* that middleware is added. It seems like the `/bin/www` structure created by the Express 4 generator causes so many problems.
Comment: The routes are called before the middleware definition, but the callbacks of the routes are called async after the server is running and the middleware are defined.
Answer: As I said in my comment, you can send to all connected clients with:
io.emit(msg, data);

This will require access to the io object that you created in your first module.  The usual way to share that with your module with your routes modeule would be to export a method from the routes module that lets you pass it the io object and then after you've required in the routes module and created the io object, you can just call that method to pass the io object to the routes module and it can save it locally for future use.
io is just a shared object like the app object is.  If you want a module to be able to use a shared object, the usual way is that you call some method in that module to share with it some objects that it can then use.
Comment: I'm afraid you're overestimating my ability to benefit from your general advice. I've updated my question with the structure of one of my route files: how would I modify it to get access to the `io` object in `bin/www`? I've tried adding `module.export.io = io;` to `bin/www` and `var io = require('../bin/www').io` to my route, but `io` is just undefined.
Answer: I have made a new file sockets.js in that file:
var socketio = require('socket.io');
var io;

module.exports = {
socketServer: function (app) {
    io = socketio.listen(app);

    io.on('connection', function (socket) {

        console.log(Object.keys(users));
        socket.on('message', function (data) {
            io.emit('updateChat', 'Hello World!')
        });
    });
  }
}

And in my app.js:
var express = require('express');
var app = express();
var http = require('http').createServer(app);
var port = process.env.PORT || 3000;

var io = require('./sockets').socketServer(http);
http.listen(port, function () {
    console.log('SERVER RUNNING.. PORT: ' + port)
});

This is working for me. Good Luck!


Java remover um item dentro de uma lista encadeada Simples

Question: Estou tendo dificuldades em gerar um código para remover um item de uma determinada posição em uma lista encadeada, isso nao eh um ArrayList, e sim uma lista encadeada, para isso estou criando um método conforme abaixo:
public Object remove(int posicao){

Sei que a criação é parecida com a do método na posição, mas não estou conseguindo desenvolver o método na forma de remover itens no meio da lista.
package slist;

import java.util.Scanner;

public class SList {

private SListNode head;
  private int tamanho;

  public SList() {
    tamanho = 0;
    head = null;
  }

  public boolean eVazio() {
    return tamanho == 0;
  }

  public int length() {
    return tamanho;
  }

  public void insereAntes(Object obj) {
    head = new SListNode(obj, head);
    tamanho++;
  }

  public void insereApos(Object obj) {
    if (head == null) {
      head = new SListNode(obj);
    } else {
      SListNode no = head;
      while (no.next != null) {
        no = no.next;
      }
      no.next = new SListNode(obj);
    }
    tamanho++;
  }

  public Object naPosicao(int posicao) {
    SListNode noAtual;

    if ((posicao < 1) || (head == null)) {
      return null;
    } else {
      noAtual = head;
      while (posicao > 1) {
        noAtual = noAtual.next;
        if (noAtual == null) {
          return null;
        }
        posicao--;
      }
      return noAtual.item;
    }
  }

  public Object remove(int posicao){

}

  public String toString() {
    int i;
    Object obj;
    String res = "[  ";

    SListNode atual = head;

    while (atual != null) {
      obj = atual.item;
      res = res + obj.toString() + "  ";
      atual = atual.next;
    }
    res = res + "]";
    return res;
  }

    public static void main (String[] args) {
    SList lst1 = new SList();
    SList lst2 = new SList();
    int escolha;
    Scanner opcao = new Scanner(System.in);

    do {
        System.out.println("Menu de opcoes \n"
        + "1 - Coloca na lista \n"
        + "2 - Mostra na Lista \n"
        + "3 - Listar conteudo de determinada posicao\n"
        + "4 - Remover conteudo de determinada posicao \n");

        escolha = opcao.nextInt();

            switch (escolha) {
                case 1: System.out.println(" Diga o nome do aluno");
                opcao.nextLine();
                String item = opcao.nextLine();
                    lst1.insereApos(item);
                    break;
                case 2: System.out.println("Listando os nomes da lista\n"
                                            + lst1.toString());
                    break;
                case 3: System.out.println("informe a posicao desejada");
                    int esc = opcao.nextInt();
                    System.out.println("Objeto na posicao " + esc + " " + lst1.naPosicao(esc));
                case 4:

            }
    } while (escolha <=4);
  }
}

E aqui a Class SListNode
package slist;

public class SListNode {
  Object item;
  SListNode next;

  SListNode(Object obj) {
    item = obj;
    next = null;
  }

  SListNode(Object obj, SListNode next) {
    item = obj;
    this.next = next;
  }

}

Comment: Só um comentário, se esta a utilizar java deveria utilizar as estruturas que ele dispõe que estão otimizadas para uma melhor performance.
Answer: Você só tem que fazer trocar a ligação removendo o atual e passar o próximo do atual ao predecessor.
A lógica é bastante simples:

Lista
{Nó-Anterior} -> {Nó a ser Excluído} -> {Nó posterior ao excluído}
Operação a ser feita:
{Nó Anterior}.next = {Nó posterior ao excluído}

Para isso modifiquei o seu método Object naPosicao() para retornar um nó da lista:
public SListNode getNo(int posicao) { //retorna direto um nó e não um objeto
    SListNode noAtual;

    if ((posicao < 1) || (head == null)) {
        return null;
    } else {
        noAtual = head;
        while (posicao > 1) {
            noAtual = noAtual.next;
            if (noAtual == null) {
                return null;
            }
            posicao--;
        }
        return noAtual; // única mudança real no método.
    }
}

Agora que já consegue obter os nós com esse método basta usá-lo para fazer a lógica que descrevi antes:
public void remove(int posicao) {
    try{
        SListNode predecessor = getNo(posicao - 1);
        SListNode excluido = predecessor.next;
        predecessor.next = excluido.next;
        excluido = null;  // Para tentar facilitar a exclusão para o garbage collector
    }catch(Exception e){
        e.printStackTrace();
    }
}

Repare que não excluí o objeto, pois isso não é possível fazer diretamente em Java, mas ao definir excluido = null; eu elimino as referências para que o mesmo seja pego (de uma forma mais explícita) pelo o garbage collector. É um passo não necessário, visto que a referência desaperecerá do programa apés esse método ser chamado, mas deixa claro que não se pretende utilizar o nó excluído novamente.
Comment: Funcionou perfeitamente, obrigado pela ajuda!


How to: If a user already exits, create the user with a "1" after their name -PowerShell Active Directory

Question: I have a script written here that checks if an AD already exists. If they do exist, then the script lets me know. If they don't, then it creates them:
<code>    if (Get-ADUser -F { SamAccountName -eq $username }) {

        # If user does exist, give a warning
        Write-Warning "A user account with username $username already exists in Active Directory."
    else {

##Then it carries on here with creating the user
</code>
What I'd like to do is, if they exist, create the user with the same naming convention, but put a "1" after their name. I know this sounds silly.... but I've been asked if that is possible.
And if they don't exist, well, carry on as usual and create them :)
Any help would be appreciated ladies and gents.
Thank you :)
Comment: [1] make the call against your AD to see if there are any with that basic user name. for example - `-like 'SmithJ*'`. [2] force the result to be an array by wrapping the call in `@()`. [3] if `$Result.Count` is not zero, grab the digit suffixes, sort to find highest, increment by 1, and finally use that number to create your new user name.
Answer: Within your if statement with the warning just add
<code>$username = $username + "1"
</code>
And then repeat the code in your else section.
Can always clean it up and place the create account code in a function and call it in each portion of the if statement.
Comment: Hi Aalom, thanks for your reply.

When I put the "$username = $username + "1" " in within the IF statement, it doesn't seem to do a great deal. It runs through the script as it should, then at the end it states WARNING: A user with username test.test1 already exists in the directory. And when I search AD, there is no one there with that name. What I need it to do is create a complete duplicate account to the one that's there, but just be "test.test1" instead of "test.test"

Appreciate the help
Comment: Did you make sure to have the code execute add-aduser after changing the $username variable? Im presuming your running in some kind of loop here, if so what does it look like?
Comment: Hey again,

I'll paste my script in an answer to the script so it's easier to read
Answer: ##full script##
<code>$ADUsers = Import-Csv C:\ps\usercreation.csv

$UPN = "METest.local"

foreach ($User in $ADUsers) {

    #Assign the data in the csv to a variable
    $username = $User.username
    $password = $User.password
    $firstname = $User.firstname
    $lastname = $User.lastname
    $OU = $User.ou #This field refers to the OU the user account is to be created in
    $telephone = $User.telephone
    $jobtitle = $User.jobtitle

    #Check and see if the user already exists in AD
    if (Get-ADUser -F { SamAccountName -eq $username }) {

        #Warn if the users already exists
        Write-Warning "A user account with username $username already exists in Active Directory."
    }
    else {

        #User does not exist then proceed to create the new user account
        New-ADUser `
            -SamAccountName $Username `
            -UserPrincipalName "$email@example.com" `
            -Name "$Firstname $Lastname" `
            -GivenName $Firstname `
            -Surname $Lastname `
            -Enabled $True `
            -DisplayName "$Lastname, $Firstname" `
            -Path $OU `
            -OfficePhone $telephone `
            -Title $jobtitle `
            -AccountPassword (convertto-securestring $Password -AsPlainText -Force) -PasswordNeverExpires:$false -ChangePasswordAtLogon:$True

        #If this user exists
        Write-Host "The user account $username is created." -ForegroundColor Cyan

        #Sleep time to sync for Exchange push
        #write-host Pausing for Exchange Sync....
        #start-sleep -Seconds 300

    #Apply licenses to users created in AD then synced to Exchange
        #Set-MsolUserLicense -UserPrincipalName $newuser.UserPrincipalName -AddLicenses UI-OF-LICENSE-HERE
        #Set-MsolUserLicense -UserPrincipalName $newuser.UserPrincipalName -AddLicenses UI-OF-LICENSE-HERE

    }
}

Read-Host -Prompt "Press Enter to exit"
</code>
P.s. dont bother about all the comments...they are there so it doesn't run certain things while I test
Answer: So firstly you dont need to assign your values from The csv to variables, they are already loaded into the object and residing in memory, so you can switch out $username to $user.username repeat it for the add user section, just change the name after the period for the dataset. I think i see what happened, so if you have john doe in the system and another 2 john doe's on your list, the first time it created a john.doe1 and was succesful but the second time it failed. So you need to pull the username string trim it to the last character, do an comparison to see if the last character is a character or number. If a letter then concatenate a 1 if a number add 1 to it and concatenate that number instead. Make sense? On my phone so writing the code and researching the syntax is a pain sorry.
Comment: Thanks for your reply. I'm going to be blatantly honest and say nope, that doesn't make much sense to me :(. Just something I've never had to mess around with so making enough sense to write it in and have it function is where I hit a wall
Comment: I'll jump on the latop in a few and try to put something together, I have had to put together an AD script before unfortunately i dont have access to the source code i wrote.
Comment: Thank you a bunch!! P.s. Feel free to just copy and paste my script and add in what you need. I'm not fussed in the slightest.
Answer: I didn't really touch the commented out parts, but hopefully this gives you an idea. I don't had an AD server handy to test it against to just be aware I can't guarantee its 100%
<code>function validation($User){
    if (Get-ADUser -F { SamAccountName -eq $User.username }) {
        $usernumber = 1
        while (Get-ADUser -F { SamAccountName -eq ($User.username + $usernumber)}){
            $usernumber++
        }
        $NewUserName = $User.username + $usernumber
        Add_User($NewUserName, $User)
        }
        else {
            $NewUserName = $User.username
        Add_User($NewUserName, $User)
        }
}

function Add_User($Username, $User){
New-ADUser `
            -SamAccountName $Username `
            -UserPrincipalName "$Username" + "@MEtest.com" `
            -Name "$Firstname $Lastname" `
            -GivenName $User.Firstname `
            -Surname $User.Lastname `
            -Enabled $True `
            -DisplayName "$User.Lastname, $User.Firstname" `
            -Path $User.ou `
            -OfficePhone $User.telephone `
            -Title $User.jobtitle `
            -AccountPassword (convertto-securestring $Password -AsPlainText -Force) -PasswordNeverExpires:$false -ChangePasswordAtLogon:$True
}

$ADUsers = Import-Csv C:\ps\usercreation.csv

$UPN = "METest.local"

foreach ($User in $ADUsers) {
    validation($User)

        #If this user exists
        Write-Host "The user account $username is created." -ForegroundColor Cyan

        #Sleep time to sync for Exchange push
        #write-host Pausing for Exchange Sync....
        #start-sleep -Seconds 300

    #Apply licenses to users created in AD then synced to Exchange
        #Set-MsolUserLicense -UserPrincipalName $newuser.UserPrincipalName -AddLicenses UI-OF-LICENSE-HERE
        #Set-MsolUserLicense -UserPrincipalName $newuser.UserPrincipalName -AddLicenses UI-OF-LICENSE-HERE

    }
}

Read-Host -Prompt "Press Enter to exit"
</code>
Comment: Thanks! :).   Unfortunately, I got this :( -->   New-ADUser : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'SamAccountName'. Specified method is not
supported.
At line:18 char:29
+             -SamAccountName $Username `
+                             ~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [New-ADUser], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgument,Microsoft.ActiveDirectory.Management.Commands.NewADUser
Comment: If you just ran it and your on ISE then in the co.mand promp at the bottom type $Username and see what it returns
Comment: It returns this:  PS C:\Windows\system32> $username
Mr.Wong. And that is 1 of the test usernames in my .csv file
Comment: You can probably add an out-string to it to convert from object to string. So -SamAccountName $Username ` would become -SamAccountName $Username | out-string `
Comment: This is the error I'm getting now after replacing that -> https://i.stack.imgur.com/SXHyS.png
Comment: Its having issues with finding the username property of the csv object, is there a username column? What is the header name?
Comment: Hi @Aalom. The headers are " FirstName | LastName | UserName | Password | JobTitle | OU | PhoneNumber
Comment: Make sure all the corresponding object properties are written case sensitive. So $User.username should be $User.UserName etc.
Comment: I have made sure that everything matches. Just made the excel sheet all lowercase to make it simpler for testing at the moment. For some reason, still getting this
https://i.stack.imgur.com/ZhPrc.png
Comment: Make sure on line 2 its $User.username if the object variable name is $User and the header is now username.
Comment: Hi Aalom. Thank you again so much for your continued help. You have no idea how much I appreciate the assistance.

I tried what you said, still the same error :(. I'll attach a screenshot of the code, the .csv and the error all in one so maybe it will make more sense to the trained eye

https://i.stack.imgur.com/xD43D.png
Comment: Wait is it creating the accounts? If so what happens when you run the script again without deleting the test accounts? Does there error go away and add a 1 to usernames?
Comment: If that is the case then its returning the error, because the account does not exist in AD. But ultimately still provides a false to the comparator, and moves on. To remove the warnings use a -erroraction ignore after the } of the get-aduser statement.


Gostaria de saber como carregar os dados de um HTML em Outro

Question: Preciso carregar em um novo HTML os dados fornecidos pelo primeiro (HTML) para realizar a alteração.A proposta da atividade que estou em dúvida é a seguinte:
"assim que o cadastro do cliente for realizado, deverá ser exibido um link para a página de alteração dos dados do cliente que acabou de ser inserido."
A tela de Cadastro funciona mas preciso de saber como carregar os dados na nova página de alteração.
Comment: A primeira página html deve ter no "action" do form uma página em php que irá guardar os dados no banco. Essa página em php deve chamar outra com o link para uma outra que irá pegar os dados do banco e exibí-los. Você deve estudar html, php e gravação e leitura em banco de dados para fazer isso. Dê uma olhada no site w3schools.com lá tem muita coisa bacana para aprender.
Answer: Thomaz,
Provavelmente o seu primeiro HTML de cadastro salvou os dados em um banco de dados, certo?
Ao exibir a segunda página, de alteração, você deverá:

Pegar os dados previamente cadastrados do banco de dados (com PDO, funções mysqli_* ou algum ORM)
Colocar estes valores no seu formulário HTML, como por exemplo:

<input type="text" name="nome_usuario" value="<?=$usuario['nome']?>" />

E realizar a ação de alterar do novo do novo formulário.

Se você quiser usar o mesmo formulário HTML tanto na página de cadastro quanto na página de edição você precisa cuidar de três coisas:

Mudar o action do form se for edição ou cadastro:

<form action=""<?=$urlCadastrarOuAlterar?>"

Nos valores dos campos, terá que verificar se existe usuário:

<input type="text" name="nome_usuario" value="<?=isset($usuario) ? $usuario['nome'] : ''?>" />

No caso da edição, salvar o id do usuário em um campo hidden.


How to prevent Symfony profiler from accessing or executing a listener

Question: My user has countTasks property, with corresponding setter and getter:
class User implements UserInterface, \Serializable
{
    /**
     * @var integer
     */
    private $countTasks;
}

I want this property to be always shown in the application's navigation bar (the "14" number in red):

Obviously, this property should be set for every controller. (Actually, only for every that deals with rendering the navigation bar, but that's not the case here). So the application should count tasks for the currently logged-in user for every controller.
I found a relevant topic in the Symfony cookbook: How to Setup before and after Filters, and I managed to implement it:
Acme\TestBundle\EventListener\UserListener.php:
namespace Acme\TestBundle\EventListener;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;

class UserListener
{
    public function onKernelController(FilterControllerEvent $event)
    {
        $controller = $event->getController();

        if ( ! is_array($controller)) {
            return;
        }

        $securityContext = $controller[0]->get('security.context');

        // now count tasks, but only if a user logged-in
        if ($securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED') or $securityContext->isGranted('IS_AUTHENTICATED_FULLY'))
        {
            $user = $securityContext->getToken()->getUser();

            // ...
            // countig tasks and setting $countTasks var
            // ...
            $user->setCountTasks($countTasks);
        }
    }
}

services.yml:
services:
    acme.user.before_controller:
        class: Acme\TestBundle\EventListener\UserListener
        tags:
            - { name: kernel.event_listener, event: kernel.controller, method: onKernelController }

It works as expected and I'm able to pull the property in a Twig template like this:
{{ app.user.countTasks }}

It works as expected in prod env.
In dev however, profiler throws UndefinedMethodException:

UndefinedMethodException: Attempted to call method "get" on class "Symfony\Bundle\WebProfilerBundle\Controller\ProfilerController" in ...\src\Acme\TestBundle\EventListener\UserListener.php line 18.

where line 18 is this one:
$securityContext = $controller[0]->get('security.context');

As a quick patch I added additional check (before line 18) to prevent profiler from executing the further logic:
    if (is_a($controller[0], '\Symfony\Bundle\WebProfilerBundle\Controller\ProfilerController'))
    {
        return;
    }

    $securityContext = $controller[0]->get('security.context');

and it has made the trick. But I'm afraid it's not the right way. I'm also afraid that I'm loosing some part of debug information in profiler.
Am I right with my concerns? Can you point me to a better way to prevent profiler from executing this listener? In config somehow?
Answer: Even in Symfony's documentation How to Setup before and after Filters, an instanceof condition is being evaluated in line 29.
I'd go about saying that if the doc's doing it, you're pretty safe doing it yourself (unless stated otherwise, which is not the case).
Comment: Thanks for pointing me in that direction @Noy - it helped me to find the right solution (I will post it later). However I can't accept your answer because of your reasoning - _if the doc's_ is not enough. Also I'm not concerned with the way I do it (`is_a()` function) but rather with coupling, that this method introduces.
Answer: In the beginning I was trying to fix the issue conversely than I should. During testing it turned out that I have to exclude some other core controllers too. Of course, rather than block unwanted controllers I should have allowed the required ones only.
I ended up creating an empty interface UserTasksAwareController:
namespace Acme\TestBundle\Controller;

interface UserTasksAwareController
{}

fixing that validity check in UserListener.php:
if ( ! $controllers[0] instanceof UserTasksAwareController) {
    return;
}

and implementing it in every other controller which deals with displaying countTasks property, like this one:
class UserController extends Controller implements UserTasksAwareController

So, the problem I had was just another one when you forget to program to an interface, not an implementation.


JQuery Mobile - botão deslocado

Question: Estou brincando no fds e aprendendo um pouco o JQuery Mobile, e fui inserir uns botões no header, porém o ultimo botão sempre fica fora da posição "deslocado para baixo". como Resolver isso?

<!DOCTYPE html>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name='theme-color' content='#00974a'/>
<title>Teste</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/latest/jquery.mobile.min.css"/>

I'm a header

    Options

One

Two

Three

Answer: O problema é que a indentação das
 estava como espaço de texto, e o snippet daqui está gerando vários   (espaço), como mostra o print abaixo:

Se você copiar seu código num bloco de notas e colar novamente no snippet, irá remover esses espaços e o botão ficará ok, como mostra abaixo:

<!DOCTYPE html>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name='theme-color' content='#00974a'/>
<title>Teste</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/latest/jquery.mobile.min.css"/>

I'm a header

    Options

One

Two

Three

Agora, dá uma revisada no seu HTML, porque tem tags duplicadas e falta
  fechar o .
Comment: Valeu cara! agora funcionou!.. show de bola!

JQuery Mobile - botão deslocado


I want to show there exist more than one measure on $\sigma (\mathcal A_{0})$ in $\mathbb Q$ which agree with $\mu$ on $\mathcal A_{0}$.

Question: Let $\mathcal A$ denote the algebra $\mathcal A=\mathcal A(\mathcal S)$.(where $\mathcal S$ denote the collection of intervals of the form $(a,b]$ where $-\infty\le a \lt b \le \infty$)
 Let $\Omega=\mathbb Q$ denote the set of rational numbers in $\mathbb R$, and let $\mathcal A_{0}=\mathcal A \cap \mathbb Q$. Consider the measure $\mu$ defined on $\mathcal A_{0}$ by $\mu(A)=0$ or $\infty$ according to whether $A=\emptyset$ or $A\neq \emptyset$. Show that there exist more than one measure on $\sigma (\mathcal A_{0})$ in $\mathbb Q$ whith agree with $\mu$ on $\mathcal A_{0}$.
thanks for any help.
Answer: Follow these steps :

Prove that $\sigma(\mathcal{A}_0) = \mathcal{P}(\mathbb{Q})$, the power set of $\mathbb{Q}$.
Let $\mu_1(A) = |A|$. Show that $\mu_1$ is an extension of $\mu$
Let $\mu_2(A) = 0$ or $+\infty$ according to whether $A = \emptyset$ or $A\neq \emptyset$. Show that $\mu_2$ is an extension of $\mu$
Show that $\mu_2 \neq \mu_1$


Filesize varies in chromes network-panel

Question: I am trying to analyze the performance of my web-app with Chrome DevTools. So I was looking at timings under "Inspect Element" > "Network". While comparing localhost to the same page on the web, I noticed that the size of several .js-Files varied significantly, i.e. one minified .js was shown with 4.5kb on the web and 13.9kb on localhost.
However, when I right-clicked these entries in nw-panel to "Save", I got identical files with 14kb.
So where do these variations come from?  (BTW, Firefox shows that file also with14kb when access on the web!)
Answer: Most probably your web server has deflate compression for plaintext files enabled while your local server doesn't. (mod_deflate in apache)
Compare the Content-Encoding headers of both variants.
Comment: I'm using exactly the same server-config in both cases. content-type for that file is `content-type: application/javascript`
Comment: @mbaas Sorry, I meant Content-Encoding
Comment: Thank you - you are right - the one from the web comes deflated whereas the local one isn't. I'm not using Apache or other well-know stuff, I'm using MiServer (a web-server written in APL) and the one thing where both systems differ is that one had a "Production"-flag whereas the other works in Debug-mode. I would not have thought that this would also impact the encoding - will get in touch with the devs now. Thanks!


How to monitor servers in different network using munin?

Question: I would like to monitor some servers using munin, that are in a different network and are not reachable directly by telnet. I wonder what are the possibilities:
Can I install a central node in the remote network, that collects all data from other servers in this network?
Or would I have to do port-forwarding for each server I want to monitor?
Comment: I heavily suggest using graphite instead of munin. That's one of the things it can do and do quite well. With graphite you can have relays that aggregate all the data and relay them back to a master node (or another relay). I.e. exactly what you're looking for. Plus it can scale and do a lot of things that munin cannot.
Comment: @V13 thanks! i'll definitely have a look at graphite.
Answer: The munin chaps seem to be aware of the need to do this, and they have a project in progress called munin relay, which would allow you to set up a single box at each site that could be seen by the central munin server, and in turn could see all the clients at that site, and which would proxy/relay the munin pull requests from the central server to the (unreachable to the server) clients.
Unfortunately, as the page states, this project isn't working yet.  So you can either contribute to the project and make it work, or wait until it's ready, or use one or more of the three other methods listed on that page for contacting the (currently directly-unreachable) clients: tcp proxy, ssh tunnel (or some other vpn, I'd be inclined to look at OpenVPN or IPSec) or ssh:// requests (which will also require port-forwarding).
Or, to summarise the answer, at the moment you've either got to do port-forwarding so the server can reach all the clients directly, or install some kind of site-to-site VPN so the server can reach all the clients directly.
Sorry.
Comment: Thanks very much and good to hear, that they are working on it! And in the meantime i'll try to get this vpn-stuff to work ...
Answer: I don't use munin. I use nagios instead, but I think the idea should be the same.
It is much more bandwidth efficient and faster when you install and run the monitoring node in the same area of the monitored servers. You can then simply access the monitoring web interface to check the servers status.
Comment: mmm ... i understand. the point is, that i have three different networks that i would like to monitor at some central point ...
Comment: Put a collection node in each network then have just those nodes report back to your central instance?
Comment: Top__Hat: lovely idea, but do you know how to do that with munin?
Comment: I think the best option in this case is to install monitoring node in each location and then send a summary of status information to one central location. You need first to find a tool in munin. The other easier option is to install just in one central location if you have a plenty of bandwidth linking all locations.
Comment: Khaled, as I said to Top__Hat, that's a lovely idea, but **how do you do it in munin**?  The original poster seems to know that he needs that, so telling him he needs that is no help - tell him **how** to do it in munin.  I use munin quite a lot, and I'm not sure that it can be done, right now.


stratifying or not? how to take into consideration mediator?

Question: I am trying to assess whether a visit to a doctor being "on time", "too early" or "too late" has an impact on the total days of sickness.
The time passed between the start of the symptoms and the visit with the doctor (expressed in weeks) could be a possible confounding factor. In particular: the more time passes between the start of the symptoms and the visit, the more likely is that the visit is considered "too late" rather than "on time".
My assumption is that "on time" visits lead to a shorter duration of the sickness and therefore it is important to decide when to see a patient (as early as possible is different from "on time").
How would you approach this problem? I could run a survival analysis estimating what is the probability of recovering over the time for "on time" visits and "too late" visits, but I would need to stratify for weeks between the start of the symptoms and the visit. This will obscure the impact of being "on time".
Another approach would be to create a Cox Proportional-Hazards Model and have a look at the coefficients...
Do you have any tip on how to correctly address this problem?
Regards and thanks
Comment: Is there some reason why you can't just use the actual number of days between developing symptoms and seeing the doctor as a continuous predictor in a Cox model? Binning into a few groups is generally [not a good idea](https://stats.stackexchange.com/q/68834/28500).
Comment: Hi @EdM, it is more a practical reason: usually appointments are planned taking into considerations the weeks... but yes, for analysis purposes it is good to use the days, thanks for the suggestion!
Answer: It's best to try to use all the information available in a continuous predictor. So if you know the actual number of days between developing symptoms and seeing the doctor, use that actual number of days rather than arbitrarily breaking that time down into categories like "on time", "too early" or "too late."
Particularly as you don't expect a simple linear relationship between that continuous predictor and outcome, perform a flexible fit that allows the shape of that relationship to be determined from the data. Restricted cubic splines are a particularly useful way to incorporate a continuous predictor into a model when you don't have a theoretical basis for any particular shape. I use the rcs() function from the rms package in R for such modeling. Then you can determine whether there is a substantial non-linearity in the relationship and plot its shape. If there is a clear minimum, the data will tell you what "on time" means in practice.
Two more things to consider with your colleagues as you pursue this study. First, if you perform a survival analysis with date of recovery as the end point, that will have to be carefully defined. (I assume that time=0 for each patient will be the date of symptom onset.) Second, when interpreting the results: what about patients who never visit the doctor, despite symptoms?
Comment: Thanks for your answer and your reflection points! Very appreciated! About the patients who never visit the doctor: usually these patients are sick for a shorter time as the problems are solved without the need of a doctor (e.g. flue etc.). However, these patients are not taken into account as the study aims at analyzing the differences between patients seen on time and not (I simplified the problem by merging the too early and too late categories into not on time)
Comment: regarding rcs()... do you mean something like this:

fit <- lrm(sickness_duration ~ age + gender + disease + rcs(time_between_symptoms_and_visit) +
timing)
with timing being "on time" or "not on time". Do you perhaps have a library to suggest for python?
Comment: @gabboshow `lrm` is for logistic models; use `cph` for survival models in `rms`. You don't use a categorical `timing` variable as a predictor at all, but let the `rcs` term handle how outcome is affected by elapsed time between symptoms and visit, as a continuous predictor. I assume that "recovery" is the event for the survival model. When you plot that relationship (e.g. with the Predict function in rms), your hypothesis is that at very short and long elapsed times the "hazard" of recovery is low, but at intermediate times it is "high." That will _show directly_ what's too early or late.


Exclude directories from pathname expansion results

Question: I have 100 directories and need to move the ones not in a certain list into a single new directory.
I am trying variations of:
for A in !(sub-9002 sub-9003 sub-9004 sub-9005 sub-9008 sub-9009 sub-9011 sub-9014 sub-9018 sub-9020 sub-9023 sub-9025 sub-9026 sub-9028 sub-9029 sub-9033 sub-9034 sub-9036 sub-9038 sub-9039 sub-9040 sub-9041 sub-9042 sub-9045 sub-9046 sub-9047 sub-9048 sub-9049 sub-9055 sub-9058 sub-9061 sub-9062 sub-9064 sub-9065 sub-9068 sub-9069 sub-9071 sub-9072 sub-9079 sub-9080 sub-9081 sub-9084 sub-9085 sub-9086 sub-9087 sub-9088 sub-9089 sub-9092 sub-9093 sub-9094 sub-9096 sub-9098 sub-9100);
do
   mv -f $A Bad/;
done

I'm also trying:
if [[! A in (sub-9002 sub-9003 sub-9004 sub-9005 sub-9008 sub-9009 sub-9011 sub-9014 sub-9018 sub-9020 sub-9023 sub-9025 sub-9026 sub-9028 sub-9029 sub-9033 sub-9034 sub-9036 sub-9038 sub-9039 sub-9040 sub-9041 sub-9042 sub-9045 sub-9046 sub-9047 sub-9048 sub-9049 sub-9055 sub-9058 sub-9061 sub-9062 sub-9064 sub-9065 sub-9068 sub-9069 sub-9071 sub-9072 sub-9079 sub-9080 sub-9081 sub-9084 sub-9085 sub-9086 sub-9087 sub-9088 sub-9089 sub-9092 sub-9093 sub-9094 sub-9096 sub-9098 sub-9100)]]; then
    mv -f $A Bad/;
fi

Comment: What's the actual issue? Any error messages? Any files not being moved? Also, [Use More Quotes™](https://mywiki.wooledge.org/Quotes)!
Answer: You can use a negative-match extended glob pattern, but you need to do set -s extglob first, and then the pattern syntax is !(sub-9002|sub-9003|sub-9004|...). I'd also recommend using lower- or mixed-case variable names (there are a bunch of all-caps names with special meanings, and you don't want to accidentally use one of those), and also double-quote variable references (e.g. "$a" instead of just $a) to avoid weird parsing problems. Oh, and you don't need a semicolon at the end of lines.
shopt -s extglob
for a in !(sub-9002|sub-9003|sub-9004|sub-9005|sub-9008|sub-9009|sub-9011|sub-9014|sub-9018|sub-9020|sub-9023|sub-9025|sub-9026|sub-9028|sub-9029|sub-9033|sub-9034|sub-9036|sub-9038|sub-9039|sub-9040|sub-9041|sub-9042|sub-9045|sub-9046|sub-9047|sub-9048|sub-9049|sub-9055|sub-9058|sub-9061|sub-9062|sub-9064|sub-9065|sub-9068|sub-9069|sub-9071|sub-9072|sub-9079|sub-9080|sub-9081|sub-9084|sub-9085|sub-9086|sub-9087|sub-9088|sub-9089|sub-9092|sub-9093|sub-9094|sub-9096|sub-9098|sub-9100);
do
   mv -f "$a" Bad/
done

BTW, [[ ]] conditional expressions don't have anything like an in operator. But they do require spaces after the [[ and before the ]].


Split Test::More suite into multiple files

Question: I'm using Test::More to test my application. I have a single script, run_tests.pl, that runs all the tests. Now I want to split this into run_tests_component_A.pl and B, and run both test suites from run_tests.pl. What is the proper way of doing this, does Test::More have any helpful methods?
I'm not using any build system.
Comment: It seems to me that you are doing it wrong. You can make as many test scripts as you want, they normally end in `.t` and put them in a directory. Then, you use Test::More's `prove` with their directory and it will run them all and report. Note that `Test::More` is now just a wrapper around Test2-Suite, so you might want to look into starting with that.
Comment: If it's not clear, for running tests you don't do `perl run_tests.pl`, you do something like `prove -lvr testdir`. For Test2, `prove` is replaced by `yath`.
Comment: @Ecuador I followed the perl documentation [Test::Tutorial](https://perldoc.perl.org/Test::Tutorial), and which never mentions `prove`. The Test::More docs have a single mention under "Other components". Are you sure I'm using it wrong and not just in another way from you?
Comment: @Anna yes, I am pretty sure, that's an ancient and very basic tutorial, from the fact that you want to have more than 1 test file you have outgrown it, so you should start using a test harness like `prove`. Perhaps take a look at https://perlmaven.com/testing - it even has an intro to Test2 which is the modern Perl test framework I mentioned.
Comment: @Ecuador Thanks for pointing me there and to `prove`!
Answer: Instead of running the creating a run_tests.pl to run the test suite, the standard practice is to use prove.
Say you have
t/foo.t
t/bar.t

Then,

prove is short for prove t.
prove t runs the entire test suite (both t/foo.t and t/bar.t).
prove t/foo.t runs that specific test file.
perl t/foo.t runs that specific test file, and you get the raw output. Easier for debugging.
perl -d t/foo.t even allows you to run the test in the debugger.

Each file is a self-standing program. If you need to share code between test programs, you can create t/lib/Test/Utils.pm (or whatever) and use the following in your test files:
use FindBin qw( $RealBin );
use lib "$RealBin/lib";
use Test::Utils;

prove executes the files in alphabetical order, so it's common to name the files
00_baseline.t
01_basic_tests.t
02_more_basic_tests.t
03_advanced_tests.t

The 00 test tests if the modules can be loaded and that's it. It usually outputs the versions of loaded modules to help with dependency problems. Then you have your more basic tests. The stuff that's like "if this doesn't work, you have major problems". There's no point in testing the more complex features if the basics don't work.


How to allow reverse ssh-tunnel connection to my host on demand?

Question: I've set up a reverse ssh-tunnel (no autossh is used right now, but I might be using it)from remote laptop to my pc, but I don't trust much the remote host, as there might be different people using it and I would like somehow to control, when remote host can connect my pc, so that I could allow or prohibit this tunnel on demand.
The problem here is also that remote laptop experiences connection issues, so I might not be able to connect to it to start ssh tunnel explicitly to allow connection to my pc, so I would like to have the tunnel run on remote laptop persistently. I use TeamViewer to connect to remote laptop to setup things.
Remote laptop is Windows with cygwin, so cygwin solution is appreciated, but a pure linux one might be helpful too, as I might ask to install some linux distro on remote machine.
Could you please suggest any solutions to these problems?
Answer: It seems like that using -N option for ssh command disables command execution, so I think no one will access my PC if ssh command is issued like that. As I force password entering when connecting, no one would seem to access my PC without reentering password even if retried to connect via the same terminal immediately after ssh session termination.
So I just need to keep ssh running and hope things are Ok.
Comments welcome, because I'm not that skilled in it.


Problema com FileDialog no QML

Question: Estou tentando usar o componente FileDialog no QML
Eu fiz exatamente o mesmo código que está na documentação do Qt no link http://doc.qt.io/qt-5/qml-qtquick-dialogs-filedialog.html e este código não mostrou o FileDialog e retornou o erro: QFileInfo::absolutePath: Constructed with empty filename. Eu tentei escrever um código simples para testar, mas ocorreu o mesmo erro. Meu código está abaixo:
import QtQuick 2.4
import QtQuick.Window 2.2
import QtQuick.Controls 1.3
import QtQuick.Dialogs 1.2

Window {
    visible: true

    width: 360
    height: 640

    maximumHeight: 640
    minimumHeight: 640

    maximumWidth: 360
    minimumWidth: 360

    title: "Acessar Galeria Test"

    Rectangle {
        id: principal

        anchors.fill: parent

        FileDialog {
            id: fileDialog

            title: "Please choose a file"

            folder: shortcuts.home

            visible: true
        }
    }
}

Answer: A propriedade visible do FileDialog não pode ser true enquanto o componente não estiver completo, por isto deve-se usar Component.onComplete para definir o FileDialog como true. Então o código deve ficar desta forma para funcionar:
import QtQuick 2.4
import QtQuick.Window 2.2
import QtQuick.Controls 1.3
import QtQuick.Dialogs 1.2

Window {
    visible: true

    width: 360
    height: 640

    maximumHeight: 640
    minimumHeight: 640

    maximumWidth: 360
    minimumWidth: 360

    title: "Acessar Galeria Test"

    Rectangle {
        id: principal

        anchors.fill: parent

        FileDialog {
            id: fileDialog

            title: "Please choose a file"

            folder: shortcuts.home

            visible: false
        }
    }

    Component.onCompleted: {
        fileDialog.visible = true;
    }
}

Problema com FileDialog no QML


Can the Visual Studio 2013 help viewer use the 2012 offline contents?

Question: Okay, so I read that Visual Studio 2013 makes use of the Visual Studio 2012 help content. Consequently I used Visual Studio 2012/2013 Help Downloader and now have a local cache of the help content.
Now I can import that into Visual Studio 2013 and 2012 respectively. But how can I make use of the already installed content from one VS version inside the other?
Is there a solution short of using hardlinks to save the disk space that would otherwise be wasted on the same contents?
Side-note: hardlinking saves approx. 1.3 GiB, but that's less than the expected half of the overall amount.
Answer: The answer to your question in the title is yes.
VS 2013 can use same VS 2012 offline help contents.
If you use the offline help contents, VS will also not duplicate the actual physical file but instead reference to it.
Comment: This is not helpful, I'm afraid. See, I am aware that I can apply the same catalogs to each HelpViewer version respectively. However, that means duplication of the data.  If I use the "Move content" option under "Manage content", I lose information that already exists and is version-specific. So what I would need is to reference an additional catalog.
Comment: I was able to get both VS 2012 & 2013 using the same offline content by deleting all the contents in the VS2013 local store path and then changing the VS 2012 local store path to the now empty directory of VS2013's store path. When you open VS 2013 back up it will then update with the contents that was in VS2012's help contents.
Comment: Could you please detail how I get it to do that? Thanks.
Comment: you need to download the file from MSDN.

after you download, set help to local help viewer and then when you press F1 you can set your help contents to the file's path.
Answer: http://www.microsoft.com/en-us/download/confirmation.aspx?id=34794 now contains and ISO for VS2012 and VS2013 documentation. Download the VS2013 ISO and it contains both. Then mount the ISO, and follow the html instructions on the disk.


K-means clustering on large number of variables

Question: Suppose K-means clustering need to be performed on large number of variables. Then,

normalisation should be performed on all variables or only the variables having high variance?
How can we define "high variance"?
Also, once the clustering is done, to infer the meaning out of the clusters, we would again have to change the normalised variables to original values.

Is my understanding right?
Answer: Don't just normalize data because some variables have "high variance".
High variance can be perfectly fine, if that variable is important.
You are supposedly trying to solve a problem. Choose the normalization that is appropriate for your problem. Don't ignore the meaning of the variables.


two samples, hypothesis test of proportions t or z test

Question: I have two samples of documents where one sample contains documents of a certain category and another sample contains documents of another category. I am analysing the occurrence of a certain word in the documents.
I want to do an hypothesis test to check if the proportions of this word is the same in both populations or not.
I know the sample sizes (200,40) and I know the proportions but I do not know the variances of the population.
The basic method is to assume that the difference of proportions is normal and to calculate a z-score for the difference of proportions.  Is it correct even if I do not know the variances?
The reason why I am asking this question is that if I am comparing the means of two different samples with different means and I do not know the variances, I should use t-test and take into consideration that I do not know the variances.
Is there a corresponding t-test for significance in the proportions in the population?
Comment: If these are count-proportions, the variance won't be $np$.
Comment: You actually **do** know the variance of your sample since you have proportions (variance is $np$). You can run a chi-square test on a 2x2 contingency table here.
Comment: Hi Affine, As you pointed out I know the sample variance (np) but I do not know the population variance. The fact that I do not know the population variance is one reason for using t-test if I am checking the difference of means.But it seems not to be a valid reason for difference of proportions. That is not clear for me.
Comment: Maybe this can help: http://www-stat.wharton.upenn.edu/~lbrown/Papers/2005c%20Confidence%20intervals%20for%20the%20two%20sample%20binomial%20distribution%20problem.pdf
Answer: Proportion tests are just particular cases of z-test and t-test, where our variable is a Bernouilli (and its mean a binomial), and therefore variance of variable just depends on proportion and variance of mean depends on proportion and sample size.
With that in mind, in principle the choice should be obvious: if we know population variance, we are doing a z-test, but if we just know sample variance we are doing a t-test. Then the only usual proportion test which is a true z-test is the proportion test for one sample because the null hypothesis is that the proportion is a given (known) value.
Anyway, any elementary statistical handbook presenting proportion tests would skip any reference to t-test and treat them just like z-tests. That might seem to contradict theory, but is backed by a very strong practical reason.
The practical reason is that usually samples for proportion tests are very large for two causes:

First, you can't assume normality if sample is not large.
Second, even if samples are large enough to yield normally distributed means, proportion tests power is very small if sample is not very large.

Then, sample sizes for proportion tests usually come in hundreds or thousands, and since t-Student distribution rapidly converges to normal when the number of degrees of freedom grows, there is no practical difference between performing a t-test or a much simpler z-test.
In summary: for reasonable sample sizes, you can go for z-score. In fact, for your sample size of (200,40) I would be more worried that the very small size of the second sample could rend your test too little powerful to be actually helpful, than for the tiny difference between t-score and z-score.
And just as an end note: all this also holds for confidence intervals on proportions.
Comment: I think much of this post is misleading, because in tests of proportions a t-test is never indicated: the estimated proportions already determine the estimated variances.  Although for large samples Z tests can be used, that does not imply "proportion tests are just particular cases" of such tests.


Submit handler is not called from theme function

Question: I am actualy trying to build up a dragable table, but for some reason after implementing the theme_function, my submit handler is not longer getting called.
This is what my Code actualy looks like:
function he_ministerienschalter_theme($existing, $type, $theme, $path) {
  $themes = array(
    'he_ministerienschalter_admin_form' => array(
      'render element' => 'element',
    ),
  );
  return $themes;
}

/**
  * Implements the ministerschalter admin form
  */

function he_ministerienschalter_admin_form($form, &$form_state, $form_id, $item) {

  $domainnames = he_ministerienschalter_domainselect();

  $count = 0;
  $form['ressortswitch'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
    '#tree' => TRUE,
    '#theme' => 'he_ministerienschalter_admin_form',
  );
  foreach ($domainnames as $key => $domainname) {
      $form['ressortswitch'][$key]['domainID-'.$key] = array(
        '#type' => 'value',
        '#value' => $domainname['domain_id'],
      );
      $form['ressortswitch'][$key]['domainname-'.$key] = array(
        '#type' => 'item',
        '#title' => $domainname['sitename'],
        '#size' => 60,
        '#maxlength' => 128,
      );
      $form['ressortswitch'][$key]['domainshort-'.$key] = array(
        '#type' => 'textfield',
        '#default_value' => $domainname['sitename'],
      );
      $form['ressortswitch'][$key]['weight-'.$key] = array(
        '#type' => 'textfield',
        '#default_value' => !empty($domainname['domain_weight']) ? $domainname['domain_weight'] : '0',
        '#size' => 3,
        '#attributes' => array('class' => array('item-row-weight')),
      );
      $count++;
    }

    $form['ressortswitch']['count'] = array(
      '#type' => 'hidden',
      '#value' => $count,
    );
    $form['ressortswitch']['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Save Settings'),
    );

  return $form;
}

/**
  * Theme callback for the he_ministerienschalter_admin_form
  */

function theme_he_ministerienschalter_admin_form($variables) {
  $element = $variables['form'];
  drupal_add_tabledrag('ressortswitch_table', 'order', 'sibling', 'item-row-weight');
  $header = array(
    t('Domainname'),
    t('Domainshort'),
    t('Weight')
  );

  $element_items = array();

  foreach($element['ressortswitch'] as $id => $record) {
    if(is_int($id)) {
      $element_items[] = $record;
    }
  }

  $rows = array();
  foreach ($element_items as $id => $item) {
      $domainNAME[$id] = $item['domainname-'.$id];
      $domainSHORT[$id] = $item['domainshort-'.$id];
      $domainWEIGHT[$id] = $item['weight-'.$id];

    $rows[] = array(
      'data' => array(
        drupal_render($domainNAME[$id]),
        drupal_render($domainSHORT[$id]),
        drupal_render($domainWEIGHT[$id]),
      ),
      'class' => array('draggable'),
    );
  }

  $output = theme('table', array(
    'header' => $header,
    'rows' => $rows,
    'attributes' => array('id' => 'ressortswitch_table'),
  ));

  $output .= drupal_render($element['ressortswitch']['submit']);

  return $output;
}

/**
  * Implements hook_form_submit
  */

function he_ministerienschalter_admin_form_submit($form, &$form_state, $item) {
  db_delete('he_ministerienschalter')
  ->execute();
  $count_domains = $form_state['values']['ressortswitch']['count'];
  $count = 0;
  // dpm($form_state);
  dpm($form_state);
  while($count < $count_domains) {
    db_insert('he_ministerienschalter')
      ->fields(array(
        'domain_id' => $form_state['values']['ressortswitch'][$count]['domainID-'.$count],
        'domain_short' => $form_state['values']['ressortswitch'][$count]['domainshort-'.$count],
        'domain_weight' => $form_state['values']['ressortswitch'][$count]['weight-'.$count]
    ))
    ->execute();
    $count++;
  }
  drupal_set_message('Eingabe gespeichert');
}

Any idea how to solve that?
Comment: `'render element' => 'element',` looks a bit suspect as you're looking for `$element = $variables['form'];` in the theme function. `'render element' => 'form',` would make more sense
Comment: Changed it, but without luck :-/
Answer: I Updated my theme function like this and now it works like a charm :-)
$output .= drupal_render($element['form_id']);
$output .= drupal_render($element['form_build_id']);
$output .= drupal_render($element['form_token']);


Multi-CPU server with CPUs of differing core counts

Question: Is it possible to have a multi-CPU server where the CPUs do not necessarily have the same number of core counts?
For example, a group of 4 at dual core and a group of four at quad core?
This question is independent of any OS.
EDIT
David answered that this is possible. So I'd like to extend my question and ask if it's possible to mix hyperthreading and non-hyperthreading CPUS.
Comment: Why was this downvoted?
Comment: Not the downvoter, but how is this a) practical, and b) relevant to SF?
Comment: Practical: I'm writing a threading framework. If not SF, then where?
Answer: There are subtle changes among CPU packages. I've yet to see such a configuration supported. Last time we wanted to upgrade a machine there was no way of getting the same chip as the one installed, and even changing the existing one and adding a twin wasn't possible as support for the motherboard was discontinued.
It is probably cheaper in the end if you just either get the same CPU (might have to rummage on ebay or such, can have a hefty premium), or move to a new/larger machine.
BTW, in Linux they are just starting work on supporting the ARM BIG.little (I believe 2 fast + 2 slow cores, can switch from one pair to the other) decently, all current systems assume the processors are identical (except for "hyperthreading" shenanigans, which are popular for a while now).
Answer: Absolutely. There's absolutely no reason this wouldn't be possible.
Comment: Thanks. Are there any restrictions the CPUs within a group?
Comment: @IanC: Particular CPUs or operating systems might have such restrictions, but conceptually, no.
Comment: @DavidSchwartz - I removed my comment because I haven't ever tried it, however, just for discussion sake: http://www.intel.com/content/www/us/en/processors/xeon/xeon-5500-vol-1-datasheet.html - looking at that datasheet on page 26 it states: Processors must share symmetry across physical packages with respect to the number of logical processors per package, number of cores per package (but not necessarily the same subset of cores within the packages).  --I'm not doubting you, just curiousity at this point. (I understand this is just 1 proc family I'm basing this on.
Comment: @TheCleaner: That's a design choice Intel chose to make in that series of CPUs. Nothing compelled that design choice.


Tensorflow classification labels datatype

Question: I am using Tensorflow DNN model to do some classification.
I have a numerical (float32) data input but string type output.
x = tf.placeholder("float", [None, n_input])
y = tf.placeholder(tf.string, [None, n_classes])

When I try to define the loss and optimizer as below:
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))

I encounter an error that

TypeError: sigmoid_cross_entropy_with_logits() got an unexpected
  keyword argument 'labels'

I looked up the document from here, it said that

logits and targets must have the same type and shape.

Do I need to convert the class into a floating number(hashing string to number)?
output_y = [["apple", "apple", "orange", "banana"]]
encoded_y = [[1], [1], [2], [3]]

Answer: If you are using tensorflow v 0.10 the keyword for labels is targets.
If you are using tensorflow v 1.0 then the keyword for labels is labels.
As per the documentation your label vector should have the same type as logits, float 32 or float64.


How to break AWS certificate to public/private keys and intermediate certificate?

Question: I've issued a wildcard certificate in AWS to install on the company's website (which is stored in a CloudFront distribution).
There's a customer support service which the company uses and when you browse to support.company.com it takes you to that service site.
Up until today, the access to the support site has been done on HTTP protocol and we would like to change it to be on HTTPS.
For that, I need to upload to that customer support service provider site the new certificate, they require Private key, Public key and Intermediate certificate.
I've run the following command to get the certificates:
<code>aws iam get-server-certificate --server-certificate-name wild_company.com_10072019
</code>
But the output shows me the "CertificateChain" - all the certificates are display in one line and another "CertificateBody" which is also displayed in one line.
The CertificateBody is easier to distinguish by the "--- Begin certificate ---" and "---END certificate---" which appear only once but in the CertificateChain there are lots of begin/end marks and I'm not sure how to transform it to Public/Private keys and Intermediate certificate.
Any idea how can it be done?
Comment: did you upload the SSL cert or use cert manager to issue the cert?
Comment: I've used cert manager to issue the certificate
Answer: So when you create a certificate using AWS Cert Manager, you cannot pull out the key for the certificate chain. You can only use it for AWS services like ELB/ALB/Cloudfront
So in short, you can't pull the key out to use it in your own infrastructure like apache or nginx.


Can I assign a taxonomy to a content type's term_reference field at runtime?

Question: I need to manage a few different types of objects, let's say "car", "pickup", and "van".  These are similar enough (for my purposes) that I can define a single content type and associated code for "vehicle" and use it for all of them, along with a field that specifies the exact type of the object.  This allows me to do things like have one page that shows all the cars, one page that shows all the pickups, and so on.  I have this code running; everything is fine.
I now want to add an OPTIONAL tag field to these items, using the taxonomy / term_reference stuff in Drupal.  The catch is that I want to have a separate tag taxonomy for each of my different kinds of vehicles, so that "car" tags don't show up in the truck's autocomplete suggestions. (Trust me -- in the context of my app, this makes sense.)  The question is how to do it; the complicating factor is that the vocabulary for a tag field has to be defined when the field is added to the content type, and, remember, my content type is generic across all the types of vehicles.
So:

Ugly possibility #1: Define a single tag field -- field_vehicle_tags? -- in the content type and write some magical code in a form_alter or theme or after_build hook or somesuch that, when building the edit form for the node, checks to see what kind of vehicle is being created (this is known upon entry to the form) and bashes the appropriate vocabulary into the field's autocomplete process.  I don't know that this is actually possible, and I suspect the opportunities for screwing myself are endless.
Ugly possibility #2: Define one tag field for each kind of vehicle -- field_car_tags, field_pickup_tags, etc -- each of which is connected to its own taxonomy.  Then, use the theming hook to throw away (= not render as part of the form) all the tag fields except for the one that matches the kind of thing being edited.  This is stupid and wasteful in all sorts of ways, but I'm pretty sure it would work.

Any thoughts or alternatives?  I'm currently leaning towards #2, but if there's a better alternative, I'd love to hear about it.
Answer: You can create a Content Type named Vehicle and make inherits his fields to your Cars, Van with the help of the Bundle Inherit module. Then you can create a Taxonomy for each kind of Vehicle then you will have.
<code>Vehicle (color, number_of_seats, etc)
 - Car (field_car_tags)
 - Van (field_van_tags)
</code>
With this you don't need to write lines of code and you can reuse the fields of the Vehicle Content Type.
Comment: @JimMiller If you solve your problem please post the answer
Comment: @JimMiller a pleasure help you, let me know the result ;-)
Comment: @JimMiller you got some advance?
Comment: Not so far -- a few other things have gotten in the way.  But soon, I hope...
Comment: @JimMiller the problem is solved?


Post-hoc for 2x2 mixed design ANOVA using SPSS with two dependent variables

Question: I am analyzing an experiment run with 162 participants using a 2×2 mixed design ANOVA.  The experiment has two independent variable with two levels each, and two dependent variables.
I need to know the significance level of each level between each dependent variable.
Is there any reason to run post-hoc test in this context? SPSS complains about variables having less than 3 levels and, for this reason, doesn't allow me to run Post-hoc tests.
Question do i need the post-hoc results to find the effect of each level of the  independent variables on each dependent variables  , If yes, how to do it in SPSS? if not then how to find such results?
Comment: You probably also "need" to know effect sizes as well :P
Comment: I KNOW ... but how by using spss?!!
Answer: If you have a Main Effect there's no need to do a post hoc test. If the two groups differ (main effect) then a post hoc test tells you nothing more (although they all use different criteria). Do you understand what a main effect means(I'm not trying to be rude/condescending)?
By the way, the analysis is in Analyze, General Linear Model, Repeated Measures.  In options you may want to select Effect Size Estimate for partial eta squared to be given.
Comment: i actually don't get what do you mean by "main effect"? ... well, if i'm getting you right.. then yes the two groups differ... For example, one of my independent variables is "qualification"; qualified and not qualified... What does post hoc tells me exactly?


What are these instruments? adkhor-pondour, damkech, enietkoutchine, joujjalka, sybyzgui, taura

Question: I'm trying to find info on some instruments from an ethnographic set of music from the former USSR area.  Namely:

adkhor-pondour - Chechen
damkech - Azerbaijani
enietkoutchine - Siberian
joujjalka - Siberian
sybyzgui - Kazakh
taura - Latvian

Can anyone help ID anything about these?  Google has been of no help with them.
Edit:   Collecting the answers here for anyone looking in the future:

adkhor-pondour: a possible mistransliteration of атхок-пондар, which appears to be a Chechen violin.
damkech - a balaban
enietkoutchine - not an instrument
joujjalka - English: Zhuzhalka.  Siberian instrument, some sort of whirligig
sybyzgui: English: sybyzgy.  a Kazakh, Kyrgyz and Mongol people sideblown flute traditionally played by shepherds and horse herders, made from apricot wood or the wood of mountain bushes.
taura - English: taure.  A birch trumpet
Comment: Don't forget that transliteration depends on the target language: Tchaïkovski, Tschaikowski, Čajkovski, Ciajkovskij, Tsjajkovski.
Comment: Google is probably of no help because those seem to be the french spellings of the names of the instruments. One useful result is this french release of a cd set which features several of the instruments: https://www.edmu.fr/2014/08/voyage-en-urss.html
Comment: Yes, that's the set I'm working on.  I've been unable to find any other language's name for those instruments if they're not latinized versions of the local names.
Comment: The CD booklet apparently has "historical essays/dictionary of instruments in French and English" according to discogs.com. You can find the booklet (including the English part) online, e.g. https://albumartcovers.wordpress.com/2014/08/22/voyage-en-urss-1-russie-ukraine-bielorussie/
Comment: Yes, but it unfortunately doesn't cover every last instrument on there.
Answer: Here are some answers:
Phandar and related Panduri. adkhor-pondour seems to be a mistake for атхок-пондар which is mentioned briefly here.
Sybyzgy
Taure
Zhuzhalka (a whirligig)
Balaban seems to be what you want for damkech. According to this document: "Balabans are played by both amateur musicians and professionals. in solo performances, two performers appear before the audience: one - usta (master) – performs a melody and the second one - damkesh (assistants) – supports him with a constant low sound of the same height."
In my opinion, enietkoutchina is not an instrument but a transliteration of the name Нутэтэин in genitive case, with k being the transliterator's attempt to represent the glottal stop in the Chukchi language. This is a performer's name, and appears together in your source with another performer's name Умка (Oumka).
Comment: Thanks!  That'll let me finish representing the instruments on https://musicbrainz.org/release/ebe60f93-8f0c-44b5-b792-8e52e1d64aab as correctly as possible, and gives me a start towards getting the missing instruments added to the system.  :)


Check discontinuity of a Function

Question: could someone please help me to check discontinuity of the following Function:
if
Comment: It is continuous at points $|x| \ne 1$. What about at $|x|=1$? In other words, is $f$ continuous at $x=1$ and $x=-1$?
Comment: Write everything you know about the question in your post. For example, mention any formulas (continuity criteria etc.) that you know. This will help us answer your question, and answer it better than if you just stated the question plain.
Answer: First note that $g(x)=\frac{(x-1)^2}{x^2+1}$ is continuous everywhere in $\mathbb{R}$, since the denominator is irreducible. Also note that $g$ can differ from $f$ at at most two points, the solutions of $\vert x\vert=1$.
In particular, we must have $\lim_{x\to 1}g(x)=\lim_{x\to 1}f(x)$ (and similar for $-1$).  Since $g$ is known to be continuous, we must have $g(1)=\lim_{x\to 1}f(x)$.
As $f$ is continuous at 1 just in the case that $\lim_{x\to 1}f(x)=f(1)$, (by definition) we can check continuity at 1 simply by  that $f(1)=g(1)$.
Answer: The function is discontinuous at $x=1$. This is because, at $x=1$, $\lim_\limits{x\to 1}f(x)=\lim_\limits{x\to1}\frac{(x-1)^2}{x^2+1}=0$, whereas $f(1)=[x^2+1]_{x=1}=2$. At other points, the function is continuous as $\lim_\limits{x\to x_0}f(x)=f(x_0)\forall x_0\in\mathbb{R}-\{1\}$

Check discontinuity of a Function


How to query a table while comparing column values of two different rows?

Question: Suppose I have a single table foo, with relevant columns flag, date and username.
I am struggling to come up with a PostgreSQL query that does the following:
Select all rows where...

date is later than a specific date
and flag = 0
and there is NO other row of a later date and with flag = 1 for the same user

...grouped by username.
The problem is very much the third requirement in the list above. I have tried building the query using subqueries with EXCEPT, WHERE NOT EXISTS, WITH and LATERAL, but I always run into a dead end when the dates of the subqueries must be compared to each other and I cannot reference them.
Is this possible within a single SQL statement?
Comment: Please provide sample data and desired results.  Your current query would also help.
Answer: This looks a lot like not exists:
select t.*
from t
where date > ? and flag = 0 and
     not exists (select 1
                 from t t2
                 where t2.username = t.username and t2.flag = 1 and t2.date > t.date
                );

If you just want user names meeting the condition, conditional aggregation should suffice:
select username
from t
where date > ?
group by username
having min(case when flag = 0 then date end) < max(case when flag = 1 then date end);

This is saying that the last flag = 1 date is later than the earliest flag = 0.
Comment: Thank you, this looks very promising! Could you explain what the `having` line in your second example does? I don't understand how the `min/max` functions work in combination with `case`.
Comment: @Hatch . . . I would suggest that you try `min(case . . .)` and `max(case . . .)` in some queries on your data (in the `select`), so you will see what happens.


Does $\sum_{n=1}^\infty \frac{1}{n^{(n^2)}}$ convergent?

Question: For $$\sum_{n=1}^\infty \frac{1}{n^{(n^2)}}$$, can we use p-sereis theorem? To be more specifically, as n>=1, n^2>=1, so we can conclude that this series is convergent.
Comment: Use the root test
Comment: $n^{(n^2)}\geq n^2$ since $n^2\geq 2$ since $n\geq 2$ for all $n\geq 2$.  Thus, the tail of the original sum is less than the tail of the sum of reciprocal squares and is convergent.
Answer: You can use $p$-series along with a comparison. You know that $\sum_{n=1}^{\infty}\frac{1}{n^2}$ converges by the $p$-series test. Then since the summand $\frac{1}{n^{n^2}}$ is always positive and $n \ge 1 \implies \frac{1}{n^{n^2}} \le \frac{1}{n^2}$, you get convergence of your series.
Answer: Yes you can use p-series
$$\sum_{n=1}^\infty \frac{1}{n^{(n^2)}} < 1 + \sum_{n=2}^\infty \frac{1}{n^{2}}$$
Then use p-series theorem.
Answer: Since
$$ \limsup_{n\to\infty}\sqrt[n]{\frac{1}{n^{n^2}}}=\limsup_{n\to\infty}\frac{1}{n^n}=0,$$
The root test tells us that the series in question is convergent.


Chord number notation for a minor song switching to a major sound

Question: I have a song that I am using Roman numeral analysis for a song I have written. The first part based on D minor.
The minor progression looks like this:
I__          Isus __       VII
   Dm         Dmsus       CMajor
However in the second part of the song I have stuck to the same scale but it sounds more like F Major. Should I still stick to the Jazz notation based of of Dm as the root note?
Answer: Difficult to say. I'd be tempted to keep it all written around the original root useless there is some obvious modulation going on (even if they are closely related). One thing I would consider is writing it out as major and looking at it that way. The notes in a Dsus (it can't be a Dmsus because we remove the 3rd.) are D G A which could imply a G9 on a d bass (notated as D/G9). And if you viewed it that way it'd be a ii - V - I in the key of C. A jazzier way of looking at it!
Another reminder is that when using roman neumarals we use lower case for minor chords and upper for majors. This helps us keep it clear which notes are where and what angle you're coming from with the analysis.
Last couple of points is that jazz uses extended chords by default and it's not typical to use just triads (it does happen though)! Try it with 7ths & 9ths and see what happens. Lastly analysis is odd there are loads of ways to do it. You just have to justify your perspective.
Hope this helps,
Cai Martlew
Comment: G9 on a D bass=G9/D
Comment: cool thanks Cai, theres enough meat in your reply to keep my thinking for a week or so :)
Comment: If the song was wholly minor would you base the numbers starting from the minor root? I just find it a bit difficult trying to remember 2 number systems.
Answer: Base all of it on the F key signature.
VIm VImsus V
Comment: Thanks, that certainly makes things more simple, but don't you think its better overall to think in terms of the chords in relation to the root, to really think in terms of the tonality of the Minor scale?
Comment: when we're talking about the relative minor, it makes more sense to reference the major key. But when you're talking about other minor keys that don't have a natural key signature, then you can use the root of that key as the reference point.