Pyglet, exit after all sounds played

Question: AVbin is installed. Both .wav and .mp3 files work.
import pyglet

music = pyglet.media.load('A.mp3')
music.play()

player = pyglet.media.Player()
player.queue( pyglet.media.load('B.mp3'))
player.queue( pyglet.media.load('C.wav'))

player.play()

pyglet.app.run()

pyglet.app.exit()

I want to create a program that plays A, then plays the queue with B and then C, and finally quits after all three sounds play.
I tried the code above but according to this post, "this is [solely] because app.run() is a never-ending loop."

How can I modify my code minimally so that the program quits after the three sounds are played?
Bonus, but how can I modify my code minimally so that the program can play two (or more) sound files, E.mp3 and F.mp3, at once?
 Thanks!
Answer: Because what you're asking is not as simple as you'd might think it is.
I've put together a code example with as much comments as I possibly could fit in without making the example to hard to read.
Below the code, I'll try to explain a few key functions as detailed as possible.
import pyglet
from pyglet.gl import *
from collections import OrderedDict

key = pyglet.window.key

class main(pyglet.window.Window):
    def __init__ (self, width=800, height=600, fps=False, *args, **kwargs):
        super(main, self).__init__(width, height, *args, **kwargs)

        self.keys = OrderedDict() # This just keeps track of which keys we're holding down. In case we want to do repeated input.
        self.alive = 1 # And as long as this is True, we'll keep on rendering.

        ## Add more songs to the list, either here, via input() from the console or on_key_ress() function below.
        self.songs = ['A.wav', 'B.wav', 'C.wav']
        self.song_pool = None

        self.player = pyglet.media.Player()
        for song in self.songs:
            media = pyglet.media.load(song)
            if self.song_pool is None:
                ## == if the Song Pool hasn't been setup,
                ##    we'll set one up. Because we need to know the audio_format()
                ##    we can't really set it up in advance (consists more information than just 'mp3' or 'wav')
                self.song_pool = pyglet.media.SourceGroup(media.audio_format, None)
            ## == Queue the media into the song pool.
            self.song_pool.queue(pyglet.media.load(song))

        ## == And then, queue the song_pool into the player.
        ##    We do this because SourceGroup (song_pool) as a function called
        ##    .has_next() which we'll require later on.
        self.player.queue(self.song_pool)
        ## == Normally, you would do self.player.eos_action = self.function()
        ##    But for whatever windows reasons, this doesn't work for me in testing.
        ##    So below is a manual workaround that works about as good.

        self.current_track = pyglet.text.Label('', x=width/2, y=height/2+50, anchor_x='center', anchor_y='center')
        self.current_time = pyglet.text.Label('', x=width/2, y=height/2-50, anchor_x='center', anchor_y='center')

    def on_draw(self):
        self.render()

    def on_close(self):
        self.alive = 0

    def on_key_release(self, symbol, modifiers):
        try:
            del self.keys[symbol]
        except:
            pass

    def on_key_press(self, symbol, modifiers):
        if symbol == key.ESCAPE: # [ESC]
            self.alive = 0

        elif symbol == key.SPACE:
            if self.player.playing:
                self.player.pause()
            else:
                self.player.play()

        elif symbol == key.RIGHT:
            self.player.seek(self.player.time + 15)

        ## == You could check the user input here,
        ##    and add more songs via the keyboard here.
        ##    For as long as self.song_pool has tracks,
        ##    this player will continue to play.

        self.keys[symbol] = True

    def end_of_tracks(self, *args, **kwargs):
        self.alive=0

    def render(self):
        ## Clear the screen
        self.clear()

        ## == You could show some video, image or text here while the music plays.
        ##    I'll drop in a example where the current Track Name and time are playing.

        ## == Grab the media_info (if any, otherwise this returns None)
        media_info = self.player.source.info
        if not media_info:
            ## == if there were no meta-data, we'll show the file-name instead:
            media_info = self.player.source._file.name
        else:
            ## == But if we got meta data, we'll show "Artist - Track Title"
            media_info = media_info.author + ' - ' + media_info.title

        self.current_track.text = media_info
        self.current_track.draw()

        ## == This part exists of two things,
        ## 1. Grab the Current Time Stamp and the Song Duration.
        ##    Check if the song_pool() is at it's end, and if the track Cur>=Max -> We'll quit.
        ## *  (This is the manual workaround)
        cur_t, end_t = int(self.player.time), int(self.player.source._get_duration())
        if self.song_pool.has_next() is False and cur_t >= end_t:
            self.alive=False

        ## 2. Show the current time and maximum time in seconds to the user.
        self.current_time.text = str(cur_t)+'/'+str(end_t) + 'seconds'
        self.current_time.draw()

        ## This "renders" the graphics:
        self.flip()

    def run(self):
        while self.alive == 1:
            self.render()

            # -----------> This is key <----------
            # This is what replaces pyglet.app.run()
            # but is required for the GUI to not freeze
            #
            event = self.dispatch_events()

x = main()
x.run()

Now, normally you'd decorate your way trough this with a bunch of functions.
But I like to subclass and OOP my way through any graphical libraries, because it gets messy quite fast otherwise.
So instead of pyglet.app.run(), I've got a custom made run() function.
All this does is mimic the pyglet.app.run(), for the most part. Enough to get going at least.
Because player.eos_* events appears to be broken.
I've added a manual example of how you could check if the songs are done playing or not.
This is a combination of self.song_pool pyglet.media.SourceGroup, self.player.time pyglet.media.player.time and self.player.source._get_duration() which returns the track duration.
The SourceGroup gives us a has_next() function which tells us if we're at the end of the queued songs. The other two variables tells us if we've reached the end of the current track. This is all we need to determinate if we want to exit or not.
Now, I haven't technically added a way to add more songs. Because again, that would also be harder than you think. Unless you opt in for if symbol == key.LCTRL: self.song_pool.queue(pyglet.media.load(input('Song: '))) for instance. But again, all you would need to do, is add more songs to the self.song_pool queue, and there you go.
I hope this answers your question. Even the bonus one.
Comment: Just to mention.... pyglet 1.4.0a1 has moved from AVbin to ffmpeg, and now mp4 and several other formats are working nicely with pyglet Player!
Comment: +1 Thank you very much for the code sample! I was having a similar problem, but with video this time. With the trick to stop teh rendering loop, everything works now (except for mp4 videos... but this seems to be a problem with AVbin).

Pyglet, exit after all sounds played


A microphone and my Yamaha PRS E363

Question: I am a beginner and I need to by a microphone.  I want to make sure I make the right choice.
Can a microphone be connected to my Yamaha E363?
Can I use a microphone connected thru my computer?
Is both methods possible?
Comment: Check out my video recording mike connected e 373 https://m.youtube.com/watch?v=cRhoZxgnAbE
Answer: Yes, you can connect a microphone to the Yamaha E363.
The E363 has an AUX-in that uses a mini-plug. To send a microphone through to the AUX-in you will need a microphone, a mixer or pre-amp, and a cable that fits the output of the mixer or pre-amp and has a mini connector on the other end.
The mixer or pre-amp can be a simple and/or inexpensive device, it just needs to convert the microphone level into Line Level. Some examples (not a recommendation, just examples of types of hardware) are:
Rolls MP13 mini mixer
Bheringer pre-amp
There are many options available.
You can also send a microphone signal to the keyboard through a computer using the USB input. This will be more complicated, and would require a digital interface for the microphone to go into the computer with, and software on the computer to send the signal to the keyboard (DAW or Digital Audio Workstation software). An example of the hardware you might use to connect a microphone to the computer is:
Scarlett 2i2
As for the microphone, what kind you buy is dependant on what you want to use it for. A simple Dynamic Microphone should be enough if you are using it to sing along to what you are playing on the keyboard.  There are many tutorials on-line on getting started with microphones, and browsing the Microphone tag on this Stack Exchange may give you some useful information; https://music.stackexchange.com/questions/tagged/microphones

A microphone and my Yamaha PRS E363


Node.js requests randomly begin to hang and won't clear until server restart

Question: I've been running into a really odd and seemingly random issue on our web app that I just can't seem to successfully debug. It runs fine for anywhere from 10 minutes to 6 hours, and then all of a sudden no remote requests to or from the server can be made, they just hang (this includes regular http and web socket requests). The odd thing is that going to the site regularly still works, until the OS file descriptor limit is reached and then http completely crashes with all of the stalled connections.
There are no errors, though the following error is thrown when the issue begins (I assume this is a side-effect of whatever is going on rather than the cause).
TypeError: Cannot read property '0' of null
    at null.<anonymous> (/app/node_modules/mongojs/node_modules/mongodb/lib/mongodb/collection.js:504:22)
    at args.(anonymous function) (/app/node_modules/strong-agent/lib/proxy.js:85:18)
    at g (events.js:175:14)
    at EventEmitter.emit (events.js:98:17)
    at Base.__executeAllServerSpecificErrorCallbacks (/app/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/base.js:315:29)
    at /app/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/repl_set/ha.js:273:22
    at /app/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/repl_set/ha.js:370:11
    at /app/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/repl_set/ha.js:352:28
    at _callback (/app/node_modules/mongojs/node_modules/mongodb/lib/mongodb/db.js:670:5)
    at /app/node_modules/mongojs/node_modules/mongodb/lib/mongodb/auth/mongodb_cr.js:47:13

I've tried raising the file descriptor limits and the global agent maxSockets with no affect on this behavior. There's no influx of traffic when this happens, and it happens equally as often during peak and off-peak times. The CPU usage consistently stays below 5% and doesn't have any perceptible changes leading up to or during the crash. The server also never drops below 1GB of free memory.
The stack: SmartOS cloud server (Joyent), Express, Socket.io, MongoDB and Redis.
I've been debugging this for several days and have completely run out of ideas where to look. Hoping someone on SO has run into something similar or has different ideas of what can be tried or tested.
Comment: is this for an array? is the array empty? if not, have you tried to access `array[index - 1]`?
Comment: That error message is not from my code, it is coming from the MongoDB native driver for Node.js. I don't think this is the source of the issue, but I thought I'd include it for completeness.
Comment: Can you regularly check the number of open file descriptors, and see if it slowly and constantly increases? If so, you have a fd leak somewhere. Likely not directly in node, since it will time out sockets.
Comment: @NitzanShaked It seems to stay fairly level and then all of a sudden goes through the roof. My assumption is that it goes through the roof as a result of the real issue, but I may be wrong about that.
Comment: OK, so next debugging step: write a small script that prints the number of open file descriptors *per process*, and when the total starts going thru the roof try to see which process is to blame. If it's node, I would first look at any modules which are wrappers around native (read: c) code.
Comment: What version of mongojs/mongodb are you using? There's a known issue from a couple months ago regarding connection leaks with db timeouts. https://github.com/mongodb/node-mongodb-native/issues/827
Comment: Latest stable version of mongodb/mongojs.
Comment: @NitzanShaked I ran 'lsof -p' last time it went down and a short time before and almost everything was node. Or are you saying to look at something else?
Comment: and what types are they? sockets? regular files? others?
Comment: @NitzanShaked Not much info is given, just an IP and port. About half are the server's public IP on port 443, while the other half are IP's of other sites at high port numbers 10k - 50k range.
Comment: ... so am I to understand that there are many open sockets just prior to the symptoms? That could of course explain it. Was there a spike in incoming traffic (requests/sec) just prior? If not -- are you using `fork()` or spawning new processes anywhere in your code, which would explain the plethora of fd's?
Comment: No, the spike is after the connections start hanging. The number of open sockets stays pretty steady and then all of a sudden shoots up.
Answer: After countless hours of debugging and more debugging, I finally found the culprit. An error was being thrown inside of several different mongojs callbacks, which appears to have bubbled up and blocked the connections from closing. Over time, this got to a tipping point and connections started hanging until the file descriptor limit was reached.
The error turned out to be in the Now.js node module (which has been abandoned). If there is anyone out there that is running into this issue using Now.js, I forked it and patched the bug. You you can find the commit here: https://github.com/goldfire/now/commit/b5bd54f8950602f752a710c606be6754b759cab2.
The way I found this bug was to attach an error listener to the DB object:
var db = require('mongojs').connect('...', ['collection']);
db.client.on('error', function(err){
  console.log(err.stack);
});


