Existem técnicas para reduzir o uso de memória (por parte do desenvolvimento) quanto ao uso do javascript?

Question: Eu gostaria de saber se existe alguma técnica para reduzir o uso de memória quanto ao uso do javascript. Digo, quanto ao desenvolvimento.
Notei que uma determinada página que estamos desenvolvendo onde trabalho parece utilizar muita memória, e isso é sinalizado no google chrome como sendo maior parte desse consumo vindo do javascript.
Como poderia solucionar isso?
Comment: Wallace, levando em conta o seu histórico, vou dizer algo que acredito que já esta fazendo: tente diminuir o numero de consultas aos elementos da pagina, reduza o numero de funções em memoria, você pode alcançar isto declarando os mesmos no inicio do escopo.
Comment: Não saberia por onde começar esta resposta. Mas certamente o problema ocorre porque está mantendo objetos demais ativos por mais tempo do que realmente é necessário.
Comment: @bigown, por exemplo, a minha aplicação carrega posts sob demana (inifinite scroll). Parece que a cada "rolada" de mouse, a memória só vai aumentando absurdamente quanto ao consumo
Comment: Primeiro, quando você carrega muita coisa, é normal que o consumo vai aumentando. Não existe milagre. Mas certamente tem jeitos certos de fazer isto para não haver desperdício e maneiras em que duplica ou multiplica dados sem necessidade. Aí já começamos entrar em situações específicas.
Comment: Tente usar mais javascript puro(não sei se é seu caso de estar usando muito jQuery) para operações mais simples, como loops por ex. De uma atenção à como você cria eventos a grande grupos de elementos ou como você manipula estes elementos, esse tipo de coisa.
Answer: Isso é um problema de arquitetura. O que eu faria é fazer uma nova etapa de levantamento de requisitos. Pode ser que há eventos aonde há desperdício de funções, objetos, etc. Tente fazer requisições via GET para aplicação receber somente as funções que necessita. Tome cuidado ao fazer uso de carregamento em JSON.
Tomando cuidados mais simples do que parece, não vai sobrecarregar o hardware na hora da aplicação.


Wedge product of a 2-form

Question: Given the 1-form, $$\alpha = dz - pdx - qdy,$$ I can calculate $$d\alpha = -dp\wedge dx - dq \wedge dy = dx \wedge dp + dy \wedge dq, $$ but I'm not so sure how to calculate $d\alpha \wedge d\alpha$.
Could someone please point me in the right direction?
Comment: Distribute: $d\alpha \wedge d\alpha = dx \wedge dp \wedge dx \wedge xp + dx \wedge dp \wedge dy \wedge dq + dy \wedge dq \wedge dx \wedge dp + dy \wedge dq \wedge dy \wedge dq$. Two of these terms are zero. The other two can be combined.
Comment: Oh wow. That's very simple. Thank you.
Answer: $$\begin{split}
d\alpha\wedge d\alpha &=(dx\wedge dp+dy\wedge dq)\wedge (dx\wedge dp+dy\wedge dq)\\
&=dx\wedge dp\wedge dy\wedge dq+dy\wedge dq\wedge dx\wedge dp\\
&=2dx\wedge dp\wedge dy\wedge dq
\end{split}$$
Use the fact that $\alpha\wedge \beta=(-1)^{\text{degree}(\alpha)\text{degree}(\beta)}\beta\wedge \alpha$ if $\beta$ and alpha are homogeneous.

Wedge product of a 2-form


DHCP not working through long bridged network

Question: I have setup a hotspot at my local harbor. I have encountered a problem with my setup. The accespoint that creates the hotspot connection is a out door long range antenna from UBNT. The distance from the nearest router, to the optimal position of the antenna is 1km. And it's not in straight open air :/
I have managed to get it to work with AirMax from UBNT. My setup looks like this:

192.168.1.1 - My Router
192.168.1.30 - My first AirMax antenna (in bridge mode). Creates a network called CARRIERONE
192.168.1.31 - A wireless station, that connects to CARRIERONE.
192.168.1.40 - My second AirMax Antenna (Bridge mode from point 3). Creates CARRIERTWO.
192.168.1.41 - A wireless station, that connects to CARRIERTWO.
192.168.1.50 - My access point that creates the hotspot (Bridge mode. Network from point 5)

This works like a charm, except that computers connected to the hotspot don't get dynamic IP's. The users have to assign static IP's.
I have tried the same setup, with only two links (Though with extremely poor link quality bc of buildings blocking the sight), and then the clients get assigned dynamical IP's.
I have managed to do a workaround by setting the access point up as a router. But we have plans to extend the network, and would really like to have everything in bridge mode.
Why does this work when we use 3 links, and not when we use 5 links? The setup is EXACTLY the same, except from the IP.
Is this a normal problem? Do I need special equipment, or is it maybe the router that is incapable of managing IP's when there are too many bridges?
Answer: If I remember correctly, the default number of routers a normal DHCP request/response (at least for Windows Server) can pass through is 4.
If your routers are behaving correctly, each time a DHCP request comes through, it is increasing the hop count by one. Once that hop count is larger than the maximum (4), it is thrown away, because it's expected that there will be a DHCP server somewhere within 4 hops from the server. It also stops the DHCP hops from flooding the network for longer than they need to.
This is why 3 works, and 5 does not.
Comment: @MarkHenderson, it's called DCHP relaying.
Comment: Cool :) Just the kind of answer I was looking for :)
Do you know if there is a way to get the request to live more than 4 hops?
Comment: @hogni89 - I honestly don't know. It might be a part of the TCP/IP spec, in which case no, but it might also depend on your DHCP server. I've never run into that issue before, so I've never had to work around it.
Comment: @Mark Henderson, since DHCP is broadcast it's not supposed to pass any router at all.
Comment: @poige - most routers have a dhcp forwarder in them. Additionally the unusual network setup of this installation using access points (which I am going to guess are also routers) probably are doing the same


Stuck with Fourier transform

Question: I'm trying to solve a simple mass-dashpot-spring system
$$m\ddot{u}(t) + c\dot{u}(t) + ku(t) = F(t)$$
by making use of the Fourier transform defined as
$$\tilde{f}(s) = \int_{-\infty}^{\infty} f(t) \, \mathrm{e}^{-\mathrm{i} (2 \pi s) t} \mathrm{d}t$$
such that the ODE transforms into
$$-(2 \pi s)^2 m \tilde{u}(s) + \mathrm{i} (2 \pi s) c \tilde{u}(s) + k \tilde{u}(s) = \tilde{F}(s)$$
to eventually solve
$$\tilde{u}(s) = \frac{\tilde{F}(s)}{-(2 \pi s)^2 m + \mathrm{i} (2 \pi s) c + k}$$
Say I have the forcing
$$F(t) = \left\lbrace\matrix{\cos(t) & 0 \leq t < \pi/2 \\ 0 & \text{otherwise}}\right. \quad \rightarrow \quad \tilde{F}(s) = \frac{\mathrm{e}^{-\mathrm{i} \pi^2 s} + \mathrm{i} (2 \pi s)}{1-(2\pi s)^2}$$
accept the initial conditions
$$u(0)=0, \; \dot{u}|_{t=0} = 0$$
and have the parameters
$$m=1.3, \; c=0.6, \; k=1.7$$
Now, I want to transform it back to the time domain using the discrete Fourier transform. I think the basic idea is to compute solutions $\tilde{u}$ for several values of $s$ like this. If I plot the vector containing the complex valued solutions this results in (red - real, green - imaginary)

Then when using Maple's InverseFourierTransform function on the resulting vector I obtain rubbish:

What am I doing wrong here?
Comment: Just a guess (as I do not know Maple), but perhaps there is some shifting of the data going on in Maple.  Something tells me, though, that is not the entire story, but at least it is a start.
Comment: Why are you using a *discrete* Fourier transform? Is this meant to be an approximation?
Comment: Yes, I'm actually trying to solve a FEM system, so this is just a simplified problem to get started... I know this can be done perfectly by hand though.
Comment: The plot does look like a decaying wave. Maybe it simply does not resolve in the graph (i.e., the number of points is too low?)
Comment: @rlgordonma: You are right, after swapping the left and right parts of the vector all is well. I suggest you turn your comment into an answer so I can accept it.
Comment: @demorge: done, and thanks.
Answer: Many times in programs like Maple, the Fourier transform routines shift the data so that what you would expect to be the center frequency is actually at the beginning of the array.  In this case, you need to shift the data by half a cycle in the array to recover your expected behavior.

Stuck with Fourier transform


NSMenuItem with action added to NSStatusBar is grayed out when the selected function is moved to other class

Question: If the function that is being called as the NSMenuItem action isn't located in AppDelegate the menu entry is grayed out.
I can't seem to figure out what exactly seems to go wrong... Maybe I'm initialising the StatusBarItemController wrong? As soon as I move the printToTheWalls to the AppDelegate class it starts to work.
import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
    var statusBarItemController: StatusBarItemController?
    let statusBarItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength)

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Insert code here to initialize your application
        statusBarItemController = StatusBarItemController()
        if let button = statusBarItem.button {
            button.image = NSImage(named: NSImage.Name("trayIcon"))
        }
        statusBarItemController?.constructMenu(with: statusBarItem)
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        // Insert code here to tear down your application
    }

}

import Cocoa

class StatusBarItemController {

    func constructMenu(with statusBarItem: NSStatusItem) {
        let menu = NSMenu()
        menu.addItem(NSMenuItem(
            title: "From the windows...",
            action: #selector(printToTheWalls(_:)),
            keyEquivalent: ""
        ))
        menu.addItem(NSMenuItem.separator())
        menu.addItem(NSMenuItem(
            title: "Quit",
            action: #selector(NSApplication.terminate(_:)),
            keyEquivalent: "q"
        ))

        statusBarItem.menu = menu
    }

    @objc func printToTheWalls(_ sender: NSMenuItem) {
        //This doesn't seem to be called and/or found
        print("To the Walls!")
    }
}

Comment: It doesn't have to be in the AppDelegate - as vadian has already commented, set the NSMenuItem's target to whatever class has the delegate method.
Comment: What is the benefit of this extra class? You have to set the `target` of the action accordingly.
Comment: You'll need to make StatusBarItemController derive from NSObject, I think. Otherwise it cannot be introspected for validation of menu items.
Comment: @vadian It's purely for organising my code
Comment: @matt I changed `class StatusBarItemController` to `class StatusBarItemController: NSObject` but this doesn't change the behaviour
Comment: Well perhaps you should put the code back where it was. Menu item validation is a complicated business and relies upon your code being in certain places.
Comment: @matt I'm ready to accept that this code can only reside in the AppDelegate file but I would really like to know why it **has** to be there
Comment: I think I've told you my theory twice already. Might want to read https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/MenuList/Articles/EnablingMenuItems.html
Comment: @matt Thanks for the interesting link. Sadly it doesn't help me solve my problem or answer my question as the why it has to be in the AppDelegate file to work at all.
Comment: Well I think it's because of how the responder chain is constructed.
Comment: @red_menace Thanks your comment made me understand vadian 's comment fully and this worked (set it to 'self'). If you would like to type out an answer I would love to mark it as the solution.
Answer: The solution was to manually set the target property to self as @vadian and @red_menace helped me discover in the comments of the question.
The working code looks like this:
import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
    var statusBarItemController: StatusBarItemController?

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Insert code here to initialize your application
        statusBarItemController = StatusBarItemController()
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        // Insert code here to tear down your application
    }

}

