Codeigniter - Autenticação de Permissão

Question: Boa tarde, gostaria de saber se existe uma solução mais prática para o meu problema.
Cada usuário tem uma permissão diferente, caracterizada por um permissao_id na tabela usuários que é correlacionada com uma id na tabela permissão.
Existe uma forma mais prática de verificar a permissão do usuário em diversos métodos sem ter que ficar trabalhando com IF/ELSE?
Pra cada método exclusivo de cada permissão preciso ficar setando essas condições pra que outros usuários não consigam ter acesso ao método.
Obrigado!
Comment: Isso aqui: [Controle de sessions PHP com Codeigniter](https://pt.stackoverflow.com/questions/180083/controle-de-sessions-php-com-codeigniter/180134#180134) deve ajudar a começar.
Answer: Pode utilizar os hooks do codeigniter segue abaixo um exemplo
<code>function restrict() {

 //Instância do CodeIgniter
 $ci = & get_instance();
 //Método atual, pega da url
 $method = $ci->router->fetch_class().'/'.$ci->router->fetch_method();

 //Métodos protegidos, aqui você especifica as funções protegidas
    $protegidos = ['funcao/index','funcao/inserir','funcao/editar',
    'funcao/atualizar','funcao/deletar','funcao/pesquisar','funcao/exports'];

 //Array gerado pelo seu algotitmo de "login" e gravado na SESSION
    $usuario_logado = $ci->session->userdata('usuario_logado');
    if (in_array($method, $protegidos)) {//Verificando se o método é protegido
        if ($usuario_logado['cargo']!='admin') {//Verificando nivel de permissao do usuario
            $ci->session->set_flashdata('alert', 'Voçe nao possui privilegios');
//Aqui vc tb pode criar um aviso pro usuário saber o motivo do comportamento da aplicação
    ?>

    <script>
      alert('você nao possui autorização');
    </script>

<?php
    $var = "<script>javascript:history.back(-2)</script>";
    echo $var;
    }
}
}
?>
</code>
pode criar varios hooks em cada um deles protegendo suas funçoes e dando acesso conforme permissao do usuarioP
Comment: Desse jeito aí não vai funcionar... ;-)
Comment: Realmente  não é a solução sobre medida, mas é o inicio para que ele pesquise e ajuste a sua necessidade
Comment: Não. Tá errado mesmo...
Comment: Eu vou dar uma olhada no link que você me mandou @ShutUpMagda!
Comment: @FelipeMirandaDeLima, obrigado pela ajuda também!!
Comment: Dá pra adaptar naquele _hook_ que mandei no link pra fazer rodar as permissões (o _hook_ só cuida de autenticação). É relativamente fácil. Se vc conseguir, posta a resposta aqui, ok? ;-)

Codeigniter - Autenticação de Permissão


THR10X recording volume very low

Question: I have been trying to recording some guitar licks with the Yamaha THR10X amp in Logic Pro X. It seems to work ok, except that the volume is quite low compared to an audio interface (scarlett 2i4 in this case):

I tried the THR editor, but however I try to alter the settings, recored volume remains low. The usb volume options are greyed out:

Anyone used this amp for recording? Any idea how to fix this?
Comment: It's a scarlett 2i4, sorry for the ambiguity.
Comment: When you say "...compared to an interface..." Are you bypassing the audio interface entirely and connecting the guitar to the built in line in?
Comment: Do you have the guitar output knob turned down?
Comment: The amp is connect via usb to a mac, the guitar volume is max.
Comment: And the USB volume us also high?
Comment: USB volume can't be adjusted, don't know why.
Answer: I had the same problem - but it's just plain simple.
I figured out that the recording program (GarageBand) gets louder input signal if I turn the MASTER up - but then it got simply too loud.
Then it struck me. You can alter the OUTPUT (on the speaker) with the GUITAR knob - to whatever you like. Its the knob next to USB/AUX knob.
So one more time - put the MASTER volume up (it serves as input volume) and turn the GUITAR knob down. Now you have a nice signal and you can record at 2am if you want!
I dont know if its supposed to be this way - but it works like a miracle!
Cheers, keep rockin!!!
Answer: From research into the USB amp, it seems that the only way you can adjust the input volume from the THR10 is through the track volume in GarageBand. The THR10 will provide a fixed signal, that apparently cannot be changed.
Either you can take the line out connection into the Scarlett interface and record that way, or carry just turn up the fader on the guitar track.
Try seeing if there is a newer version of the Editor software, and any Mac drivers for the hardwards. Contact Yamhaha support if the level is too low for use. It should be between 12 and 20db to allow for good headroom.
http://download.yamaha.com/search/product/?language=en&site=usa.yamaha.com&category_id=16173&product_id=1702689

THR10X recording volume very low


How to add the post_author into the new post record without having post_author input?

Question: I'm using active_admin to manage my data. I manage the posts via active_admin, and now I just want to create a new post, so in the new page, I created a form for the post_title、post_content and so on. But I don't want the author to fill the post_author himself, so the problem comes: What should I do when the author click the create button then the author's name or author's id will added to the new post record automatically without having certain input for post_author?
<code>form do |f|
  f.inputs "add title and time" do
    f.input :event_title,:label=>"title"
    f.input :event_time, :label=>"time"
  end
  f.inputs "add event" do
    f.input :event_description,:label=>"description"
  end
  f.buttons
end
</code>
Comment: presumably you're using active admin bundled with devise, in which case you can set your `@post.post_author = current_user` in your controller when saving.
Answer: You can use a hidden field that's populated with the current poster's name.
The default, as shown on the Active Admin docs, is:
<code># config/initializers/active_admin.rb
config.current_user_method = :current_admin_user
</code>
which you need to embed in your hidden form field. Either use a helper method or an instance variable to access the name in the view to populate the form.
Alternatively, you can assign the author after the fact in the #create controller method for a post.
Comment: Thanks for so much.I thought the hidden input can be much easier for me. By the way, I installed the active_admin in the former time, it will install the devise, but there isn't the controller for devise.It seems that if I install the devise again it will have conflict, so it will be hard to modify the #create?


Primes in Gaussian Integers