$L^1$ convergence of this martingale

Question: Let $(X_n)_n$ be a martingale, with $X_0=1$ and $X_n=2U_nX_{n-1}$ such that $(U_n)$ is i.i.d and follows a continuous uniform distribution on $[0,1]$
Does $X_n$ converge in $L^1$ space ?

I showed that $X$ converges a.s towards $0$ (using the logarithm and the law of large numbers) and that it does not converge in $L^2$.
For this question does this have to do with uniform integrability?
Answer: As you showed $X_n\rightarrow 0$ almost surely.
If $X_n\rightarrow 0$ in $L^1$, then $E(X_n)\rightarrow 0$ which is not true since $E(X_n)=1$.
From Jensen's inequality $E(X_n^2)\geq E(X_n)^2$, hence $L^2$ convergence implies $L^1$.

$L^1$ convergence of this martingale


como fazer o react renderizar uma tabela

Question: Estou tentando fazer uma tabela , 5 de altura por 7 largura , dentro do react , porém , quando eu tentou rodar o 2° for loop  ele não reconhece e acaba não fazendo a ação , obg pela ajuda S2
function Principal(){

var altura = 5;
var largura = 7;
const desing = [];

for(var i ; i < altura ; i++){
  desing.push(
);
  for(var a ; a , largura ; a++){
      desing.push("a"	)
  }
  desing.push(
);
}
return(

   {desing}

);
}

Comment: não entendi sua pergunta!
Answer: Componentes do React não são strings HTML, como se faria num jQuery da vida.
Você deve usar map sempre que for fazer uma lista de componentes de tamanho arbitrário.

function Principal() {
  const altura = 5;
  const largura = 7;

  // cria Array de 0 até n - 1:
  const linhas = Array.from(Array(altura).keys());
  const colunas = Array.from(Array(largura).keys());

  return (

          {linhas.map((linha) => (

              {colunas.map((coluna) => (
                {`(${linha}, ${coluna})`}
              ))}

          ))}

  );
}

ReactDOM.render( <Principal/> , document.getElementById('root'));

Carregando ...

Comment: Rodrigo nos temos em nosso site como renderizar componentes REACT, fiz a edição e coloquei como exemplo, apesar que poderia ter montado um estado nesse componente, fazer assim solto pode trazer problemas futuros.
Comment: muito obrigado , mas ainda tenho uma duvida.Se nós colocarmos as chaves entre os elementos do JSX ele ira executar o código como javascript, certo? .Então , por que se eu colocar o for..loop dentro das chaves ele não executa ?Sendo que eu consigo chamar variaveis e fazer até expressões simples como 3 + 7
Comment: Dentro das chaves é permitido colocar apenas uma expressão que resulta num valor, algo que poderia ser atribuído a uma variável antes do "return". Uma variável não pode ser igual a um loop. Também é permitido usar os métodos .reduce ou .filter, por exemplo.


entityform association with organic group

Question: Is it possible to associate entityform with organic group?
Ive created form and would like it to be accessible by a group specified.
Organic Groups allow to make that possible with content types but I was wondering if this is possible with entityform.
If not - are there any alternatives?
Comment: Anyone have any idea
Answer: It looks like you and I have two very similar questions going. This is a link to my question, which you (@sly) have a nice answer to, and which also includes my custom module answer: Organic Groups access to Entityforms: is it possible?.


Save data from HTML form into .CSV filve using PHP

Question: I'm struggling a bit with obtaining data from my form and saving it to CSV file via PHP. This code is not working and I run out of ideas how to fix it. Is there anything wrong with the way I save it to CSV file? I'd be grateful for your help.
The code is supposed to work this way: I want the user to input some data to HTML form. Then with the usage of AJAX and PHP I want to save it to a csv file. The saving doesn't work - the file stays empty.
 <!DOCTYPE html>

AJAX

<form action='' method='post'>

Name
<input type='text' name='name' value=''>

Email
<input type='text' name='email' value=''>

<input type='submit' name='submit' value='Submit'>

</form>

Comment: What do you mean by it is not working? Are you getting any errors?
Comment: This `$FileName = "sth.txt"//"formdata-".date("d-m-y-h:i:s").".csv";` should be throwing you a parse error and not idea why you have all that PHP wrapped inside script tags. Plus, you're not even writing anything.
Comment: Where is the actual code for saving to .csv file?
Comment: It was supposed to write with echo $content. How do I write to file differently?
Answer: You've commented ; character
Change:
$FileName = "sth.txt"//"formdata-".date("d-m-y-h:i:s").".csv";

To:
$FileName = "sth.txt";//"formdata-".date("d-m-y-h:i:s").".csv";

Also I don't see where You save data to file.
So use this example:
$FileName = "sth.txt";
file_put_contents($FileName, $Content);

Comment: I've changed code to http://wklej.org/id/2304785/ but unfortunately the data I write in form is still not daved in the sth.txt file. Any other ideas?


Finding Lipschitz for trigonometric functions

Question: how would i find the Lipshitz constant for  $$\sin(x)\times \cos(x)$$
or other trigonometric functions?
How would I get my $\operatorname{abs}{x_1 - x_2}$
Comment: What is a cross in $\sin\times\cos$?
Answer: If a function is differentiable on some convex set $C$, then by the mean value theorem you have
$|f(x)-f(y) | \le \sup_{c \in C} |f'(c)| |x-y|$ (with $x,y \in C$).
In your case, $f'(x) = \cos^2 x - \sin^2 x = \cos (2x)$, so we have $|f'(x)| \le 1$ for all $x \in \mathbb{R}$. Hence
$|f(x)-f(y) | \le |x-y|$.
Answer: Notice that $\sin x \cos x = \frac{1}{2}\sin(2x)$. Then, $$\left|\frac{1}{2}\sin(2x) -\frac{1}{2} \sin(2y)\right| = \cos(2c) |x - y| \leq  |x-y|,$$
where $c$ is between $x$ and $y$. Using the mean value theorem usually works, if the derivative of the function is bounded.
Answer: When a function is everywhere differentiable and its derivative is bounded, then it is Lipschitz-continuous, and the Lipschitz constant is the maximum absolute value of its derivative (or anything bigger).
This is a corrolary of the mean value theorem: Suppose $|f'(x)|\le M$ for all $x$.  Then for every distinct $w,x$, there is some number $u$ between $w$ and $x$ such that $|f(w)-f(x)|=|f'(u)||w-x|\le M|w-x|$.


Combining Probability/Forecasts within Groups

Question: I am familiar with the concept of combining forecasts.  In the simplest scenario, that could be just averaging the forecasts.  For example, let's say I have three forecasts representing the likelihood of an event such as (35, 50, 40).  The combined forecast would be (35+50+40)/3 = 41.67 (although I realize there are some more sophisticated methods).  This seems straightforward enough. Although I understand there are some risks associated with this, I was under the impression that combining forecasts is a common approach as in this question's answers.
However, let's say I have a situation that has multiple forecasts for multiple different groups (alternative options). As an intuitive example, a list of orders to be picked up from different locations.
<code>order  prob  location
1      0.4   A
2      0.5   A
3      0.35  A
4      0.95  A
5      0.6   B
6      0.5   B
7      0.75  B
8      0.15  B
</code>
Each order has a probability of being accepted (i.e. forecast).  I want to say the probability of which location an order will be accepted.  My initial instinct was to average the probabilities but I'm hesitant.
Note - the number of probabilities could exceed 100 per group and there could be >20 groups.
Answer:
The combined forecast would be (35+50+40)/3 = 41.67

This is known as Simpson's paradox, a very dangerous approach to share values. The items you work with are probability estimations derived on samples of different sizes, and by averaging the share you will get a confusing result if the actual numbers of right / wrong answers are really different across groups.
It is better to make counts of right answers and divide them by total counts.
Comment: The intent is to use the results as a forecast, so the 'right' answers are not known.
Comment: OK, so I will clarify now what I meant. Averaging probabilites is a popular practice, as you would do when creating a forest of decision trees with binary output. I wanted instead to suggest using exact counts if you accumulated them. If those counts come from samples of different size, then instead of averaging probabilites (shares), you can divide "success" count (as you would do with a number of successes accumulated in terminal tree node) by total count for let's say location A.
Comment: So you are simply suggesting a weighted average by group size?
Comment: Yes, the weighted average according to a train sample size from which you derived the probabilities.


Reading data from a Bluetooth device low energy rfcomm python3

Question: Faced a problem. There is a bluetooth device with low power consumption. BLE. The goal is to send a command to the device and get the data back.
For example: command - 0x** 0x** 0x**, where first 0x** - code command, second 0x - data lenght. Response mast be - 0x** 0x** 0x**. I can not send a command to the device. The device works by RFCOMM. Actually the code that is available, but it does not give a result - it says that the device is off.
from bluetooth import *
import socket

class Work:

    def __init__(self):
        self.rfcon = BluetoothSocket(RFCOMM)
        # self.socket = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM)
        self.server = '**:**:**:**:**:**'
        self.port = 1
        self.data = '0x01 0x00 0x00'

    def scan_device(self):
        connection = self.rfcon.connect((self.server, self.port))

        print('con ===>>> ', connection)
        senddata = self.rfcon.send(self.data)
        print('senddata ====>>>> ', senddata)
        data = self.rfcon.recv(256)
        if not data:
            print("no data!!!")
            self.rfcon.close()
        else:
            print(data)

            self.rfcon.close()

if __name__ == '__main__':
    a = Work()
    a.scan_device()
    a.rfcon.close()

I made it through another library - the code:
from bluepy.btle import *

class Work:

    def __init__(self):
        self.initialize = Peripheral()

    def scan_devices(self):
        scanner = Scanner()
        devices = scanner.scan(10.0)

        for dev in devices:
            print("Device %s (%s), RSSI=%d dB" % (dev.addr, dev.addrType, dev.rssi))
            for (adtype, desc, value) in dev.getScanData():
                print("  %s = %s" % (desc, value))

    def connect_to_device(self):
        print('start con')
        connection = self.initialize.connect('**:**:**:**:**:**', 'public')
        print('initialize complite')
        return connection

    def check_device_status(self):
        print('test ====>>> ', self.initialize.getCharacteristics())
        cmd = '0x01 0x00 0x00 0x20 0x00'.encode('UTF-8')
        print(cmd)
        status_device = self.initialize.readCharacteristic(cmd)

        print('Device status => ', status_device)

    def diconnect(self):
        self.initialize.disconnect()