import Cocoa

class StatusBarItemController: NSObject {
    let statusBarItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength)

    override init() {
        super.init()
        if let button = statusBarItem.button {
            button.image = NSImage(named: NSImage.Name("trayIcon"))
        }
        constructMenu()
    }

    func constructMenu() {
        if let button = statusBarItem.button {
            button.image = NSImage(named: NSImage.Name("trayIcon"))
        }
        let menu = NSMenu()

        let fromTheWindowsItem = NSMenuItem(
            title: "From the windows...",
            action: #selector(StatusBarItemController.printToTheWalls(_:)),
            keyEquivalent: ""
        )
        fromTheWindowsItem.target = self
        menu.addItem(fromTheWindowsItem)
        menu.addItem(NSMenuItem.separator())
        menu.addItem(NSMenuItem(
            title: "Quit",
            action: #selector(NSApplication.terminate(_:)),
            keyEquivalent: "q"
        ))

        statusBarItem.menu = menu
    }

    @objc func printToTheWalls(_ sender: NSMenuItem) {
        print("To the Walls!")
    }
}

Comment: Any idea why the target didn't need setting in `AppDelegate`?
Comment: I had to set the target for the individual NSMenuItems to the entity that will handle the action. In this case StatusBarItemController


Complex Analysis: Infinite Products problem

Question: I am currently trying to solve #3 here (taken from Lang's Complex Analysis):

I am not seeking the answer, I just have a few questions:

Since $\alpha_n = 1 - \frac{1}{n^2}$, $|\alpha_n|$ is redundant, and I can simplify $\frac{|\alpha_n|}{\alpha_n}$ to be 1, correct?
What does $\overline{\alpha}_n$ mean? I thought it might be complex conjugate, but $\alpha_n$ is not complex.
Why do we need to know that $0<x<1$?
Comment: It is unfortunate that in the quoted problem (3), one has $\alpha_1 = 0$ which is forbidden by hypothesis in problem (2). One does have that the other $\alpha_n$ are positive real numbers, so yes, that fraction is $1$, and also each $\alpha_n$ is equal to its complex conjugate (being real). This problem is just a special case of the preceding problem. The problem is just focusing on particular values, so in this case he is considering only small positive real values of $z$ (they are still in the disk, so no greater than $1$).
Answer: To your first question, you're correct, since $\alpha_n$ is always real in this case, you can simplify $\frac {|\alpha_n|}{\alpha_n}$ to one
To your second question, you're also correct that $\bar {\alpha_n}$ denotes the complex conjugate, since $\alpha_n$ is real, the complex conjugate of $\alpha_n$ is just $\alpha_n$
To your third question, $0<x<1$ is important because it restricts the domain to values of $x$ where $f$ is defined


What is the rhythmic displacement I hear in the verse of Thriller?

Question: I have long struggled to articulate why I always feel a sense of rhythmic surprise and unease when the verse of Thriller breaks in over the bassline vamp, roughly [0:50 - 1:06] in the song.
If you asked me to transcribe how I hear it in my head, I would write something like:
<code>(pickup)      |Bar 1         |2                              |3       |4
              C♯m7                                                    F♯7
It's close to mid-night, and something evil's lurking in the dark.
</code>
No matter how many times I've heard the song, my brain wants to hear "It's close to mid-" as a pickup to bar 1 of the verse, and it expects the i chord (C#m) to land square on the first beat of that bar 1. (and I am not the only one, many chord sites feature some version of the above!).
Of course, what actually happens is this:
<code>(pickup)          |Bar 1         |2                              |3     |4
F♯7                              C♯m7                                     F♯7
    It's close to mid-night, and something evil's lurking in the dark.
</code>
The change to the F♯7 actually comes on the pickup measure before Bar 1, and the i chord doesn't appear until bar 2. In other words, the harmonic rhythm isn't aligning with the beginning and end of the melodic phrase, as you would expect.
When the F♯7 comes back around, harmonically I now want to hear that bar as Bar 1 of the next phrase because of the chord change, but my ear is still hearing the melody in that bar as a pickup to the following bar:
<code>|Bar 1              |2            |3                                 |4
 F♯7                              C♯m7
          Under the moonlight you see a sight that almost stops your heart
</code>
I think what is going on is a tension between the harmonic rhythm and the melodic phrase length. It's like the harmonic and melodic phrases have been displaced by one bar, causing me to perceive the verse as having some kind of uneven phrase length.
I am curious though if someone has a more precise analysis of what is going on here. In any case it is a wonderful effect that still succeeds in subverting my expectations even after who knows how many listens.
Comment: Can't listen to the song right now, but... if I recall correctly, the melody note on "mid" of _midnight_ is an E, right? I think that's quite relevant for the explanation.
Comment: @leftaroundabout You recall correctly.
Answer: I've always heard "Thriller"'s verse like this:
(intro bass vamp) ... F♯7 chord lands squarely on the first beat of bar one of the cycle, and counting eighth notes, we hear: 1 + 2 + 3 "It's close to...".
Alternatively, it's easy to remember that the bass riff B-C♯-E-F♯-C♯ lines up squarely on the eighth notes:
1 +  2 +  3 + 4 +
B C♯ E F♯ C♯

Notice where the beat lands in relation to the lyrics (vocal line in blue) and bass vamp (in bass clef).
And counting from there, the "and" of the first bar is when Jackson's lyrics enter. This is true of every single verse of the song.
You also correctly noticed that each chord takes a full two bars. The F♯7 chord is the first two bars, and the C♯m7 chord is the last two bars of each phrase. Because of this, the lyrics actually aren't in a pickup measure, but are in fact staring half a bar late compared to the chords!
In my opinion, there's nothing specific about the song that was written to subvert the listener's expectations in terms of rhythm. I think that somehow, you've misidentified the beat of the piece, and because of this, you feel the shock of syncopation. This is normal, it happens to everyone every once in a while, so don't worry.
I'd be interested to see where you feel the start of each bar during the chorus. The piece is written in straight 4/4 time, and the downbeat during the chorus lands on the syllable "Thrill-". The chord changes in the song align with the downbeat (except for the synth riff in the chorus, but in general).
Comment: You are right: if you analyze the song in terms of 4-bar sections, the bar that I've identified as the pickup is really the first bar of the verse, and both the start of the bass vamp and the start of the chorus supports this analysis. I think the combination of the melody entering on the and-of-three, plus the fact that the harmony changes from i to IV is making my brain want to hear that bar as a pickup. The IV has a cadential function here and I keep wanting to hear it as a kind of turnaround into the verse. But, as you note, thats not what's actually happening. Thanks for your response!
Answer: Basically, you 'learned' it the wrong way & every time you hear it again without preparation, you fail to correct it until that key moment.
The word 'midnight' is on the first beat of bar two of the section, not one. Count it right from the top if you have to.
A late thought on this is that it's relatively rare for a 'good' song to 'follow the chords'. They do tend to lead them, any pickup will be to the downbeat of bar one of the section. "That's how the pros do it". Starting the melody in the middle of bar one & then 'running along after the chords' is often considered a rookie mistake.
Thriller, of course, puts paid to that argument, but it could be part of why you're hearing it a bar out.
Different people have different issues with different songs. It's just one of those things.
Personally, Kings of Leon's Sex on Fire, Sparks' This Town Ain't Big Enough for the Both of Us & Hendrix's All along the Watchtower have similar 'timing changes'.
If I'm concentrating right from the start I can turn them over. If I'm not, then I'm out of sync until my personal turnaround point.
For me, if it's a beat change rather then being a whole bar out, I stripe the track in a DAW, add a click count, then slide one against the other until it's a) correct & b) gives me a 4-count in. That way, I can quite quickly get my head out of its bad timing habit & learn to recognise it properly.
Another one, came to me late - Arctic Monkeys - When the Sun Goes Down. As it transitions into the 'fast bit' it appears to cycle the new main riff 5 times. If you're concentrating it makes sense as the first is the last turnaround of the old section, then there are 4 with the whole band. If you're not concentrating… there are a surprising 5 to wait through.
Answer: As I already commented, I think the reason you're mislead is melodic rather than rhythmic. Simplified it is this:
<code>X:1
L:1/8
M:C
K:C#m
%%score T1
V:T1           clef=treble
% 1
[V:T1] z5 c cd | e4 c2 z1 c | cb, cb, cb, ce | c4 r4
</code>
Crucially, the first note of bar 2 is an E. Now, that is contained in F♯7, but not in F♯ per se. Thus is has a bit of a non-chord-tone character, which may be surprising for a note on the 1 beat. OTOH, ordinary c♯m does contain an E, as well as of course the C♯ that's next, so inferring the harmony from the melody one could easily expect it to switch to c♯m at that point.


How to pass parameters to a partial view

Question: I have this view
@model IEnumerable<Helpdesk.Infrastructure.Tools.IdNameSurname>

            Show timesheet for user

                <select class="form-control">
                    <option value="" disabled selected>Select user...</option>
                    @Url.Action("Timesheet", "Administrator")
                    @foreach (var users in Model)
                    {
                        <option value="@users.Id">@users.Name @users.Surname</option>
                    }
                </select>

        @{
            Html.RenderPartial("PartialTimesheet", new { userId = ??? });
        }

How I can assign my select option value to my RenderPartial view?
Comment: You cant. `Html.RenderPartial` is generated on the server before its sent to the client. If you want to respond to client side events, you need javascript and ajax to call a controller method that returns a partial view
Answer: Basically, you can't do it. The reason is: Razor syntax is a server side code, it will turn into HTML before returning to the client.
So, the correct way to do this is using javascript. Here are the steps:

Prepare your controller. It must return a PartialView.
In your javascript code, get the value of dropdownlist.
Make an Ajax call to your PartialView controller to get the appropriate view.
Display the view.