Question: Let $p$ be a rational prime. It is is well known that if $p\equiv 3\;\;mod\;4$, then $p$ is inert in the ring of gaussian integers $G$, that is, $p$ is a gaussian prime. If $p\equiv 1\;mod\;4$ then $p$ is  decomposed  in $G$, that is, $p=\pi_1\pi_2$ where $\pi_1$ and $pi_2$ are gaussian primes not  associated. The rational prime $2$ ramifies in $G$, that is $2=u\pi^2$, where $u$ is a unit in $G$ and $\pi$ a prime in $G$.
where can I find a proof of this fact?  I want a direct proof, not a proof for the quadratic integers and then deduce this as a particular case.
Comment: Possible duplicate of [What's are all the prime elements in Gaussian integers $\mathbb{Z}[i]$](https://math.stackexchange.com/questions/458795/whats-are-all-the-prime-elements-in-gaussian-integers-mathbbzi)
Answer: Well, hopefully a proof right here will suffice instead of some resource. This is a rather nice proof of the case of Gaussian Integers, but it fails to generalize for the other quadratic integer domains without putting in more work at least.
Define the norm $N(a+bi) = a^2 + b^2$. It is straightfoward to check it is multiplicative.
Now, consider a prime $p \equiv 3 \pmod{4}$. Suppose it is not inert, i.e. it factors as $p = \alpha \beta$ for some $\alpha, \beta \in \mathbb{Z}[i]$ and neither of them are units.. Then it is easy to see $N(\alpha) = N(\beta) = p$. However, the equation $a^2 + b^2 = p$ has no solutions modulo $4$, therefore we have reached a contradiction so primes $3 \pmod{4}$ remain inert.
Now to prove primes $1 \pmod{4}$ split. It suffices to show $p = a^2 + b^2$ has a solution where $a,b$ are integers. Let $z$ denote the least value of $\sqrt{-1} \pmod{p}$. Now define $\mathcal L = \{(a,b) \in \mathbb{Z}^2 | a \equiv zb \pmod{p}\}$. It is straightfoward to check $\mathcal L$ is a lattice whose fundamental parallelogram has area $p$. Now by Minkowski's theorem one has $\mathcal L$ contains a nontrivial lattice point inside the circle $x^2 + y^2 < 2p$. Call this point $(a,b)$. But then $a^2 + b^2 \equiv 0 \pmod{p}$ based on the definition of the lattice, thus it must be $a^2 + b^2 = p$. But then $p = (a+bi)(a-bi)$, proving it factors so we are done.
Proving $2$ ramifies is trivial, since it's just $2 = -i(1+i)^2$.
Comment: Can it be done by elementary ring theory without involving lattice?
Answer: There are several places where you can find a direct proof of this. For instance, you can find it in the first 4 pages of Jurgen Neukirch's Algebraic Number Theory about the Gaussian integers. Also, LeVeque's Elementary Theory of Numbers has a short chapter dedicated to the Gaussian integers, where he proves this fact (see section 6.5).
Answer: Try the following:
== Primes in Gaussian Integers
== http://www.google.co.il/url?sa=t&rct=j&q=&esrc=s&frm=1&source=web&cd=9&ved=0CGYQFjAI&url=http%3A%2F%2Fwww-users.math.umd.edu%2F~smeds%2FgaussianIntegers.pdf&ei=L4KNUN2OHLGN0wXpk4GIAg&usg=AFQjCNEbCxHldP9wGEroPul1p_DgLSegiw&sig2=eM5tx6LrUXRfSQy2Xl0GUg
== http://www.google.co.il/url?sa=t&rct=j&q=&esrc=s&frm=1&source=web&cd=11&ved=0CBwQFjAAOAo&url=http%3A%2F%2Fwww.springer.com%2Fcda%2Fcontent%2Fdocument%2Fcda_downloaddocument%2F9780387955872-c6.pdf%3FSGWID%3D0-0-45-101818-p2293254&ei=qIKNUK_DK6Kn0QX3wIH4Aw&usg=AFQjCNEE0166P93tfpMdDxcgDerabbOM5Q&sig2=YWp7XxzMiagTvvgPrBNDZQ
BTW, google is your friend...
Comment: @hardmath I have never answered a question in such a lame way as above. Someone tampered my answer and did that.
Comment: I suspect if you were answering this Question today, you'd be more articulate.  In the first link, you are giving the Question here that you are responding to, so this seems redundant.  The other two links (to an Italian version of Google search) seem to be undesirable proxies for the underlying links that contain useful information.  In any case we should "quote verbatim the most relevant material to be found at those locations" or summarize in the post what that link provides.
Comment: I'd offer to make the obvious changes, but if you'd care to do it, I'd feel more confident you got the wording as you wish it to be.  I'm not seeing much in the edit history, but it is quite old by now.

Primes in Gaussian Integers


what is this "require" thing?

Question: I see this in many JS libraries out there, mostly looking through GitHub, currently looking at PeerJS. I'm referring to this:
var util = require('./util');
var EventEmitter = require('eventemitter3');
var Negotiator = require('./negotiator');
var Reliable = require('reliable');
...
window.Socket = require('./socket');
window.MediaConnection = require('./mediaconnection');
window.DataConnection = require('./dataconnection');
window.Peer = require('./peer');
window.RTCPeerConnection = require('./adapter').RTCPeerConnection;
window.RTCSessionDescription = require('./adapter').RTCSessionDescription;
window.RTCIceCandidate = require('./adapter').RTCIceCandidate;
window.Negotiator = require('./negotiator');
window.BinaryPack = require('js-binarypack');
...

Just from intuition, it seems like require() is importing/including whatever is being passed in, i.e., EventEmitter. However, I can't figure out where require() is coming from?
I'm not too familiar with NodeJS, and this seems like it's a NodeJS thing, but I don't understand how require() fits into a web browser context, where NodeJS doesn't exist.
I've seen RequireJS and Browserify, but these are libraries that would need to be included with application in order to use the require() function. In the example of PeerJS, I can just include it:

... and it uses require() no problem. However, it doesn't look like there's any 3rd party libraries that are defining require() that are being bundled along with the PeerJS source code.
How is it being included? How is it being initialized? How is it fetching whatever is being passed in, i.e., "EventEmitter"?
Comment: http://requirejs.org/ explains itself
Comment: @PM77-1: PeerJS does not use the RequireJS library.
Comment: thanks @Qantas94Heavy. it doesn't seem like RequireJS is being used here
Comment: PeerJS uses Browserify to bundle the scripts together, the `require` function is defined as a function parameter in the first line of the built code. https://github.com/peers/peerjs/blob/cf5be327ae20df97e21ac9ba91838deafcbeeb7e/dist/peer.js#L1
Comment: You can also see this from the Gruntfile.js, which is used to specify how the file is built. https://github.com/peers/peerjs/blob/cf5be327ae20df97e21ac9ba91838deafcbeeb7e/Gruntfile.js#L40
Comment: ahhh I see what's going on now. thanks @Qantas94Heavy! why don't you put that down as an answer so you can get credit?
Comment: Sorry for VTCing, I thought this was a more general question about what `require` does rather than where it was coming from.
Comment: no problem. I can understand why that's what you'd have thought. suggestions on how to reword the question to avoid confusion?
Answer: It's a way to include external JavaScript (or really any other file) into your script through a single point of entry without introducing globals.  It's most often used with Asynchronous Module Definition (AMD) and CommonJS modules.  At it's highest level, require() is an API to use JavaScript modules.  NodeJS uses the CommonJS syntax for the most part.
There's also no definite "better" one to use.  It becomes almost an East Coast/West Coast turf war trying to discuss one vs the other.  Some say that AMD modules are too verbose since you have to capture all of your imports in a closure and then use them which means you have to look in two different places for where you are defining your variables and imports:
AMD from RequireJS also Dojo
define('myModule', ['dep1', 'dep2'], function (dep1, dep2) {
    return function () {};
});

CommonJS
var foobar = require('./foobar').foobar,
    test   = new foobar();

test.bar(); // 'Hello bar'

Additionally, some say that the A part of AMD doesn't really benefit you often enough to be worth the overhead.
Where does the "require" part come from?
In the browser, the require() comes from whatever library you are loading whether it be an AMD or CommonJS loader.  However, for your above examples, you look like you're using it in a NodeJS context.  NodeJS has the require() defined within the environment just like module.exports.  In fact, the module.exports is what is given to whatever variable you're assigning to with the require(...).
Contrast the module.exports from CommonJS to how AMD gets your module into your variable's hands which is just the return from the closure that you put in a call to define().
Can these be used together?
One other thing to touch on is that they aren't exclusive to one another.  They can be coerced into playing with one another either using some kind of wrapper or by using another convention: UMD.  UMD tries to let you create modules that work no matter the environment exposing your module through whatever convention is available be it module.exports or define().
Comment: but where is it implemented? it doesn't seem to be a browser API; typing in `require` in the console doesn't do anything...
Comment: I'm not using it in a NodeJS context. I'm just including the PeerJS library in my web app. From one of the comments, it looks like PeerJS is using browserify...
Comment: @Hristo How do you build your webapp?  If this is using `browserify` then it is most likely going through some build step that still uses `nodejs` be it a `gulpfile`, `gruntfile`, `npm build` call, or some other magic.
Comment: it's not about how I build my webapp, it's about how PeerJS packages their library. looks like they use `grunt.js` and `browserify`

what is this "require" thing?


process_file(sys.argv[1]) IndexError: list index out of range

Question: This is the code I am working with that comes from Practical Programming:
 import sys

def process_file(filename):
 '''Open, read, and print a file.'''

 input_file = open(filename, "r")
 for line in input_file:
  line = line.strip()
  print line
 input_file.close()
 if __name__ == "__main__":
  process_file(sys.argv[1])

After import this module in IDLE and pass a text file argument through process_file(), I receive this error:
    Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    process_file("data.txt")
  File "C:\Python26\read_file_2.py", line 14, in process_file
    process_file(sys.argv[1])
IndexError: list index out of range

How can I get this program to work without receiving this error? Any help is appreciated.
Comment: Is it `sys.argv[0]` or `sys.argv[1]`? You've not very consistent theer. ;) It if is 1, I'd guess that there's no parameter passed.
Comment: Firstly please post the actual code that causes the error - note that you've got `sys.argv[1]` in your code, but `sys.argv[0]` in your traceback. Secondly, please make sure your indentation is correct in your posted code - this is even more important in Python, where whitespace is significant.
Comment: My bad, I had experimented with changing the code to sys.argv[0] and copied the wrong error message. edited it out.
Answer: you should move
if __name__ == "__main__":
    process_file(sys.argv[1])

out of the process_file function. When importing into IDLE make sure process_file is available and pass file name to it.
Answer: It looks like you've got the
if __name__ == "__main__":
  process_file(sys.argv[1])

block at the same indentation level as the rest of the process_file definition, so it's being run when you call process_file from another module. I suspect that might be causing your problem - unindent it so the if is in line with the def.
Comment: This removes the error when I run this program from the command line, but does nothing for the problem in IDLE(which I am not that worried about).
Comment: So what _is_ the problem in IDLE? If you've stepped that back out, you can't hit it when you call through.
Comment: IDLE still gives the list index out of range error when I pass the .txt file through process_file().
Comment: It... can't. There's no longer any list indexing going on in that function. Have you made sure IDLE has reloaded the module since you changed it?


Fitting a simple linear regression

Question: A professor in the School of Business in a university polled a dozen colleagues about the number of professional meetings they attended in the past five years $x$ and the number of papers they submitted to refereed journals $y$ during the same period. The summary data are given as follows:
$n = 12$, $\bar{x}= 4$, $\bar{y}=12$, $\sum x^2 = 232$, $\sum xy = 318$.
Fit a simple linear regression model between x and y by finding out the estimates of intercept and slope. Comment on whether attending more professional meetings would result in publishing more papers.
I know that this is a linear regression problem. But I only know how to solve it using given values of $x$ and $y$. The only values given with the problem are the sample $n$, mean of $x$,mean of $y$, summation of $x^2$ and summation of $x*y$. I really don't know how to start with this problem.
Answer: HINT:
Let's assume your model is $y=\theta x$, then the least-squares solution will be $\hat{\theta}=\min_{\theta} \|Y-\theta X\|_2^2$, where $X$ and $Y$ are column vectors made up of the data points (that you don't have, you only have some sufficient statistics that are extracted from them).
We have:
$\|Y-\theta X\|_2^2=(Y-\theta X)^T(Y-\theta X)=Y^TY-2\theta X^TY + \theta^2 X^TX$.
Note that, $ X^TX=\sum x^2=238$, $ X^TY=\sum xy=318$, the only missing part is $Y^TY=\sum y^2$, but you don't need that!
Now you problem is $\hat{\theta}=\min_{\theta} ~Y^TY-2*318\theta + 238\theta^2$
$\frac{d}{d\theta}Y^TY-2*318\theta + 238\theta^2=-2*318+ 2*238\theta=0$,
Therefore: $\hat{\theta}=\frac{318}{238}\approx 1.33$
More HINTS:
If your model is affine, i.e. $y=\theta_1 x+\theta_2$, then you can use a similar approach to solve it, now let $L=[\underbrace{1,\ldots,1}_{\text{12 times}}]^T$,then your problem is:
 $\hat{\theta}_1,\hat{\theta}_2=\min_{\theta_1,\theta_2} \|Y-\theta_1 X-\theta_2 L\|_2^2$.
By the same expansion procedure, you can get quadratic forms in $\theta_1$ and $\theta_2$, but this time you'll need $n$, $\bar{x}$ and $\bar{y}$, try it yourself, and let us know if you got stuck!
Hope this helps.

Fitting a simple linear regression


What can conclude about $[G:H]$?

Question:
Assume that $H$ is a subgroup of a finite group $G$, and that $G$ contains elements $a_1, a_2,...,a_n$ such that $a_i a_j^{-1} \notin H $ for $1\leq i < n, 1 \leq j <n $, and $i \neq j$. What can you conclude about $[G:H]$?

My answer is:
$[G:H] = {e}$
I came up with this answer since I see from what is given that we have no
$a=hb $  for some $h \in H$
therefore, $Ha \neq Hb$
and in this case, the identity is the only coset to the subgroup $H$.
Comment: $[G:H]$ should be a number, not an element of $G$.
Comment: It is given that there exists an element $a_i a_j^{-1} \notin H$ (assuming $n \geq 2$). Then $a_i a_j^{-1} H$ is a different coset than $H$ right? Also what are $a$ and $b$?
Comment: @ Arthur: $a, b \in G$
Comment: @ Alex Kruckman: I meant to specify the elements that exist in the coset
Comment: Are you saying that there exist no $a,b \in G, h \in H$ such that $a = hb$? Surely $a = b = h = 1$ works.
Comment: @ Arthur: The theory at hand says "if H is a subgroup of a group G, and a,b \in G, then the following four conditions are equivalent:

1- $ab^-1 \in H$
2- $a = hb$ for some $h \in H$
3- $a \in Hb$
4- $Ha = Hb$

As a consequence, the right coset of $H$ to wich a belongs is $Ha$
Comment: I have no clue at all what you're trying to say. Please rephrase your argument.
Comment: @ Arthur: I'm trying to use these equivalent statements to prove that the coset of H is only the identity.
Comment: If $n \geq 2$, then clearly there is an element $a_i a_j^{-1} \notin H$, and there are two different cosets $H$ and $a_i a_j^{-1} H$. So what you are trying to prove is false.
Answer: You can conclude that $[G:H] \geq n$ : In fact the cosets
$$
\{Ha_1, Ha_2, \ldots, Ha_n\}
$$
are all distinct by the given condition.
Comment: can we have $[G:H] \geq n$ where $n = |G|$ ?
Comment: Dear Prahlad, the distinct classes are $Ha_i$.

What can conclude about $[G:H]$?


Expected value of random sum of random variables

Question: In example 3.2.2 of the book "An Introduction to Stochastic Processes" by Kao, the following statement is presented. Why are $X_i$ and $N(t)$ dependent? I would be thankful if you can clarify the procedure to determine $E[S_N]$.
If $\{X_i\}$ are identically distributed random variables with a common mean $\mu$, and $N$ is independent of $\{X_i\}$, then we know that $E[S_N]=E[X]E[N]$, where $S_N=X_1+X_2+⋯+X_N$. In a renewal process, we see that $S_N(t)=X_1+⋯+X_N(t)$ denotes the time of the last renewal before t. Unfortunately, it is not true that $E[S_N(t)]=E[X]E[N(t)]$ because $N(t)$ depends on $\{X_i\}$ (I cannot understand the difference with the former case). However, the following related result holds:
$$E[S_{N(t)+1}]=E[X](M(t)+1).$$
I cannot understand the difference between two cases and how to determine which formula is appropriate to use.
Comment: You give no context for your displayed equation at the end. One might need to look at the textbook to understand the notation. Please clarify. // It seems you are looking at a`'random sum of random variables`. The mean $E(S_n)$ is as you say. However, $Var(S_n)$ has two components; the formula is often derived via a conditioning argument. Check your text or google for more information online. I will give an example with a simulated solution.
Comment: In the book, it is stated that $N(t)$ is not stopping time so, $N(t)+1$ is instead used and the author says that now, $N(t)+1$ is a stopping time which confuses me. $M(t)$ is expected renewals up to time $t$.
Comment: _Maybe_ try the result in the link at the end of my Answer using $N^\prime = N+1$ instead of $N.$ Context is still not very clear, so I can't be sure.
Answer: Let $X_i \sim \mathsf{Norm}(\mu=50, \sigma=10),$ and independently
let $N \sim \mathsf{Pois}(\lambda=10).$ Then $S_N = \sum_{i=1}^N X_i.$
<code>set.seed(1114)
s.n = replicate(10^6,  sum(rnorm(rpois(1,10), 50, 10)))
summary(s.n);  var(s.n)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
    0.0   386.1   490.9   500.0   604.1  1575.3