if __name__ == '__main__':
    a = Work()
    a.connect_to_device()
    a.check_device_status()
    a.diconnect()

It gives a connection but does not send a command and does not return a value since this library does not know what RFCOMM is. Perhaps someone faced this problem in the python and knows how to solve it?
Answer: RFCOMM is a protocol of Bluetooth Classic, BLE does not support it. It is impossible to use RFCOMM for communicating with a BLE device.
You should read an  introduction to BLE, it will give you a basic understanding of BLE.
Anything further will be guessing, it depends on how the BLE device is configured.
If you are using your own device that you can configure, one possibility is to create a characteristic that supports Write and Indicate. You can indicate (to be notified when the characteristic value changes and what is the new value) and write the command. The response will be received via an indication.
Answer: For most practical purposes the answer that RFCOMM is only available in Bluetooth "Classic" is true: most Bluetooth LE devices don't support RFCOMM. However, in principle the Bluetooth Core Spec describes how a channel for RFCOMM can be opened between two LE devices using LE credit-based control flow with an L2CAP_LE_CREDIT_BASED_CONNECTION_REQ command (introduced in Core Spec v4.1 Vol 3 Part A Chapter 4.22 and the Assigned Numbers document).


Why can we drop the absolute sign in this case of trig-substitution?

Question: My question is about dropping the absolute-sign when solving this integral using substitution:
$$\int\frac{dx}{x^2(x^2-1)^{3/2}}$$
We can do the following substitution: $x=\sec\theta$ and $dx=\sec\theta\tan\theta d\theta$:
$$\int\frac{sec\theta\tan\theta d\theta}{\sec^2\theta(\tan^2\theta)^{3/2}}$$
Which equals:
$$\int\frac{\tan\theta d\theta}{\sec\theta|\tan\theta|^{3}}$$
Since $\theta=arcsec(x)$ we can conclude the following (I would think):

When $x\ge1$ then $0\le\theta\le\frac{\pi}{2}$ so therefore $\tan\theta\ge 0$ and we can drop the absolute signs.
But when $x\le-1$ then $\frac{\pi}{2}\le\theta\le\pi$ and then $\tan\theta\le 0$ and therefore I would think we cannot drop the absolute-sign.

But according to my calculus-book we can drop the the absolute sign. So what's going on here?

EDIT: What further confuses me is that the correct answer seems not to be split in two domains. The correct answer apparently is:
$$\frac{1-2x^2}{x\sqrt{x^2-1}}$$
... for all domains (!) according to Wolfram Alpha
Comment: You are correct. Stripping off the absolute sign of $\lvert \tan\theta \rvert^3$ to obtain $\tan^3\theta$ is valid only when $\theta > 0$ (or equivalently, $x > 1$). Although not always the case, it seems that some calculus textbooks tend to be sloppy about specifying the correct domain on which a particular integration technique works.
Comment: This substitution leads to $$ \frac{1-2\sec^2 \theta}{\sec\theta \tan\theta}+C. $$ In order to plug $x=\sec\theta$, we still need to resolve the sign of $\tan\theta$, for otherwise you pickup the sign of $\sec\theta$ (which is equal to the sign of $x$) and obtain$$ \frac{1-2\sec^2 \theta}{\sec\theta \tan\theta}=\operatorname{sign}(x)\frac{1-2x^2}{x\sqrt{x^2-1}}. $$ Of course, when $x > 1$ this sign just disappears and we can safely ignore this, but when you started from $x<1$, this sign also cancels out with the sign that you picked up from $\lvert\tan\theta\rvert^3=-\tan^3\theta$.
Comment: Well, you picked up one $\mathrm{sign}(x)$ when stripping off the absolute signs from $\lvert\tan^3\theta\rvert$. But then you pick up another $\mathrm{sign}(x)$ when rewriting the integral $$\int\frac{d\theta}{\sec\theta\tan^2\theta}=\frac{1-2\sec^2\theta}{\sec\theta\tan\theta}+C$$ in terms of $x$. So they eventually cancel out in both cases $x>1$ and $x<1$. Putting altogether, we have $$\int\frac{dx}{x^2(x^2-1)^{3/2}}=\mathrm{sign}(\tan\theta)\int\frac{d\theta}{\sec\theta\tan^2\theta}=\frac{1-2\sec^2 \theta}{\sec\theta\lvert \tan\theta\rvert}+C=\frac{1-2x^2}{x\sqrt{x^2-1}}+C.$$
Comment: @SangchulLee If I am correct, then why is the split in domains not reflected in the final answer? (See my edit of the question)
Comment: @SangchulLee But according to wolfram alpha we don't need the $sign(x)$
Comment: I added the explanation. :)
Comment: @SangchulLee I don't get it: the minus sign we picked up from $-tan^3\theta$ IS the cause of $sign(x)$ isn't it?
Comment: In fact, it is $\cos\theta=-\lvert\cos\theta\rvert$ when $\frac{\pi}{2}<\theta<\pi$. Anyway, $\lvert\tan\theta\rvert=\sqrt{\sec^2\theta-1}$ is *always* true and that is why we do not have $\mathrm{sign}(x)$ in the end.
Comment: @SangchulLee Your comments helped much! If you transform it into an answer I can accept the answer.
Answer: You can choose a different domain for $\theta$; for example, $\theta \in (0, \frac{\pi}{2}) \cup (\pi, \frac{3\pi}{2}) $.
As $\theta$ ranges from $\pi$ to $3\pi/2$, $\sec(\theta)$ decreases from $-1$ to $-\infty$ and $\tan(\theta)$ increases from $0$ to $+\infty$.
In particular, on this domain for $\theta$ the substitution $x = \sec(\theta)$ still covers the domain $x \in (-\infty, -1)$, but you have $\tan(\theta)$ remaining positive.

Incidentally, a point often overlooked in introductory courses is that when you antidifferentiate a function on a disconnected domain, each component of the domain gets is own distinct constant of integration.
So, if you want to speak in the full generality of covering both the $x > 1$ and $x < -1$ domains, you need to remember that each of those domains gets is own separate constant of integration.
Comment: Thanks for an interesting alternative to my method. But it doesn't really address the question if and why we can remove the absolute sign in that case... Also see the edit to the question, which shows that the solution is not divided into seperate domains.


Probability Theory. Moving from finite to continuous

Question: This has probably been asked before, as this is (I think) a fundamental theory of statistical theory, but I don't know what it is called, hence I have not yet found an answer.
Consider a box which produces random numbers.
The observed values are $x_i$.
If we have a total of $N$ observations, we could add them together. $\sum_{i=1}^N x_i$.
If we divide by $N$ we get something more interesting. $\frac{\sum x_i}{N}$ This is the mean.
If we were to assume there exists some underlying probability distribution $P(x)$ then we should be able to calculate the mean of this probability distribution. This is also the first moment of the distribution. It is obtained by integrating.
$$\int_x x\cdot P(x) \mathrm{d}x=\mu$$
How can we prove the two functions are related? There is a discrete form, and a continuous form. It should be possible to relate the first form to the second by taking a limit of $N\to\infty$. But I cannot rigerously convince myself how to connect the two. This seems like a difficult problem - but I am not sure if that is because it is actually trivial, or because this is genuinely difficult to prove.
How can we prove this?
$$\frac{\sum x_i}{N} \to \int_x x\cdot P(x) \mathrm{d}x=\mu$$
Comment: Search your textbooks or the Web (or even this site) for the "Weak Law of Large Numbers" and the "Strong Law of Large Numbers."  They trace their origin to J. Bernoulli's posthumous [*Ars Conjectandi,*](https://en.wikipedia.org/wiki/Ars_Conjectandi) published in 1713.
Answer: I think I have an answer to this now, however I am not exactly confident as to how mathematically rigerous this is.
Firstly let me address the Weak Law of Large Numbers.
The Weak Law does apply here, because it makes the following statement about sampling a large number of IID Random Variables from a distribution. It says that:
$$\lim_{n\to\infty}\sum_{i=1}^{n}\frac{X_i}{n}=\mu$$
where $\mu$ is obtained by integrating the underlying probability density function.

The Weak Law makes a statement about how far from the mean a set of $n$ samples is likely to be, in other words it relates probabilities to this sum.

However, what I had intended in asking my question was a bit of a different approach.
I think the answer is actually fairly trivial.
We make the following definition of the expectation value:
$$\mathbb{E}[{X_n}]\hat{=}\sum_i^n \frac{x_i}{n}$$
What can we say about the $x_i$? If we assume that these are drawn from an underlying probability density function, then we could calculate the weighted average.
At this point, I am not sure about the how rigerous this is. Is this a circular proof? I think not, and here is why:
We could imagine a specific probability density function $p(y)$. Each $x_i$ could take one of $m$ possible values of $y_j$, where $j\in[1,m]$.
At each value $p(y_j)$, we have a sampled value of the pdf $p_j$.
At this point I had drawn a diagram on paper with an arbitrary squiggly line for the pdf, and drawn evently spaced sampling points along the horrisontal axis. (Which confusingly here I have labeled as "$y_j$".)
We can imagine comparing this "sampled" pdf with different values of $m$. (Different numbers of samples.) If we sample it, and add up all the samples, then if we were to take more samples, the number we would end up with would be larger.
The pdf is everywhere $>=0$. If we sample it an infinite number of times, we obtain something which is infinite.
The solution is to normalize. Irrespective of how many samples of the pdf we take, we want the sum of those samples to be 1.
We are taking $m$ samples of $p(y_j)$. These are evenly spaced samples between the minimum and maximum values of $y_j$.
This is what we obtain, the weighted average of any $x_i$:
$$\frac{\sum_j p(y_j)y_j}{\sum_j p(y_j)}$$
When calculating this I made a number of intermediate steps, but I do not think these necessarily make the result any clearer. I will append those to the end of this question.
To continue, since all the $x_i$ are the same (iid), we obtain this:
$$\mathbb{E}[{X_n}]=\sum_i^n \frac{1}{n}\frac{\sum_j^m p(y_j)y_j}{\sum_j^m p(y_j)}$$
This seems to be quite a trivial result, and there isn't anything complicated about it. It is not quite the same as "just taking a weighted average", because although this is a weighted average, the more important point is that:

If $n$ is large, then although the individual values of $x_i$ are "fixed" values, and may be highly variable in value, we can move from a manner of thinking where $x_i$ is a number, to a manner of thinking where $x_i$ takes all possible values, but those values are weighted by their respective probabilities.

The respective probabilities are proportional to the underlying pdf, and the constant of proportionality is obtained by performing a normalization. Although the pdf itself is normalized, sampling it as uniformly spaced points is not. The more samples we take, the larger the resulting weighted value $x_i$ will be.