For the code, you can look here. It's for radio button, but for dropdownlist is the same.
Comment: ok, my partial view will be writed on angularjs, but how I can get the value of my dropdownlist?
Comment: Use this: `$('#dropDownId :selected').text();`. Here is the [link](http://stackoverflow.com/questions/2780566/get-selected-value-of-a-dropdowns-item-using-jquery) to the answer.


Servers unexpectedly change to BDC on AD?

Question: I've got two AD virtual machines runnning on HyperV. AD1(PDC) syncs its time with pool.ntp.org and AD2(BDC) syncs with AD1 to get the time correct. Both are windows server 2008 servers.
This worked fine for a while, but lately servers seem to drop out from AD1 and authenticate with AD2 instead, even though AD1 is up and running.
I've tried to shut down AD2 and restart all servers on the domain to force them to authenticate to AD1 which works fine. But whenever I put AD2 on the network again servers will still auth to AD2 on reboot.
This behavior is unknown to me and I'm having a hard time troubleshooting the issue.
Comment: What exactly are you considering as a problem?
Comment: *I'm having a hard time troubleshooting the issue.* - I'm not surprised. There's no 'issue' to troubleshoot. This is expected behaviour. You might as well troubleshoot why water is wet.
Answer:
This doesn't have anything to do with time synchronization. Your time sync configuration appears to be correct from what you've stated in your question. The DC that holds the PDCe role should sync with a reliable external time source. All other domain members should sync with the domain hierarchy. This includes all other Domain Controllers.
Stop calling them PDC and BDC. That terminology is no longer valid and is a hint that you're not exactly up to snuff in your understanding of AD. AD uses a Multiple-Master model (referred to as Flexible Single Master Operations or FSMO), which you can read about at this link. - https://support.microsoft.com/en-us/kb/197132
Your domain clients are behaving exactly as expected. An AD domain client can authenticate to any available Domain Controller. You should neither try to control that behavior nor discourage it. The fact that you see this as a problem that needs to be solved is another clue that you really don't have a good understanding of AD. It might serve you to do some in depth reading on the subject.
Answer: if AD2 is suitable as a good time source, i don't think there's a need to change the topology.
if AD2 has itself incorrect time and is therefore not a good choice, i would recommend to ensure that AD2 has the correct time (which in replication solves incorrect times on clients).
we saw something related at one of our customers (where one DC had in fact incorrect time).
it seems that the timeservice on ad2 is still announcing as authorative.
you may set the timeserver on ad2 so that it's no longer considered as reliable timeserver.
http://blogs.msdn.com/b/w32time/archive/2008/05/29/to-be-reliable-or-not-to-be-reliable.aspx
otherwise you may use GPOs to assign the timeserver explicitly - as i personally would still prefer the first choice


Show that $P(A\cap B) \geq 1-P(A^{c})-P(B^{c})$.

Question: So far I have:
$$P(A\cap B)  = 1-P((A\cap B)^{c})    $$   (complement axiom)
                                 $$= \[1-P(A^{c}\cup B^{c})\]$$  (DeMorgan's)
                                       =...
I'm not sure what to do after this ;(
Comment: As a mathjax suggestion, I applaud you for trying to typeset it.  It is more common to use `\cup` and `\cap` than `\bigcup` and `\bigcap` for the intersection of just two sets.  You normally see `\bigcup` and `\bigcap` for iterated union/intersection as in $\bigcup\limits_{k=1}^n A_k$ similarly to how $\sum$ is used.  [More mathjax tips here](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).
Comment: **Hint:** Inclusion-exclusion rearranged a bit tells us that $P(A\cap B)=P(A)+P(B)-P(A\cup B)$
Comment: Note that the statement you have to prove is equivalent to $$P(A)-P(B^c)-P(A\cap B)=P(A)+P(B)-P(A\cap B)-1=P(A\cup B)-1\leq 0$$
Answer: Note that for any event $C$, $P[C]\le 1$. So $P[A\cup B]\le 1\iff -P[A\cup B]\ge -1$. Call this inequality $(a)$. Note that $P[A\cup B]=P[A]+P[B]-P[A\cap B]\implies P[A\cap B]=P[A]+P[B]-P[A\cup B]$. Using $(a)$ in here, what do you get?
Answer: Hint: Use $1-P(A^c)-P(B^c) = P(A) + P(B) - 1$
Answer: Rearrange the inequality in the following way
$$ P(A \cap B) \geq P(A) + P(B) - 1 $$
And thus
$$ 1 \geq P(A) + P(B) - P(A \cap B) $$
which implies
$$ 1 \geq P(A \cup B) $$
which is true always


Database and Models present still programming error is coming in DJango

Question: I am trying to get the models data on the browser using the urls.py and views.py for last 3 days and failing miserably, although I am able to get the database in a json file but not on browser. This is the error log [http://dpaste.com/2DQZX1Z][1] and the code is here
models.py
from __future__ import unicode_literals

from django.db import models

class Authors(models.Model):
    aid = models.AutoField(primary_key=True)
    aname = models.CharField(max_length=200, blank=True, null=True)
    adescription = models.CharField(max_length=8000, blank=True, null=True)

class Books(models.Model):
    bid = models.IntegerField(primary_key=True)
    bname = models.CharField(max_length=200, blank=True, null=True)
    bdescription = models.CharField(max_length=8000, blank=True, null=True)

class Bookauth(models.Model):
    bid = models.ForeignKey(Books, models.DO_NOTHING, db_column='bid', blank=True, null=True)
    aid = models.ForeignKey(Authors, models.DO_NOTHING, db_column='aid', blank=True, null=True)

views.py
from __future__ import unicode_literals

from django.shortcuts import render
import requests
from django.http import HttpResponse
from django.db import models
from .models import Books

import json
from django.core import serializers

def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")

def getObject(request):
    all_books = Books.objects.all()
    html = serializers.serialize('json', all_books)
    return HttpResponse(html)
    #data = serializers.serialize("json", Books.objects.all())
    #return HttpResponse(data, mimetype='application/json')

urls.py
from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^non', views.index, name = 'index'),
    url(r'^auth', views.author_search, name = 'AuthSearch'),
    url(r'^book', views.getObject, name = 'Books')
]

Comment: What happens when you ran manage.py migrate?
Comment: @DanielRoseman the error was with my my database too like I have changed the feilds in the models but not in MySql db  but now its working!
Answer: change your models to this and then makemigrations then migrate and then check in the browser
from __future__ import unicode_literals

from django.db import models

class Authors(models.Model):
    aid = models.AutoField(primary_key=True)
    aname = models.CharField(max_length=200, blank=True, null=True)
    adescription = models.TextField( blank=True, null=True)

class Books(models.Model):
    bid = models.IntegerField(primary_key=True)
    bname = models.CharField(max_length=200, blank=True, null=True)
    bdescription = models.TextField(blank=True, null=True)

class Bookauth(models.Model):
    bid = models.ForeignKey(Books, on_delete=models.DO_NOTHING, db_column='bid', blank=True, null=True)
    aid = models.ForeignKey(Authors, on_delete=models.DO_NOTHING, db_column='aid', blank=True, null=True)

Comment: well you were providing 8000 characters for CharField which is not justfied, it can hold 255 characters, thus i changed it to TextField which can contain a large number of charaters, and you missed on_delete key before the models.DO_NOTHING
Comment: can you please tell me what you changed?


como replicar funções do jquery em javascript $(), hide()

Question: To criando um site, simples em javascript mais gostaria de automatizar a seleção elementos, e uma função pra esconder/mostrar os elementos. Mais acabo recebendo erro. Mais não entendi o porque.
Pra selecionar os elementos eu to usando
function $(par){
    return document.querySelector(par)
}

e para esconder:
function hide(e){
    return e.style.display = 'none';
}

a declaração fica:
$('.header').hide()

só que me é retornado o erro:
Uncaught TypeError: $(...).hide is not a function

Comment: Está parecendo que vc não está chamando o jquery na sua página. Lógico, vc deve chamar antes de chamar o seu script js.
Comment: Ah ideia e refazer essas duas funcitons do jquery em javascript puro
Answer: Para replicar as funções do Jquery você pode usar o prototype, por exemplo para fazer a função hide ficaria dessa forma:
Element.prototype.hide = function(){
   this.style.display = "none";
   return this;
}

Com isso você basicamente esta incluindo o metodo hide() dentro da classe Element.
Mais sobre prototypes: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype
Comment: Brigado, funcionou! Vou pesquisar agora sobre prototype. Pra entender como funciona.


iOS Accessibility Voiceover Reads Out Unnecessary Content in Web

Question: My iPhone application is built using Cordova and it for the most part native and I am having an issue with Accessibility. During my accessibility testing I noticed that when Voice Over is selected on some elements it reads out more than just the text of the label or button. For instance here is what a pages header looks like in my HTML:

<%= title %>

When H1 is selected the following is read out to the user:
Banner Title Heading Level 1 Landmark
Is there any way to restrict it to only speak out the title content?
Answer: Looks like you are using jQuery Mobile. jQuery mobile adds some markup to the elements based on where you have placed them and the attributes applied. In this case it is placing role="banner" on the div with the data-role="header".
The way that is being read out is fine. If you are in fact using the header as a header, then the screen reader user now has that useful piece of information. If they do not want it, they can tell their screen reader to suppress it. Think of it as the audio equivalent of the fact that the header is visually distinct from the rest of the page.


Characterisation isomorphisms of ringed spaces: $(f,f^\flat)$ iso iff $(f,f^\sharp)$ iso?

Question: So I was trying to understand isomorphisms of ringed spaces, looking for a characterization of them. I'll explain what I've found out already and what I don't know yet. Before, I will set some notations and state the pushforward-pullback adjunction of sheaves along a continuous function.
If $X$ is a space and $\mathsf{C}$ is some category, we denote by $\mathsf{Sh}_\mathsf{C}(X)$ the category of $\mathsf{C}$-sheaves over $X$. In the following, we suppose $\mathsf{C}$ is cocomplete (i.e., it admits all colimits. But we may just assume $\mathsf{C}=\mathsf{Set}$ and consider only sheaves of sets, if that makes us more comfortable).
Let $Y$ be another space. If $f:X\to Y$ is a continuous map, there are functors
$$f_*:\mathsf{Sh}_\mathsf{C}X\rightleftarrows\mathsf{Sh}_\mathsf{C}Y:f^*,$$
where $f_*$ (resp., $f^*$) is called the pushforward (resp., the pullback) along $f$ (see for example the section on continuous maps and sheaves of Stacks Project for reference. There on SP they actually denote $f^*$ as $f^{-1}$. In order for $f^*$ to exist, we need cocompleteness for $\mathsf{C}$).
There is an adjunction
$$
\mathsf{Sh}_{\mathsf{C}}(X)(f^{*}\mathcal{G},\mathcal{F})\cong\mathsf{Sh}_{\mathsf{C}}(Y)(\mathcal{G}, f_*\mathcal{F}),\tag{1}\label{eq:adj}
$$
where $\mathcal{F}\in\mathsf{Sh}_\mathsf{C}X$ and $\mathcal{G}\in\mathsf{Sh}_\mathsf{C}Y$ (for a reference, see the link above, specially Lemma 6.21.6 and comments between lemmas 6.21.4 and 6.21.5).
Characterization of isomorphisms of ringed spaces: Recall that a morphism of ringed spaces $(X,\mathcal{O}_X)\to(Y,\mathcal{O}_Y)$ can be specified in two ways: either in the form $(f,\psi^{\flat})$ or $(f,\psi^\sharp)$, where $\psi^\flat$ and $\psi^\sharp$ are adjunct. We say that $(f,\psi^{\flat})$ is an isomorphism if there exists $(g,\varphi^{\flat}):(Y,\mathcal{O}_Y)\to(X,\mathcal{O}_X)$ such that $(g,\varphi^\flat)\circ(f,\psi^\flat)=1_{(X,\mathcal{O}_X)}$ and $(f,\psi^\flat)\circ(g,\varphi^\flat)=1_{(Y,\mathcal{O}_Y)}$ (see this question to understand how to compose morphisms of ringed spaces). In a similar fashion, it is possible to define what it means for $(f,\psi^\sharp)$ to be an isomorphism. I am interested in showing the proving result:

Proposition. Let $(f,\psi^\flat)$ or $(f,\psi^\sharp):(X,\mathcal{O}_X)\to(Y,\mathcal{O}_Y)$ be a morphism of ringed spaces. The following are equivalent:

$(f,\psi^\flat)$ is an isomorphism.
$f$ is a homeomorphism and $\psi^\flat$ is an isomorphism of sheaves.
$(f,\psi^\sharp)$ is an isomorphism.
$f$ is a homeomorphism and $\psi^\sharp$ is an isomorphism of sheaves.

Furthermore, in the case these equivalent statements hold, we have
$$
(f,\psi^\flat)^{-1}=(f^{-1},(f^{-1})_*[(\psi^\flat)^{-1}])\\
(f,\psi^\sharp)^{-1}=(f^{-1},(f^{-1})^*[(\psi^\sharp)^{-1}]),
$$
where $g_*$ denote the pushforward and $g^*$ the pullback of sheaves along the continuous function $g$ (which is a functor between some sheaves categories).

The implication $(1\Rightarrow 2)$ should be clear. For a proof of $(2\Rightarrow 1)$, see for example this answer. Equivalence $(3\Leftrightarrow 4)$ can also be proven by an analogous argument (for $(4\Rightarrow 3)$, one must also note that, from the definition of the pullback of sheaves, if $f$ is a homeomorphism then we have $f^*\mathcal{O}(U)=\mathcal{O}_Y(f(U))$, for $U\subset X$ open). On the other hand, the proofs of the formulas of the inverses of $(f,\psi^\flat)$ and $(f,\psi^\sharp)$ are an immediate computation using the fact that an inverse is unique, and the facts that $h_*$ and $h^*$ are functors and that the assignments $h\mapsto h_*$ and $h\mapsto h^*$ are functorial.
But I was having trouble showing ([$1$ or $2$] $\Leftrightarrow$ [$3$ or $4$]). Does anyone know how to prove this?
Answer: If $f$ is a homeomorphism, the adjunction $(1)$ can be made explicit.
Let $\varphi^\flat:\mathcal{G}\to f_*\mathcal{F}\in\mathsf{Sh}_\mathsf{C}(Y)$ be a morphism of sheaves over $Y$, where $\mathcal{F}\in\mathsf{Sh}_\mathsf{C}X$ and $\mathcal{G}\in\mathsf{Sh}_\mathsf{C}Y$. Call $\varphi^\sharp:f^*\mathcal{G}\to\mathcal{F}$ to the adjoint of $\varphi^\flat$ under the adjunction $(1)$. Then, if $f$ is a homeomorphism, these two are explicitly related by
$$\tag{2}\label{eq}
\varphi^\flat=f_*\varphi^\sharp.
$$
A proof of \eqref{eq} can be given by

relating $\varphi^\flat$ with $\varphi^\sharp$ using the proof of Lemma 6.21.8, where they make the adjunction $(1)$ explicit.
using that $f_*f^*=1_{\mathsf{Sh}_\mathsf{C}(Y)}$. Why is this true? Well, first we have $f^*\mathcal{G}(U)=\mathcal{G}(f(U))$, for $U\subset X$ open, since $f$ is a homeomorphism. In other words, we have $f^*\mathcal{G}=(f^{-1})_*\mathcal{G}$, where $f^{-1}$ is the inverse function of $f$. Since this works for arbitrary $\mathcal{G}$, this implies
$$\tag{3}\label{eq:3}
f^*=(f^{-1})_*.
$$
Also, the assignment $g\mapsto g_*$ is functorial. That is, the pushforward defines the action on morphisms of a functor $\mathsf{Sh}_\mathsf{C}(-):\mathsf{Top}\to\mathsf{CAT}$, where $\mathsf{CAT}$ is the category of locally small categories. It then follows from \eqref{eq:3} that $f^*f_*=1_{\mathsf{Sh}_\mathsf{C}(X)}$ and $f_*f^*=1_{\mathsf{Sh}_\mathsf{C}(Y)}$.

The equation \eqref{eq} can be used to prove equivalence $(2\Leftrightarrow 4)$ from the proposition. Observe that $f$ being a homeomorphism (i.e., a topological space isomorphism) implies that $f_*:\mathsf{Sh}_\mathsf{Ring}(X)\to\mathsf{Sh}_\mathsf{Ring}(Y)$ is a category isomorphism (from the functoriality of the assignment $g\mapsto g_*$). Thus, by \eqref{eq}, $f$ and $\varphi^\sharp$ are isos iff $f$ and $\varphi^\flat$ are isos.
Note that this argument does not use any particularity of the category $\mathsf{Ring}$ and it works for an arbitrary cocomplete category $\mathsf{C}$. The proposition is still true if stated for the "category of $\mathsf{C}$-sheafed spaces." This category has as objects pairs $(X,\mathcal{F})$, where $X$ is a space and $\mathcal{F}\in\mathsf{Sh}_\mathsf{C}(X)$ is a $\mathsf{C}$-sheaf on $X$, and a morphism $(X,\mathcal{F})\to(Y,\mathcal{G})$ and composition of morphisms are defined just on the same fashion as in the case $\mathsf{C}=\mathsf{Ring}$. In particular, the category of $\mathsf{Ring}$-sheafed spaces coincides with the already familiar category of ringed spaces. The category of $\mathsf{C}$-sheafed spaces is addressed on EGA 0, 3.5.2., although there they do not give it a name.
Answer: Here is an easier answer. When I wrote the other answer I was a newbie in category theory and algebraic geometry.
The fact that [$1$ or $2$] $\Leftrightarrow$ [$3$ or $4$] follows from functoriality. We can consider a first type (resp., second type) category of sheafed spaces in which morphisms are given in the form $(f,\psi^\flat)$ (resp., in the form $(f,\psi^\sharp)$) and then define an isomorphism of categories from the first type to the second type by sending $(f,\psi^\flat)$ to $(f,\psi^\sharp)$. The fact that this assignment is indeed functorial is explained here.


Split-half reliability on binary scores

Question: I'm very new at statistics, so excuse me if my questions are to simple or obvious.
I have a dataset with response times for two conditions. These response times were converted into a binary score of either 0 (absence of the effect) or 1 (presence of the effect).
The experiment is designed in 7 blocks. For each block participants receive a 1 or 0. The total score for each subject can range from o to 7.
So, I want to do a split-half reliability to see if the criteria I used to evaluate the presence of the effect is a reliable indicator of what I'm studying.
At first I just split the column of 1s and 0s in half and correlated it, but that give me a nonsense value (something like 0.0009) so I'm missing something here. Conceptually I know I should correlate two parts of the test that are supposedly measuring the same thing, but I'm having difficulties at figuring out exactly how to do this for this dataset.
Any help is much appreciated.
Answer: You need to split the test in half, i.e. in a group of 3 and a group of 4 items and then correlate those groups. So as if you have 2 tests both consisting of half the total test.
Comment: Thanks for your answer simmons.
This seems a bit counter intuitive for me. Are you saying I would be correlating all scores obtained from block 1 to 3, on the one hand, and blocks 4 to 7 on the other?
I would think the scores would naturally change as blocks go by, so even if the test is reliable I wouldn't expect results from the earlier blocks to be correlated with the results of the last blocks.
Comment: The idea is that the test measures 1 dimension. So if you split it in half and correlate the them you get a measure of the consistency of the test, which gives you information if it really measures one thing.
Edit: what do you mean with 'blocks go by'? Also you should randomly assign items into groups. Furthermore, you were asking for split-half reliability, which is exactly what I explained. If you want to do something else, please elaborate on what your goals are.
Comment: Thanks simmons. Split-half reliability is indeed what I intended to do.
My data corresponds to a motor learning task, where learning is measured by decreases in response time.
I think what I have been doing wrong is that I was just splitting my data.frame in two halves and then correlating the two vectors of 1s and 0s... If you say I have to assign what goes into each half randomly, then I think I'm missing something.
The relevant parts of my data.frame for this problem is one column with subjects and one with the 1 or 0 scores, and one column for block. How would you recommend to proceed?
Comment: I am still not 100% sure what your experiment is, but I think I understand your data. You have for every subject 7 entries specifying subject id, score, and block id. The blocks are added together to get a compound measure, i.e. test score. What you called blocks, I called item.

Now randomly assign items to groups and calculate the score for each subject and in both groups. You should now have three vectors: subject id, group1 and group2 score. Each subject id should occur only once! Then you correlate the score of group 1 with the score of group 2.
Comment: Thanks for your clarifying answer simmons. Given my n is 219, I should have a column with 219 rows, one for each subject. What I don't understand is what goes in the other two columns. Suppose I were to assign to one half blocks 1,3,5 and to the other half blocks 2,4,6 and 7. Then in my first set of rows I would have subject one, the score he got on block 1 and the score he got on block 2. In the second row I would have subject 2, the score he got in block 3 and the score of block 4. In the third row subject 3 and the score he got in block 5 and then on block 6, etc. Is that it?
Comment: If I understand correctly,if I have only one row per subject and two columns (besides the column for subjects) then I can have only two scores per subject, meaning that for each subject I'm not using 2/7 of the data I actually have for that subject. Is that ok?
Comment: No, you should have per subject a row containing id, the sum score of the group1 and the sum score of group2. So you are creating two tests from one and are correlating.
Comment: I understand. In one group I have the sum of 3 or 4 values taken at random from the 7 blocks. In group 2 I have the sum of the remaining values for that subject. I correlate both for every subject.
Many thanks for the help.
Answer: It really sounds like you want to do cross-validation.  I am assuming you use the data to construct the criterion.  A way to do this that is a type of cross validation would be to randomly split the data into tow groups ( could be an equal split but you may want a larger sample for the fitting of the criterion).  Construct the criterion on the first set and then test how it does.
Comment: Thanks for your suggestion Michael, but right now I'm trying to replicate some results, so I need to perform a split-half reliability test, even though there might be better ways to test the reliability.
Comment: I don't know what that is or why it is approapriate.

Split-half reliability on binary scores


Drive to fail in 24 hours - Possible Hard Drive Failure Soon

Question: Here's what the smartctls is saying.  How accurate is the 24 hours failure?  Any successful fixes to the Reallocated_Sector_Ct fail?
<code>Here's what I got from running the attributes command:
== START OF READ SMART DATA SECTION ===
SMART Attributes Data Structure revision number: 10
Vendor Specific SMART Attributes with Thresholds:
ID# ATTRIBUTE_NAME          FLAG     VALUE WORST THRESH TYPE      UPDATED  WHEN_FAILED RAW_VALUE
  1 Raw_Read_Error_Rate     0x000f   076   063   044    Pre-fail  Always       -       46668818
  3 Spin_Up_Time            0x0003   095   094   000    Pre-fail  Always       -       0
  4 Start_Stop_Count        0x0032   100   100   020    Old_age   Always       -       53
  5 Reallocated_Sector_Ct   0x0033   022   022   036    Pre-fail  Always   FAILING_NOW 3214
  7 Seek_Error_Rate         0x000f   089   060   030    Pre-fail  Always       -       10217282021
  9 Power_On_Hours          0x0032   061   061   000    Old_age   Always       -       34447
 10 Spin_Retry_Count        0x0013   100   100   097    Pre-fail  Always       -       0
 12 Power_Cycle_Count       0x0032   100   100   020    Old_age   Always       -       52
184 End-to-End_Error        0x0032   100   100   099    Old_age   Always       -       0
187 Reported_Uncorrect      0x0032   100   100   000    Old_age   Always       -       0
188 Command_Timeout         0x0032   100   099   000    Old_age   Always       -       14
189 High_Fly_Writes         0x003a   100   100   000    Old_age   Always       -       0
190 Airflow_Temperature_Cel 0x0022   063   059   045    Old_age   Always       -       37 (Min/Max 30/41)
191 G-Sense_Error_Rate      0x0032   100   100   000    Old_age   Always       -       0
192 Power-Off_Retract_Count 0x0032   100   100   000    Old_age   Always       -       48
193 Load_Cycle_Count        0x0032   100   100   000    Old_age   Always       -       53
194 Temperature_Celsius     0x0022   037   041   000    Old_age   Always       -       37 (0 20 0 0 0)
195 Hardware_ECC_Recovered  0x001a   112   099   000    Old_age   Always       -       46668818
197 Current_Pending_Sector  0x0012   100   100   000    Old_age   Always       -       0
198 Offline_Uncorrectable   0x0010   100   100   000    Old_age   Offline      -       0
199 UDMA_CRC_Error_Count    0x003e   200   200   000    Old_age   Always       -       0
</code>
Comment: What does it matter how accurate it is? Replace the disk.
Answer: Your disk has probably been dying for quite some time. Maybe you'll get 48 hours. Maybe a week or a month. Maybe it'll die before I finish typing this out.
This error means that your drive is developing bad sectors, and the disk is running out of spare sectors to replace them with. This is eligible for warranty replacement if the disk is still in warranty.
In any case, as soon as the drive does run out of spare sectors, (when 022 reaches 000) you will start silently losing data. The time to replace it is before that happens.
Comment: In addition to that, I suggest to immediately stop using the faulty disk completely. Next time you start it must be for copying of data to the replacement media.
Comment: Michael - thanks - I was wondering what the numbers meant.  So when spare sectors hits 36 - that's the threshold for the warning?  We're still at 22.  This is a server drive.  I've been trying to get my server guys to set up a new server and migrate the data over.  I would love to stop using it right away.  Hopefully I'll get this rolling today.  I have sites backed up - but if there's a complete fail then we may have a gap in data - like email.  Was hoping to migrate then rsync it.
Comment: @larry888 Yes, the threshold (36 of 100) is when FAILING_NOW appears and you get an alarm. The drive is actually considered bad and can be RMA'd as soon as even _one_ reallocated sector (raw value) appears.


Where is the information in the node_info hook displayed in drupal

Question: I am beginning with drupal. I cannot see where the information which I write in the hook node_info displayed in drupal. What is the link to check it?
Comment: version D7 or D6?
Answer: You should see it on the add content page. If you don't, either you need to clear cache, the module isn't enabled, or the module is coded incorrectly.


jquery webcam plugin picture

Question: i am trying to use the jquery webcam plugin and i believe i have placed every thing right but still i have a problem .
thought the #webcam div is working fine and show frames from the cam but on clicking capture no image is taken
i get the following error on the chrome console :
Uncaught TypeError: Object # has no method 'capture'
there are similar questions here but none seems to solve my problem
i have placed the callbacks too .
jQuery("#webcam").webcam({

    width: 320,
height: 240,
mode: "callback",
swffile: "../jcam/jscam_canvas_only.swf",

onTick: function(remain) {
},

onSave: function(data) {...
    }
},
onCapture: function () {....
},

debug: function (type, string) {
},
onLoad: function () {.......
    }
}
});