[1] 26049.51
</code>
An exact value of $E(S_N) = E(X_i)E(N) = 50(10) = 500,$ simulated above as $500.0.$
The value of $Var(S_N)$ has squared units and so is not quite so precisely
estimated in the simulation.
$Var(S_N) = E(N)Var(X_i)+[E(X_i)]^2Var(N) = 26000.$
See these notes for a proof.
Comment: ok I had understood was asking about how to argue dependent but if all $X_i$ are common distribution then either via conditioning argument or via  independence you can arrive at this result. The OP's question is a bit unclear I think.
Comment: the question does not appear to make any assumption about the distribution (no normality assumption) or was this in the book section referenced?
Comment: Correct but irrelevant. // Normal $X_i$ were just an arbitrary choice for my simulation. Formulas for $E(S_N)$ and $Var(S_N)$ are illustrated by the simulation, but the formulas themselves do not assume normality (as is clear in the Univ Nebraska link at end.).
Comment: @LucasRoberts, If you think you have additional insights into OP's question and something helpful to say, please give your own answer, which I'll read with interest.
Answer: In the first model, $N$ is a nonnegative integer-valued random variable that is independent of the identically distributed random variables $X_1, X_2, \ldots$ with common mean $E[X]$. $S_N$ is defined as $\sum_{i=1}^N X_i$ (note that $S_N=0$ when $N=0$) and  we wish to find $E[S_N]$. Note that
$$E\left[S_N\,\big\vert\, N=n\right]= E\left[\sum_{i=1}^N X_i \,\bigg\vert\, N=n\right] = E\left[ \sum_{i=1}^n X_i\right]
= nE[X].\tag{1}$$ Hence,
\begin{align}
E[S_N]  &= \sum_{n=0}^\infty P(N=n)\cdot E\left[S_N\,\big\vert\, N=n\right]\\
&= \sum_{n=0}^\infty P(N=n) \cdot nE[X]\\
&= E[X]\sum_{n=0}^\infty P(N=n) \cdot n\\
&=E[X]\cdot E[N]
\end{align}
exactly as the OP claimed.
In the second model, the $X_i$ are i.i.d. strictly positive continuous random variables representing inter-arrival times. That is, the first arrival after $t=0$ is at time $X_1$, the second arrival is at time $X_1+X_2$, the third arrival is at time $X_1+X_2+X_3$, and so on.  Now, for any fixed time $t$, $N(t)$ is defined as the number of arrivals in the time interval $(0,t]$. Thus, $N(t)$ is a nonnegative integer-valued random variable just as $N$ was in the previous model, but $N(t)$ and the $X_i$ are no longer independent random variables. Note, for example, that conditioned on $N(t) = n$, we immediately have that the conditional density of $X_1, X_2, \cdots, X_n$ is nonzero only in the region bounded by the hyperplane $X_1+X_2+\cdots+X_n \leq t$. A little thought reveals that we must also insist on $X_{n+1} > t-(X_1+X_2+\cdots+X_n)$ to ensure that there are exactly $n$ arrivals in $(0,t]$. Thus, computation of $E\left[S_{N(t)}\,\big\vert\, N(t)=n\right]$ is not as easy as the computation of  $E\left[S_N\,\big\vert\, N=n\right]$ in $(1)$ where the independence of the $X_i$ and $N$ made life a lot easier: here, the $X_i$ are definitely not independent of the value of $N(t)$.
Comment: Thank you so much.


Sum over the primes of $\frac{\ln(p)}{p^2}$

Question: $$\sum^{\infty}_{p\in \mathbb P} \frac{\ln(p)}{p^2}$$
I've been able to prove the sum converges ($P(2)<S<\sum^{\infty}_0 \frac{\ln(n)}{n^2}$  where $P$ is the prime zeta function).
I've been trying to solve it by replacing 2 with $s$ and integrating.
$$\int^\infty_s\sum^{\infty}_{p\in \mathbb P} \frac{\ln(p)}{p^k}dk=\sum^{\infty}_{p\in \mathbb P}\int^\infty_s \frac{\ln(p)}{p^k}dk=\sum^\infty_{p\in \mathbb P} \frac{1}{p^s}$$
but I'm unsure how to continue and I am pretty sure undoing the integral will be rather hard.
Can any of you help?
Comment: Don't expect a closed form for this, but you can numiercally evaluate such sum quite precisely https://oeis.org/A136271
Answer: $\sum \limits_{p \in \mathbb{P}} \frac{\ln p}{p^2}  \leq  \sum \limits_{p \in \mathbb{P}} \frac{\sqrt {p}}{p^2}$ since $ \ln x  \leq \sqrt{x} $ for all $x>0$ and we want to prove that $ \sum \limits_{p \in \mathbb{P}} \frac{\sqrt {p}}{p^2}$ converge !
$\sum \limits_{p \in \mathbb{P}} \frac{\sqrt {p}}{p^2} \leq \sum \limits_{2\leq j \in \mathbb{N}} \frac{1}{j \sqrt{j}}$ since $ \frac{1}{j \sqrt{j}}$ is monotone function then $  \frac{1}{j \sqrt{j}} \leq \int \limits_{j-1}^{j} \frac{dx}{x \sqrt{x}} $
And so $\sum \limits_{2\leq j \in \mathbb{N}} \frac{1}{j \sqrt{j}} \leq \sum \limits_{2\leq j \in \mathbb{N}} \int \limits_{j-1}^{j} \frac{dx}{x \sqrt{x}} = \int \limits_{1}^{\infty} \frac{dx} {x \sqrt{x}}  = 2$
The approach you took is harder because its more accurate and in general used when we want to calculate something like $ \sum \limits_{p > x} \frac{\ln p}{p^2}$ (as function related to $x$) and not just to check convergence though you can do it.


Find conjugate indicator function

Question: I'm doubt with this problem. Let $C=\left\{(x,y)\in \mathbb{R}^2|x+\frac{y^2}{2}\le 0\right\}$. I have to find $I_C^{*}(Y)$ defined by
$I_C^{*}(Y)=\sup_{X \in \mathbb{R}^2} \left\{\langle X,Y\rangle-I_C(X)\right\}$
with $I_C$ is an idicator function of $C$.
I just know how to determine the conjugate function in 1-dimensional, but have never seen for 2-dimensional. So anybody can guide me?
Thank you so much.
Answer: $I_C(X)$ in the expression of the $I_C^*(Y)$ can be treated as a constraint. So you get $$I^*_C(Y=\left[\array{y_1\\y_2}\right])=\sup_{x_1,x_2} x_1y_1+x_2y_2\\ \qquad\qquad\qquad\text{subject to }x_1+\frac{x_2^2}{2}\leq 0.$$ You can see that if $y_1<0$ then the supremum would be $+\infty$ as you can tend $x_1\to-\infty$. If $y_1\geq 0$ then you must have $x_1=-\frac{x_2^2}{2}$, thus you want to find $\sup_{x_2} -\frac{y_1}{2}x_2^2+y_2x_2$ which is attained at $x_2=\frac{y_2}{y_1}$. Hence, $$I_C^*(Y)=\left\lbrace\array{\frac{y_2^2}{2y_1}&,y_1>0\\+\infty&,y_1\leq0}\right. .$$

Find conjugate indicator function


Deriving the formula of the surface of a sphere using triangles.

Question: My friend tried to find the formula of the surface of a sphere using the following reasoning, but we can't see the mistake:
Let's first take half a sphere and divide the sphere into infinitely small triangles like this:
 Bad drawing, but I hope you understand the idea.
Then, we can unwrap it and arrange the hemisphere into half a rectangle:  The height will be $\frac{\pi r}{2}$ because it is a quarter of the length of a circumference and the base will be $2 \pi r$.
We can now insert the other half rectangle of the other hemisphere divided in infinitely small triangles in this way:
It will nicely create a rectangle (if we rearrange the side triangles) and to get the area of the rectangle, just multiply the base times height, ending with $\pi^2 r^2$.
We know that that the correct answer is $4 \pi r^2$, but we can't figure out the error.
Answer: At the most abstract level, the discrepancy is due to the sphere not being a developable surface: it cannot be projected onto a plane while preserving areas and angles at once. Thus, it is not correct to say that the triangle on the unit sphere with angles $\frac\pi2$, $\frac\pi2$ and $dx$ – the "infinitely small triangles" in the argument – has the same area as the planar right triangle of leg lengths $dx$ and $\frac\pi2$.


C# value type casting: how it works?

Question:
Possible Duplicate:
Why does this conversion doesn't work?

Hi,
i discovered a strange behaviour of the framework.
This code throws an exception:
    byte a = 1;
    object b = a;
    Console.WriteLine(b.GetType());
    Console.WriteLine((byte)b);
    Console.WriteLine((int)(byte)b);
    Console.WriteLine(Convert.ToInt32(b));
    Console.WriteLine((int)b);

The last line throws a System.InvalidCastException.
I'd like to know what are the mechanism in the framework that make this code illegal.
Is it a problem of boxing/unboxing?!
Comment: It's not a problem, its a c#-specific behaviour.
Comment: Duplicate of http://stackoverflow.com/questions/3666195/why-does-this-conversion-doesnt-work/3666203#3666203 and http://stackoverflow.com/questions/1085097/why-cant-i-unbox-an-int-as-a-decimal and http://stackoverflow.com/questions/1667169/why-do-i-get-invalidcastexception-when-casting-a-double-to-decimal and http://stackoverflow.com/questions/2651754/how-does-the-clr-know-the-type-of-a-boxed-object and http://stackoverflow.com/questions/1812172/why-downcast-fails-at-runtime and ...
Answer: Yes, boxed value types can only be unboxed to the exact same type.
The variable b is a boxed byte.

When you do (int)(byte)b you're unboxing b back to a byte and then converting that unboxed byte to an int.
When you do (int)b you're attempting to unbox b directly to an int, which is illegal.

Edit...
As Jon mentions in his answer, there are cases where you don't have to unbox to the exact same type. Specifically:

A boxed T can be unboxed to Nullable<T>.
A boxed Nullable<T> can be unboxed to T, assuming that the nullable isn't actually null.
A boxed enum with an underlying type of T can be unboxed to T.
A boxed T can be unboxed to an enum with an underlying type of T.
Comment: Not quite to the *exact* same type. See my answer for examples of unboxing to other types.
Comment: @Jon: True, but those are corner-ish cases. I didn't mention them because I was trying to keep the answer simple, but I guess it's better to be explicit about these things. I'll edit, and throw your answer an upvote too!
Answer: Eric Lippert has a blog post on this.

Why? Because a boxed T can only be
  unboxed to T.
Or Nullable< T >.
Answer: When you unbox, it has to be to one of the following:

The exact same type
The nullable form of the exact same type
If it's an enum type value, then you can unbox to the underlying type
If it's an integral type value, you can unbox to an enum which uses that underlying type

Examples:
using System;

class Test
{
    enum Foo : short
    {
        Bar = 1
    }

    static void Main()
    {
        short x = 1;
        object o = x;

        short a = (short) o;
        short? b = (short?) o;
        Foo c = (Foo) o;

        o = Foo.Bar;
        short d = (short) o;
    }
}

Anything else will give an exception. In particular, you can't unbox to a different type even if there's an implicit conversion from the actual type to your target type, which is what you're trying to do on the last line of your example.
You also can't unbox from an integral value to a nullable form of an enum with the same underlying type (or the reverse situation).
Note that if you box a nullable value type value, the result is either null (if the original value was the null value for the type) or the boxed non-nullable value... there's no such thing as a "boxed nullable value type" if you see what I mean.
Answer:
Is it a problem of boxing/unboxing?

Yes. bis a boxed byte. So you need to unbox it to a byte first , like in (int)(byte)b