The set of $y_j$ and $p_j$ are discrete. We can obtain something continuous by multiplying by one and taking the limit $\lim m\to\infty$.
$$\lim_{m\to\infty}\sum_i^n \frac{1}{n}\frac{\sum_j^m p(y_j)y_j \frac{\Delta y}{m}}{\sum_j^m p(y_j)\frac{\Delta y}{m}}$$
$\Delta y = y_{max}-y_{min}$. $y_{max}$ and $y_{min}$ are arbitrarily large, and we can take them to infinity.
We obtain:
$$\sum_i^n \frac{1}{n}\frac{\int_y p(y_j)y_j \mathrm{d}y}{\int_y p(y_j)\mathrm{d}y}$$
The definition of the average of the underlying pdf, which is the first moment, exists in the above equation, and is $\mu$.
$$\sum_i^n \frac{1}{n}\frac{\mu}{1}=n\frac{1}{n}\mu=\mu$$
Therefore
$$\mathbb{E}[X_n]=\mu$$

Sampling the PDF:
$x_i$ is a idd random variable drawn from some pdf $p(y)$. We drop the index $i$.
$$x=\sum_j^m p_j y_j$$
where $p_j$ is the probability to obtain $y_j$. $p_j$ depends on how we sample the underlying pdf. It depends on $m$. We sample from some minimum and maximum value of $y$, $y_{max}$, $y_{min}$.
Because $p_j$ depends on $m$, better to write $p_m(y_j)$.
$$x=\sum_j^m p_m(y_j) y_j$$
$p_m$ is proportional to the pdf $p(y)$. Therefore $p_m(y_j)=\alpha_m p(m_j)$
The symbols $p(y_j)$ and $p_m(y_j)$ mean totally different things here. The former is the underlying pdf, and the latter is a sampled version of it.
From here, things are relatively trivial. We calculate $\alpha_m$ by normalizing:
$$1=\sum_j^m \alpha_m p(y_j)$$
hence
$$\alpha_m^{-1}=\sum_j^m p(y_j)$$

Not totally sure about this answer so some feedback would be helpful?


Testing for significant difference in mortality rate between multiple groups

Question: How do I test for a significant difference between the mortality rate of 4 groups (each group with a different n)
group 1: mortality rate = 30.9%, n=55
group 2: mr = 0%, n = 4
group 3: mr = 23.3%, n = 30
group 4: mr = 24.6%, n = 69
is it sufficient to just do a t-test between each group? seems like that would be a convoluted way to present the results.
Answer: Since you have binomial data, the modern way is to use a binomial generalized linear model. Then we can get an overall test of the null of no differences between groups. Your approach of t-tests runs into multiplicity problems. To do this we first need to recover the number of deaths from your percentage and n, in R:
perc <- c(30.9, 0.0, 23.3, 24.6)
n    <- c(55, 4, 30, 69)
x    <- round((perc/100)*n)
yourdata <- data.frame(x=x, n=n, perc=perc, Group=as.factor(1:4))
yourdata
   x  n perc Group
1 17 55 30.9     1
2  0  4  0.0     2
3  7 30 23.3     3
4 17 69 24.6     4

Then we can set up a binomial regression:
mod0 <- glm( cbind(x, n-x)  ~ Group, data=yourdata, family=binomial)
mod0

Call:  glm(formula = cbind(x, n - x) ~ Group, family = binomial, data = yourdata)

Coefficients:
(Intercept)       Group2       Group3       Group4
    -0.8044     -22.5610      -0.3852      -0.3137

Degrees of Freedom: 3 Total (i.e. Null);  0 Residual
Null Deviance:      3.253
Residual Deviance: 5.697e-10    AIC: 20.25

Then the test, which is analogous to anova:
anova(mod0, test="Chisq")
Analysis of Deviance Table

Model: binomial, link: logit

Response: cbind(x, n - x)

Terms added sequentially (first to last)

      Df Deviance Resid. Df Resid. Dev Pr(>Chi)
NULL                      3     3.2531
Group  3   3.2531         0     0.0000   0.3542

But, our data have the form of a contingency table, so we can do a traditional chisquare test, in this case using simulation for the p-value:
with(yourdata, chisq.test(cbind(x, n-x), sim=TRUE, B=20000 ))

    Pearson's Chi-squared test with simulated p-value (based on 20000
    replicates)

data:  cbind(x, n - x)
X-squared = 2.2744, df = NA, p-value = 0.5335


Using linear probability model with panel data - what to do when R-squared is low?

Question: I have a dependent variable (innovate) which is binary (0 or 1 outcome) and an independent variable (week). Sample of the panel data:

So for instance, firm 1 innovated in week 3, firm 2 innovated in week 6, and firm 3 innovated in week 2 in response to a policy change.
When I run an OLS regression with Y = innovate and X = week, I get this in Stata:

Now, R-squared is low, signalling that the model isn't a good fit. I have a few questions:
1) Is this an appropriate way to estimate the effect of increasing the number of weeks on the probability of innovating?
2) Is it acceptable to use OLS on panel data with binary outcomes?
3) What could I try now that I know the R-squared is low?
Thank you!
Answer: 1) No, this is not an appropriate way to estimate the time to an event.  Imagine you changed your scale from weeks to days, or seconds. You would automatically inflate how much data you have, and so the estimated probability would tend to zero. Your outcome shouldn't change based on what scale you measure it on in this way. Tools from survival analysis are better suited, even if there is no censoring in your data.
2) LPM is an area of heavy debate. The arguments for and against LPM are moot because your approach should not focus on the binary outcome innovate but rather the week variable.
3) R squared will cease to be a good measure of model fit once you move to something like cox regression or the Kaplan Meier estimator.  I'm sure there are metrics similar to R squared in which the log likelihood is replaced by the sum of squares, but I'm not familiar enough with survival analysis to say for sure.
Don't believe survival analysis is appropriate?  I'll demonstrate.  let me remake your data and run it through a survival analysis in python using lifelines
import numpy as np
import pandas as pd
from lifelines import KaplanMeierFitter
import matplotlib.pyplot as plt

%matplotlib inline

frames = []

# Create some data.
# Randomly generate observations in time
# I assume we stop observing when they innovate
for i in range(100):

    num_weeks = np.random.poisson(13.5)
    weeks = np.arange(1,num_weeks)
    innovate = np.zeros_like(weeks)
    innovate[-1] = 1
    frame = pd.DataFrame({'firm': i, 'weeks':weeks, 'innovate':innovate})

    frames.append(frame)

df = pd.concat(frames)

# We only need observations where innovation occurs.
df_needed = df.query('innovate==1')

kmf = KaplanMeierFitter()

kmf.fit(df_needed.weeks, df_needed.innovate)

ax = kmf.plot_cumulative_density()

You only need the data when the innovation occurs or the latest observation for each firm (these would be censored data).  In this case, the innovate column would have a 0 rather than a 1.  Here is the result from a Kaplan Meier Estimator

This plot shows us the probability that a firm does not innovate provided it has not innovated up until now.  As time goes on, the probability of not innovating goes to 0 (which makes sense, at least in this cooked up example).
Comment: There are only two variables.  Their relationship is the question.  In analyzing that, how can one focus on 1 variable but not the other?
Comment: @rolando2 The rows where `innovation==1` indicate the time when the incident took place.  All that is needed are the rows where `innovation==1`  or the latest observation from each firm in the case the firm did not innovate.  That makes use of both variables, and is a better approach than an LPM, at least according to the facts presented by OP.


Does C# have implicitly-named parameters for the Lambda syntax similar to Swift?

Question: In Swift, the concept of closures is closely synonymous to lambda expressions in C#. Using an example where there's a function foo() (Foo() in C# due to different standardized naming rules) that takes in a lambda/closure which has two parameters, you can write them like this...
C#:

Foo( (a, b) => a + b );

Swift:

foo{ a, b in a + b };

However, Swift can also implicitly name those variables...
foo{ $0 + $1 };

Note that there is no in in that statement.  The compiler confirms that if there are two parameters required, then you have to have both $0 and $1.  If there were three parameters, it would also require $2.
I'm wondering if C# has anything similar where the parameters are implicitly defined.
Comment: As of C#8, there is no such similar support.
Comment: @user2864740, can you post that as an answer so I can mark it as such? Otherwise this'll just sit open, or I'll have to answer my own question and you won't get those shiny new ten points!
Answer: There isn't something similar in C# (as of C# 8).


Formula excel SOMASE

Question: Coloquei esta fórmula no Excel e não deu certo, porque?
=SOMASE(E2:E158;"<=4>=10";B2:B158)

Não consigo colocar que seja maior que 4 e menor que 10, ele só aceita uma das duas hipóteses... como fazer?
Answer: Para vários critérios, você deve usar o SOMASES
=SOMASES(B2:B158;E2:E158;">=4";E2:E158;"<=10")

Sintaxe:
=SOMASES( intervalo_soma, critérios_intervalo1, critérios1, [critérios_intervalo2, critérios2], ...).

Formula excel SOMASE


Why A2billing doesn't charge customer-to-customer calls?

Question: I have installed A2Billing+Asterisk13.18-cert3. Outgoing calls are configured and billed correctly.
Once a customer calls another, two CDR records stored, Calltype:DID_Voip and CallType:DID-ALEG, but none of them are charged and the charges are zero.
I googled to find out any workaround to fix the issue. All results were incomplete and outdated.
I created a LOCAL provider, then a TRUNK with Tech=local, Provider IP:a2billing. DIDa are also configured and I can receive calls.
When using simulator, it can find the correct Call Plan and rates. but it doesn't apply to the call.
I have two questions:
(1) How can I setup asterisk to pass the call through a local trunk so A2Billing can apply charges to calls?
(2) What should I do to make A2Billing charge the customer-to-customer calls?
Thanks
Answer: A2Billing designed to charge prefix.
So if you want it charge customer call, you have create prefix and charge it.
You need call go via Local provider, not just create it.


How do variable functions in PHP work?

Question: In php.net the following is written:

Variable functions won't work with language constructs such as echo, print, unset(), isset(), empty(), include, require and the like. Utilize wrapper functions to make use of any of these constructs as variable functions.

source
What does that mean?
Could anyone give examples because I've tried using the variable function in an echo and it worked perfectly:
function city()
{
    return "new york";
}
$var = "city";
echo "city:  "  . $var();

Answer: It means you can't do something like this:
$var = "echo";
$var "Hello World!";

Comment: `+1` Ding ding ding! :-D
Comment: The comment about wrapper functions means you /can/ do something like this:
`function myecho($str) { echo $str; } $var = "myecho"; $var("Hello world!");`
Answer: You cannot do that with these functionns echo, print, unset(), isset(), empty() because actualy in php they are not functions, they are reserved keywords with functions call like.
Answer: Correct Way is
function city()
{
    return "new york";
}
$var = "city";
echo "city:  "  . city();

It will Return :
city: new york
Comment: This answer is not helpful and you've completed negated the purpose in setting `$var`.

How do variable functions in PHP work?


sendKeys is not sending '@' character in WebDriver

Question: I am facing below problem. Can anyone provide me the solution?
Problem: WebDriver sendKeys method is not sending @ character to a text box..
I tried normally- i.e, sendKeys("Test@123"), but passing Test123 only...
I tried below as well, but none of them worked..
driver.findElement(By.xpath(<xpath expr>)).sendKeys("Test\@123");
driver.findElement(By.xpath(<xpath expr>)).sendKeys("Test\\@123");
driver.findElement(By.xpath(<xpath expr>)).sendKeys("Test/@123");