Answer: Try this
$(function(){
jQuery("#webcam").webcam({

    width: 320,

    height: 240,

    mode: "callback",

    swffile: "../jcam/jscam_canvas_only.swf",

    onTick: function(remain) {
    },

    onSave: function(data) {...
        }
    },
    onCapture: function () {....
    },

    debug: function (type, string) {
    },
    onLoad: function () {.......
        }
    }
});

});

jquery webcam plugin picture


BIND 9.16 dnssec-policy default is not automatically renewing keys

Question: Three months ago I upgraded my DNS servers to BIND 9.16 (currently running 9.16.25) to take advantage of the new dnssec-policy default option which would allow me to easily run DNSSEC for my domains.  Documentation indicated that key management would happen automatically.  I implemented this, tested locally, looked like everything was getting signed just fine, and all seemed right with the world.  I had not previously implemented DNSSEC in any form for these zones.
I later learned that I should have uploaded my DS records to my registrar to report to the TLD that my zones were signed and that would complete the circuit to allow DNSSEC to actually happen... so I started doing that this month.  However, doing so, things started failing, and I quickly learned that all my signatures had expired 15 days after I implemented DNSSEC.
I tried doing a manual rollover of the keys for one zone.  That changed the sigs for some of the records, but not all (no A, AAAA, CNAME records, for example).  I looked in the docs for details of how dnssec-policy default is implemented, and found that the keys are set to not expire, but that the signatures are set to expire after 15 days or so... and that if the keys don't expire, no rollover will ever be scheduled.  So what am I supposed to do about the expired sigs?
Does the dnssec-policy default really work as advertised and I'm missing something crucial, or should I really be rolling my own here?
Relevant settings in named.conf.options:
options {
[..]
        dnssec-validation auto;
        dnssec-policy default;
        dnssec-dnskey-kskonly yes;
        managed-keys-directory "/var/lib/bind";
[..]
};