C# value type casting: how it works?


Split requests to subdomain to 2 ports

Question: I have a subdomain on an Apache web server that contains 2 folders: frontend and backend. My frontend is running a node application, whereas my backend has a headless CMS. I have both of these running on different ports.
How can I set up my .htaccess so that, for example, requests to subdomain.domain.com go to the frontend whereas some specific ones such as subdomain.domain.com/admin go to the backend?
Comment: Do you have access to **Apache**'s main configuration or **** configuration?
Answer: It's quite simple, actually. First, enable some Apache modules with the following commands:
<code>$ sudo a2enmod proxy proxy_http
$ sudo systemctl restart apache2
</code>
Modify your configuration, so it looks something like this:
<code><VirtualHost *:80>
    # A lot of directives come here...
    ProxyPassPreserve On

    <Location /frontend>
        ProxyPass http://localhost:8000/
        ProxyPassReverse http://localhost:8000/
    </Location>

    <Location /backend>
        ProxyPass http://localhost:8001/
        ProxyPassReverse http://localhost:8001/
    </Location>
</VirtualHost>
</code>
Restart or reload your Apache service with:
<code>$ sudo systemctl reload apache2
</code>
Comment: No worries Stefano. I'll play around with this and come back to accept your answer when I can get it working :)
Comment: Thanks for the answer Stefano! Seems like that could be a good fix, hadn't seen mention of the  before. Unfortunately, I can't seem to get any of those commands to work. I've ssh'd into my server and whether I run a2enmod, systemctl, mod_rewrite, jailshell keeps telling me "command not found". Any thoughts on this?
Comment: Phil, these commands are used in Debian-based Linux distributions, like Ubuntu. If you're using other distribution, like Fedora, CentOS, etc. you should use similar commands, like `yum` for package management, for instance. Also, as far as I remember, the Apache module management is a little bit different, even if the logic and the Apache configuration remains the same. I'm not familiar with jailshell, unfortunately. :(

Split requests to subdomain to 2 ports


Android drawable sizes/resolutions - Best Practice

Question: I am working on a library app that allows the user sort/organize all kind of stuff. The app offers about 150 icons the user can use to categories the entries. Since this is my first Android app I am not sure what is the best way to provide these icons:
So far I only created xxxhdpi versions, stored them in drawable-xxxhdpi and everything is working fine. I am using Nexus 5 and a Kindle Fire as test devices which show no problem. Also when using the simulator to test lower resolutions everything seems fine.
The app should support Android 4.0 up. The more version of the icons are integrated in the app, the bigger the app gets.
The docu says that one should provide different sizes so avoid scaling by the system. But is there any reason to provide other version of the icons (hdpi, mdpi, etc.) as well if the down-scaling seems to be working just fine?

Could it have an impact on performance if the system has to scale the icons instead of using pre-scaled versions?
Is the test with the simulator reliable or could it be, that on real devices the down-scaled version look bad?
I am aware, that the xxxhdpi format is quite new and almost no devices will use this actual size. Would it be better to use another size (e.g. xhdpi) instead?
Comment: This seems to be loosely related to this question: http://stackoverflow.com/q/5998865/450534. If the app's size is a constraint, I personally prefer using larger bucket sizes (either of `xhdpi` or `xxhdpi`) and let the devices scale down. Certainly a lot better than devices having to scale up resulting in image distortions. Although, I haven't come across this constraint yet, considering the number of _Phablets_ being launched, I would most probably go with `xxhdpi`.
Comment: Look at my ans : http://stackoverflow.com/questions/19875158/android-background-image-size-in-pixel/19875228#19875228
Answer: It does have an impact on performance, but you should not be bothered about it that much.
What will hurt more is the greater size due to multiple definitions.
Here is what I would suggest:

Using 9Path images-they do rescale, but in a 'pretty' way.If the resource has a repeatable area,then it is possible to define that using a 9patch image. This way the size of the resource can be kept low.                   http://developer.android.com/tools/help/draw9patch.html
Using Multiple Apks. You can have multiple apks for the same app as per device definition. http://developer.android.com/google/play/publishing/multiple-apks.html

I suggest you use a combination of both for the most efficient results
Comment: Thanks! Using 9Path images is not an option here since this is about "complex" icons (e.g. a car or a house). Using multiple APKs could an option. But the the question remains: It is necessary / has it an advantage to provide sizes/resolutions other than (x)xxhdpi if the down-scale quality is good and the performance is not really a factor?
Comment: I am not sure why it happens, but in my experience, I have noticed many times that lots of images look really bad when they are scaled down. Also, many fine lines might disappear. I also had issues with scaling down a HUGE pic in an imageView(appCrash). so you might not want to take those risks.
what i could suggest is you make 2 or 3 definitions of resources.
something like, one for lowest dpi, and one for xhdi, and then let android decide


Listar dados em colunas separadas

Question: Tenho a seguinte lista vindo do banco de dados

    <?php foreach($cidades_presentes as $valor){ ?>

<?php echo $valor->categoria; ?>

    <?php } ?>

$cidades_presentes retorna 15 cidades no seguinte formato:
Array
(
    [0] => stdClass Object
        (
            [id] => 1
            [id_cidadesbairros] => 0
            [categoria] => Foz do Iguaçu
            [ativo] => 1
        )

    [1] => stdClass Object
        (
            [id] => 4
            [id_cidadesbairros] => 0
            [categoria] => São Miguel do Iguaçu
            [ativo] => 1
        )

    [2] => stdClass Object
        (
            [id] => 6
            [id_cidadesbairros] => 0
            [categoria] => Medianeira
            [ativo] => 1
        )

)

A minha questão é: Se retornar 15 linhas, preciso exibir da seguinte forma:

8 itens da lista aqui

7 itens da lista aqui

Como eu posso fazer isto?
Atualização,
Função que busca as cidades:
public function get_cidades_presentes(){
    $this->db->where("id_cidadesbairros", '0');
    return $this->db->get('cidadesbairros')->result();
}

Answer: Um jeito simples de dividir um array em blocos iguais (dentro do possível) é usando a função array_chunk

http://php.net/manual/pt_BR/function.array-chunk.php

Para dividir sua lista de cidades em duas colunas, e exibir em seguida, essa seria uma alternativa bem simples:
$colunas = 2;
$linhas  = round(count($cidades) / $colunas, 0, PHP_ROUND_HALF_UP);
$blocos  = array_chunk($cidades, $linhas);

Para exibir conforme a pergunta, um bloco por vez:
for( $i = 0; $i < $colunas; ++$i ) {
   echo '
';
   foreach( $blocos[$i] as $bloco ) {
      echo '<tagDesejada>'.$bloco['categoria'].'</tagDesejada>';
   }
   echo '
';
}

Veja funcionando no IDEONE.
(no caso de objetos, como você já notou, seria $bloco->categoria)
Se fosse exibir lado a lado, numa tabela:
for( $i = 0; $i < $linhas; ++$i ) {
    echo '
';
    echo ''.$blocos[0][$i]['categoria'].'	';
    echo ''.$blocos[1][$i]['categoria'].'	';
    echo '
';
}

Veja funcionando no IDEONE.
(neste último caso, seria bom um if na última coluna para identificar o final do bloco, visto que nem sempre ela vai ter todas as linhas)
Comment: Ok beleza, muito obrigado!

Listar dados em colunas separadas


Question about r(t), movement along line

Question: So I'm studying for an exam in calculus when i came across the concept of objects moving along a curve. I have a general idea of how to calculate speed, velocity and such when r(t)(position vector I think it is called) is given, but I can not quite understand how to determine r(t) myself.
As an example:

$r = r(t) = x(t)i+y(t)j+z(t)k$

Then if I have $y=x^2$ should not $r=x^2i - yj$? The book says $r=xi+x^2j$
Answer: You need to parametrize the curve, i.e., insert another variable lets call it $t$ to describe the x-axis and y-axis in terms of $t$. In our case we can let $x(t) = t$. Thus $y(t) = t^2$. So our curve is $r(t) = t i + t^2 j$.
Different curves needs different parametrizes.


Is it possible to turn my surface pro into a midi input device for my mac book pro

Question: I have surface pro and I use GarageBand on osx. I was wondering if there is anything I could do to input MIDI from the device (maybe some sort of software that would turn my touch screen surface pro into a midi device)
I've tried searching google but perhaps I am using wrong keywords.
Comment: idk specifically for a Surface, I'm on iOS.. but Google Midi OSC - the protocol exists, you just need to find appropriate software for your platform. https://en.wikipedia.org/wiki/Open_Sound_Control
Comment: Possibly. But wouldn't a cheap MIDI keyboard be much easier?
Answer: An example of a software you could use as a midi interface would be xotopad
If you wanna try Ableton live, you could even use something cool like yeco.io (not free)
As you want to send the MIDI information to your macbook, you could use something like midinet, which can be found here: https://www.humatic.de/htools/mnet/man.htm
It is an Windows and OSX MIDI driver that can transfer and receive MIDI information using various network protocols (Multicast, RTP, Bluetooth, ADB, WebSockets and Serial). It can even communicate with other clients on android, linux, windows and OSX
However, I would really recommend using a real hardware MIDI controller as it is significantly easier to set up and use, and much more efficient.
My personal recommandations would be something like a Nektar Impact LX49+, an Akai Professional MPK249 or an Arturia MiniLab MkII 25 if you are on a really tight budget.
These are all USB, and easy to setup in GarageBand.
Comment: Welcome to Music Stack Exchange.  Your answer is well worded and clearly answers the question.  Thanks for contributing.
Answer: You could give MIDI Control a go (you also need to install the server on your computer). It's an editable control surface that works over Wifi (as far as I can tell, I haven't tried it).
It's inspired by TouchOSC, for iOS and Android.


Inspecting assumption of homoscedasticity

Question: Using a Fligner test to infer about the respect of the assumption of homoscedasticity is not very smart given that the Fligner test tests to the null that there is no difference of variance between the groups. This will wrongly favors small sample size. As it has been said by @Michael Mayer here.
How can we further investigate if the assumption of homoscedasticity is respected?
Is it worth plotting the model's residuals versus the fitted values? Below lines are R coded:
<code>m = aov(myFormula, myData)
plot(residuals(m), m$fit)
</code>
I don't have much experience in statistics and it seems rather hard for me to decide from this plot whether the assumption of homoscedasticity is respected. What else can I do?
Comment: If you `plot(m)` you should get 4 plots, including a scale-location plot, which should be easier to interpret - if the mean of the scale location plot clearly changes, you don't have homoskedasticity.
Answer: You might consider Levene's test, and this discussion of how to use it in R. It may be less sensitive to non-normal distributions than Bartlett's test, according to the following reference. There's also the Brown-Forsythe test for ANOVAs on transformed response variables, though this may be another version of Levene's test, judging from this question.
It sounds like your independent variable (IV) has discrete categories, but if this isn't the case, this answer provides loads of good recommendations for testing homoscedasticity across a continuous dimensional IV.
Reference
Bartlett's test. NIST/SEMATECH e-Handbook of Statistical Methods, 22.214.171.124. Available online, URL: http://www.itl.nist.gov/div898/handbook/eda/section3/eda357.htm. Retrieved December 31, 2013.
Comment: You are correct about the relationship between Levene's and Brown-Forsythe--they both use the exact same formula, but the latter uses the median, and the former uses the mean.  https://en.wikipedia.org/wiki/Brown%E2%80%93Forsythe_test


Connecting Shibboleth as a IdP and API Publisher as SP

Question: The Plan
We went to configure shibboleth as the IdP so we can do SSO. We have shibboleth configured already for the many other things we do like email and account information, but when trying to add in our API publisher to the mix we seem to be getting an error. We believe it to be a wso2 configuration error. We been using this wso2 documentation as a template: How to Configure Shibboleth IdP as a Trusted Identity Provider
The Situation
So far we are able to get to the login screen and put in our credentials, but when it tries to redirect us we get a Error 401 : Authorization Required.
SAML code
<code><saml2p:Response
Destination="localhost"
ID="mbnfmmagbmefckldpefbmjopkadjahbkocadhmib"
InResponseTo="lihfmcpiofkdkhphfbahlndllmmemhldckammgaf"
IssueInstant="2016-12-05T16:20:37.939Z"
Version="2.0"
xmlns:saml2p="urn:oasis:names:tc:SAML:2.0:protocol"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<saml2:Issuer
    Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity"
    xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion">IdsDev