I can not provide the website URL, as it can not be accessible outside.
Just fyi, its an asp.net application.
Any help would be greatly appreciated...
Comment: That's an old version of Firefox. Have you tried updating it and seeing if you face the same problem? From what else you've said though I do have to ask - can you manually enter a `@` into this particular website and is it captured normally?
Comment: What versions are you running of all relevant details - webdriver, browser, java, etc.
Comment: Hi Mark, I am using webdriver using java.
Comment: I could tell from your tag and the language you used, I was asking what versions are you running? :)
Comment: Webdriver 2.33 [Latest version] and FF 15.0..
Comment: Mark, I am able to pass in other websites..But its not working in our website.. I can not share the website, as it can not be accessible outside..
Comment: Can you do this manually in your application?
Comment: Hi Mark and Chetan, I tried manually and it is working..But using sendKeys(), its not working...
Comment: I tried below as well..But none of them worked.. :( 'fd.findElement(By.xpath("//*[@id='txtLoginID']")).sendKeys(String.valueOf(Character.toChars(64)));'
'fd.findElement(By.xpath("//*[@id='txtLoginID']")).sendKeys(Character.toString((char)64));'
Answer: Have you tried replace special characters with its codes?
For example:
>>> a='@'
>>> ord(a)
64
>>> string="test"+chr(64)+'123'
>>> string
'test@123'


The service "redirect.request_subscriber" has a dependency on a non-existent service "path_alias.manager"

Question: We have inherited a Multisite Drupal setup and are managing the migration for a client. We have the codebase set up locally and have two of the sites up and running. We are hitting an error on the third though:

Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException: The service "redirect.request_subscriber" has a dependency on a non-existent service "path_alias.manager". in Symfony\Component\DependencyInjection\Compiler\CheckExceptionOnInvalidReferenceBehaviorPass->processValue() (line 86 of /Users/{hidden}/Sites/{hidden}/vendor/symfony/dependency-injection/Compiler/CheckExceptionOnInvalidReferenceBehaviorPass.php).

We're not sure why this error is displaying on this one site and not on the others. Can anyone help please? Drupal core is up to date - running 9.3.12.
Comment: Is the `path_alias` module enabled? https://www.drupal.org/node/3092086
Comment: I cannot access this particular site's admin (the whole site is erroring), but running `drush pm-list --type=Module --status=enabled` tells me that the module is enabled.
Comment: ... however, the fact that the `path_alias` and `path_alias_revision` database tables do not exist for this site suggests otherwise!
Comment: Then the database is not in syn with the codebase. You can try if update.php can fix this, but if there is such a big gap I doubt it works. If you can't log in anymore you can grant access to update.php in settings.php
Comment: I'd uninstall the module in question and then enable it so it goes through the installation process properly. I've seen this happen before but never worked out why, but turning it off and on again :) seems to do the trick.
Comment: Thank you all. @4uk4 accessing update.php revealed what appears to have happened. The previous development team went through an exercise of updating all the sites to Drupal 9 before handing them over to us. It would appear that they missed a couple!
Answer: For me, a search and replace in the .sql file changed path_alias.manager data entries unwanted ... so needed to get my data back right ..


Why do the balls used in rugby and American football have a similar shape?

Question: Is there any reason for the fact that rugby and American football share this (quite unusual) ball shape?

Do they have common roots? Does the American football ball come from the rugby one (which doesn't have the laces)? Is there any accepted "proof" behind this?
Answer: Since American football evolved partly from rugby1, it's no surprise that their shapes are similar.
The main reason for the oblong shape is to allow carrying the ball by hand. A round ball kicks very well indeed, but is very easy to knock away; an oblong ball is still effective to kick and is much easier to grip.
American footballs kept the same basic shape but added laces and pointed ends because both features make the ball easier to throw. Rugby, of course, needs neither feature.

1 See Wikipedia's History of American Football. Ironically, the first American football game that used an oblong ball and allowed carrying was Harvard vs. McGill, a Canadian university.
Comment: There are far more passing of the ball in Rugby than in American Football.  It is much easier to spiral an oblong ball than a round one which will keep its direction better. Shorter rugby passes dont tend to use the spiral but for quick passing between the backs the shape of the ball goes a long way in achieving this. Passing in Rugby is mostly done with 2 hands where as America football it is one
Comment: Gaelic football also has a lot of ball carrying, but uses a round ball (somewhat smaller and heavier than a soccer ball).
Answer: The shape of both is mostly to do with aerodynamics.  An American football needs to be thrown over long distances, and the ball's shape helps it maintain its trajectory and is therefore easier to throw.  Although it doesn't need to be thrown over as long a distance, the game is predominantly played from hand to hand.  I'd disagree with admartian in that the ball is passed far more than it is kicked.  As an example, look at the recent six nations match between Wales and France where Wales completed 164 passes and France completed 99, compared to both teams combined only kicking whilst in possession 67 times.
Answer: They are similar and different because they share a similar lineage.
The main difference is down to their purpose. American footballs are predominantly designed to be thrown (hence the narrower end-points), while Rugby balls tend to be thicker as they are just as commonly kicked as they are passed around.
Answer: Here is another link which shows photos of the oblong Native American ball..
We still play this game today at our ceremony grounds.
http://delawaretribe.org/blog/2013/06/27/pahsahman-the-lenape-indian-football-game/
Comment: Do you have any assertions for your beliefs on rugby's roots? Also, you can add onto your previous answer by editing it. https://sports.stackexchange.com/help/editing
Comment: However, rugby isn't derived from any native American sports.
Comment: I believe it is and that this is an oversight or outright repression of Native History.  These games were played in prep schools in the Northeast US which had strong elite ties to their English roots.
Comment: I believe rugby's roots are as American as the Irish Potato
Answer: Please see the following link to the oblong ball's origin in Native American Football centuries before modern football or European Rugby were ever thought of.
http://lenapelady.tripod.com/football.html
Like Lacrossse, Rugby and Football are both adaptations of Native American games.
Comment: Welcome to Sports SE. "Links to external resources are encouraged, but please add context around the link so your fellow users will have some idea what it is and why it's there." https://sports.stackexchange.com/help/how-to-answer
Comment: Are the authors of that piece (and you) misusing "oblong" to mean "oblate spheriod", or is this actually evidence *against* your claim?


Grace note introduces spurious symbol in Lilypond

Question: I have this simple code:
\new StaffGroup <<
  \new Staff \with {
    instrumentName = "Vocal"
    shortInstrumentName = "Voc"
  } \new Voice = "voice" \relative {
    a4 b c d
  }

  \new Lyrics \lyricsto "voice" {
    \lyricmode { A B C D }
  }
>>

As expected it produces the following:

But the moment I add a grace note at the beginning:
\version "2.24.0"
\header {
  title = "Jara si dil me de jagah"
  composer = "Pritam"
}

\score {
  <<
    \time 4/4
    \tempo 4 = 82
    \new StaffGroup <<
      \new Staff \with {
        instrumentName = "Vocal"
        shortInstrumentName = "Voc"
      } \new Voice = "voice" \relative {
        %\grace {s16}
        \grace {g16} a4 b c d
      }

      \new Lyrics \lyricsto "voice" {
        \lyricmode { A B C D }
      }
    >>
  >>

  \layout {
  }

  \midi {
  }
}

this happens:

There is a spurious "C" symbol. How can I fix this?
Comment: Does this answer your question? [Errors with slashed grace notes in LilyPond](https://music.stackexchange.com/questions/77497/errors-with-slashed-grace-notes-in-lilypond)
Comment: Tried adding a grace s16. Didn't work.
Comment: Oh, then can you please edit your question to show the other staffs/voices. Because without them second code block doesn't exhibit the bug. (the code blocks don't match the images)
Comment: I have only one staff. Using lilypond 2.24.0 on Mac.
Comment: Added full code.
Comment: Thanks for adding more of the code, but I don't understand how you got that image from it; the notes don't match.
Comment: Oops! There was a transpose block too.. But I guess that is not relevant
Answer: Move the \time and \tempo commands inside the \new Voice block, like this:
...
\new Voice = "voice" \relative {
    \time 4/4
    \tempo 4 = 82
    \grace {g16} a4 b c d
}
...

This will prevent the extra staff from being created, and hence avoid the issue 34 bug from happening.


Form not validating on client side after implementing ajax

Question: The Index page has a partial view (ReservSearch.cshtml) to enter the search arguments  and another to display the result (Rates.cshtml) via ajax, that calls the GetRates() action in the HomeController.
Before using the ajax call, the form was validating correctly, i.e., it didn't call the GetRates() action unless all the required fields were filled in, but the Rates partial view was displaying in another page of its own, thus the ajax call to display it correctly in the Index page.
After implementing the ajax call, the Rates View displays where it is supposed to be, in a div on the Index page, assuming the user entered all values correctly before clicking the submit button.
The problem is that, now, whenever the form is submitted, it always call the GetRates() Action method in the controller, even if there is no values entered in the form. It still works, because the ajax executes the error function and not the success, but I wonder if this is the proper way to do it and if my code is correct.
// VIEW: ReservSearch.cshtml

@model Models.ReservSearch

@using (Html.BeginForm("GetRates", "Home", FormMethod.Post, new { @id = "reservSearch"}))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

        @Html.TextBoxFor(model => model.DropOffDate)
        @Html.ValidationMessageFor(model => model.DropOffDate)

        @Html.TextBoxFor(model => model.PickUpDate)
        @Html.ValidationMessageFor(model => model.PickUpDate)

        <input type="submit" value="GET RATES"/>

}

enter code here

// HOME CONTROLLER
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult GetRates([Bind(Include = "DropOffLoc,DropOffDate,PickUpDate")] ReservSearch reservSearch)
{
    if (ModelState.IsValid)
    {
        // Code ....
        return PartialView("~/Views/Shared/Rates.cshtml", rates);
     }
     return PartialView("~/Views/Shared/ErrorInfo.cshtml");
}

Comment: You might also need to prevent the form from submitting the traditional way so that AJAX can process it for you: `$('#reservSearch').submit(function (e) { e.preventDefault(); // followed by your $.ajax call}`
Comment: @MonkeyZeus, he does by returning false.
Comment: @Zabavsky I retract my comment
Answer: You should check whether your form is valid and after that make an ajax call:
$('#reservSearch').submit(function () {
    if($(this).valid()) {
         // ajax call
    }
    return false;
});


Is there a simple expression for universal quantification without vacuous truth?