Comment: "I later learned that I should have uploaded my DS records to my registrar to report to the TLD that my zones were signed" Yes otherwise there is no DNSSEC chain of trust so the fact that your zone is signed is pretty much irrelevant. This is kind of core of DNSSEC design, I recommend you make sure to fully understand this before going further (you mention not having done DNSSEC before there). As for "that all my signatures had expired 15 days after I implemented DNSSEC." this may be the case but is separate from the fact of sending the DS to the registry through registrar.
Comment: Thanks Patrick.  The problem I ran into was that once I did upload my DS records, everything broke because the signatures had expired.  I need to fix the signature expiration before I can upload the DS records in order to keep things from breaking when I do.  Do you have any insight on how I can do that?
Comment: Did you look at your bind log files? Zones signatures and key updates should be logged? This can help: https://gitlab.isc.org/isc-projects/bind9/-/wikis/DNSSEC-Key-and-Signing-Policy-(KASP) (it is about changes in 9.17 and if you can you should switch to it). See https://bind9.readthedocs.io/en/v9_16_26/dnssec-guide.html: "The dnssec-policy statement causes the zone to be signed and turns on automatic maintenance for the zone. This includes re-signing the zone as signatures expire and replacing keys on a periodic basis. "
Comment: I did indeed.  I found the same documentation that you quoted, and that's exactly why I upgraded to Bind 9.16 to begin with (I mentioned that in the post).  The logs show "reconfiguring zone keys" for each zone once an hour.  Nonetheless, the signatures expired without them being renewed.  The dnssec log shows the initial configuration, and then nothing except repeated reconfiguration entries despite the expirations.
Comment: Increase log level and double check all files/directories permissions. Do note also that 9.17 should be even simpler regarding DNSSEC than 9.16. I recommend you just try calmly from scratch with a toy zone and experiment. At this stage with the elements given I have no idea why things do not work for you. This: "I tried doing a manual rollover of the keys for one zone." is concerning. You either have to let bind do everything for you or you do everything manually but mixing the too might be a recipe for problems.
Comment: "The logs show "reconfiguring zone keys" for each zone once an hour." I don't think this should be the expected case. keys do not have to change so often. KSK are like for a year, ZSK for a few weeks. What can change more often is signatures. If bind is talking about keys so often there may be a problem there.
Comment: "There may be a problem there."  RIGHT!  That's why I'm asking the question.  :)  I've only got it using `dnssec-policy default` with no other configuration.  It's using CSK instead of KSK/ZSK.  I cannot use 9.17 because I'm using this on Ubuntu 20 which only appears to support 9.16 at the moment.
Answer: See example in https://bind9.readthedocs.io/en/v9_16_26/dnssec-guide.html
that says:

Enabling Automated DNSSEC Zone Maintenance and Key Generation
To sign a zone, add the following statement to its zone clause in the
BIND 9 configuration file:
options {
    directory "/etc/bind";
    recursion no;
    ...
};

zone "example.com" in {
    ...
    dnssec-policy default;
    ...
};

The dnssec-policy statement causes the zone to be signed and turns on
automatic maintenance for the zone. This includes re-signing the zone
as signatures expire and replacing keys on a periodic basis. The value
default selects the default policy, which contains values suitable for
most situations.

Not that dnssec-policy can be in a zone statement, or in options but then it applies everywhere. Specially at the beginning, to test things, you might want to restrict things per zone.
But other than that, it should work out of the box with that configuration.
If not the case for you, you need to give more details based on your logfiles.
Later in the same page you can have a look at the expected log lines with the above configuration:
07-Apr-2020 16:02:55.045 zone example.com/IN (signed): reconfiguring zone keys
07-Apr-2020 16:02:55.045 reloading configuration succeeded
07-Apr-2020 16:02:55.046 keymgr: DNSKEY example.com/ECDSAP256SHA256/10376 (CSK) created for policy default
07-Apr-2020 16:02:55.046 Fetching example.com/ECDSAP256SHA256/10376 (CSK) from key repository.
07-Apr-2020 16:02:55.046 DNSKEY example.com/ECDSAP256SHA256/10376 (CSK) is now published
07-Apr-2020 16:02:55.046 DNSKEY example.com/ECDSAP256SHA256/10376 (CSK) is now active
07-Apr-2020 16:02:55.048 zone example.com/IN (signed): next key event: 07-Apr-2020 18:07:55.045

See the signed on last line and the timestamp given when something (probably new signatures) will happen.
As for:

I need to fix the signature expiration before I can upload the DS records in order to keep things from breaking when I do.

Even without problems, NEVER upload a DS without having checked locally the validation works end to end. You can do it with an online tool like DNSViz, specifying explicitly the new DS that you are about to add, and the tool will test things as if the DS is ok already.
Note that normally the KSK (of which the DS record is an hash basically) is supposed to change "regularly" to the tune of once yearly to each 2 years or things like that. At which point you need to rotate the DS as well, but with cautions if you don't want to break resolution.
Comment: _Config_: I put the `dnssec-policy` line in my options statement intentionally because I wanted it to apply to all zones.
_Logfiles_: my /var/log/named/dnssec log has the entries you describe except that it never says "(signed)" after any zone entry, and the "next key event" is always 60 minutes hence.  When the 60 minutes is up, I get an entry: `zone example.com/IN: reconfiguring zone keys` and immediately after that another `next key event` entry.  Nothing ever gets reconfigured.  There are no errors present in the logs related to this process.


Need help understanding harmonic series and intervals