</saml2:Issuer>
<ds:Signature
    xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
    <ds:SignedInfo>
        <ds:CanonicalizationMethod
            Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
        <ds:SignatureMethod
            Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
        <ds:Reference
            URI="#mbnfmmagbmefckldpefbmjopkadjahbkocadhmib">
            <ds:Transforms>
                <ds:Transform
                    Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
                <ds:Transform
                    Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#">
                    <ec:InclusiveNamespaces
                        PrefixList="xs"
                        xmlns:ec="http://www.w3.org/2001/10/xml-exc-c14n#"/>
                </ds:Transform>
            </ds:Transforms>
            <ds:DigestMethod
                Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
            <ds:DigestValue>9xbWKA7A+
                7k7Vaz6O18z8Xliqbo=
            </ds:DigestValue>
        </ds:Reference>
    </ds:SignedInfo>
    <ds:SignatureValue>kX11Q4eCUyME+VP5M7+5iI6D45kqQgE6MIqth7hNosSmfdSD3kZS0dwlcNwVlrzA64LMUZxclU256xP6w6nn0TqEqLjKy/tGXeQbKjaYrPcXx6336kIp8YGajqDiBh7IJswFDxugLoRx70APaKGthJi5VwRea1oT3lE4RHJoMgiN7o5FO1N+8IE34zEJLmTIpt+lYdXQPJanN29GY9YfIouFe2TGfHfXd9PT2nt7Dmf+M69DM3giEyizbzljYHdkjJrTlqoYTlHBHNPq8NF/+1wwuL76SP0Bory4k/7JvelW6RSAz82pdjDc0ublBmuceTENza2GiC2sitVQPycl/
        g==
    </ds:SignatureValue>
    <ds:KeyInfo>
        <ds:X509Data>
            <ds:X509Certificate>MIIFejCCBGKgAwIBAgIQCKTAgWTgw/Ea7HQ+L665tTANBgkqhkiG9w0BAQsFADBwMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMS8wLQYDVQQDEyZEaWdpQ2VydCBTSEEyIEhpZ2ggQXNzdXJhbmNlIFNlcnZlciBDQTAeFw0xNjA5MjYwMDAwMDBaFw0xOTEwMDExMjAwMDBaMHIxCzAJBgNVBAYTAlVTMQ4wDAYDVQQIEwVJZGFobzEQMA4GA1UEBxMHUmV4YnVyZzEnMCUGA1UEChMeQnJpZ2hhbSBZb3VuZyBVbml2ZXJzaXR5LUlkYWhvMRgwFgYDVQQDEw9pZHNkZXYuYnl1aS5lZHUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCeLpdcJnXbGKRYujiUIoCOFrjR3PZ2E+BmzGNNTSTbnxjRPCJpjoI/5OWXPV/59I4s+b/lMaVuth5G8FD/yGDE/cyOKHM79G8UR399aqflqVWCfBc5Kqf7oKByBiost5JQyLGUTlXOvOKvLNTSHEC1gZUYP6Sn9m7/HOtcaMji32N0Pr22NYk92LSbUZqwVUM5e71q7Yze4OTiAv/Sd3Us1M4YgD+qJpy15Rph5Uo7jq1J9YE38dVmznJKD5xKt6G5Bn/b7pWipnhfG9gNJhjkpP/IVOfkpsDIm4QDXOArjzV/qLck8GF6zr8+PiUM4k/peottkvq6UV0AKPiv/DPJAgMBAAGjggIMMIICCDAfBgNVHSMEGDAWgBRRaP+QrwIHdTzM2WVkYqISuFlyOzAdBgNVHQ4EFgQUgpnRRipdTainSlDqezFYUGdyKWgwPgYDVR0RBDcwNYIPaWRzZGV2LmJ5dWkuZWR1ghBJZHNEZXYxLmJ5dWkuZWR1ghBJZHNEZXYyLmJ5dWkuZWR1MA4GA1UdDwEB/wQEAwIFoDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwdQYDVR0fBG4wbDA0oDKgMIYuaHR0cDovL2NybDMuZGlnaWNlcnQuY29tL3NoYTItaGEtc2VydmVyLWc1LmNybDA0oDKgMIYuaHR0cDovL2NybDQuZGlnaWNlcnQuY29tL3NoYTItaGEtc2VydmVyLWc1LmNybDBMBgNVHSAERTBDMDcGCWCGSAGG/WwBATAqMCgGCCsGAQUFBwIBFhxodHRwczovL3d3dy5kaWdpY2VydC5jb20vQ1BTMAgGBmeBDAECAjCBgwYIKwYBBQUHAQEEdzB1MCQGCCsGAQUFBzABhhhodHRwOi8vb2NzcC5kaWdpY2VydC5jb20wTQYIKwYBBQUHMAKGQWh0dHA6Ly9jYWNlcnRzLmRpZ2ljZXJ0LmNvbS9EaWdpQ2VydFNIQTJIaWdoQXNzdXJhbmNlU2VydmVyQ0EuY3J0MAwGA1UdEwEB/wQCMAAwDQYJKoZIhvcNAQELBQADggEBADAayQq4l5DqWmgste9KgnqWOkOkjWw7bxu7WOh++oPyaNlyzieaz2ZJXrf4bHHeF5pCA9FUzhpdwGg+iWzt5Wd8L3G50mEUBJKjKgAzkOr9ywoGlPio/GaqqNrMmKhmLQDz6hcIoCk3SXAR5GDzRCjn5PZvboL9l+uTCE0h6Sg8qCRjgIYvOHbN8FhMla2opx2B7mnX5jAnfzfnJgGQZERLDSy8dvYhtXBaxaCzDqfYwZFQjec+IRjHHHLQpAPKzB5ARNe5IYlSMfkbi71kNpaFQ1WAJtAO+9pld5zgA/
                OvSamgXd5RBJbXq376LX3r9jcYGpQwJT3hqMl9Qa1B0pY=
            </ds:X509Certificate>
        </ds:X509Data>
    </ds:KeyInfo>
</ds:Signature>
<saml2p:Status>
    <saml2p:StatusCode
        Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
</saml2p:Status>
<saml2:Assertion
    ID="gihomiibdbpcojhdmjofkecelaibhdcdonghhkpm"
    IssueInstant="2016-12-05T16:20:37.939Z"
    Version="2.0"
    xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion"
    xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <saml2:Issuer
        Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">IdsDev
    </saml2:Issuer>
    <ds:Signature
        xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
        <ds:SignedInfo>
            <ds:CanonicalizationMethod
                Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
            <ds:SignatureMethod
                Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
            <ds:Reference
                URI="#gihomiibdbpcojhdmjofkecelaibhdcdonghhkpm">
                <ds:Transforms>
                    <ds:Transform
                        Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
                    <ds:Transform
                        Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#">
                        <ec:InclusiveNamespaces
                            PrefixList="xs"
                            xmlns:ec="http://www.w3.org/2001/10/xml-exc-c14n#"/>
                    </ds:Transform>
                </ds:Transforms>
                <ds:DigestMethod
                    Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
                <ds:DigestValue>Z7DIvjwTk4JpF0TRMNzo3Z/
                    4sfc=
                </ds:DigestValue>
            </ds:Reference>
        </ds:SignedInfo>
        <ds:SignatureValue>h1Stjkbw306VU7TN5OEou2XII3nzvhr34GVbced5Gk7q+EZailZusYISkC11eJjk4Y+CejMa4RODelwnMAdpfeWmMYz6ukk0jh9RH97/uWPOWKfOp4n/oXVnYE3rdImGcb1egas/zprqM7Pl8mbwI7vK3ScMUagBg6Td1sxHfRgVBk6r8C+40sgTAG8LsOd+q8LKNYj5mSeZ5K34SBdkmMWNpAS9mOT9CSJfWOrd9uAvFXHeuWN31MbIgVV5seEMfUzC18I/4s3qXwWqIvQxIsF8l9WuIuMYsFPT+oQJBU/ltQVf54w29k50tvN+LyvmNbZCZANf+
            3JXwygyImc2Yg==
        </ds:SignatureValue>
        <ds:KeyInfo>
            <ds:X509Data>
                <ds:X509Certificate>MIIFejCCBGKgAwIBAgIQCKTAgWTgw/Ea7HQ+L665tTANBgkqhkiG9w0BAQsFADBwMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMS8wLQYDVQQDEyZEaWdpQ2VydCBTSEEyIEhpZ2ggQXNzdXJhbmNlIFNlcnZlciBDQTAeFw0xNjA5MjYwMDAwMDBaFw0xOTEwMDExMjAwMDBaMHIxCzAJBgNVBAYTAlVTMQ4wDAYDVQQIEwVJZGFobzEQMA4GA1UEBxMHUmV4YnVyZzEnMCUGA1UEChMeQnJpZ2hhbSBZb3VuZyBVbml2ZXJzaXR5LUlkYWhvMRgwFgYDVQQDEw9pZHNkZXYuYnl1aS5lZHUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCeLpdcJnXbGKRYujiUIoCOFrjR3PZ2E+BmzGNNTSTbnxjRPCJpjoI/5OWXPV/59I4s+b/lMaVuth5G8FD/yGDE/cyOKHM79G8UR399aqflqVWCfBc5Kqf7oKByBiost5JQyLGUTlXOvOKvLNTSHEC1gZUYP6Sn9m7/HOtcaMji32N0Pr22NYk92LSbUZqwVUM5e71q7Yze4OTiAv/Sd3Us1M4YgD+qJpy15Rph5Uo7jq1J9YE38dVmznJKD5xKt6G5Bn/b7pWipnhfG9gNJhjkpP/IVOfkpsDIm4QDXOArjzV/qLck8GF6zr8+PiUM4k/peottkvq6UV0AKPiv/DPJAgMBAAGjggIMMIICCDAfBgNVHSMEGDAWgBRRaP+QrwIHdTzM2WVkYqISuFlyOzAdBgNVHQ4EFgQUgpnRRipdTainSlDqezFYUGdyKWgwPgYDVR0RBDcwNYIPaWRzZGV2LmJ5dWkuZWR1ghBJZHNEZXYxLmJ5dWkuZWR1ghBJZHNEZXYyLmJ5dWkuZWR1MA4GA1UdDwEB/wQEAwIFoDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwdQYDVR0fBG4wbDA0oDKgMIYuaHR0cDovL2NybDMuZGlnaWNlcnQuY29tL3NoYTItaGEtc2VydmVyLWc1LmNybDA0oDKgMIYuaHR0cDovL2NybDQuZGlnaWNlcnQuY29tL3NoYTItaGEtc2VydmVyLWc1LmNybDBMBgNVHSAERTBDMDcGCWCGSAGG/WwBATAqMCgGCCsGAQUFBwIBFhxodHRwczovL3d3dy5kaWdpY2VydC5jb20vQ1BTMAgGBmeBDAECAjCBgwYIKwYBBQUHAQEEdzB1MCQGCCsGAQUFBzABhhhodHRwOi8vb2NzcC5kaWdpY2VydC5jb20wTQYIKwYBBQUHMAKGQWh0dHA6Ly9jYWNlcnRzLmRpZ2ljZXJ0LmNvbS9EaWdpQ2VydFNIQTJIaWdoQXNzdXJhbmNlU2VydmVyQ0EuY3J0MAwGA1UdEwEB/wQCMAAwDQYJKoZIhvcNAQELBQADggEBADAayQq4l5DqWmgste9KgnqWOkOkjWw7bxu7WOh++oPyaNlyzieaz2ZJXrf4bHHeF5pCA9FUzhpdwGg+iWzt5Wd8L3G50mEUBJKjKgAzkOr9ywoGlPio/GaqqNrMmKhmLQDz6hcIoCk3SXAR5GDzRCjn5PZvboL9l+uTCE0h6Sg8qCRjgIYvOHbN8FhMla2opx2B7mnX5jAnfzfnJgGQZERLDSy8dvYhtXBaxaCzDqfYwZFQjec+IRjHHHLQpAPKzB5ARNe5IYlSMfkbi71kNpaFQ1WAJtAO+9pld5zgA/
                    OvSamgXd5RBJbXq376LX3r9jcYGpQwJT3hqMl9Qa1B0pY=
                </ds:X509Certificate>
            </ds:X509Data>
        </ds:KeyInfo>
    </ds:Signature>
    <saml2:Subject>
        <saml2:NameID
            Format="urn:oasis:names:tc:SAML:2.0:nameid-format:persistent">username
        </saml2:NameID>
        <saml2:SubjectConfirmation
            Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
            <saml2:SubjectConfirmationData
                InResponseTo="lihfmcpiofkdkhphfbahlndllmmemhldckammgaf"
                NotOnOrAfter="2016-12-05T16:25:37.939Z"
                Recipient="localhost"/>
        </saml2:SubjectConfirmation>
    </saml2:Subject>
    <saml2:Conditions
        NotBefore="2016-12-05T16:20:37.939Z"
        NotOnOrAfter="2016-12-05T16:25:37.939Z">
        <saml2:AudienceRestriction>
            <saml2:Audience>API_PUBLISHER</saml2:Audience>
        </saml2:AudienceRestriction>
    </saml2:Conditions>
    <saml2:AuthnStatement
        AuthnInstant="2016-12-05T16:20:37.941Z"
        SessionIndex="cbc00514-954b-4de2-8e7b-b50edf9c5976">
        <saml2:AuthnContext>
            <saml2:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:Password</saml2:AuthnContextClassRef>
        </saml2:AuthnContext>
    </saml2:AuthnStatement>
    <saml2:AttributeStatement>
        <saml2:Attribute
            Name="http://wso2.org/claims/fullname"
            NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic">
            <saml2:AttributeValue
                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                xsi:type="xs:string">username
            </saml2:AttributeValue>
        </saml2:Attribute>
    </saml2:AttributeStatement>