Question: I'm working on a software problem and trying to describe it in symbolic logic so that I can get my head around it.
I have
$isnt(n) := \mathbf{F} \neq \emptyset \wedge \forall f \in \mathbf{F} : P(n,f)  $
Basically, I'm checking n against all elements in F, unless F is empty.
Is there a way to simplify this so as to have no conjunctions (or disjunctions) outside of the quantifiers
Comment: Just today I was wondering whether it would be worthwile having a separate symbol for this.
Comment: In the opposite direction, $\exists f\in\mathbf{F}: P(n,f))\wedge\forall f\in\mathbf{F}: P(n,f)).$
Comment: Well, $\neg(\mathbf{F}=\emptyset\vee\exists f\in\mathbf{F}:\neg P(n,f)).$ But I don't suspect this is what you want. Can you clarify what is allowed?
Comment: I'd like to remove any conjunction or disjunctions outside of the quantifier
Comment: @Dancrumb: In that case the quantifier can't be $\forall$, since that's always true on an empty set. It can't be $\exists$ alone, since that can't distinguish between some cases and all cases. Can you use nested quantifiers?
Comment: @Charles: yes, nested quantifiers would be acceptable. In short, these quantifiers map onto functions in a programming language: `some` for $\exists$ and `every` for $\forall$... so i can nest these quite easily
Comment: @Dancrumb: Of course so does `||` map to $\vee.$
Comment: @Dancrumb:  Could you please explain _why_ you would prefer nested quantifiers to conjunctions or disjunctions outside of the quantifier?
Comment: @Charles: yes... and `&&` maps to $\wedge$
Comment: @TaraB: Maybe I won't; I'm looking for an expression that lends itself to a more graceful implementation in code. Rearranging the expression with junctions outside the quantifiers won't change the way the code looks, just the operators that I'm using.
Comment: @Dancrumb: So why not `F.length > 0 && every f in F P(n,f)`?
Comment: @Dancrumb:  Right, well then I don't think that answers to the question as you've phrased it are likely to be very helpful to you.  Could you please have a look at my answer and let me know why that's not how you want to do it (if it's not)?
Answer: So you can nest quantifiers, but you can't use conjunctions or disjunctions outside the quantifiers. So how about
$$
\exists f\in\mathbf{F}\ \forall g\in\mathbf{F}: P(n,f)\wedge P(n,g)
$$
Comment: Why $P(n,f)$?  How about just $\exists f \in \textbf{F} \forall g \in \textbf{F} \thinspace \colon \thinspace P(n,g)$?
Comment: This looks like it could make the program run a lot slower, though.
Comment: @TaraB: Yes, substantially. But that seems unavoidable under the constraints, see my comments to the question.
Comment: @MartianInvader: Sure, that works too.
Comment: @MartianInvader:  That's better. =]
Answer: I don't understand why you're asking for what you seem to be asking for.  Surely the efficient way to define the function is something like:
if $F = \emptyset$ then return false;
else for $f\in F$ do
for $f\in F$, if $P(n,f)$ = false then return false;
return true;
Comment: That was my thought, and the reason I posted the `||` comment. But perhaps there is some reason.
Comment: Yes, I've asked for clarification, and perhaps all will become clear shortly.
Comment: In the end, that's what I did; I created a function generator that takes in **F**, *P* and returns a function that takes *n*... appreciate people's efforts though!
Comment: Well, it is the natural and efficient way to do it. =]


Interesting opensource projects to contribute to as a sysadmin?

Question: I know that as a sysadmin you can contribute to opensource projects such as a Debian and Fedora. Joining their infrastructure groups and help with administration. I'm just wondering if there are any other interesting opensource projects/communities. To which sysadmin with a free time can contribute and sharpen his skills.
Answer: While a good question, the options are endless.  I tend to try to contribute to things I use and find useful, while focusing on projects that are especially in need of assistance.  Inprotect is a team that could definitely use some additional assistance.

CentOS - Linux distribution. (Debian, Slackware, and other distributions are acceptable as well.)
Inprotect - Front end for Nessus, a vulnerability scanner.
SNORT - A network IDS.
Request Tracker - A very customizable ticket system.
Answer: Monitoring products : OpenNMS, Nagios, MRTG, Orca, etc.


Time column average in access database

Question: I have an access database one table has time column  that shows the total time from (endtime - starttime)  I need to have that column averaged (hh:mm) ss not needed.  I need to store this average into another table, and then be able to display that in a textbox. with conditional formating as far as color for certain time ranges.  I'm going to need to do this for a daily range and a monthly range, just wonder what would be the best way to accomplish this.  this monthly and daily average will need to update each time the table has records added to it.
My thoughts on this was pull the daily times into an array, then average the array, and store that average in another table.  Then use the daily average table to display in a textbox, along with the conditional formatting. and then the same thing for the monthly time average as well.
Answer: It is by no means difficult to obtain this information from a query, time is just the decimal portion of a number.
<code> SELECT Format(Avg(CDbl([Atime2])-CDbl([ATime1])),"hh:mm:ss") AS Diff
 FROM Table;
</code>
Or
<code> SELECT Sum(DateDiff("n",[ATime1],[ATime2])) AS SumMins,
        Count([ATime1]) AS CountRecs,
        Avg(DateDiff("n",[ATime1],[ATime2])) AS AvgMins
 FROM Table;
</code>
Furthermore, MS Access 2010 has data macros and calculated columns that are good even outside of Access.
Finally, it is not generally recommended that you store a value that becomes invalid at every edit when the value can easily be calculated.
Comment: the values in the other table are needed for historacle data, they are bound by a date field for each individual day
Comment: You can use a query similar to the above to update the table as required.

Time column average in access database


Initialise and return a byte array in java

Question: In my code i have to pass a bye array (byte[] temp = null;) to a
     function which is allocated and filled with data inside it. After
     returning from  function it is still null. How can i find a
     solution to this problem.??? Please help me.
  byte[] temp = null;
  ret = foo(temp);

  boolean foo(byte[] temp)
  {
      temp = new byte[];
      //fill array
  }

Comment: Show us the code you have.  If you are not returning the type that was created then of course it will be null.  The object is destroyed once you return to main.
Comment: Can you provide the code of your function ?
Comment: If thats your code then you can see why its null, post your code in your question as an edit.
Comment: i know it will be null, i need data in temp array in main method. Is there any way to do so?
Comment: Java only passed reference by value so you can't change an argument the way you suggest.
Comment: @UnnikrishnanPV "Is there any way to do so?" - No. Not unless you pass in an actual array to `foo` (not null) and stop overwriting the reference to it, or you change the method signature to either return the array or take an object that can hold your reference for you (though I wouldn't recommend that as simply returning the array is a better option if you're changing the signature anyway).
Answer: You're not very clear about your code, but if I understand you right, you have something like the following:
byte[] temp = null;
methodThatAllocatesByteArray(temp);
// temp is still null.

If this is a correct understanding of what you're saying, the problem is that temp is a reference to nothing. Sending that reference to another method makes a copy of that reference (rather than use the same reference), therefore, changing that reference (assigning to the parameter variable) only changes it for the local method. What you need to do is to return a new byte[] from the method like this:
public byte[] methodThatAllocatesByteArray() {
    // create and populate array.
    return array;
}

and call it like this: byte[] temp = methodThatAllocatesByteArray(). Or you can initialise the array first, then pass the reference to that array to the other method like this:
byte[] temp = new byte[size];
methodThatAllocatesByteArray(temp);

Since in this case the parameter in methodThatAllocatesByteArray will point to the same array as temp, any changes to it (other than reassigning it to a different array or null), will be accessible through temp.
Comment: @UnnikrishnanPV I'm afraid I have to second Peter Lawrey; why can't you return a `byte[]`? And at some point you must know the size of the array, there should be a way of determining that from where you're calling this. The way you want to do this is simply impossible unless you want to change to a different language (such as C). You'll have to tell us what your limiting factors are though if you want us to work around them. Is your API frozen? If so you might have to initialise the array with a value that you know is AT LEAST large enough, then treat the first `null` value as the end.
Comment: please see my comments @ankur
Answer: You need to use this:
 byte[] temp = new byte[some_const];
  ret = foo(temp);

  boolean foo(byte[] temp)
  {
      //fill array
  }

or
 byte[] temp = null;
  temp  = foo(temp);

  byte[] foo(byte[] temp)
  {    temp = new byte[some_const];
      //fill array
      return temp;
  }

Comment: i cant return temp.:-) Also i size of temp is only known inside foo
Comment: Why can't you return a `byte[]`? Having foo know what size it should be is ideal, I don't see a problem with it.


Importing MYSQL database to NeO4j