Question: So I need some clarification as this is confusing me terribly. What are the first 12 harmonic series of a fundamental (Lets say A (440hz)?
Do those harmonic series of the fundamental pertain to every note in an equal temperament scale? Such as if we use A as the fundamental, do the notes B,C,D,E,F,G exist in the harmonic series of A?
Could you explain to me in a simplified manner, how we take a fundamentals harmonic series and turn them into intervals? How does that process work exactly?
Answer:
What are the first 12 harmonic series of a fundamental (Lets say A (440hz)?

You probably mean (as other answers indicate) the first 12 harmonics of A. I list the frequencies and the pitch name according to the western music scale in scientific notation.

1st: A4 (440Hz)
2nd: A5 (880Hz)
3rd: E6 (1320Hz)
4th: A6 (1760Hz)
5th: C#7 (2200Hz)
6th: E7 (2640Hz)
7th: (none) (3080Hz), this is between F#7 and G7
8th: A7 (3520Hz)
9th: B7 (3960Hz)
10th: C#8 (4400Hz)
11th: (none) (4840Hz), this is between D8 and D#8
12th: E8 (5280Hz)

Do those harmonic series of the fundamental pertain to every note in an equal temperament scale?

You can calculate the harmonic series of every fundamental frequency. But you do not obtain all 12 pitches of the equal temperament scale from the series. In fact, you do not obtain any pitch from the equal temperament except for the different octaves of A exactly, because the ratio between different pitches is irrational (as it is powers of the twelth root of 2), but the harmonic series produces rational ratios. The harmonics listed above coincide with just tuning based on A. The frequencies of the named pitches are different in equal temperament tuning, but they are quite close.

Such as if we use A as the fundamental, do the notes B,C,D,E,F,G exist in the harmonic series of A?

As you see, the harmonic series only has A, B, C# and E (and some frequencies that sound out-of-tune for the western ear). You can obtain further frequencies that can sound in-tune with A by dividing instead of multiplying by integers. In that case you are not looking for frequencies that are in the harmonic series of A, but frequencies that contain A in their own harmonic series:

The 3rd harmonic of D3 is A4
The 5th harmonic of F2 is A4
The 9th harmonic of G1 is A4

Still, this does not provide all pitches from the A major scale (F# and G# missing) or from the A minor scale (C natural missing).

and last question, could you explain to me in a simplified manner, how we take a fundamentals harmonic series and turn them into intervals? How does that process work exactly?

Intervals are frequency ratios. In all western scales, we treat pitches with a ratio of 2 (or a power of two) as "nearly identical", and call a ratio of two an "octave". The exact value of the other intervals depends on the tuning you use. If you base the tuning on harmonics, the intervals will be simple fractions, whereas if you use equal temperament, the intervals are powers of the twelth root of two. The names from the intervals are counting how many steps in a typical western scale they cover, so you first need to settle down on a scale before you can understand the names of the intervals. Yet you can identify frequency ratios you expect to appear in the scale. As western scales contain 7 pitches (within each octave), and interval names are counting the number of steps they take in the scale, with one indicating the first note, i.e. no step, the first interval, with a ratio of 2, is called the octave. If you continue to look into the series, you discover the following ratios that are of use:

Ratio 3: A4 to E6. If you step down 1 octave, it's 3/2 for A4 to E5. The (perfect) fifth.
Ratio 5: A4 to C#7. If you step down 2 octaves, it's 5/4 for A4 to C#5. The major third.
Ratio 9: A4 to B7. If you step down 3 octaves, it's 9/8 for A4 to B4. The major second.

You can step down another octave (i.e. divide by 2), so the intervals are no longer going up, but going down:

The perfect fifth upwards, A4 to E5 gets the perfect fourth downwards, A4 to E4 with a ratio of 3/4, so the pure fourth upwards from E4 to A4 has a ratio of 4/3.
The major third upwards, A4 to C#5 gets the minor sixth downwards, A4 to C#4 with a ratio of 5/8, so the minor sixth upwards has a ratio of 8/5.
The major second upwards, A4 to B4 gets the minor seventh downwards, A4 to B3, with a ratio of 9/16, so the major seventh upwards has a ratio of 16/9.

Note that I did not include any interval based on the 7th harmonic. This ommision is not inherent to how the harmonic series works, but this interval just isn't used in western music and does not appear (even approximately) in the equal temperament scale. This does not mean there are no other scales that do include that interval.
In the end, you need to be aware the just intonation you obtain from the harmonic series and the equal-temperament scale are different. In just intonation, not every major second is equal. We defined that A4-to-B4 is 9/8, and A4-to-C#5 is 5/4. This makes B4-to-C#5 to be 5/4 divided by 9/8, which is 10/9. We call both A4-to-B4 and B4-to-C#5 a "major second", but they turn out a different ratios! Equal temperament is designed as an approximation of the just intonation (which actually sounds more pure in the key it is base on) where the ratio of neighbouring pitches is always exactly the same, so in equal temperament, A4-to-B4 and B4-to-C#5 in fact has the same ratio, which is neither 9/8 nor 10/9, but something inbetween.
Comment: "The frequencies I listed above are from just tuning": I would say that the *pitch names* you listed are from just tuning, since the frequencies are the harmonics, and those just come from physics.  That is, the 3rd harmonic of 440 Hz is 1320 Hz, no matter what.  But whether 1320 Hz is the note E depends on your temperament or tuning system; in equal temperament E is 1318.51 Hz.  Also, it is a myth that just intonation allows one to tune a keyboard that sounds good in one key.  Even to sound good in one key, the keyboard must be tempered.
Comment: The ones you listed as "none", I might explain which two notes they're in-between. +1
Comment: @phoog I understand your concern. What I meant to say was that 1320Hz is the frequency of E6 in (5-limit or 3-limit) just tuning based on A440, whilst in equal temperament on A440 the frequency of E6 is *not* the frequency I listed. I check how I can rework that sentence to be more clear on that.
Comment: Thanks for the suggestion. I intentionally didn't list the pitches, because all the pitches I did list could be *defined* from the harmonic series. The 7th and 11th harmonic do not define any pitch of the western scale in any common tuning. I still added the pitches that are in-between as a coarse guide. To support this distinction, I intentionally left it being "none" in the list, but added the "hint" at the end of the rows.
Answer:
What are the first 12 harmonic series of a fundamental (Lets say A (440hz)?

I assume you mean the first 12 harmonics in the harmonic series.
The theoretical 'perfect' harmonic series is simply the multiples of 440 - 440, 880, 1320... and so on. 12 * 440 is 5280. (For fuller detail, please see Michael Karcher's excellent answer!)
In real life, the few instruments actually have overtones following a perfect harmonic series - partly though design, as it sounds very boring and flat.

Do those harmonic series of the fundamental pertain to every note in an equal temperament scale?

The overtone structure of a note determines what the timbre of the sound is. Different notes played on the same instruments often have slightly different overtone structures. In most cases, they will have a strong correlation with the theoretical 'perfect' harmonic series, but this depends on all sorts of factors (such as how the instrument is played).

Such as if we use A as the fundamental, do the notes B,C,D,E,F,G exist in the harmonic series of A?

They do, but in some cases at frequencies much higher than the fundamental. In a note played by a real instrument, those overtones might be entirely absent, or very quiet. On the other hand, there might be lots of overtones present in the sound of a note that don't relate directly to the frequencies of other notes in the scale. The harmonic series effectively goes on forever and will contain frequencies relating to so many notes that it would be hard to make a discrete-pitched instrument (such as a piano, or fretted guitar) that could play them all.

Could you explain to me in a simplified manner, how we take a fundamentals harmonic series and turn them into intervals?

It sounds like you've got the impression that musical scales and intervals are derived in a direct way from the harmonic series, but that isn't really the case. It is true that the important notes in some scales correlate with the frequencies of what are often strong overtones, but other harmonics will be present that don't correlate with notes in the scale.
So, how are scales formed?
Generally, I would say that they're formed to allow both satisfying consonances, and interesting dissonances, to occur between the notes in the scale.
Very simply speaking,

Consonances occur when the harmonics of the notes coincide (have the same, or similar frequencies). If enough of the harmonics coincide, the ear may hear two or more notes 'blending' together.
Dissonances occur when the harmonics of the notes don't coincide - although they are strongest when the differences between strong harmonics are still within a critical bandwidth, such that beat frequencies occur.

So it is a question of harmonics / overtones, and it is related to the harmonic series. it's just not quite as simple as finding the notes in the harmonic series and using those notes, because:

We want to allow consonances between pairs or groups of notes that don't include the tonic note. The 7th note in the major scale, for example, is very dissonant with the tonic, but very consonant with the fifth. It's these relationships between notes other than the tonic that allow interesting harmonic motions in the music to occur.
We want to allow dissonances, as well as consonances, to create tension and resolution with the music
What consonances and dissonances occur is partly a question of what instrument is playing them; What consonances and dissonances are satisfying is somewhat subjective, and a question of musical culture.

Thinking of it from another angle: The harmonic series is the same in every country in the world. But as Albrecht points out in his answer, different musical cultures have come up with many different scales from which music can be made! Thinking of it this way will provide further evidence that scales aren't directly derived from the harmonic series.
Comment: Understood. So how then are scales formed from a physics standpoint? I was under the impression that scales were created from the harmonic series but you don't believe thats the case? My goal here basically is to understand the source of scale creation.
Comment: @Seery many people ascribe to this theory that the scale is derived from the harmonic series, but that is a huge overstatement.  If you're taking a theory class, though, the teacher might want you to learn this theory.  Just be aware that it really doesn't explain everything.  For example, if you're building a C-major scale, F is not in the harmonic series of C; rather, C is in the harmonic series of F.
Answer: I hope by this answer your next question will be enlightened too.
A scale or (sound) scale in the music is a series of the pitch of ordered notes, bounded by frame tones beyond which the tone row is usually repeatable.
In most cases, a scale has the circumference of one octave and in many cases follows a heptatonic tone scale construction. How a scale is built up is determined in the sound system.
The most common European and non-European scales are based on five or seven notes within the octave, which are called tone levels. Widely used are diatonic scales in major and minor or the church modes. Scales are defined by pitches. The tones contained in the concrete scale are called conductor-specific tones.
In non-European music such as classical Arabic or Indian music, there are sound systems and scales that divide the sound space differently. So there are scales that contain more than seven fixed tone levels, such as Mugam, Maqam or Raga.
https://en.wikipedia.org/wiki/Scale_(music)


Java (Android) - Equações Matemáticas

Question: eu preciso de uma pequena ajuda.
Pra ir direto ao assunto, eu estava a tentar criar um pequeno sistema de equações que me permitissem obter um conjunto de números com umas pequenas particularidades. Basicamente o que eu pretendia, depois de pressionar um botão, era criar quatro números aleatórios (de 1 a 9) que, juntos e submetidos a certas equações matemáticas, o resultado final fosse por exemplo 22. Imaginem: 8, 2, 5, 1, são quatro números aleatórios que permitem esta equação "(8*2)+5+1=22".
Sei como criar os quatros números aleatórios e passa-los para TextView's:
Random a = new Random();
int i1 = a.nextInt(10 - 1) + 1;
TextView tv = (TextView) findViewById(R.id.textView1);
Random b = new Random();
int i2 = b.nextInt(10 - 1)+1;
TextView tv2 = (TextView) findViewById(R.id.textView2);
Random c = new Random();
int i3 = c.nextInt(10 - 1)+1;
TextView tv3 = (TextView) findViewById(R.id.textView3);
Random d = new Random();
int i4 = d.nextInt(10 - 1)+1;
TextView tv4 = (TextView) findViewById(R.id.textView4);

Aqui estão as várias equações:
    int soma = i1 + i2 + i3 + i4;
    int mult0 = i1 * i2 * i3 * i4;
    int mult1 = (i1*i2*i3)+i4;
    int mult2 = (i1*i2)+i3+i4;
    int mult3 = i1 * (i2 + i3 + i4);
    int mult4 = i2 * (i1+i3+i4);
    int mult5 = i3 * (i1+i2+i4);
    int mult6 = i4 * (i1+i2+i3);
    int mult7 = (i1*i3)+i2+i4;
    int mult8 = (i1*i4)+i2+i3;
    int mult9 = (i2*i3)+i1+i4;
    int mult10 = (i2*i4)+i1+i3;
    int mult11 = (i4*i3)+i1+i2;
    int mult12 = (i1*i3*i4)+i2;
    int mult13 = (i1*i2*i4)+i3;
    int mult14 = (i4*i2*i3)+i1;

Mas o próximo passo que é escolher aleatoriamente uma das equações e conseguir que o conjunto de números aleatórios i1, i2, i3, i4, nessa equação seja igual a 22, isso eu não consigo descobrir como fazer.
Eu tenho ainda este código mas não está a fazer o que eu pretendo,(PS: TF = 22):
    if (soma == TF || mult0 == TF || mult1 == TF ||
mult2 == TF || mult3 == TF || mult4 == TF || mult5 == TF ||
mult6 == TF || mult7 == TF || mult8 == TF || mult9 == TF ||
mult10 == TF || mult11 == TF || mult12 == TF || mult13 == TF || mult14 == TF){
        tv.setText(String.valueOf(i1));
        tv2.setText(String.valueOf(i2));
        tv3.setText(String.valueOf(i3));
        tv4.setText(String.valueOf(i4));}

Este código basicamente mostra os quatro números aleatórios que obedecem a uma dessas equações, mas não é de forma automática, é por tentativas(é preciso carregar no botão várias vezes até aparecerem novos números).
Eu pretendia mesmo que sempre que carregasse no botão, os números certos aparecessem automaticamente, logo à primeira tentativa.
Obrigado se me puderem ajudar :)
Answer: Pode fazer uma função que calcule os valores todos e ir chamando até acertar num resultado valido.
Primeiro pode isolar a verificação de quatro números num método à parte:
public boolean verificarNumeros(int i1, int i2, int i3, int i4){

    //construir as equações
    int[] mults = new int[]{ //agora em array para facilitar
    i1 + i2 + i3 + i4,
    i1 * i2 * i3 * i4,
    (i1*i2*i3)+i4,
    (i1*i2)+i3+i4,
    i1 * (i2 + i3 + i4),
    i2 * (i1+i3+i4),
    i3 * (i1+i2+i4),
    i4 * (i1+i2+i3),
    (i1*i3)+i2+i4,
    (i1*i4)+i2+i3,
    (i2*i3)+i1+i4,
    (i2*i4)+i1+i3,
    (i4*i3)+i1+i2,
    (i1*i3*i4)+i2,
    (i1*i2*i4)+i3,
    (i4*i2*i3)+i1
    };

    //e indicar se alguma se verificou
    for (int i=0; i < mults.length; ++i){
         if(mults[i] == TF){
              return true;
         }
    }

    return false;
}

Agora no método principal pode ir chamando este método de verificação até achar uma combinação que funciona:
public void gerarNumeros(){
    boolean combinacaoEncontrada = false;
    Random a = new Random(); //apenas uma instancia de Random
    int i1,i2,i3,i4;

    while (!combinacaoEncontrada){
       i1 = a.nextInt(10 - 1) + 1;
       i2 = a.nextInt(10 - 1) + 1;
       i3 = a.nextInt(10 - 1) + 1;
       i4 = a.nextInt(10 - 1) + 1;
       combinacaoEncontrada = verificarNumeros(i1,i2,i3,i4);
    }

    //mostrar a combinação encontrada
    TextView tv = (TextView) findViewById(R.id.textView1);
    TextView tv2 = (TextView) findViewById(R.id.textView2);
    TextView tv3 = (TextView) findViewById(R.id.textView3);
    TextView tv4 = (TextView) findViewById(R.id.textView4);

    tv.setText(String.valueOf(i1));
    tv2.setText(String.valueOf(i2));
    tv3.setText(String.valueOf(i3));
    tv4.setText(String.valueOf(i4));
}

Recomendações:

Para gerar 4 números de 0 a 8 seria melhor fazer uma permutação entre os números todos possíveis a custa de fors ou recursão pois aleatoriamente podemos processar muitos mais números e potencialmente não chegar a uma solução!
Em android e todas as outras linguagens que tenham interface gráfica, todo o processamento pesado não deve ser feito na thread principal, senão o sistema irá ficar como se não estivesse respondendo e bloqueado até chegar ao resultado. Para contornar este efeito pode usar Thread ou AsyncTask
Comment: Obrigado Isac!! Eu mudei umas coisinhas e consegui chegar ao que queria, tá agr nos comentários
Answer: Muito obrigado Isac!! Mas tive que mudar umas pequenas coisas no teu código.. Dá uma olhada a ver :
@Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); }
int TF = 24;
Random b = new Random(); //apenas uma instancia de Random
int i1 = b.nextInt(10 - 1) + 1;
int i2 = b.nextInt(10 - 1) + 1;
int i3 = b.nextInt(10 - 1) + 1;
int i4 = b.nextInt(10 - 1) + 1;

public boolean verificarNumeros(){

    //construir as equações
    int[] mults = new int[]{ //agora em array para facilitar
            i1 + i2 + i3 + i4,
            i1 * i2 * i3 * i4,
            (i1*i2*i3)+i4,
            (i1*i2)+i3+i4,
            i1 * (i2 + i3 + i4),
            i2 * (i1+i3+i4),
            i3 * (i1+i2+i4),
            i4 * (i1+i2+i3),
            (i1*i3)+i2+i4,
            (i1*i4)+i2+i3,
            (i2*i3)+i1+i4,
            (i2*i4)+i1+i3,
            (i4*i3)+i1+i2,
            (i1*i3*i4)+i2,
            (i1*i2*i4)+i3,
            (i4*i2*i3)+i1
    };

    //e indicar se alguma se verificou
    for (int i=0; i < mults.length; ++i){
        if(mults[i] == TF){
            return true;
        }

        }

    return false;
    }

public void perform_action(View v){

    boolean combinacaoEncontrada = false;
    Random a = new Random(); //apenas uma instancia de Random

    while (!combinacaoEncontrada){
        i1 = a.nextInt(10 - 1) + 1;
        i2 = a.nextInt(10 - 1) + 1;
        i3 = a.nextInt(10 - 1) + 1;
        i4 = a.nextInt(10 - 1) + 1;
        combinacaoEncontrada = verificarNumeros();
    }

    //mostrar a combinação encontrada
    TextView tv = (TextView) findViewById(R.id.textView1);
    TextView tv2 = (TextView) findViewById(R.id.textView2);
    TextView tv3 = (TextView) findViewById(R.id.textView3);
    TextView tv4 = (TextView) findViewById(R.id.textView4);

    tv.setText(String.valueOf(i1));
    tv2.setText(String.valueOf(i2));
    tv3.setText(String.valueOf(i3));
    tv4.setText(String.valueOf(i4));
}

}

Java (Android) - Equações Matemáticas


nginx SSL termination for apache2.2 svn server results in endless redirects

Question: I'm trying to set up a SVN  repository on our new company server.
We are using nginx for SSL termination and apache as SVN backend.
I don't know whats wrong with my configuration, but if I call svn info https://svn.example.com/repo I'm getting:
Redirecting to URL 'https://svn.example.com/repo':
Redirecting to URL 'https://svn.example.com/repo':
svn: E195019: Redirect cycle detected for URL 'https://svn.example.com/repo'

If I use wireshark to sniff the unencrypted traffic from nginx frontend to our apache backend I can see an "Options" request for "/repo" followed by a 301 Moved Permanently redirect to http://svn.example.com/repo/.
But the svn client apparently only sees a redirect to https://svn.example.com/repo (trailing slash stripped off by nginx) which it follows only to get this redirect again
I think my error is some simple configuration directive I forgot to set or something similar, but after googling for more than 3 hours without finding anything that helps, I'm feeling al little helpless.
My nginx cofiguration:
server {
        ssl                     on;
        ssl_certificate         ssl/svn.example.com.crt;
        ssl_certificate_key     ssl/svn.example.com.key;
        listen                  126.96.36.199:443 ssl spdy;
        allow                   all;
        server_name             svn.example.com;
        location / {
                set $fixed_destination $http_destination;
                if ( $http_destination ~* ^https(.*)$ ) {
                        set $fixed_destination http$1;
                }
                proxy_set_header Destination $fixed_destination;
                proxy_set_header Host $http_host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-Forwarded-By $server_addr:$server_port;
                proxy_set_header X-Forwarded-Proto $scheme;
                proxy_pass http://127.0.0.1:8080;
                proxy_redirect http:// https://;
        }
}

And this is the apache virtual host config:
<VirtualHost *:8080>
        ServerName svn.example.com
        ServerAdmin email@example.com

        DocumentRoot /srv/svn
        <Directory /srv/svn>
                Options none
                AllowOverride None
                Order deny,allow
                Deny from all
        </Directory>

        <Location />
                Order deny,allow
                Allow from all

                DAV svn
                SVNParentPath /srv/svn
                SVNReposName "Subversion Repository"

                #our access control policy
                AuthzSVNAccessFile /srv/svn/access

                #only authenticated users may access the repository
                Require valid-user

                #how to authenticate a user
                AuthType Basic
                AuthName "Subversion Repository"
                AuthUserFile /srv/svn/users

                Satisfy All
        </Location>

        ErrorLog ${APACHE_LOG_DIR}/svn_error.log

        # Possible values include: debug, info, notice, warn, error, crit,
        # alert, emerg.
        LogLevel warn

        CustomLog ${APACHE_LOG_DIR}/svn_access.log combined
</VirtualHost>

My software versions:
# apache2ctl -v
Server version: Apache/2.2.22 (Debian)
Server built:   Feb  1 2014 21:26:04

# nginx -v
nginx version: nginx/1.6.0

#svn --version
svn, version 1.8.9 (r1591380)
   compiled May 21 2014, 03:09:46 on x86_64-pc-linux-gnu

Copyright (C) 2014 The Apache Software Foundation.
This software consists of contributions made by many people;
see the NOTICE file for more information.
Subversion is open source software, see http://subversion.apache.org/

The following repository access (RA) modules are available:

* ra_svn : Module for accessing a repository using the svn network protocol.
  - with Cyrus SASL authentication
  - handles 'svn' scheme
* ra_local : Module for accessing a repository on local disk.
  - handles 'file' scheme
* ra_serf : Module for accessing a repository via WebDAV protocol using serf.
  - using serf 1.3.6
  - handles 'http' scheme
  - handles 'https' scheme

Same svn version on the client.
Comment: Why do you have a proxy_redirect there ?
Comment: @melsayed Because the apache server redirects to http:// (I corrected that typo in my question)
Answer: Well, after googling some more I finally found the solution: https://stackoverflow.com/questions/18474825/what-is-the-cause-of-svn-e195019-redirect-cycle-detected-for-url/18474826#18474826
After moving the DocumentRoot to another location than the "svn root" all things works as expected.
I hope this helps someone having the same problem.


Trouble loading an ISO

Question: I've created a boot disk and ISO image with paragon. I boot up the Virtual pc with the disk in and I get to my recovery page.
When I am supposed to select an ISO image?
My Virtual PC doesn't acknowledge any of my physical hard drives on my host PC. I've also tried copy/paste the files into my datastore and they do not show up. I've tried the option during the set up to start with the ISO but again I am not able to browse to my external hard drive that I have stored the ISO on. VMWare will acknowledge it and say that it is connected but I can't browse to it.
Am I doing something wrong? I created the back up disk and ISO image on the external with paragon.
Comment: Which version of VMWare? ESX? ESXi? Workstation? Fusion? Player?
Answer: Have you added a virtual CD rom drive to your VM? If you have, then you should be able to either set the ISO as the default image for that virtual drive (if you haven't already booted the VM) or connect the virtual CDrom to that ISO (after booting).
If not, then you will need to add the virtual CD rom drive to the VM first.
Hope this helps,
By the way, I'm assuming that that when you refer to "Virtual PC" you are talking about your VMware Virtual Machine (VM)and not a 'Microsoft Virtual PC' VM, since the tag on this post is vmware.
Answer: Is it a USB extenal disk? Do you have to enable/connect to the USB subsystem in VirtualPC? Can you try and copy the ISO to the local disk?

Trouble loading an ISO


My new approach to wp_enqueue_script

Question: OK, i'm trying to eliminate all possible variables for troubleshooting purposes. So instead of in my functions.php, I've dropped this code in my header.php file:
<?php $mdgtemplateloc = get_bloginfo( 'template_url' ).'/js/'; ?>
<?php echo ' ?>
<?php wp_enqueue_script( 'hoverIntent', $mdgtemplateloc.'hoverIntent.js', array( 'jquery' ) ); ?>
<?php wp_enqueue_script( 'mdMenuAnimation', $mdgtemplateloc.'mdMenuAnimation.js', array( 'hoverIntent' ) ); ?>

The result is a few white space insertions into the source and the comment appears as requested. My understanding was that this would insert something like

I want to do this the correct way, but wp_enqueue_script has been giving me NOTHING. I suspect I'm doing something fundamentally wrong, but I can't find it and nothing I find through google or stackoverflow or the wp codex is helping at all.
To clarify, here's what I had before, in the functions.php file:
function mdg_setup_scripts() {
  $mdgtemplateloc = get_bloginfo( 'template_url' ).'/js/';
  wp_register_script( 'hoverIntent', get_bloginfo('template_url').'/js/hoverIntent.js', array( 'jquery' ));
  wp_enqueue_script( 'hoverIntent' );
  wp_register_script( 'mdMenuAnimation', $mdgtemplateloc.'mdMenuAnimation.js', array( 'hoverIntent' ));
  wp_enqueue_script( 'mdMenuAnimation' );
}
add_action( 'wp_enqueue_scripts', 'mdg_setup_scripts' );

This also produced no output that ever called a script. I understand that this second is more like what is supposed to be, but it isn't doing anything.
Answer: wp_enqueue_script() does not output anything. You're using it incorrectly.
You need to create a callback and add it to the wp_enqueue_scripts action. Typically this belongs in your functions.php file.
Re-read the docs. There are examples of exactly what you are wanting to do.
Comment: Yes, there's this:
``
To be put in the functions.php. I do that, and I get the same exact action (substituting my own script names/locations, of course).
Comment: yes, but no `
Comment: GORRAMIT Somewhere along the line I had commented out the add_action line. I don't even have any idea when. I've been banging my head over something that should have been working this whole time if I wasn't such a derp. Thanks for the help, Jason.

My new approach to wp_enqueue_script


How can I convert a vector to an array?

Question: import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

//Write your own version of the x.split()method

public class Splitting {

    public static void main(String[] args) {
        System.out.println(mySplit("A/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q/t/s/t/u/v/w/x/y/z/", "/"));
    }

    public static String[] mySplit(String x, String y) {
        {
            Vector<String> Final = new Vector<String>();
            String f = null;
            String z = null;

            for (int i = 0; i < x.length(); i++) {

                z = (x.substring(x.indexOf(y), x.indexOf(y) + 1));
                f = x.replace(z, "\n");
                Final.add(f);

            }
            String[] Finale = Final.toArray(new String[Final.size()]);

            System.out.println(Finale[0]);

            return Finale;
        }
    }
}

This is a coding assignment for High School where I have to write my own .Split() method, I have understood how to do it as a String but am having trouble converting the vector to an array if anyone could please help me it would be much appreciated. Also I don't know what would be more convenient an Arraylist or a Vector?
Comment: You are clearly young and new to this site, it's awesome that you're interested in coding. This website is not meant to be used for somebody else to figure out your homework. If you are stuck, ask a question specific to what you are stuck on and provide a simple example if possible. Dumping your homework in a question will get you a lot of frowns most of the time. Also, avoid admitting that it's your homework :)
Comment: This may help you http://stackoverflow.com/questions/7500259/how-to-convert-vector-to-string-array-in-java
Comment: You can make you `mySplit` method more readable by renaming your `x` variable to `input` and your `y` variable to `splitter`. Also, avoid using Capitalized variable names in java, e.g. `final`. These are just cosmetic tips that do not change the functionality of your code, but will be important in the future.
Comment: Questions seeking debugging help ("why isn't this code working?") *must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it* in the question itself. Questions without a clear problem statement are not useful to other readers.
Answer: Don't use Vector since it is deprecated. Use ArrayList instead of that.
You can use toArray() method to convert Vector to Array in if you really want to do so.
Eg:
Vector<String> vector= new Vector<>();
String [] s = vector.toArray(new String[vector.size()]);

You can try this way too
 Vector<String > vector = new Vector<>();
 String[] arr=new String[vector.size()];
 int a=0;
 for(String  i:vector){
     arr[a]=i;
     a++;
 }

Comment: `vector.toArray(new String[vector.size()]);` is much better +1
Comment: -1 It'll convert to `Object[]` not to `String[]`
Comment: Yes, the method must return an array of strings.
Comment: @alfasin yes and so?
Answer: You can convert a vector of Strings into a String-array like this:
    Vector<String> vec = new Vector<>();
    vec.add("A");
    vec.add("b");
    vec.add("C");
    String[] arr = new String[vec.size()];
    vec.copyInto(arr); // that's how you "convert" it
    System.out.println(StringUtils.join(Arrays.asList(arr), ",")); // debug printing

That said, I agree with Ruchira Gayan Ranaweera: you shouldn't use Vector - use ArrayList instead (Vector is synchronized which makes it performance heavy).
Comment: But, java.lang does not contain StringUtils.
Comment: @user3754559 you don't want to use that, alfasin use that for print array content.
Comment: @user3754559 true, this line is for debugging purpose only, if you want to use StringUtils you should import `com.sun.deploy.util.StringUtils`.
Comment: BTW, it's pretty simple to implement this `join()` if you don't want to depend on sun libraries.
Answer: I used c# code to create custom Split function. Hope you can get an idea on how to do this in java.
private static List<string> Split(string x, string y)
    {
        var returnVal = new List<string>();

        int i = 0;
        foreach (char c in x)
        {
            if (c != '/')
                returnVal.Add(c.ToString());
        }

        return returnVal;

    }

How can I convert a vector to an array?


Posso colocar uma imagem da internet num ImageButton?

Question: É possível criar um imageButton e dentro dele colocar uma imagem da internet. Consigo fazer isso com a webView, mas é possível fazer com o imageButton?
Answer: Julgo que a forma mais simples será esta:
URL imageUrl = new URL("url_da_imagem");
Bitmap imagem = BitmapFactory.decodeStream(imageUrl.openConnection().getInputStream());
meuImageButton.setImageBitmap(imagem);

Fonte SOen
No entanto o correto é fazer este procedimento num AsyncTask:
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    ImageButton imageButton;

    public DownloadImageTask(ImageButton imageButton) {
        this.imageButton = imageButton;
    }

    protected Bitmap doInBackground(String... urls) {
        URL imageUrl = null;
        try {
            imageUrl = new URL(urls[0]);
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Bitmap imagem = null;
        try {
            imagem = BitmapFactory.decodeStream(imageUrl.openConnection().getInputStream());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return imagem;
    }

    protected void onPostExecute(Bitmap result) {
        imageButton.setImageBitmap(result);
    }
}

Para colocar a imagem no seu ImageButton faça:
ImageButton imageButton = (ImageButton) findViewById(R.id.doSeuImageButton);
new DownloadImageTask(imageButton).execute("url_da_imagem");

É necessário adicionar a seguinte permissão ao AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />

Comment: Olá, obrigado pela resposta, sou iniciante no android e não consegui entender muito bem como posso utilizar, estou estudando e vendo como posso usar. Obrigado
Comment: É fácil. Copie o código da classe `DownloadImageTask` para a *Activity* onde você tem o *ImageButton*. Copie o último código da resposta para dentro do `onCreate` dessa *Activity*. Tem de substituir `R.id.doSeuImageButton` e `url_da_imagem` pelos valores corretos.
Comment: Eu consegui antes de você falar, pesquisei e foi isso mesmo que você disse, agora vou tentar ver como redimensionar a imagem ao imageButton, muito obrigado pela resposta novamente.
Comment: Terá de adicionar `` ao *AndroidManifest.xml*
Comment: No stackoverflow a melhor forma de agradecer a quem te ajudou é assinalar a melhor resposta e/ou votar naquelas que foram úteis.
Comment: Já fiz isso agradeci. Esse android.permission é para aumentar?
Comment: Para aumentar o quê? A imagem? A permissão é necessária para que a aplicação possa aceder à internet. Sem isso o código não irá funcionar.
Comment: Funcionou sem utilizar o AndroidManifest. ahhhhh mas foi pq eu já tinha utilizado para outra coisa que tentei fazer com webView.
Comment: Seria o tamanho da imagem para se adaptar ao tamanho do imageButton, to procurando pra ver se axo como fazer.
Comment: No *xml* do `ImageButton` coloque estes dois atributos: `android:scaleType="fitCenter"` e `android:adjustViewBounds="true"`
Answer: Primeiramente você precisa fazer download desta imagem pois não existe uma forma direta de informar uma URL diretamente na propriedade src, por exemplo.
Você pode ter um método assim, para fazer este o download e obter um Drawable:
public Drawable drawableFromUrl(String url) throws IOException {
    Bitmap x;

    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    connection.connect();
    InputStream input = connection.getInputStream();

    x = BitmapFactory.decodeStream(input);

    return new BitmapDrawable(x);
}

E então, só definir a propriedade do ImageButton:
btn.setImageResource(drawableFromUrl("http://..."));

Não testei, mas provavelmente você terá que fazer isso em uma thread diferente da UI.


Create Node contains Field collection with restws + services

Question: I am trying to create a node with RESTFULL api using restws and services modules (latest versions) on Druapl 7 - openpublish destro.
the node contains a Field collection (images field collection field) i was trying to attache the fid returned from the /backbone/rest/files.json [POST] but the field accept nothing
JSON Sample for the field

"field_op_gallery_image": {

"und": [

<code> {
   "value": "3",
   "revision_id": "3"
 },
 {
   "value": "4",
   "revision_id": "4"
 },
 {
   "value": "5",
   "revision_id": "5"
 },
 {
   "value": "6",
   "revision_id": "6"
 },
 {
   "value": "7",
   "revision_id": "7"
 },
 {
   "value": "8",
   "revision_id": "8"
 }
</code>
]
       },

Can any one help , thanks in advance
Comment: Could you edit the question and include your code please? A JSON dump of the payload you're sending with the request would also be extremely useful
Comment: Done please recheck
Comment: Did you solve this?
Comment: I did not fiend any solution :( but the best way to use field with multi value enabled
Comment: Any luck with this? I have a similar problem.
Answer: This sandbox will implement a field_collection service for services 3.x: https://www.drupal.org/sandbox/graber/2141747


react-hook-form input handler taking too long

Question: I had a big performance issue using react-hook-form in context mode. Input events like onblur, onchange and onfocus were taking more than 1 second to respond.
Comment: It's honorable that you want to share the solution to a problem that others may encounter. I would be nice if you could add the solution as an answer to your own question instead of including it in the question itself. This way it will be shown as having an answer rather than being unanswered.
Answer: Solution
The problem root was having a Google Chrome/Edge extension enabled called React-Sight. When the add-on finally crashed due to memory issues, the form performance was improved so much in a point to be finally usable again.