</saml2:Assertion>
</code>

IdP Config
Shibboleth IDS configuration
Shibboleth IDS configuration
Comment: Does the 401 Error occurs on the Shobboleth or WSO2IS server? Could you switch to the DEBUG level and see what's in the logs (wso2carbon.log)?  (I believe it's not the cause, but at least make the signatures consistent, ticket is using sha1 digent and rsa-sha1 signature, your screenshots are stating otherwise)
Comment: Found a documentation and a blog post regarding this question. See if they help to solve your problem.
https://docs.wso2.com/display/IS510/How+To%3A+Configure+Shibboleth+IdP+as+a+Trusted+Identity+Provider
http://xacmlinfo.org/2014/12/04/federatation-shibboleth/
Comment: @GabrielVince Thanks for the comment. It looks like it's on the WSO2IS server. When I go check the wso2carbon.log nothing shows up, no errors or anything. So far we think that the cause may be the name ID we get from shibboleth. Shibboleth is only sending the username back but the IS server needs the nameID back as _domain name_ / _username_ to see that the user is authorized. Or so far is are best guess.
Comment: Looking through yesterdays logs I found this:

[2016-12-05 14:44:45,100] ERROR {org.wso2.carbon.identity.application.authenticator.samlsso.manager.DefaultSAML2SSOManager} -  Error while populating SAMLRequest wit
h AttributeConsumingServiceIndex: urn:oasis:names:tc:SAML:2.0:nameid-format:persistent
java.lang.NumberFormatException: For input string: "urn:oasis:names:tc:SAML:2.0:nameid-format:persistent"

not sure if it really concerns are current problem though.
Answer: We solved the problem! So we couldn't get shibboleth 2 to send the right information in the subject/nameID in the SAML code, but when we tried shibboleth 3 the customization of the nameID was an easier thing to work with. Anyways, wso2 could not authorize access with just the username in the subject/nameID, it also needed the domain and formated like this domain/username. With that we got SSO to work.


.Net Core 3 Entity Framework with Firebird database and charset none

Question: I have a legacy Firebird (2.5.9) database that was created with no charset and since it is in production all data was inserted using WIN1252. I'm migrating to .Net Core and I'm using FirebirdSql.Data.FirebirdClient as provider (in both .Net Framework and .Net Core).
In .Net Framework and EF 6 I just had to set the charset WIN1252 in the connection string.
In .Net Core 3.1 the connection string's charset is used only while reading as I have to set the column type in code first like this:
entity.Property(e => e.description).HasMaxLength(255).HasColumnType("VARCHAR(255) CHARACTER SET WIN1252");

to make it save strings with the same encoding.
The problems I'm facing now are related to the fact that all query parameters seem to use UTF8 that is the new default encoding in .Net Core and some special characters are, of course, different.
So, for example, assuming I have a record with accented characters in the field description like "èèè".
The following query fails to retrieve it:
string filter = "èèè";
Product p = context.Products.Where(x => x.description == filter).FirstOrDefault();

This query gets translated into:
SELECT "a"."product_id", ... , "a"."description"
FROM "products" AS "a"
WHERE "a"."description" = CAST(@__filter_0 AS VARCHAR(8191))

That cast happens in .Net Framework too but queries like this work correctly there.
Also if there are multiple parameters I get the error
Implementation limit exceeded. block size exceeds implementation restriction
that is exactly what is described in this question even if that was in EF5 and .Net Framework. Basically it seems that you easily hit the row size limit of 64k because that VARCHAR(8191) cast weights more in terms of bytes as UTF8.
I'm sure that one solution would be to upgrade to a new database with UTF8 encoding and encode all data properly but it's something I would like to avoid if possible at the moment. Also I don't think that would solve the block size error.
Is there a way to make it work like in .Net Framework?
Comment: The Firebird issue [DNET-934](http://tracker.firebirdsql.org/browse/DNET-934): *Cast of string values to VARCHAR(8191) results in "Implementation limit exceeded"* seems to be related to what you are describing. Not sure if that helps just providing something I came across which seemed tangentially related.
Comment: @ahsteele yes, it is related to the block size limit. Unfortunatly when I use the provider option to disable the casts there are a lot of new "Data type unknown" errors that need to be investigated
Comment: _"the connection string's charset is used only while reading"_ that doesn't mesh with my understanding of the Firebird wire protocol. I would recommend asking your question on the [firebird-net-provider Google Group](https://groups.google.com/d/forum/firebird-net-provider).
Comment: `Firebird (2.5.9) database that was created with no charset` - can you just edit SYSTEM TABLES and retroactively introduce character sets there ? it might also needs a refresh alter, like backup-restore cycle or making simple app which connects using propr charset and then issues `UPDATE T SET X=X, Y=Y, Z=Z` over all the tables (the script can be auto-generated using those very system tables)
Comment: @MarkRotteveel I posted there, I'll share what I find here. Thank you.
Comment: @Arioch'The I always avoided messing with the system tables (in fb3 in fact they became readonly) but apparently, since the table RDB$CHARACTER_SETS already contains all the character sets supported, there's RDB$DATABASE->a.RDB$CHARACTER_SET_NAME that contains the charset used. It feels like an hackish way to convert to UTF8 instead of new DB + data pump. I'm trying to understand if I can avoid that since I would have to update other legacy apps in delphi with the new encoding.
Comment: That is why I tried to convince Mark to prohibit non-explicit NONE connections in Jaybird regardless of a one-time storm of flawed apps, for the sake of clean break and safety from now on. Sadly I failed. Though, in my case I was coming from a JDBC app, whose devs only did bare minimum to support any DB but their beloved one. Which is reasonable. So they did not make deep research into all historical quirks of FB but just went with minimal possible efforts expecting FB to have safe defaults...
Answer: I just got an answer from Jiří Činčura in firebird-net-provider Google Group
The reason behind the different behavior between .Net Framework and .Net Core is, in fact, due to the default encoding of .Net Core (UTF8).
My database had the column charsets set to none. So what happens is that even if you set the column type like this:
.HasColumnType("VARCHAR(255) CHARACTER SET WIN1252");

the provider always uses the column charset in the database when comparing values.
This means that if you set the column type in code first you only fix the string saving but when the provider needs to compare values he checks the columns configuration in the database.
So the solution is to properly define/fix charsets on the columns/database and check/copy the data.
Personally, instead of forcing the WIN1252 charset on all the columns, I went ahead and converted the whole database in UTF8 so that, even if I keep the column charset to none, strings are already saved in the same .Net Core default encoding and it's also more future proof.
The row size limit problem is somehow unrelated, it's just something that will happen when you start using UTF8. Fortunately you can set this option in the context configuration
new FbDbContextOptionsBuilder(optionsBuilder).WithExplicitParameterTypes(false);

to reduce those varchar casts.
Additional Info
To convert the database I used fbclone, since it can clone a database pumping data from one database to another using the same structure and at the same time handling different charsets.
Also, you may need to check your indexes since in Firebird 2.x the maximum size is a quarter of the page size (source) and strings in UTF8 are stored internally as 4 bytes/char so if you come from WIN1252 (1 byte/char) like me you can hit that limit easily.


how to include and execute php variable with html and other php variables in it

Question: I'm stuck...
I have a variable which has html (sometimes javascript) and php code (other variables) in it and is stored in a mysql db.
Basically, what I have to do is insert the variable into a page -> what works but the php code is not executed its just displayed like txt. So I am looking for a way to insert the variable so that the php code is recognized and executed (the vars are inserted)..
What I tried so far:
(very simple) Sample code stored in db:
Image Var (new_p_img):

Image Display Code Var (new_p_dis):

<?php echo $new_p_img; ?>

To display in site I try
 <?php echo $new_p_dis; ?>

The code is displayed perfectly in source code but the php echo code is not recognized/executed its treated like normal txt.
I also tried to include it thru an extra file.
Sample code new-product.php
<?php echo $new_p_img; ?>

To display in site I try
<?php echo include('products/new-product.php'); ?>

didnt work... If i put the "new_p_dis" code direct into the site or the new-product.php file like this

<?php echo $new_p_img; ?>

it works fine but than I would have to re-code the entire site..... thats not an option :(
Is it somehow possible to maybe preload the var "new_p_dis" add the missing "new_p_img" var and then insert the final code into the page?
A code example would really help me out.
Thx
PS: eval() isnt an option ;)
PPS: The above codes are just a simple sample, the real codes are much more complicated, the vars are all dynamicly created via php and stored in the database -> I only need a starting point :)
Comment: How do you think you are going to execute an arbitrary string without using `eval`? Why are you storing code in your database?
Comment: the code is generated and inserted during import from a "order processing software" and cant be changed.... the direct usage of "eval(the code)" was what i first tried it worked local, but isnt allowed on the hosting plan....
Comment: `eval` is the answer, period. Also, keep in mind "if eval is the answer, you're almost certainly asking the wrong question" (Rasmus Lerdorf).
Answer: Actually this does work... with a work around.
What I did was simply creat a function where I grabbed the stored variable, added what I needed and then "called" it in my Page.
function main_p_lnk_shortcode() {
    global $uf_vars;
    $p_lnk1 = '';
    return $p_lnk1;
  }
 add_shortcode('main_p_lnk', 'main_p_lnk_shortcode');

In this case I added a WP-ShortCode
I did the same with all other vars that had php tags in them, load, manipulate then return, as direct function or shortcode....


Can I create a link to a taxonomy page?