Question: I have a mysql database on a remote server which I am trying to migrate into Neo4j database. For this I dumped the individual tables into csv files and am now planning to use the LOAD CSV functionality to create graphs from the tables.
How does loading each table preserve the relationship between tables?
In other words, how can I generate a graph for the entire database and not just a single table?
Comment: See [this page](http://neo4j.com/developer/guide-importing-data-and-etl/#_northwind_introduction) for an example of how to import the Northwind dataset into Neo4j.
Answer:
Load each table as a CSV
Create indexes on your relationship field (Neo4j only does single property indexes)
Use MATCH() to locate related records between the tables
Use MERGE(a)-[:RELATIONSHIP]->(b) to create the relationship between the tables.

Run "all at once", this'll create a large transaction, won't go to completion, and most likely will crash with a heap error. Getting around that issue will require loading the CSV first, then creating the relationships in batches of 10K-100K transaction blocks.
One way to accomplish that goal is:
<code>MATCH (a:LabelA)
MATCH (b:LabelB {id: a.id}) WHERE NOT (a)-[:RELATIONSHIP]->(b)
WITH a, b LIMIT 50000
MERGE (a)-[:RELATIONSHIP]->(b)
</code>
What this does is find :LabelB records that don't have a relationship with the :LabelA records and then creates that relationship for the first 50,000 records it finds. Running this repeatedly will eventually create all the relationships you want.
Comment: Thanks Tim, how do you keep the data in sync after this initial import?
Comment: You'll have to dump deltas, do a full dump and refresh the db, or change the application to update the graph db when it updates the sql db.

Importing MYSQL database to NeO4j


Creating template function overloads for pointer and non pointer type data held inside a container

Question: I am trying to create a template function that is overloaded for pointer and non pointers. I did this and it works.
    template<class D, class V>
    bool Same(D d, V v){ return d == v; }

    template<class D, class V>
    bool Same(D* d, V v) { return *d==v;}

Now I want to extend it such that a templated container is a paramater and there must be one version for the container with pointer  and other with the container for non pointers. I am not able to figure it out. I tried this but it won't work.
    template< template<class> class Container, class Data, class Value>
    bool func(Container<Data> &c, Value v)
    {
        return c[0] == v;
    }

    template< template<class> class Container, class Data, class Value>
    bool func(Container<Data*> &c, Value v)
    {
            return *c[0] == v;
    }

The error c2040 says int* differs in level of indirection from int and points to the first function.
How can I get it to work?
Rest of thecode
template<class D>
class Vec
{
    std::vector<D> m_vec;
public:
    void push_back(D d) { m_vec.push_back(d); }
        D operator[](int i) { return m_vec[i]; }
};
void test_template()
{
    Same<int, int>(2,3);
    Info i = {4};
    Same<Info, int>(i, 2);
    Info ii = {2 };
    Info *pi = ⅈ
    Same<Info, int>(pi, 2);

    Vec<int> iv;
    iv.push_back(3);
    func<Vec, int, int>(iv, 3);
    Vec<int*> pv;
    pv.push_back(new int(3));
    func<Vec, int*, int>(pv, 3);
}

Answer: For the second call to func, the second template parameter should just be int, not int *. Otherwise, the second func declaratino will look for a Vec<int **> as the first template argument (since it has its own pointer).
func<Vec, int, int>(pv, 3);

EDIT: as DyP mentioned, you can also leave out the template arguments completely, as the compiler should be able to deduce them from the actual function arguments.


Instagram API curl code command to php

Question: I can't find the curl equivalent in php for this command

curl -F 'client_id=CLIENT_ID' \
    -F 'client_secret=CLIENT_SECRET' \
    -F 'grant_type=authorization_code' \
    -F 'redirect_uri=AUTHORIZATION_REDIRECT_URI' \
    -F 'code=CODE' \
    https://api.instagram.com/oauth/access_token

I know it should start like that

$ch = curl_init('https://api.instagram.com/oauth/access_token');
curl_setopt($ch, something, ...);
...
...
Answer: One of the equivalents to
curl -F 'client_id=CLIENT_ID' \
    -F 'client_secret=CLIENT_SECRET' \
    -F 'grant_type=authorization_code' \
    -F 'redirect_uri=AUTHORIZATION_REDIRECT_URI' \
    -F 'code=CODE' \
    https://api.instagram.com/oauth/access_token

would be
$url = 'https://api.instagram.com/oauth/access_token';
$fields = array(
    'client_id' => 'CLIENT_ID',
    'client_secret' => 'CLIENT_SECRET',
    'grant_type' => 'authorization_code',
    'redirect_uri' => 'AUTHORIZATION_REDIRECT_URI',
    'code' => 'CODE'
);

$ch = curl_init();

curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

$result = curl_exec($ch);

curl_close($ch);

Hope I helped! -CM
Comment: but what is $fields_string ? Do you mean $fields ?

Instagram API curl code command to php


Entity alteration to prevent entity from being indexed by search_api

Question: I'm using search_api/search_api_solr, and would like to be able to exclude certain nodes from being indexed by Solr at all.  In looking at search_api.api.php, I see this text:

Please be aware that generally preventing the indexing of certain items is
  deprecated. This is better done with data alterations, which can easily be
  configured and only added to indexes where this behaviour is wanted.
  If your module will use this hook to reject certain items from indexing,
  please document this clearly to avoid confusion.

I'm just getting into the whole entity API, so it's not so "easy" for me to do this.  I'm thinking that he's referring to hook_entity_property_info_alter(), and I've used that to add a property to an entity so it is available as a facet and field available in search results.  However, I'm not seeing how to alter the entity so that I can control whether it is indexed by search_api or not.  Can someone point me in the right direction?
Thanks.
Answer: When he says "better done with data alterations" he is referring to the "Data Alterations" fieldset / section in the "Workflow" tab for each index in the UI and that is accessible in code through hook_search_api_alter_callback_info().
You can see a patch that uses this (it doesn't use the hook but the original function because it is being added to the actual search_api module but you get the idea) to not index unpublished nodes: http://drupal.org/node/1507882
I think his audience for this comment is other contributed module makers. You can imagine it would be extremely confusing for a user if certain items didn't get indexed because a module they turned on used that hook.
If you are trying to exclude nodes from being indexed (be aware that you can use the "Node Access" data alteration which will keep unpublished nodes from being returned for searches for users who don't have content editing access) you can use that hook checking for the node ids and unsetting them as in the example function.


Which test to use: t-test independent or wilcoxon rank-sum?

Question: I have two groups: A and B. Based on QQ plot and Shapiro-Wilks test, both A and B are not normally distributed. I have included the histogram images below for further context.
A has a sample size of 3068, and B has a sample size of 1981.
The variance for A is 278.3801 while B's is 281.8245.
The variables being compared are independent.
I am conflicted whether or not to use t independent test or Wilcoxson's Rank Sum test. The argument for using the t independent test is because the sample size is large enough to apply the Central Limit Theorem.
On the other hand, I am leaning towards Wilcoxson's Rank Sum test because the sample size of the two groups are drastically different (3068 vs 1981), and the distribution for both groups are non-normal.
Which test do you think you would use? It would also be great to give your explanation as to why you choose the test. Thank you.
Additional context:
Shapiro-Wilk normality test
For A: W = 0.97652, p-value < 2.2e-16
For B: W = 0.97989, p-value = 4.384e-16
Histogram
For A:

For B:

EDIT
Ho: There is no difference in between A and B.
Ha: There is a difference between A and B.
summary(A)
Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
17.00   35.00   50.00   48.84   62.00   90.00
summary(B)
Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
18.00   38.00   53.00   51.33   64.00   90.00
Levene's Test
group coerced to factor.Levene's Test for Homogeneity of Variance (center = median)
<code>    Df F value Pr(>F)
</code>
group    1  0.2123  0.645
      5047
Answer: You have already answered your own question, even if you don't realize it.
When selecting a test you first decide what you are trying to measure. You don't include this so I'll assume you are trying to measure whether there is a difference between unpaired groups (the purpose of a t-test or rank sum test). More help selecting methods is available elsewhere.
Next you check the assumptions of the tests you want to use. T-tests are parametric tests that assume the data is normal. Since you state that the data is not normal you cannot use the t-test.
EDIT
whuber correctly points out that I wrongly assumed that the distribution of sample means would be normal. The above should not be taken at face value, and his comment below should be read. Please feel free to post another answer as a correction to this one.
Comment: This is incorrect, because t-tests only require that the *sampling distributions of the means* be sufficiently close to normal.  That will certainly be the case here due to the sample sizes and the constrained, near-uniform distributions of the data.  Assuming the purpose is to compare means, the t-test can be recommended because of its power.
Comment: Not at all.  These are tests of two different hypotheses.  They have different purposes.  You wouldn't change your decision objectives just because the test you were first thinking of using is inapplicable, would you?  Consider this analogy.  Suppose you go to your physician complaining of a headache.  After examining you, the physician says "ordinarily I would prescribe aspirin, but I see you are sensitive to aspirin.  How about I give you something for your stomach instead?"
Comment: Yes, I am trying to measure if there is a difference between the unpaired group, specifically if median of B > median of A since the distribution doesn't look normal.

@whuber Is it possible to get further clarification because I am conflicted for the same reason you stated?
Comment: User185046, you are doing something fishy by adapting your question to what you see in the data.  At the outset either you wanted to compare the means or you wanted to compare the medians.  If it was the former, use the t-test; if the latter, use a Wilcoxon test.
Comment: @whuber Do you not decide which test to use if the sample data fit the assumptions? i.e. Use the t-test if it fits the normality assumption and the assumption of homogeneity of variance?


Integration of Gaussian random variables.

Question: Suppose $g(t)$ is Gaussian random variable for real $t \in D $. Assume $[t,t+\Delta t] \subseteq D $.
I want to prove that, for
\begin{equation}
\xi = \int_t ^{t+\Delta t} g (\tau ) d\tau
\end{equation}
$\xi$ is Gaussian random variable.
I already know that for random variables $X_1, X_2$ with normal distribution,
\begin{equation}
X = X_1 + X_2
\end{equation}
is have normal distribution.
However, I have difficulty on continuous and integral instead of discontinuous and sum.
Does anyone have idea or counter examples of my question?
Answer: It is not true in general that the sum of Gaussian random variables is Gaussian - this is only true if they are independent, as well. In a similar way, your claim about the integral is not true without some further assumptions on the covariance structure of your Gaussian process $g(t)$.
A well-known counterexample goes as follows. Let $X,Y$ be independent standard Gaussians, and let
$$
Z=\text{sign}(X)\cdot |Y|.
$$
Then $Z$ is also standard Gausian, but it can be shown that $X+Z$ is not Gaussian at all.
Comment: Then, is there any theorem about integrals of independent Gaussian variables? I want to know what assumption is needed if there is relative theorem about that.
Comment: It is not even clear what this would mean exactly, since a Gaussian process with independent values is not continuous - rather it is a type of white noise, which is not even defined as a function (it is too rough)! Perhaps you can get a better response by asking a question that is more specific to the specific process $g(t)$ you have in mind.
Comment: I was studying physics about Langevin Equation. Since $g(t)$ is a type of noise, I think it does not hold rigorously. Thanks.
Comment: A rigorous statement and proof can be constructed using basic Ito calculus https://en.wikipedia.org/wiki/It%C5%8D_calculus. However if you are after something a little simpler, consider a theorem that applies to Riemann approximations of the integral (rather than the integral itself), in which case there are no such difficulties.


Series convergence test

Question: $$\sum_{n=1}^{\infty} \frac{1}{(\log{n})^{(\log n)}}$$
I tried using Cauchy's condensation test:
$$\sum_{n=1}^{\infty} 2^n\frac{1}{(\log{2^n})^{(\log 2^n)}}$$
Assume that the log is of base 2:
$$\sum_{n=1}^{\infty} 2^n\frac{1}{n^{n}}$$
$$\sum_{n=1}^{\infty} \left(\frac{2}{n}\right)^n$$
And now I'm stuck.
Thanks in Advance.
Answer: The series $\sum_{n=1}^\infty(\frac{2}{n})^n$ converges, since $(\frac{2}{n})^n\leq(\frac{1}{2})^n$ for $n\geq 4$.

Series convergence test


Regex that does not contain a substring after some point

Question: I want a regex that doesn't match a string if contains the word page, and match if it's not contain.
^https?.+/(event|news)/.+(?!page).+$ this is the regex I'm currently using, so I want it to not match with, e.g. https://www.foosite.com/news/foopath/page/10, but it does. Where did I made a mistake?
The double .+ expressions should imply that there should be some string around the page string, and (?!page) should imply there must not be a string like page between them. What's wrong with this expression? Thanks, and sorry for poor grammar.
Comment: will page word is always there in string ? if yes you can use lookahead [`Regex demo`](https://regex101.com/r/li1dxK/1/)
Comment: Thanks for the suggestion, but I need the regex match if the string doesn't contain `page`. Sorry I forgot to mention that.
Answer: Your problem is that .+(?!page).+ will match foopath/page/10 because the first .+ match can end at the 1 in 10, and the second can match from there until $. Instead, just assert there is no combination of characters plus the word page after (event|news)/:
^https?.+/(event|news)/(?!.*page)

Demo on regex101
If you want more than just a match/nomatch decision, you can capture the entire matching string with this regex:
^https?.+/(event|news)/(?!.*page).*$

Demo on regex101
Comment: This will allways only match links up to `https://www.foosite.com/news` even if they are longer and don't include `page`.
Comment: @CennoxX From the wording of the question, OP only wants a match/nomatch decision based on the presence of the word `page`. This regex will achieve that.
Comment: @CennoxX I've added a regex that will capture the entire string on a match if that's what OP wants.
Answer: You might be looking for
^https?.+/(event|news)/(?:(?!page).)+$

See a demo on regex101.com.
Answer: Matching is usually way easier in regex than excluding.
I would rather match your excluded words and invert the logic on the if-clause.
if(!re.match(...


HQL how to join two tables with out any association

Question: I have searched around and some answers are using criteriabuilder, my prob is in HQL.
I have two tables A & B, they are not associated in anyway but I need to match one from each field to get the value of fieldB2 from the table B.
My query:
Table A - fieldA1 (ex. value of '20'), fieldA2 A
Table B - fieldB1 (ex. value of '20'), fieldB2 B

this doesn't work:
select new map (fieldA1 as fa, (select fieldB1 from B as b where a.fieldA1=b.fieldB1) as fb) from A as a

so basically, I need to get fieldB1 from B if the value it consists is the same with the value of fieldA1 from A.
what is the correct way of doing this?
Answer: It is not possible to write HQL or query using Criteria without association.
Use native SQL query to retrieve the records.
Comment: I figured that might be the case, but is there a work around not using native sql? thanks
Comment: No. There are no workarounds. Simple, if you write HQL, hibernate will translate that to SQL. But how will hibernate know how two classes are related if there are no associations (relationship)?


Split string in c

Question: im trying to split a string in C (Not in C#, C++ or any other kind). I tried using de strtok function, but it turns out that this only works when the limit between each word is a single character such a space, a semicolon....
I have a variable which is a string that contains html code like this:

Index of /davidgoudet

 Parent Directory

 Horario/

 Oferta/

 Registro/

<address>Apache mod_fcgid/2.3.6 mod_auth_passthrough/2.1 mod_bwlimited/1.4                FrontPage/184.108.40.20635 Server at turpialdevelopment.com Port 80</address>

And i want to have the  chunks in between the href tags such as Horario, Oferta, Registro inside a variable
but when i tried to use strtok(string, "href") it gives me some weird result which is not the one im looking for.
Any ideas?
Thanks
Comment: Use a [parser](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454). He comes.
Answer: strtok takes a char array of all possible delimiters and it splits based on any of those characters (in your case, splitting on h, r, e, or f), which is probably why you are seeing weird behavior.
Is there a reason why you aren't using an HTML parsing library to pull the names?
the libxml html parser is pretty good: http://www.xmlsoft.org/html/libxml-HTMLparser.html
Answer: Why don't you just use a proper HTML parser?  lib2xml has a nice HTML parser in C.
Answer: This is my solution, and I hope will solve your problem.
int split(char ***dst, char *str, char spliter)
{
    int str_num = 0;
    int each_size;
    int index = 0;
    int str_index = 0;
    int start_index = 0;

    while (str[index] != '\0')
    {
        if (str[index] == spliter)
        {
            str_num++;
            index++;
            while(str[index] == spliter)
            {
                index++;
            }
        }
        else
       {
            index++;
       }
    }
    str_num++;

    *dst = (char **) malloc((str_num + 1)*sizeof(char*));
    index = 0;

    while (str[index] != '\0')
    {
        if (str[index] != spliter)
        {
            start_index = index;
            each_size = 0;

            while (str[index] != spliter && str[index] != '\0')
            {
                index++;
                each_size++;
            }

            (*dst)[str_index] = (char*) malloc((each_size + 1)*sizeof(char));
            int cur_i = 0;

            while (start_index != index)
            {
                (*dst)[str_index][cur_i] = str[start_index];
                start_index++;
                cur_i++;
            }

            (*dst)[str_index][cur_i] = '\0';
            str_index++;
        }
        else
        {
            index++;
        }
    }

    (*dst)[str_num] = NULL;
    return str_num;
}

Answer: Try using strstr() and then offsetting the pointer it returns to you.
strstr(big_string_of_tags,"href")+6; //Leaves pointer at the word you're seeking, read up until you see a double quote char.

Its not a very elegant solution but if you're constrained to C alone it might be a good start.
Answer: You can use a string comparison function like strnstr() to locate substrings, such as begin and end tags. Then you can easily calculate the position and length of the substring you want and use strncpy() to copy that data.
Answer: char* split(char *string, char chr, char *output){
    int seek=0;
    for(seek; seek<strlen(string); seek++){
        if( *(string + seek) == chr ){
            break;
        }
    }
    memcpy(output, string  , seek);
    *(output + seek ) = '\0';
    if( (seek + 1) >= strlen(string)){
        return NULL;
    }
    return (string + seek + 1);
}

for use:
char *string = "hello world";

while(1){
    string = split(string, ' ', out);
    if(string == NULL) break;
}

set the cut value in (out) and returns the pointer to continue the string

Split string in c


How to install Puppet Enterprise in Redhat?

Question: I am installing Puppet Enterprise in  Master(redhat) and I have followed the below steps. Let me know how to solve this
while Executing below command
yum -y install puppet-enterprise-installer

Getting Error like below

No match for argument: puppet-enterprise-installer
  Error: Unable to find a match: puppet-enterprise-installer
Answer: The problems is that puppet-enterprise-installer isn't installed using yum.
You need to follow the instructions on https://puppet.com/docs/pe/latest/install_pe_getting_started.html, download the installation tarball, untar it and run puppet-entreprise-installer from there.


Tomcat 7 service manual start, stops immediately on Windows 7

Question: I have just performed a fresh installation of Tomcat 7 (apache-tomcat-7.0.30) using the 32-bit/64-bit Windows Service Installer available here, on my local Windows 7 PC.
Yet, when I go in Service to start it manually, it starts and stops immediately after displaying the following message:

I have noticed that each time I try, I get the following lines in my tomcat-7-stdout log:
<code>2012-09-16 18:41:12 Commons Daemon procrun stdout initialized
Error occurred during initialization of VM
java/lang/NoClassDefFoundError: java/lang/Object
</code>
Anyone knows what is happening and how to solve it?
Answer: Ok, I found it. For some unknown reason, my Java JRE6 was corrupted. I reinstalled it manually and the issue disappeared.


TFS4JIRA settings issue

Question: what should i write in Synchronizer Application's External URL at TFS4JIRA settings?
and what should be its password?? Can anyone give me an example??
Comment: How did find Synchronizer  External URL & password and tfs4jira synchronize app need to be install all windows machine who using tfs?
Answer: For free you would have to roll your own. I usually recomend TaskTop($).

TFS4JIRA settings issue


Green formula, Maxwell

Question: Have we got a similar Green identity with the following, $\Omega \subset \mathbb{R}^3$, $E \in H(curl, \Omega)$, $\Phi$ test function smooth enough and scalar,
$$
\int_\Omega curl(E)\Phi d\Omega \overset{?}{=} ...
$$
Moreover, I'd like to know if the change of coordinate system impacts on Green formula ?
Thanks in advance
Comment: $ \int_\Omega \space ( \phi \nabla \times \mathbf{E} - \mathbf{E} \times \nabla \phi ) \space dV = \int_\Omega \nabla \times (\phi \mathbf{E}) \space dV = \int_{\partial\Omega} d \mathbf{S} \times (\phi \mathbf{E}) $
Answer: For a better understanding of the space $H(\operatorname{curl},\Omega)$, I suggest you to take a look in this book page 257. For your second question, after knowing that there is a formula for your expression, try to apply change of variables on it and see what happens.
Comment: I have access to this book, but can you direct where one can find more details around the fact that $u\in H_0(\operatorname{curl},\Omega)$ if $v|_{\partial\Omega}\times n=0$?

Green formula, Maxwell


How split date in this line?

Question: I have some problem with parse some information from String line. In this example, I would like to work with the line 2011-08-28 19:02:30.
I have a lot of lines for this template. How to parse this date? Thanks
 [47.611910999999999, -122.335178]  6   2011-08-28 19:02:30 I'm at Saigon Vietnamese Restaurant II (1529 6th Ave., at Pine St., Seattle) http://example.com

Thanks all. Here is my solution.
 private Date parseDate(String line) {
    line = line.replaceAll("\\s+", " ").trim();
    String[] masWords = line.split(" ");
    DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date = null;
   try {
        date = format.parse(masWords[3] + " " + masWords[4]);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return date;
}

Comment: @sferencik in my example it is necessary to cut a string date
Comment: @ЕгорУрбанович search for String split.
Answer: i'd do it like that:
   String[] s1 = "[47.611910999999999, -122.335178]  6   2011-08-28 19:02:30 I'm at Saigon Vietnamese Restaurant II (1529 6th Ave., at Pine St., Seattle) http://t.co/8s86hNX".split(" ");
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for(int i = 1; i< s1.length ; i++  ){
            try {
                Date date = format.parse(s1[i-1]+" "+s1[i]);
                System.out.println("Date found: "+s1[i-1]+" "+s1[i]);
                break;
            } catch (ParseException e) {
                continue;
            }
        }

Split the String
loop through the String Array
cast to date until you found a valid date.

if the you know the date is always on the same place in the string you can do it much easier by you cast:
String[] s1 = "[47.611910999999999, -122.335178]  6   2011-08-28 19:02:30 I'm at Saigon Vietnamese Restaurant II (1529 6th Ave., at Pine St., Seattle) http://t.co/8s86hNX".split(" ");
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
format.parse(s1[6]+" "+s1[7]);

Answer: You need to normalize your string by removing the extra spaces... () Regex can do that fast and easy), then split the string, concatenate the elements of the string that you need for building a date, parse those to a Date object Woala...
a snippet for this:
String chain = "[47.611910999999999, -122.335178]  6   2011-08-28 19:02:30 I'm at Saigon Vietnamese Restaurant II (1529 6th Ave., at Pine St., Seattle) http://t.co/8s86hNX";
        chain = chain.replaceAll("\\s+", " ").trim();
        System.out.println(chain);
        String[] var = chain.split(" ");
        for (String string : var) {
            System.out.println(string);
        }

        String string = var[3] + " " + var[4];
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = format.parse(string);
        System.out.println(date);

Comment: Good Example. Thanks)
Answer:
Split with a space as the delimiter String[] parts = str.split(" ");
Loop through parts[] to find items matching your date and time.
You can use the following regexes:

Date: \d{4}-\d{2}-\d{2}
Time: \d{2}:\d{2}:\d{2}

You can work with detected strings containing your time and date using java.util.Date

How split date in this line?


jquery: concatenating with insertAfter()

Question: Objective: When 'Submit' is clicked, add the contents of the textbox below the button into a h3 element.
So I made a variable contents which takes in the value from the textbox. When I click the submit button, it should insert the h3 element with contents inside it. I'm not sure if it's something with concatenating in jquery or if there's something else I'm missing here. Apologies since I'm still new to jquery.
$(document).ready(function() {
  var contents = $('#textInput').val();
  $('#submitBtn').click(function() {
    $("
" + contents + "
").insertAfter('#submitBtn');
  })
})

What seems to be the problem here?
Thanks.
Answer: You're getting the value of the text area before the button is clicked. You need to obtain it inside the event handler (notice that you may also need to use preventDefault() on the event in case your button is submitting a form or similar):

$(function() {
    $('#submitBtn').click(function(e) {
        e.preventDefault();
        $("
" + $('#textInput').val() + "
").insertAfter(this);
    });
});

<textarea id="textInput"></textarea>
<button id="submitBtn">Submit</button>
Comment: @4castle No, it isn't. That will literally append an `` element to the ``.
Comment: Ah, I was thinking of `$(this).after(...`
Answer: You have to take input inside the click handler
check this snippet

$(document).ready(function() {

  $('#submitBtn').click(function() {
     var contents = $('#textInput').val();

    $("

").insertAfter($(this)).html(contents);
  })
})

<input type="text" id="textInput">

<input type="button" id="submitBtn" value="submitbtn">

Hope it helps