Question: I have a page that has a single category applied to it, for this example, "Self Help Books".
I want to put a place on content type that display a "view all [insert category here]" that links to that category listing page. I was hoping I could do something like view all %taxonomy:books% which would pull in the category for anything using that content type. I'm using the Panels module, so I had planned on placing this in a panel the content type was using.
Is it possible?
I thought about creating a block and placing that in a panel.
Answer: There's a default path that links to taxonomy/term/term_id. For instance if the term_id for the term Self help books is 42, the following path will list all self help books.
taxonomy/term/42

Now, to replace this with the appropriate string, navigate to:
Home » Administration » Configuration » Search and metadata » URL aliases

and specify that Self help books should be an alias for taxonomy/term/42.
First, make sure all nodes that you want listed as self help books is tagged with the tag Self help books.
Then, to create a link to the nodes tagged with a specific term based upon vocabulary, you need to install and enable the Token module and the Token Filter module (unless you've already done so).
Next navigate to:
Home » Administration » Configuration » Content authoring » Text formats

and click Configure on the text format (or formats) you plan to use. Under Enabled filters. make sure the filter named Replace tokens is activated.
You can now see the what tokes that exist by going to:
Home » Administration » Help » Token

and expand the Nodes item.  Let us say that your book category field is named node:field_book_category.
Then, if you put an HTML link like this somewhere on a page tagged with Self help books:
View more [node:field_book_category]

you will get a link back to a page listing all nodes tagged with Self help books.
This will of course work with any other taxonomy term (e.g. sport books, cooking books, etc.) as well. However, the node can only be tagged with a single term from a particular vocabulary for this method to work.
Note: For this to work, the node must actually be tagged with exactly one taxonomy term from the relevant vocabulary.  You can easily check that the node is tagged this way: When you view the content of the node, the taxonomy term or terms it is tagged with is automatically inserted by Drupal with link to a list of all nodes tagged with the term. If this link does not appear, then the node is untagged. If multiple links appear, then there are multiple taxonomy terms. If the node is untagged, there will be no token replacement and the token will appear as plain text. If the node is tagged with multiple terms, then the token will expand into a list of taxonomy categories, and can no longer be inserted in a single link.
PS: As an alternative solution you can override the template for the node (node.tpl.php), you can replace the simple link mentioned in the previous paragraph with the string "View more" followed by the link.  This also work if there are more than one tag from the vocabulary on the page.
Comment: If I go to the alias URL I created for the taxonomy term (site.com/categories/selfhepbooks) all the nodes I tagged with that category show with a title, summary, and a read more link. So it is getting tagged.
Answer: Create a taxonomy term reference field in the content type where you want to place the link. Select Books as the vocabulary so that this field can reference the terms of the Books vocabulary. Let the field machine name be field_book_reference.
Use the following code.
$node = menu_get_object();
if(is_object($node)) {
  $title = $node->title;
  $book_tid = $node->field_book_reference['und'][0]['tid'];
  echo 'View all ' . $title . '';
}

You may place that code anywhere PHP code is accepted. Better, create a PHP block and place it in a panel.

Can I create a link to a taxonomy page?


Why does the classic guitar have a body with that specific size and shape?

Question: After having played a steel, cut-out acoustic, and back to my non-cut-out, nylon acoustic, I started to think "what the hell":

Why so few frets?
Why the body meets the neck at the 12th fret not higher?
Why do classic acoustic guitars even have this waist / body shape in the first place?

So the question is: what is the design intent of the shape and position (neck meeting body at 12th fret) of the classic acoustic guitar?
Answer: In an acoustic instrument, the tone depends very much on the resonances not only of the material the instrument is made from, but also on the size of the air cavities inside, and also the size and position of the holes connecting the inside to the outside - i.e. the rose on a guitar.
The structure of the instrument also has to be strong enough to withstand the tension of the strings, and any other mistreatment that it might receive while being played or carried around! And of course it has to be physically possible for a "normal sized" human to actually play it.
So in the end, the question "why does a classical guitar look the shape it is" amounts to "why does a guitar sound like a guitar" - which is probably unanswerable! In fact the earliest guitars often had quite small bodies, short necks, fewer strings (e.g only 4) and relatively few frets (sometimes only 7 or 8) compared with the later "Spanish guitar" design.
Of course modern materials and construction techniques can solve the mechanical and acoustic design problems in ways that were not practical using only the materials and hand tools that were available several hundred years ago.
Answer: Without any research, whatsoever, my two cents is
(1) The 12th fret is the octave for each string so it is a good visual cue for the player. It may also have to do with the maximum amount of resonance given that that is exactly the half-length of the string.
(2) The Neck is also wider to facilitate the intricacies of the classical repertoire.
(3) There isn't a need for much range beyond the frets for the vast majority of classical guitar music. Of course, some composer push this, but most of the music is fine with the 3 octave range from low E to E on the 12 fret of the first string.
(4) I think the body design with the waist is just for the convenience of putting it on your leg.
Anyways, that's one persons take on it. I'm the interwebs will yield plenty of more info on the topic.
Comment: About the waisted design- it's hard to say where that comes from.  If you look at illustrations of the early guitar and its predecessors the vihuela and citole, it's usually not played on the leg.


How can I find my public ip address with built in system commands without relying on any third party websites or services?

Question: Are there any built in system commands such as ping that let me discover my public ip-address either on a Windows or Linux operating system?  This should not rely on any third party websites or services.
Comment: You cannot.  Didn't you see the other nearly identical question on the front page?  http://serverfault.com/questions/475445/one-liner-to-retrieve-external-ip-address
Comment: @Zoredache Thank you for the information with the link.  I have seen ways of using third party utilities.  I have figured out how to do it and will post the answer.
Comment: Several protocols, such as SMNP and UPnP, can be used to automatically query your router for its WAN-side IP address.  But, as @Grant mentions, this might not be the same as your external Internet-facing address.
Answer: To tell what your public ip address appears to be to third parties you need a third party to tell you what they see.
If you don't want to rely on a third party...be the third party and have your own web server located somewhere else tell you.
Even if you can get the information from your router that may not always be what other systems see - you may be behind carrier NAT or an ISP proxy server.
Answer: Before the packets reach the NAT device, there's not enough information to determine what the external IP address is going to appear as.  To answer your question, I'd log on to the ADSL modem (if that's what is supplying your internet connection and doing the NAT for you) and check the connection and see what IP address was assigned by the ISP.
If my assumptions accurately reflect your network setup, that IP address you see should be the address other hosts on your LAN appear to be when viewed from the Internet.
The config at my workplace is messy and has unnecessary bits... if I do a tracert, I don't see a hop with an IP address that matches what whatismyip.com reports is my IP address.


MongoDB Panache queries not returning any result

Question: I am having problems with querying with MongoDB.
Whenever I try to find by ID or any other field, I always get zero results back.
And I am also having trouble to use the 'like' operator.
What I wanna query is the titles of the books in a case insensitive way. And I know you can do it like this in MongoDB:
{title: {$regex: /^query.*/i}}

And I try to do this with Panache but I can't get it working:
Book.find("title like ?1", "/^" + query + ".*/i");

I see the following line on the console getting printed out:
    {'title':{'$regex':'/^Harr.*/i'}}
I've also tried it with a Document, but also not success:
Document query = new Document();
query.put("title", "$regex: /^" + query + ".*/i");
Book.find(query);

And I get zero results back.
And here is my Book class:
public class Book extends PanacheMongoEntity {

@NotEmpty
public String title;

@NotEmpty
public String isbn;

@NotEmpty
public String author;

@Min(1)
@NotNull
public BigDecimal price;
}

And here is my BookResource:
@Produces(APPLICATION_JSON)
@Consumes(APPLICATION_JSON)
@Path("/books")
public class BookResource {

@GET
public List<Book> get() {
    return Book.listAll();
}

@GET
@Path("/{id}")
public Book find(@PathParam("id") String id) {
    return (Book) Book.findByIdOptional(id).orElseThrow(() -> new NotFoundException("Book not found"));
}

@GET
@Path("/title/{title}")
public PanacheQuery<PanacheMongoEntityBase> findByTitle(@PathParam("title") String title) {
    Document query = new Document();
//        query.put("title", new BasicDBObject("$regex", ).append("$options", "i"));

    return Optional.ofNullable(Book.find("title like ?1", format("/^%s.*/i", title))).orElseThrow(() -> new NotFoundException("Book not found"));
}

@POST
public void add(@Valid Book book) {
    Book.persist(book);
}

@PUT
@Path("/{id}")
public void update(@PathParam("id") String id, @Valid Book book) {
    Book result = Book.findById(id);
    if (result != null) {
        result.author = book.author;
        result.isbn = book.isbn;
        result.price = book.price;
        result.title = book.title;

        Book.update(result);
    }
}
}

When I do a findAll via curl I get this:
[
{
"id": "5eb9475b8a4314145246cc10",
"author": "J.K. Rowling",
"isbn": "12345678",
"price": 24.95,
"title": "Harry Potter 1"
},
{
"id": "5eb95a758a4314145246cc25",
"isbn": "456",
"price": 0,
"title": "Java for dummies"
},
{
"id": "5eb95b1a8a4314145246cc27",
"author": "steven king",
"isbn": "456",
"price": 10,
"title": "IT"
}
]

And when I try to find a Book by id, I also get zero results:
curl -X GET "http://localhost:8080/books/5eb9475b8a4314145246cc10" -H "accept: application/json"

=> 404 No Books found.

The only operation that seems to work is the POST (persist), the rest of the methods don't return anything.
I have the following setup:

MongoDB 4.2 running via Docker
Quarkus 1.4.2
JDK 11

And here is my application.properties:
quarkus.mongodb.connection-string=mongodb://localhost:27017
quarkus.mongodb.database=books
quarkus.log.category."io.quarkus.mongodb.panache.runtime".level=DEBUG

Answer: The following piece of code is wrong:
@GET
@Path("/title/{title}")
public PanacheQuery<PanacheMongoEntityBase> findByTitle(@PathParam("title") String title) {
    Document query = new Document();
    //query.put("title", new BasicDBObject("$regex", ).append("$options", "i"));

    return Optional.ofNullable(Book.find("title like ?1", format("/^%s.*/i", title))).orElseThrow(() -> new NotFoundException("Book not found"));
}

Book.find() return a PanacheQuery, you need to call one of the terminator operations of the query to get the results: list/stream/findFirst/findOne.
I would suggest implementing it like this:
@GET
@Path("/title/{title}")
public List<Book> findByTitle(@PathParam("title") String title) {
    return Book.list("title like ?1", format("/^%s.*/i", title)));
}

list() is a shortcut for find().list(), if you don't need pagination or other things that are available on the PanacheQuery interface you can directly use list().
Comment: Indead, only String pattern is currently supported in Quarkus not JavaScript pattern (the one started with / and ending with / and possibly some options).
Support of JavaScript pattern is currently on discussion here: https://github.com/quarkusio/quarkus/issues/9219
Comment: OK, I've changed it into list()...and I see the following line on the console:
[io.qua.mon.pan.run.MongoOperations].... {'title':{'$regex':'/^harr.*/i'}}

And I see still no any result.
Comment: OK, I see what's happening...the correct query should be without quotes !
If I do this, then it works: return Book.list(format("{title: {$regex: /.*%s.*/i}}", title));

And this is a bug in Panache, it places quotes on the property (title) and on it's value.

Another question: why is findById also not returning any result when I just search by ObjectId ?
Comment: If this acts similar to the mongo java driver, you might get to the correct result by using "=" and Pattern.compile() as the query. Might be worth a try.


How to read data in collection in MongoDB?

Question: I am working on a social media app using Node.js and MongoDB. I've got a problem with reading the data in the collection. I want to get everything from the collection.
Router.js:
router.get('/feed', async (req,res) => {
    try{
        await db.client.connect()
        await db.feed(db.client)
        res.render("feed")
    }catch(err){
        console.log(err)
    }finally{
        db.client.close()
    }
})

Db.js
async function feed(client, res){
    let result = await client.db('secret_db').collection('secrets')
    console.log(result)
}

Output:
Collection {
  s: {
    db: Db { s: [Object] },
    options: {
      raw: false,
      promoteLongs: true,
      promoteValues: true,
      promoteBuffers: false,
      ignoreUndefined: false,
      bsonRegExp: false,
      serializeFunctions: false,
      fieldsAsRaw: {},
      writeConcern: [WriteConcern],
      readPreference: [ReadPreference]
    },
    namespace: MongoDBNamespace { db: 'secret_db', collection: 'secrets' },
    pkFactory: { createPk: [Function: createPk] },
    readPreference: ReadPreference {
      mode: 'primary',
      tags: undefined,
      hedge: undefined,
      maxStalenessSeconds: undefined,
      minWireVersion: undefined
    },
    bsonOptions: {
      raw: false,
      promoteLongs: true,
      promoteValues: true,
      promoteBuffers: false,
      ignoreUndefined: false,
      bsonRegExp: false,
      serializeFunctions: false,
      fieldsAsRaw: {}
    },
    readConcern: undefined,
    writeConcern: WriteConcern { w: 'majority' },
    slaveOk: false
  }
}

Take into consideration that I don't have a problem with rendering the pages. The problem must be done inside the async function feed()
Comment: MongoDB NodeJS Driver documentation has this: [Read Operations](https://docs.mongodb.com/drivers/node/current/fundamentals/crud/read-operations/) (how to read data from a collection).
Comment: Thank you soo much <3
Answer: You need to use find method of the collection to get the actual data from the DataBase. In your case try this.
 let result = await client.db('secret_db').collection('secrets').find({})

Comment: I tried this but it didn't work. The guy helped me above and I solved the problem, thank you for your answer.


Perl Question with UserAgent Get Website on Loop

Question: I'm able to grab the first image fine, but then the content seems to be looping inside itself. Not sure what I'm doing wrong.
#!/usr/bin/perl
use LWP::Simple;
use LWP::UserAgent;
my $ua = LWP::UserAgent->new;
for(my $id=1;$id<55;$id++)
{
    my $response = $ua->get("http://www.gamereplays.org/community/index.php?act=medals&CODE=showmedal&MDSID=" . $id );
    my $content = $response->content;
        for(my $id2=1;$id2<10;$id2++)
        {
                $content =~ //;
                $url = "http://www.gamereplays.org/community/style_medals/" . $1 . $id2 . ".gif";
  print "--\n\r";
  print "ID: ".$id."\n\r";
  print "ID2: ".$id2."\n\r";
  print "URL: ".$url."\n\r";
  print "1: ".$1."\n\r";
  print "--\n\r";
  getstore($url, $1 . $id2 . ".gif");
        }
}

Comment: I don't completely understand your question. Does it get stuck in an infinite loop? Also I don't think you need to use LWP::Simple and LWP::UserAgent. You just need LWP::Simple
Comment: Here is an example of the output: http://pastebin.com/WMy5wYWM - I meant to say that it seems to be using the same content in a sense like content+=content
Answer: The problem comes in your regular expression. (.*) is greedy, in which it will match all characters between style_medals/ and $id2.gif. When $id2 is 1, this is fine, but when $id2 is 2, it'll match everything up until 2.gif, which includes the full string from 1.gif.
Try making (.*) non-greedy by adding the ? non-greedy modifier: (.*?). This should fix your problem.
Edit: Ideally you wouldn't be using a regular expression to parse HTML, instead using something like, say, HTML::Parser.
Comment: I looked into Greed and Ungreedy matching and I see what you mean. However, I still have the same issue. Do I need to fine tune the RegEx?
Comment: Realistically you should rewrite your code to use an HTML parser instead, then loop through each of the images your parser says it finds.
Answer: As others have stated, this is really a job for an HTML::Parser.  Also, you should 'use strict;' and remove use LWP::Simple as you're not using the library.
You could change your regex to the following:
$content =~ m{http://www\.gamereplays\.org/community/style_medals/([\w\_]+)$id2\.gif}s;

But you won't get style_medals/comp_graphics_10.gif - which may be what you want.  I think something like the following would work better.  My apologies for the style changes but I can't resist modifying for PBP.
#!/usr/bin/perl

use LWP::UserAgent;
use Carp;
use strict;

my $ua = LWP::UserAgent->new();

# Fetch pages from 1 to 55.  Are we sure we won't have page 56?
# Perhaps consider running until a 404 is found.
for (my $id = 1; $id < 55; $id++) {

    # Get the page data
    my $response = $ua->get( 'http://www.gamereplays.org/community/index.php?ac\
t=medals&CODE=showmedal&MDSID='.$id );

    # Check for failure and abort
    if (!defined $response || !$response->is_success) {
        croak 'Request failed! '.$response->status_line();
    }

    my $content = $response->content();

    # Run this loop each time we find the url
  CONTENT_LOOP:
    while ($content =~ s{<img src="(http://www\.gamereplays\.org/community/styl\
e_medals/([^\"]+))" }{}ms) {

        my $url   = $1;  # The entire url, no need to recreate the domain
        my $file  = $2;  # Just the file name portion
        my ($id2) = $file =~ m{ _(\d+)\.gif \Z}xms; # extract id2 for debug

        next CONTENT_LOOP if !defined $id2;         # Handle SOTW.gif file(s)

        # Display stats about each id found
        print "--\n";
        print "ID:  $id\n";
        print "ID2: $id2\n";
        print "URL: $url\n";
        print "1:   $file\n";
        print "--\n";

        # You might want to consider involving the $id in the filename as
        # you could have the same filename on multiple pages
        getstore( $url, $file);
    }
}

Answer: I won't push on the HTML parsing module (though LinkExtor can be your friend here...) as I understand the problems that can come with HTML parsers: If the HTML isn't properly valid, they often choke, where a simple regex can do the trick on anything no matter how broken as long as you're looking for the right thing.
As has been stated above by CanSpice, (.*) is greedy. The non-greedy modifier will usually do what you want. However, another option is to let it be greedy, but make sure it doesn't grab anything past the quoted src attribute of the image tag:
/]*>/

Note: I also modified it to not care if there's an alt attribute. However, I'm not familiar with the site you're grabbing things from.
If it's generated code it should be fine unless they change something on a grand scale. But to avoid that contingency, even not using a proper HTML parser, you may want to write a mini-parser just for the image tags yourself -- extract the image tags into the keys of a hash (grab them with a regex like /<\s*(img\s+[^>])\s>/) and then for each key in the hash (using a hash avoids dupes), then read everything inside quotes into separate storage and replace the quoted values to remove any whitespace inside quotes, then split it into attributes on whitespace (with element 0 being the tagname, and the rest being attributes which you split into values on the =, getting back the values you just stored a moment ago (or treat as something like '0E0' when they don't have a value--thus keeping them true but effectively valueless)
If it's handwritten code, however, you may be up against some nightmares because many people aren't consistent with their use of quotes on attributes, if they use them at all.
Comment: BTW: mheckman: You do know that [\w\_] is redundant don't you? \w means the same thing. "\w matches a word character (alphanumeric or _), not just [0-9a-zA-Z_] but also digits and characters from non-roman scripts"


Is $\frac{\sin x}{x}$ undefined at $x=0$?

Question: I have read that any function (correction: expression) divided by zero is undefined, so is $\frac{\sin x}{x}$ undefined at $x=0$?
Out of curiosity, I entered $\frac{\sin x}{x}$ into Wolfram Alpha, and the plot does not show any sign of being undefined at $x=0$.
Comment: The function has a removable singularity. If we add the point $(0,1)$ , it becomes a smooth function. But it is not defined at $x=0$ since division by zero is forbidden. The singularity is however not visible unless we make a circle around the point $(0,1)$ which is the common way to indicate such a case.
Comment: @WilliamBarnes That's what "removable singularity" means.
Comment: A funny thing about the "singularity" here: writing out $\sin x$ as a Taylor series allows the factor of $1/x$ to cancel out, and there is no longer a singularity.
Answer: A function and an expression are two different things. A function has a domain (and codomain), and for each element of its domain assigns a value from its codomain.
For some functions, this assignment may be denoted by an expression, for all or some of its domain.
As such, "$\frac{\sin x}{x}$" isn't a function. It's an expression. On the other hand,

The function with the real numbers as domain and codomain, given by $x\mapsto\frac{\sin x}x$.

is almost a function. Phrased this way, it is undefined at $x=0$, even though that's an element of the domain, and this makes it not a function. There are two common ways to mend this and make the above into a bona fide function. One is

The function with the real numbers except $0$ as domain and the real numbers as codomain, given by $x\mapsto\frac{\sin x}x$.

The other is

The function with the real numbers as domain and codomain, given by $x\mapsto\frac{\sin x}x$ for $x\neq 0$, and $0\mapsto 1$.

There is no way to just look at "$\frac{\sin x}x$" and know which one of these (or something different) is intended.
Comment: I don't quite agree to say that $x=0$ is in the domain. I'd rather say that the domain is $\mathbb R\setminus\{0\}$, and that $\dfrac{\sin x}x$ is a *partial function* over $\mathbb R$.
Comment: @Joe Does my answer not address this exact concern in quite some detail?
Comment: Does it even make sense to consider $\sin(x)/x$ if $x\in\mathbb{R}$, rather than $x\in\mathbb{R} \setminus \{0\}$? I feel uncomfortable saying that $x=0$ could be part of the domain of $\sin(x)/x$, even if we are not talking about functions per se.
Comment: I think the term domain should be reserved for functions, and since a function is a set of ordered pairs of elements, $f(x)=\sin(x)/x$ can only be well-defined if from from the outset we state that $x \neq 0$. But I'm curious to hear your view on the matter.
Comment: @YvesDaoust I am pretty certain that this is explicitly addressed in my answer.
Comment: It's possible that you just phrased it in a way that was liable to confusion. So, are you saying that $x \mapsto \sin(x)$ for $x \in \mathbb{R}$ is in a sense 'almost' a well-defined function, but actually the domain has to be restricted further to $\mathbb{R} \setminus \{0\}$?
Comment: @Joe That's what "is almost a function" is meant to signify. But yes, it might've been a bit unclear.
Comment: That makes sense. I think it was the bit where you said 'even though that's an element of domain' which was confusing, since we were essentially talking about a pseudo-function. It would have made more sense to me if you had written 'but $0$ shouldn't be in the domain of $\sin(x)/x$, so in order to make the function well-defined, we have to stipulate that $x \neq 0$'. But it's fine now that you have clarified your comments.
Answer: Confusingingly, people often talk about the behaviour of this function as $x$ approaches $0$ (but is not equal to it). This can be easily be confused with evaluating $\sin(0)/0$, which is non-sensical. However, we can say that
$$
\lim_{x \to 0}\frac{\sin(x)}{x}=1 \, .
$$
Roughly speaking, the above expression means 'as $x$ gets closer and closer to $0$, $\sin(x)/x$ gets closer and closer to $1$'. It does not mean that if $x=0$, then $\sin(x)/x=1$.
Answer: A function is defined on a domain. Since we are (implicitly) considering functions from the real line with values in the real line, you cannot divide by zero, hence the domain of the function is $\mathbb{R} - \{0\}$.
Plotting the function, you probably see that the limit of $\frac{sin(x)}{x}$ is well defined for $x \rightarrow 0$, since limits are defined in a neighborhood of a point that does not contain the point itself (as you explain in your nice blog :) )
Answer: Wolfram Alpha explicitly says that the domain (in the reals) is
$$\{x\in\mathbb R:x\ne 0\}.$$
Don't trust a plot blindly.
Answer: It has a limit but not a value.  That is, we can all see where the graph is going.  The value of the function will be infinitely close to 1 as $x$ gets infinitely close to 0.  This means that it is generally okay to use 1 as the value for $\frac{\sin(0)}{0}$ but it is technically non-existent precisely at the number 0.  In nearly all applications, it will work just fine.
As @Peter noted in the comments, this discontinuity is so small that it won't show up on graphs unless the graphing software is written to explicitly make it obvious to you.