Programmatic scroll to offset expressed in pixel with respect to leading anchor, in SwiftUI

Question: I'm trying to implement this kind of functionality in SwiftUI. The basic idea is that I have a slider and a ScrollView, and moving the slider around lets me scroll through the ScrollView content (which is not necessarily a video as shown in the above example, it can be any view).
Of course ScrollViewReader doesn't wrap UIScrollView.setContentOffset and only offers scrollTo(_ id: Hashable [, anchor: UnitPoint]), that doesn't let me control the offset as I would like to.
In my interpretation, the Slider will produce a number between 0 and 1, and then you obtain the corresponding offset to scroll to (with respect to the leading anchor) using lerp on the value obtained from the Slider's binding, where a basic implementation for lerp might be the following:
extension Range where Bound: BinaryFloatingPoint {
    func lerp(_ t: Bound) -> Bound {
        return (1-t)*self.lowerBound + t*self.upperBound
    }
}

extension ClosedRange where Bound: BinaryFloatingPoint {
    func lerp(_ t: Bound) -> Bound {
        return (1-t)*self.lowerBound + t*self.upperBound
    }
}

So I made an attempt to hack around the limitation of the ScrollViewReader trying to avoid Introspect and UIViewRepresentable/UIViewControllerRepresentable, that kinda flows as follows:

Add an overlay to the ScrollView's content that fills the entire size with frame(maxWidth: .infinity, maxHeight: .infinity) and is .leading aligned.
The overlay will contain a simple Rectangle() with .clear background and .contentShape(Rectangle()), whose position with respect to the .leading anchor of the ScrollView's content is controlled using a @State private var offsetAnchor: CGFloat variable, initially .zero and a static id assigned to it, eg .id("scrollAnchor").
When I want to move the content of the ScrollView to a given offset, first thing I set offsetAnchor to the desired offset, and then invoke scrollProxy.scrollTo(scrollAnchor).

Unfortunately the workaround didn't work and it seems to scroll to random offsets (which doesn't mean it's actually random, just I couldn't figure out the criteria). Here is a very basic implementation of my idea
struct ContentView: View {

    @State private var inputValue: String = ""
    @State private var contentOffset: CGFloat = .zero {
        didSet {
            self.updateOffset("scrollAnchor")
        }
    }
    @State private var updateOffset: (String) -> Void = { _ in }

    var body: some View {
        VStack {
            ScrollViewReader { scrollProxy in
                ScrollView(.horizontal, showsIndicators: true) {
                    Rectangle()
                        .fill(Colors.teal500)
                        .frame(width: 1000, height: 100)
                        .overlay(
                            ZStack {
                                ForEach(1..<40) { i in
                                    VStack(alignment: .leading) {
                                        Rectangle()
                                            .fill(Colors.white)
                                            .frame(width: 1, height: 10)

                                        Text("\(i*25)")
                                            .font(.caption)
                                    }
                                    .offset(x: CGFloat(i*25))
                                }
                            }
                            .fillMaxWidth(alignment: .leading)
                        ,alignment: .topLeading)
                        .overlay(
                            ZStack {
                                Rectangle()
                                    .fill(Color.red)
                                    .contentShape(Rectangle())
                                    .frame(width: 1, height: 100)
                                    .position(x: self.contentOffset, y: 50)
                                    .onAppear {
                                        self.updateOffset = { id in
                                            DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                                                scrollProxy.scrollTo(id)
                                            }
                                        }

                                    }
                                    .id("scrollAnchor")

                            }
                                .fillMaxWidth(alignment: .leading)
                            , alignment: .leading
                        )
                }
            }

            TextField(
                    "Scroll offset:",
                    text: self.$inputValue
                )
            .keyboardType(.decimalPad)

            Button(action: {
                self.contentOffset = CGFloat(Int(inputValue) ?? 0)
            }) {
                Text("Scroll to input offset")
            }

        }
        .fillMaxSize(alignment: .leading)
    }
}

Where Colors.teal500 is a syntactic sugar for #319795 color, and the fillMaxWidth()/fillMaxHeight()/fillMaxSize() are implemented as follows:
struct FillMaxSize: ViewModifier {
    private var alignment: Alignment?

    init(alignment: Alignment?) {
        self.alignment = alignment
    }

    func body(content: Content) -> some View {
        if self.alignment != nil {
            return content
                .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: self.alignment!)
        } else {
            return content
                .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
        }
    }
}

struct FillMaxWidth: ViewModifier {
    private var alignment: Alignment?

    init(alignment: Alignment?) {
        self.alignment = alignment
    }

    func body(content: Content) -> some View {
        if self.alignment != nil {
            return content
                .frame(minWidth: 0, maxWidth: .infinity, alignment: self.alignment!)
        } else {
            return content
                .frame(minWidth: 0, maxWidth: .infinity)
        }
    }
}

struct FillMaxHeight: ViewModifier {
    private var alignment: Alignment?

    init(alignment: Alignment?) {
        self.alignment = alignment
    }

    func body(content: Content) -> some View {
        if self.alignment != nil {
            return content
                .frame(minHeight: 0, maxHeight: .infinity, alignment: self.alignment!)
        } else {
            return content
                .frame(minHeight: 0, maxHeight: .infinity)
        }
    }
}

extension View {
    func fillMaxSize(alignment: Alignment? = nil) -> some View {
        return self.modifier(FillMaxSize(alignment: alignment))
    }

    func fillMaxWidth(alignment: Alignment? = nil) -> some View {
        return self.modifier(FillMaxWidth(alignment: alignment))
    }

    func fillMaxHeight(alignment: Alignment? = nil) -> some View {
        return self.modifier(FillMaxHeight(alignment: alignment))
    }
}

I need help either correcting what's wrong with my implementation (I suspected that scrollTo might be invoked before the "scrollAnchor" is moved to the new position, but this doesn't seem to be the case since I tried to execute the scrollTo action with few seconds delay and nothing changed), or some hint to get this working.
Much appreciated!!
Answer: I have generally found that ScrollViewProxy needs to be helped as much as possible by keeping the hierarchy flat and avoiding any possible confusion about exactly which ids are being scrolled to. I should think it also helps to stick to simple HStack or VStack layout designs, avoiding offsets or other adjustments of position.
You have explained that you want to scroll horizontally. So I would suggest using the main content of the body for the calibrated ScrollView based on a simple HStack, then overlay the interesting content using .overlay. The overlay automatically adopts the size of the main content:
struct ContentView: View {

    @State private var inputValue: String = ""
    @State private var contentOffset = 0.0

    var body: some View {
        GeometryReader { geometryProxy in
            VStack {
                ScrollViewReader { scrollProxy in
                    ScrollView(.horizontal, showsIndicators: true) {
                        HStack(spacing: 0) {

                            // The main content consists of a row of rectangles
                            // that are 1-pixel wide, each associated with an
                            // identifier that corresponds to the index position
                            ForEach(0..<1000, id: \.self) { pixel in
                                Rectangle()
                                    .frame(width: 1)
                                    .frame(maxHeight: .infinity)
                            }
                        }
                        .overlay(

                            // The scale is shown as an overlay
                            HStack(spacing: 0) {
                                ForEach(0..<40) { i in
                                    VStack(alignment: .leading) {
                                        Rectangle()
                                            .fill(Color.white)
                                            .frame(width: 1, height: 10)

                                        Text("\(i*25)")
                                            .font(.caption)
                                            .allowsTightening(true)
                                            .minimumScaleFactor(0.1)

                                        Spacer()
                                    }
                                    .frame(width: 25, alignment: .leading)
                                }
                            }
                            .background(Color.teal)
                        )
                    }
                    .frame(height: 100)
                    .onAppear {
                        scrollProxy.scrollTo(0, anchor: .leading)
                    }
                    .onChange(of: contentOffset) { newOffset in
                        scrollProxy.scrollTo(Int(newOffset), anchor: .leading)
                    }
                }
                // A slider for adjusting the scroll position interactively
                Slider(
                    value: $contentOffset,
                    in: 0...(1000 - geometryProxy.size.width),
                    step: 1
                )
                .padding()

                // Allow an explicit scroll position to be entered manually
                TextField(
                    "Target offset",
                    text: $inputValue
                )
                .frame(width: 100)
                .keyboardType(.decimalPad)

                Button("Scroll to target offset") {
                    contentOffset = Double(inputValue) ?? 0.0
                }
            }
        }
        .frame(height: 400)
    }
}

Comment: Well ScrollViewProxy works with ids, not with pixel positions, so you need to build the view using items that have ids. But the rectangles do not necessarily need to be 1 pixel wide, they don't even need to be equal size. They just need to be as wide as the lowest level of scrolling granularity and/or your scrolling stop-points.
Comment: I really appreciate your effort to help. However I'm kind of concerned with the performance because the content of the `ScrollView` will end up being an image captured from a spectrogram, which can easily get to be 10k+ pixels wide and I'm kinda concerned this approach of drawing a rectangle for each pixel will cause stutters as the project scales. For instance what if I'm adding a `MagnificationGesture`? This would mean that on a 2.0x zoom level the image could 20k pixels wide.
Comment: I know that `ScrollViewProxy` works with IDs, that's also why I tried to circumvent the limitation using a single rectangle with a static ID whose position changed according to my needs. Too bad it didn't work, it looks like at the moment the content appears the IDs and positions are registered once and for all and do not update when the content changes. It's such a shame cause with `Introspect` this takes no more than 4 lines.
Comment: The difference between the solution we have here, and the the film example that you linked to, is that the user is able to adjust the scroll position here by dragging the main view. In other words, the user is not dependent on a Slider to adjust the main view. This means, the rectangles for building up the main view just need to correspond to the positions you want to scroll to programmatically. If we are talking about spectogram inspection then surely there will not be thousands of these?
Comment: Yeah let me throw in some numbers from my use case: my current default settings for the spectrogram are the following: window size: 2048, hop count: 4 (ie an offset between two time bins of 512 samples), sampling frequency of 44100 Hz, audio durations of about 3 minutes. Assuming a three minutes with these settings you get (7938000 - 2048)/512 = 15000 pixels, assuming a time bin takes one pixel in the output image.


Where to find regions

Question: Now I have created regions.
Where I can find it to put block in it. I have search module to put so that I can render it.
Comment: Hi, that makes absolutely no sense I'm afraid. Please take the time to describe your problem properly, including how you've tried to solve the problem, what went wrong, etc, so what you're asking can be understood properly, and your question becomes useful to the Q+A repository here. Once you've done that please flag for re-opening. Thanks
Comment: oh sorry its block. I am good with html and php but new to drupal
Comment: and thank you @Clive... It solved my problem.... I was searching it in Module
Answer: You can't put module in region. You put blocks in regions.
Go to http://example.com/admin/structure/block to see regions and blocks assigned to them. Of course substitute example.com with your real domain name.

Where to find regions


How much faster than a speeding bullet is superman?

Question: I need some help with a problem I want to solve.
You have a gunman standing 50 ft away from a human target. According to google, the average bullet travels at 2,500 fps. If my math is correct (debatable, my math skills are kind of sad) this gives the target .02 seconds or 20 ms to react before the bullet reaches them.
Also according to google, The average reaction time for humans is 0.25 seconds to a visual stimulus, 0.17 for an audio stimulus, and 0.15 seconds for a touch stimulus (Logically speaking, I believe this is the time between the initial stimulus and the time motion is initiated, not completed). I'm not sure (could not find) the amount of time would take this average human to actually finish moving their hand into a position to block the bullet's path if it is headed directly for the person's heart. Edit: couldn't find numbers online, so I found a victim and measured him. He is 6 ft tall, his arm is about 30 inches long from finger-tips to shoulder, and the straight-line distance between his hand and the approximate area of his heart was about 25 inches (2.08333 ft). So let's assume the hand needs to cover a distance of about 25 inches. I also found this statement: "The human hand can move 150 MPH(.04 miles per second which equals 215 feet per second" here: http://highdeas.com/lifestyle/This_is_insane_but_I_cant_disprove_it (but there was no reference to say where the number came from).
Edit 2: I checked the number with an online calculator and it would seem that 150 mph is actually 220 fps, not 215.
Obviously, average Joe (and even exceptional Bob) are far to slow to have a prayer of putting their hand in the way of a bullet (and even if they did, the bullet would rip a hole in their hand).
What I want to know is if it is possible to determine how many times faster than normal human reaction time Superman would need to be in order to block a bullet with his hand.
Comment: There are some data missing for me to give an answer. I would need to know the top speed of the hand and the expected distance between the hand and the heart. Throwing some numbers in, if he average human would take less than a second to finish his/her defence movement (think of martial arts specialists), then Superman would need to be around 50 times faster.
Comment: Thanks, I'll look up a few more things an add as much as I can find
Comment: @Ertxiem edited the original post
Comment: Not much to do here.  Your calculations of the bullet taking $0.02$ secons is correct and if you conversion of $150 mph$ to fps is correct then then $\frac {25}{215}=0.116$ seconds.  Even with instantaneous reflex it can't be done, not if superman has normal hand velocity.  But if his reflex is $k$ times faste and his speed is $m$ then you need $0.15/k + 0.116/m = 0.02$.  If superman is $n$ times faster in all thing you need $0.15/n+0.116/n=0.266/n=0.02$ or superman is $13.3$ times faster in all ways.
Comment: @fleablood: I did almost the same approach you did, but you also considered in separate the two different ways of being faster, nice! Regarding the computations, I saw a small mistake: you divided $25$ inches by $215$ feet per second.
Comment: Update: I checked the number with an online calculator and it would seem that 150 mph is actually 220 fps, not 215. Also, https://physics.stackexchange.com/questions/33326/can-human-hand-move-at-a-speed-rate-like-this-baseball-pitch-or-is-it-just-the-s over on the physics stack indicates the top speed for a shorter motion might be about 100 mph, rather than 150. I ran some numbers and looked at how long it takes a pitcher to make a quick motion to release a ball, and decided it's a fair number to say a person *may* be able to move their hand from their side to their heart in about 0.03 sec.
Comment: Alas, all this just means Superman probably needs to move even FASTER compared to our non-super human :(
Answer: So, from your data, it seems that the average human would take around $0.25s$ from the moment he/she saw the gun firing to start the movement.
Then, the same human would need at least $0.01s$ to move the hand in front of the heart, assuming that the hand can immediately move at top speed.
Therefore, average humans would complete their defence movement in over $0.26s$ after they saw the gun firing.
Superman would need to be 13 times faster to do the same thing in $0.02s$, since $\frac{0.26}{0.02} = 13$.
By the way, looking at a related scientific article we can see that the reaction times of young male adults is around $0.226s$, so it's close to the estimates in here.
Comment: What if he started moving when he first heard, rather than saw, the gun fire? (oh boy, I just realized that the sound, and the light from the muzzle flash hitting the eye, both also take time to travel... but maybe for the sake of simplicity I should just ignore this)
Comment: Then Superman would have to be $\frac{0.17+0.01}{0.02}=9$ times faster. It's still around $10$ times faster, so not much of a difference, considering that we are using approximate values.
Comment: Neat. Thank you. I looked up the speed of sound (1125.328 fps) and it is actually slower than the bullet. So Superman is going to have to use his eyes! Fortunately for him, if my calculations are correct, light crosses a 50 ft distance in about 5.09 one hundred millionths of a second, which isn't going to slow him down much!
Comment: So, revising your equation for what I discovered is a slightly more realistic (maybe?) time of 0.03 seconds for the hand movement, I believe that results in Superman needing to be 14 times faster.
Comment: Yes, it would result in 14 times faster. By the way, if you think it's appropriate, you can accept my answer (there is a green button).


2 user registration forms

Question: I need to show users 2 registration forms. 2 different forms with different fields. 1 form for free registration and 1 form with admin approval registration. how can i achieve that?
Comment: Do you want to create two profile for the users ?
Comment: @mohit_rocks yes. it would be great
Answer: It seems there is not any module that provides this functionality directly. But certainly you can achieve it using other contributed modules.

Profile2
This module allows you to create user profile for the users. You can create profile for the two users like free_registered user and admin_approved users, and can add any number of fields on the user profiles.

Profile2 Registration Path
This module allows you to set the unique registration path for each profile2 user profile.
So after installation you will have two registration forms for each profile2 user profiles. You can access this form from the path specified in Profile2 Registration Path module configuration.

Let me know if any issue occurs. :)
Comment: how can i make one registration with admin approval and another without?
Comment: To achieve it you either have to create two registration form or one with some kind of flag that distinguish each other..

2 user registration forms


How to create a service connection with access to all namesapces in azure kubernetes pipeline?

Question: I tried to create a service connection to azure kubernetes cluster, but it is asking to provide namespace mandatory.
So I provided one namespace and set the cluster admin option selected.

And in the release pipeline, using this connection, I tried to create a secret but in a different namespace.
But I got error as forbidden during release deployment.

How to create a service connection with access to all namesapces in azure kubernetes pipeline
Answer: Trying picking default as the namespace and ensure cluster admin is checked like you said and it should work.
I just set this up for mine like this and was able to deploy to the cluster, and as the namespace names are in my manifest files, they are creating OK.


part b of a operator theory problem

Question: Problem:
For any integer number
$ k \geq 1, $
let
$T_{k} : L_{2}(\mathbb{R}) \to L_{2}(\mathbb{R})$
be the linear and continuous operator defined by
$$T_{k}(u)(x)=u\left(x+\frac{1}{k}\right).$$
Let
$I$
be the identity operator on
$L_{2}(\mathbb{R})$
and let
$\mathcal{L}(L_{2}(\mathbb{R}); L_{2}(\mathbb{R}))$
be the Banach space of bounded linear operators on $L_{2}(\mathbb{R})$
endowed with the norm
$$  \Vert T\Vert_{\mathcal{L}}:=\sup \{ \Vert T\Vert_{L_{2}(\mathbb{R})} :\; u\in L_{2}(\mathbb{R}),\; \Vert u\Vert_{L_{2}(L_{2}(\mathbb{R})}\leq 1 \}. $$
(a) Prove that for each
$u \in L_{2}(\mathbb{R}) $
it holds true
$T_{k}(u)\to u$
strongly in
$L_{2}(\mathbb{R}).$
(b) Prove that the sequence of the norms
$\Vert T_{k}-I\Vert_{\mathcal{L}}$
does $\underline{not}$ converge to
$0$ as
$k \to \infty.$
The part (a) is obvious, because
$$ \left\| u\left(x+\frac{1}{k}\right)-u(x)\right\|\to 0 \ \mbox{ as } k\to \infty, $$
but for the part (b) I have no idea. Would you mind suggesting only hint to me?
Comment: As hint try to find a sequence $(u_k)$ such that $||u_k||_2 = 1$ and $T_k(u_k) - u_k$ does not converge to $0$ in $L_2$
Answer: Hint : $u_k (x) = \frac{\sin(k\pi x)}{x\sqrt{k\pi}}$. $T_k(u_k) = ?$. The principal idea is to find a sequence of functions $(u_k)$ with bounded norm in $L_2$ and $(T(u_k) - u_k)$ does not converge to zero.
Comment: While the OP does ask "only [for] hint to me", a modest elaboration would be helpful to Readers to tell where you expect the "hint" to lead.
Comment: @hardmath I edit my answer to explain what I want
Comment: @Youem Thank you for the hint. Unfortunately, I couldn't handle your hint.
Firstly, I couldn't prove
$\Vert u_{k}\Vert_{2}=1$ (your suggested $u_{k}$).

Next, I also couldn't prove
$\Vert T_{k}-I\Vert_{\mathcal{L}}$
not to tend to
0.
Comment: First $||u_k||_2^2 = \int_{-\infty}^{+\infty}\left(\frac{\sin(k\pi x)}{x\sqrt{k\pi}}\right)^2dx = \int_{-\infty}^{+\infty}\frac{\sin(k\pi x)^2}{x^2k\pi}dx\underbrace{=}_{s = k\pi x} \int_{-\infty}^{+\infty}\frac{\sin(s)^2}{s^2}ds < +\infty$ which is also independent of $k$. On the other hand $T_k(u_k)(x) = \frac{\sin(k\pi (x+\frac{1}{k})}{(x+\frac{1}{k})\sqrt{k\pi}} = - \frac{\sin(k\pi (x)}{(x+\frac{1}{k})\sqrt{k\pi}}$ then and with the same idea we can compute  $||T_k(u_k) - u_k||_2$ to show that it does not converge to 0.
Comment: For the computing of $||T_k(u_k) - u_k||_2^2 = \int_{-\infty}^{+\infty} \frac{\sin(k\pi x)^2}{k \pi} \left(\frac{2x+\frac{1}{k}}{x(x+ \frac{1}{k})}\right)^2 dx \underbrace{=}_{s = k\pi x} \int_{-\infty}^{+\infty} \frac{\sin(s)^2}{s^2}\left(\frac{2s + \pi}{s + \pi}\right)^2 ds > 0$ and independent of $k$.
Comment: I hope this is clear now

part b of a operator theory problem


DRY x Ortogonalidade

Question: Li aqui uma resposta à pergunta: O que é ortogonalidade?, nela dizia que o que "não é DRY não é ortogonal", então fiquei em dúvida nas seguintes questões:

Qual é a relação entre ambos?
Tudo que é DRY é ortogonal, mas tudo que é ortogonal é DRY?
Answer: São conceitos bem distintos embora possam ser confundidos em cenários específicos.
Existem coisas que são DRY e não são ortogonais e vice versa, a única situação que que podemos afirmar é o que foi colocado na resposta lá, algo não DRY não consegue ser ortogonal, as outras combinações são possíveis.
Se você não cumpre o DRY a ortogonalidade está quebrada porque tem mais de um lugar onde a mesma coisa acontece, se você alterar um e não no outro dá resultado diferente do que seria esperado.
Se manter o DRY terá canonicidade daquilo, mas pode ser em algo não ortogonal até porque pode estar comparando com algo diferente. Você pode ter um local único que cuida de tudo que envolve juros de mercado, e uma alteração ali vai alterar outros dados em outros lugares, o que quebra a ortogonalidade. O contrário acontece de forma simétrica.
Lembre-se que DRY é sobre a mesma coisa, ortogonalidade é sobre coisas distintas.
Pegando o exemplo do helicóptero, não existe dois lugares para você acelerar, existem dois ações necessárias para acelerar corretamente, por isso chamei de não DRY, isto é mais não ortogonal do que não DRY, mas não deixa de ser.

DRY x Ortogonalidade


Get rate from Future Value of Annuity

Question: $FV = \dfrac{(1+i)^t-1}{i}\cdot C$
What are the algabraic steps I need to rearrange to get i? The i divided by the i is specifically tripping me up.
Many thanks!
Comment: Sorry - was going off memory. Updated to change PV to C
Comment: What is $C$? The annual payment amount?
Comment: Cash flow per period
Answer: In general, given $C$, $\text{FV}$, and $t$, we have
$$\dfrac{\text{FV}}{C}i=(1+i)^t-1$$
or $$1=\dfrac{\text{FV}}{C}i+(1+i)^t\text{.}$$
There is no way to write a (simple) formula for $i$ in this case for general $t$. Usually what is done is assuming you have the three variables, you would use a financial calculator, such as a BA-II+, to solve for $i$.
Comment: @SebastianPatten There is no simple formula for $(1+i)^t$ and thus no way to isolate $i$.
Comment: Sorry - I'm new to Math - what about the formula would indicate that there is no simple way to re-arrange for i? Is it because there is i over i? Just looking for a way of identifying myself in the future. Thanks!

Get rate from Future Value of Annuity


In gnuplot, with "set datafile missing", how to ignore both "nan" and "-nan"?

Question: The gnuplot command set datafile missing "nan" tells gnuplot to ignore nan data values in the data file.
How to ignore both nan and -nan? I tried the following in gnuplot, but then the effect of the first statement is overwritten by the next.
gnuplot> set datafile missing "-nan"
gnuplot> set datafile missing "nan"

Is it possible to somewhow embed a grep  -v nan in the gnuplot command, or even some kind of regexp to exclude any imaginable non-numerical data?
Comment: Refer to this question for using grep with gnuplot commnad http://stackoverflow.com/questions/7600048/gnuplot-missing-data-with-expression-evaluation
Comment: Upvote for being the #1 pick in Google June 2018
Answer: It is not possible to use a regexp for set datafile missing, but you can use any program to filter you data before plotting, and replacing a regexp with one character, e.g. ? which you set to mark a missing data point.
Here is an example which accomplishes, what you originally requested: filtering -nan, inf etc. For testing, I used the following data file:
1 0
2 nan
3 -inf
4 2
5 -NaN
6 1

And the plotting script may look like the following:
filter = 'sed -e "s/-\?\(nan\|inf\)/?/ig"'
set datafile missing "?"
set offset 0.5,0.5,0.5,0.5
plot '< '.filter.' data.txt' with linespoints ps 2 notitle

This gives the following output:

So the plot command skips all missing data points. You can refine the sed filter to replace any non-numerical values with ?, if this variant is not enough.
This works fine, but allows only to select columns e.g. with using 1:2, but not doing computations on the columns, like e.g. using ($1*0.1):2. To allow this, you can filter out any row, which contains nan, -inf etc with grep, like its done in gnuplot missing data with expression evaluation (thanks @Thiru for the link):
filter = 'grep -vi -- "-\?\(nan\|inf\)"'
set offset 0.5,0.5,0.5,0.5
plot '< '.filter.' data.txt' with linespoints ps 2 notitle

Comment: Upvote for being the #1 pick in Google June 2018, and for allowing me to get this answer in under a minute.  This is a great database because of contributors like yourself.
Comment: This is really good, thanks! Your suggested sed filter only replaces the first match by a "?". It is really fine for my purpose because gnuplot will ignore a line if there is just one "?" in it. It's a bit off-topic question now: How can the filter replace all occurrences of the relevant strings, for example with "inf -nan 2.43" the filtered one should be "? ? 2.43"
Comment: @user1069609 Just add a `g` behind the `i` in the sed pattern. I'll update the answer.
Answer: Here is a simple gnuplot-only solution without using sed or grep, hence, platform-independent.
You can also do calulations on the columns, e.g. x0=$1*0.1 or y0=$2**2.
There is the gnuplot function valid() which checks if a column value is valid (check help valid).
This works for NaN, nan, -nan, etc., but strangely inf, +inf and -inf are considered as valid.
So, you have to filter them separately as well.
The simple "trick" making the linespoints plot connected between datapoints, even without set datafile missing is taken from here.
Data: SO18718100.dat
1 0
2 nan
3 -inf
4 2
5 -NaN
6 1
7 +inf
8 +NaN
9 1
10 inf
11 0

Script: (works with gnuplot>=4.6.0, March 2012)
### ignore several non-valid data entries
reset

FILE = "SO18718100.dat"
Check(col) = valid(col) && !(s=strcol(col), s[sgn(strstrt('+-',s[1:1]))+1:strlen(s)] eq "inf")

plot FILE u (Check(2)?(y0=$2,x0=$1):x0):(y0) w lp pt 7 ps 2 lc rgb "red"
### end of script

The shortest version if you don't have inf values in your data would be:
plot FILE u (valid(2)?(y0=$2,x0=$1):x0):(y0) w lp

Result:


Laplacian of step function

Question: Is the second derivative of the step function equal to zero?
$\partial^2_{\theta}\bigg(\Theta(\theta-\frac{\Pi}{2})-\Theta(\theta-\frac{5 \pi}{4})\bigg)= \:?$
Answer: What follows is extremely nonrigurous. By integration of parts, we can 'define' $\frac{d(\delta x)}{dx}$ -
\begin{align}
\int \delta (x) dx &= x\delta (x) - \int x\frac{d(\delta x)}{dx}dx
\end{align}
As $\delta(x) = 0$ at $x\ne 0$, and $x\delta (x) = 0$ everywhere.
So, we can define $\frac{d(\delta x)}{dx} = \frac{-\delta(x)}{x}$.
Comment: But there are two derivatives in my question
Comment: Also, how did you remove $dx$ in the left-hand side?
Comment: Derivative of step function is the Dirac Delta, so one derivative is okay. It is the 2nd derivative which was problematic, as it involved the derivative of the Dirac Delta. That is the formula I derived.
Comment: @Mari: But $\delta(x)$ is the derivative of $\Theta(x)$, right?

Laplacian of step function


Obtain location using service(background) and update gui at regular intervals

Question: I am trying to run a service in the background. Where location is obtained at regular interval and the activity text views are updated whether the app is in E background or foreground. Any pointers or tutorials you guys aware of the? Maybe working examples? I searched a lot and couldn't find something concrete
Thank you
Note: Battery consumption is not an issue for this app
Answer: My first recommendation would be not to run location services like that, battery consumption would be a really bad issue, to get the location on regular intervals you can either use the Alarm Manager or TimerTask depending on what fits your needs, sorry I cant be more specific but I'm on my phone, hope it helps though.
Comment: I dont think that answers my question. I need it as background service. I am not worried about battery consumption
Comment: Well the answer remains the same, use an IntentService that fetches your location and call it using an Alarm Manager or a Timer Task depending on your needs
Answer: I did a small blog post about Android location services that should help. It's not service based but it will provide you live location updates in the activity whilst running. Once your activity is paused there is little point in the service providing updates any way and it will hammer your battery as @aehs29 mentioned.
Example code in the blog too: http://www.scotthelme.co.uk/blog/android-location-services/
Comment: The main point behind my question is to run it in the background (not while the activity is running)
Comment: You can adapt that activity to run as a service. Can I ask why it needs to run as a service? Is it some kind of GPS tracker app that needs to run in the background? I only ask because there may be a better way of tackling the problem.
Comment: The app is supposed to get GPS coordinates every second and write it to a file. It has to write something to a file every second even if the coordinated didn't change. This needs to be done whether the app is in background or foreground. Ideas ?:)
Comment: Then these should do the job:
Comment: http://pastebin.com/7KTCCLij
http://pastebin.com/ZcbU1nAg
http://pastebin.com/3gv3biqf
Comment: There are also some permissions and an intent you need to register in the manifest: http://pastebin.com/qBUU9EMP
Comment: Great this looks like what I want. But where is the timer part :)
Comment: Take a look in the service (MainActivity.java) for Thread.sleep(60000); My tracker sends results to a web server, hence the name, and once it was done it waits 60 seconds before it starts over. Change the time 1000 if you want it to be every second.
Comment: No probs, best of luck with it.


The Series $\sum_{n=1}^{\infty}\frac{1}{n^4\sin n}$ converges or diverges?

Question: The question is closely linked with Convergence of the sequence $\frac{1}{n\sin(n)}$. I am afraid if I am not interpreting it wrong (read it for the first time when I was asked to do the exercise that I mentioned above). Also the comment box of the above mentioned question gave a helpful info. It was mentioned that if we refer to the sequence $\frac{1}{n^u\sin^vn}$, then it converges to $0$ as soon as $1+\frac{u}{v}>7.6063$. The exercise that I mentioned above does not hold it fine. So if it doesn't hold then the sequence will not get close to $0$. Sine the initial criteria for the convergence of a series doesn't hold, therefore the series will diverge as well. To write its theoretical proof, the same situation as in above link mentioned will happen. To which non-zero irrational number the sequence in my question will converge(if it do)? Correct if I misinterpreted.
Comment: The result says that if $1+\frac{u}{v}>7.6063$, then the sequence converges. But it doesn't claim that this is an if and only if, so trying to argue the opposite statement (if the inequality fails, the sequence diverges) is not valid. Indeed we should expect convergence whenever $1+\frac{u}{v}>2$. So the series in question should converge, but I doubt anyone knows how to formally prove it.
Comment: Thanks for clarifying @Wojowu.
Answer: It is not known whether this series converges, nor even whether $$
\lim_{n\rightarrow\infty} \frac1{n^4 \sin(n) }  = 0
$$
Corollary 3 of Alekseyev (cited in the answer you link) implies that $\lim_{n\rightarrow\infty} \frac1{n^4 \sin(n) }  = 0$ would imply $\mu(\pi) \le 5$, where $\mu(\cdot)$ is the irrationality measure. But currently, all we know is that $$
2\le \mu(\pi)\le 7.1032...
$$
If $\mu(\pi) < 4$, then $\sum\limits_{n=0}^\infty \frac1{n^4 \sin(n)}$ converges absolutely, whereas if $\mu(\pi) > 5$ then the sum diverges because the summands do not go to $0$. If $\mu(\pi)\in[4,5)$, then I suppose the series will converge but not absolutely, as it is basically like an alternating series.
Comment: Just for completeness let me say that it is generally expected that $\mu(\pi)=2$, so the series should indeed converge absolutely.


Does this prove my table work?

Question: I think i create mnesia well because I add record in one node and i can see it in same table in the other node. Does this prove it work?
Comment: yes, it does my friend. It has worked ! Next Time though, paste your code to show what you have done so that we may fix other mistakes if any. well done
Answer: You covered distribution - good job ;)
The missing part is persistence. Make sure that your schema and tables are on disc (not in memory) -- of course only if it is desired.
Your friends are:
<code> mnesia:change_table_copy_type(schema, node(), disc_copies).
 mnesia:add_table_copy(SomeTableName, node(), disc_copies).
</code>
Usually it requires restart to apply changes.
You can consult mnesia:info() to see how your database looks like.

Does this prove my table work?


jquery add remove inputs

Question: My jQuery right now works perfectly when I use it to perform creation, and deletion, of textboxes. But the code does not work properly when I decide to allow users to edit them after they submit and the same code upon modification does not work anymore.
My rules are such that there needs to be a minimum of 2 iterations boxes and 1 task in each iteration, anything less than that would cause the jQuery to disable my remove iteration and minus task button respectively.
Now my codes cannot seem to allow a user to reduce a task even though there is more than 1 task in the iteration and the remove iteration button is forever disabled, despite starting off with, say, 5 iterations.
I cannot remove the 'disable' at the beginning because a user may end up with zero task if he has only filled in one task, so I can only remove the 'disable' once the if-loop proves that there is more than the minimum required.
HERE is my jQuery code, can somebody please help and give some advice? :)) Thanks in advance!
PS: $('.plus') refers to my add task class button, $('.moins') refers to my minus task class button, $('#removeIteration') and $('#addIteration') both represent remove iteration and add iteration respectively.
Answer: Please give us some context on your problem (what is it exactly your code is supposed to do, and how is it doing it right now (a rough description of your approach is enough), and paste only the relevant code in your question. Right now it is not clear at all what you mean with iteration, as you do not explain what your iterations are supposed to be doing.
--edit 1
I see you have split up the question in paragraphs, very good. Please keep making it better by providing the context.
--edit 2
I see you use parent().parent().parent(). This is rather inflexible code. You should use .closest('query describing the parent you are looking for').
Instead of 'return false;' you should use 'event.preventDefault();' and edit the lines like
$(".moins").live("click", function() {

to
$(".moins").live("click", function(event) {

Comment: The thing is: you are asking a question here. When you ask a question you should try making it as easy as possible to understand. Right now, it is rather hard.
Comment: @pivotal developer - This question is quite difficult to answer as-is. Please consider expanding it, and being a bit more understanding in comments. I've starred this and will follow up.
Comment: i already explained at the beginning of the question. the codes are all relevant. Which part of it do you not understand? The iterations are supposed to contain textboxes that contain user's task..just think simple. You have an iteration box that contain a number of tasks. you can choose to increase or decrease the number of iterations or tasks but the minimum you are allowed to go is, 2 iterations left with a minimum of one task in each iteration. Get it?
Comment: Sorry, I still do not (perhaps I'm just being stupid here). Can you please describe, in the first paragraph of your question, what your program is supposed to be doing. Something like: *I am creating a website for a bank. The users have bank-accounts which I display with textboxes, it can be one or more. The users can than deposit money in their accounts using checkboxes.* (This example is complete nonsense, but please write a short intro like that)
Comment: I have looked at your code again. Without the html it is virtually impossible to answer your question. I do have some remarks, see the edit in my question.

jquery add remove inputs


How do I convert Cramer's V to Cohen's d?

Question: Say I have a chi-squared test that compares 3 different groups:
$\chi^2_2 = 9.81$, $p=.012$, Cramer's $V=.33$
How would I go about converting this to a $d$-statistic?
Is the proper approach in this case:
$\sqrt{(4\times 9.81)/N}$, with $N$ = number of participants?
Comment: Where did that formula come from?  In what circumstances does it make sense?
Comment: How could you have a single value for Cohen's *d* --- which compares two groups --- when you say you have three groups to begin with?
Answer: There is no general method to convert Cramér's V to Cohen's d.
Both statistics are considered effect size statistics, but they convey different kinds of information.
Cohen's d compares values from a continuous variable between two groups, as might be analyzed with a t-test.  It is essentially the difference in means between two groups divided by the pooled standard deviation.  The absolute value of Cohen's d ranges from 0 to infinity.
Cramér's V is used for contingency tables of counts, for tables larger than 2 x 2.  It expresses how far the counts are from expected values.  It can be thought as the chi-square value normalized for sample size.  It ranges from 0 to 1.
Perhaps certain conditions could be specified where a conversion between Cramér's V and Cohen's d makes sense. For example, where it is known that a continuous variable had a certain distribution and was dichotomized according to a certain rule.  But this would not hold for cases outside of these pre-determined conditions.
Answer: Cramer's $V$ is an effect size from the 'correlation family' of effect sizes. Therefore, you could convert using the formula for converting $r$ to $d$:
$$\text{Cohen's }d=\frac{2r}{\sqrt{1-r^2}}$$
However, note that this '$d$' is quite different from the regular Cohen's $d$, which represents the difference between two means expressed in standard deviations.
Note
If you're conducting a meta-analysis and the variable that's "trichotomized" in this case, but dichotomized in all other cases, this can be ok if the variable is the same variable (although you'll have to caution when interpretating the result). If the 'trichotomized' variable in reality is continuous, but happens to be operationalized as a categorical variable in this case, I'd suggest instead converting all effect sizes to $r$. Whether these conversions are appropriate at all depends very much on the context and nature of the variables.
Comment: What is *r* here ?  What is this Cohen's *d* that "is quite different from the regular Cohen's *d*" ?
Comment: $r$ is Pearson's correlation; and (Cohen's) $d$ normally represents the difference between two means. However, when converting from a metric that is not based on one dichotomous and one continuous variable (e.g. two continuous variables, or one categorical variable with three levels and one with four levels, such as you may encounter when Cramer's V is reported), this interpretation makes no sense.
Comment: Okay.  So this formula works when there are two groups, and r = cor(Y, Group) and d = cohensD(Y ~ Group).  It looks like this matches the form of Cohen's d where the denominator is (n) not (n - 2).
Comment: I still have no idea how this would relate to Cramer's V.
Comment: What is your question exactly? Or what is the problem you need to solve?
Comment: I'm trying to figure out if this answers the OP's question.
Comment: You seem to be implying that you could use Cramer's V as though it was an r and apply the above transformation for r to d. I don't see the connection of how this would produce anything resembling a Cohen's d.


Hierarchical linear modelling in R

Question: I am trying to build a hierarchical linear model based on data structured like this dataset below. The model form I am looking to build is
Purchased ~ f(price + color + more item attributes + age + gender + other person attributes)
Betaprice ~ f(age + gender + other person attributes)
Does anyone know a good approach for this?
<code> person item purchased age  gender  Color   Price
    1   1    1         23   F     Blue      20
    1   2    0         23   F     Red       15
    1   3    1         23   F     Green     18
    2   1    0         34   M     Blue      20
    2   2    1         34   M     Red       15
    2   3    0         34   M     Green     18
    3   1    1         19   M     Blue      20
    3   2    1         19   M     Red       15
    3   3    0         19   M     Green     18
</code>
Answer: I'm not really sure if I understand the question correctly but since I'm not able to comment due to my less reputation I'll post an answer:
I assume this can be done via a linear mixed model, where the persons are random samples. But to answer your question: What is your goal?
Do you want to know which persons buy something? Or do you want to know which persons buy something special? Or a special color?
I assume you are interested in the total purchase of one person, so in R maybe something like
<code>library(lme4)
fit<- lmer(Price ~ person + (1 | item/color/purchased) + (1 | gender) + (1 | age) + (1 + person | item)..)
</code>
Comment: Interesting. How many individuals do you have? And in which way shall the model be hierarchically?
Comment: right now I'm just trying a logistic regression with purchased~color + attribute2 + attribute3+...+ price + price:age + ... then after I can obtain the price coefficients and build a formula like 1(price coef)+age(price:age coef)+...
Comment: My goal is to predict how sensitive a member is to price based on attributes about that individual. In the end, I want to be able to compute kind of like a price elasticity at the individual level.
Comment: In my sample now, I have about 5k individuals and 5 items. I can get more though. I am not sure how the hierarchy is structures, which is why I'm on here ;) . I know I would like to predict probability of purchase for each item and the beta on price be a function of attributes about individuals.
Comment: I guess what you are looking for are so-called logistic-functions/models. But I only stumbled over them and it looks appropriate to me because you are having a boolean factor (purchased yes/no). But I'm not sure since the predicted probability won't be a boolean, of course. I will think about it.

Hierarchical linear modelling in R


Strange Visual Studio Behavior: Very long execution time

Question: I have noticed that some code takes a very long time to execute in Visual Studio as opposed to compiling it manually with CL and running the executable.
Here is an example of code which exhibits this behavior:
<code>int DP[MAX][MAX];
class CartInSupermarketEasy {
public:
int calc(int N, int K) {
    clock_t begin = clock();
    for (int i = 0; i < MAX; ++i) {
        DP[0][i] = 0;
        DP[1][i] = 1;
        DP[i][0] = i;
    }

    for (int n = 1; n <= N; ++n) {
        for (int k = 0; k <= K; ++k) {
            int min_res = N;
            for (int i = 1; i < n; ++i) {
                for (int j = 0; j < k; ++j) {
                    int curr_res = max(DP[n - i][k - 1 - j], DP[i][j]) + 1;
                    min_res = min(curr_res, min_res);
                }
            }
            DP[n][k] = min(min_res, DP[n - 1][k] + 1);
        }
    }
    clock_t end = clock();
    double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
    cout << elapsed_secs << '\n';
    return DP[N][K];
    }
} CI;

int main(){
    cout << CI.calc(100,100) << '\n';
    return 0;
}
</code>
When run in VS2013, the function calc takes about 13.5 seconds to calculate the answer. In VS2012, this goes down to 3.5 seconds. However, when compiled manually with CL (or any other compiler that I've tried ), the executable returns an answer in .4 seconds.
How can this discrepancy be explained, and how can I make VS execute on par with manual compilation/execution?
Thank you.
Comment: Are you comparing *release* vs. *release* and also with the same optimization levels (or equivalent)?
Comment: Are you timing the Visual Studio versions with or without the IDE?
Comment: Yea I was actually not comparing to release rather to debug build. Thank you, and thanks to Pawel who commented earlier but I don't see his comment anymore.
Comment: Are you using the `std::max` function or one you wrote yourself?  Same with the `min` function.  The compiler may have optimized versions of these functions.
Comment: By the way, are you safely accessing your arrays?  When `k` is less than or equal to  `j`, you will have a negative index when using the `max` function.
Comment: @Thomas Matthews Using std::max/min. You are saying it's better to use the built-in one instead of one I write myself? The inner loop has `j<k` as the entrance condition.
Comment: Any version of VS after 2008 is slow.  If you want the actual time taken to run, pop up a MessageBox after main so you can start timing when you click on the button.  The discrepancy is the time taken to set up the system for debugging.  It needs to load up the .pdbs and tie up the symbols with the ones in the .sdf file.  If you have included iostream,   there are a few hundred symbols to tie up, even though most of them are not used.
Comment: @Thomas Matthews Interestingly, using my own min/max functions, improved performance x10 in Debug and x2 in Release
Comment: [Optimizing Compiler](http://en.wikipedia.org/wiki/Optimizing_compiler)
Comment: From that page: While writing an application, a programmer will recompile and test often, and so compilation must be fast. This is one reason most optimizations are deliberately avoided during the test/debugging phase. Also, program code is usually "stepped through" (see Program animation) using a symbolic debugger, and optimizing transformations, particularly those that reorder code, can make it difficult to relate the output code with the line numbers in the original source code. This can confuse both the debugging tools and the programmers using them.
Answer: The problem was that I was running using the "Debug" configuration instead of "Release". Changing it the build configuration to "Release" has solved the problem. Interestingly, it runs about 4 times faster than manual compilation/execution now.
Update:
As pointed out in the comments, a lot of the slowdown was caused due to use of std::min and std::max functions. Switching to custom made min/max functions, sped up the execution by a factor of 3-4. Here is an article confirming this observation: std::min causing three times slowdown
Comment: I don't know what computer you're using but your program takes roughly .1 seconds on mine using VS2013/Win32/Debug.
Comment: Really? Very strange. That's about what I am getting in Release now, but Debug is still giving me 13.4 secs.
Comment: I tried doing that, but I don't know how to understand from the report why it's taking so long in Debug.
Comment: Are you using the [Performance Wizard](https://msdn.microsoft.com/en-us/library/ms182372.aspx)? If not you could still upload the report and we will see what causes the slowdowns.
Comment: Interesting: I replaced the std::min/max functions with custom made ones, and the run time in Debug has been reduced x10 to 1.46 sec, which is still x10 more than release run time. Here is a link to the performance report (still using the std::min/max) [Work150211.vsp](https://drive.google.com/file/d/0BzZo3mTuII-pbE4tMTIxaWJNZ0E/view?usp=sharing)
Comment: Here is another question: When running CI.calc(300,300), the program returns an answer in 6 seconds (Release). If I understand correctly, the run time of the program should be: (300^4)/8 which is about 10^9 ops. Isn't that a bit too fast for so many ops?
Comment: Yes that is another question and it should be treated as one and not as a comment. Apart from that, your uploaded report reveals that the slowdowns are in fact caused by std::min/std::max. Here a [tip](https://msdn.microsoft.com/en-us/library/dd551466.aspx) on how to read those reports. You can then open the resulting .vsps file in VS.
Comment: I see, thanks for looking at it. Still, even with my own min/max, getting 1.6 secs in Debug for the calc(100,100), where as in Release it takes about 0.04
Comment: Thank, My video render (ffmpeg & directx) on debug take 130ms-140ms to convert a frame. But when i run exe on non-debug it take only ~10ms.


Bang-bang Solution to Optimization Problem on the Sphere

Question: For $x,y\in\mathbb R^n$ define
$P(z) = \sum_{i=1}^n z^i x_i y_i$.
I want to minimize the function
$$
\frac{1-P(z)^2}{P'(z)^2}
=\frac{1-(\sum_{i=1}^n z^{i} x_i y_i)^2}{(\sum_{i=1}^n i z^{i-1} x_i y_i)^2}
$$
for a given $z\in[-1,1]$ over all $x$ and $y$ restricted by $\|x\|_2=\|y\|_2=1$.
Conjecture: For any $z\in[-1,1]$ there is some $i\in[1,n]$, such that the optimal solution is to put all the weight of $x$ and $y$ on some $i$.
That is, let $x_i=y_i=\pm 1$, and put $0$ on the remaining coordinates.
I believe this is known as a ''bang-bang'' solution.

I can prove the conjecture for $z$ close to $0$:
Using a Taylor expansion
$$
\frac{1-P(z)^2}{P'(z)^2}
=\frac{1-P(0)^2}{P'(0)^2} + O(z)
=\frac{1}{(x_1y_1)^2} + O(z),
$$
it's clear that in the case $z=0$ we should put all the weight on the first two coordinates.
Numerically I have verified the conjecture for many other choices of $z$ and $n$, but I barely know where to start for the proof.
Update:
By the suggestion of Michael Grant we can define
$$
f_z(w) = \sum_{i=1}^n z^i w[i]
\quad\text{and}\quad
\bar{f_z}(w) = \sum_{i=1}^n i z^{i-1} w[i],
$$
and the problem then reduces to showing that the function
$$\frac{\bar{f_z}(w)^2}{1-f_z(w)^2}$$
is convex in $w\in\mathbb R^d$, such that $\|w\|_1\le 1$.
Numerically I have verified this is true for $n$ up to 4.
Update 2:
For any $\alpha\ge 0$, the set of $w$ such that
$\frac{\bar{f_z}(w)^2}{1-f_z(w)^2}\le \alpha$
is the same as the set such that
$\bar{f_z}(w)^2+\alpha f_z(w)^2\le \alpha,$
which is clearly convex, as the function $\bar{f_z}(w)^2+\alpha f_z(w)^2$ is a positive sum of convex functions.
That shows $\frac{\bar{f_z}(w)^2}{1-f_z(w)^2}$ is quasi-convex, which should be enough to prove the original conjecture!
Comment: The notation is a little confusing. You want to minimize $\frac{1-P(z)^2}{P'(z)^2}$ with respect to $x$ and $y$ on the sphere, for a fixed $z$?
Comment: @angryavian You are right. I've updated the statement. Michael Grant, you are right, except the functions are squared.
Comment: Since $x$ and $y$ only appear in product form, I would replace them with a single variable $w$. Then examine the set $\{w\,|\,w_i=x_iy_i,~i=1,..,n,~\|x\|=\|y\|=1\}$ and see if that gets you some insight.
Comment: (That's not a hint, it's a suggestion :-))
Comment: How is this an optimal control problem?
Comment: @MichaelGrant Can we say anything about the shape of this set? I've updated with a proof for the $x=y$ case, which uses that the variable set is convex in this case.
Comment: I don't think it's convex in the $x=y$ case, because $\|x\|=1$ is not a convex set, but $\|x\|\leq 1$ is. However, if you go back to my $w$ variables, it's easy to get $w=0$ if $x$ and $y$ or orthogonal to each other. So maybe the $w$ set is convex.
Comment: I think it's quite possible that the $w$ set is an $\ell_1$ norm ball.
Comment: @MichaelGrant I think you are right! One side follows from Cauchy Schwarz, and surely the interior values are achievable. Combined with the "one variable convexity proof" I believe that completes the proof! If you want to add it as an answer, I will mark it as accepted.
Comment: It's OK, go for it!
Comment: I tend to be skeptical of convexity of functions that are not obviously so. There's a lot of wishful thinking that takes place about convexity
Comment: @MichaelGrant Thinking more about it, it's actually the multiplicative inverse of the function I need to be convex, and numerically that appears to be true. Then it's just the question of how to prove it...
Answer:
Lemma: For $n\ge 2$, let $v\in\mathbb R^n$ be a vector with $\|v\|_1\le 1$, then there exists $x,y\in\mathbb R^d$ with $\|x\|_2=\|y\|_2=1$ such that for all $i\in[n]$, $v_i=x_iy_i$.

Proof: We prove the lemma by induction.
For $n=2$ let $x=(\alpha,\sqrt{1-\alpha^2})$ and $y=(v_1/\alpha, \text{sign}(v_2)\sqrt{1-(v_1/\alpha)^2})$.
For $|\alpha|\le|v_1|$ these are unit vectors with $x_1 y_1=v_1$.
We further need $(1-\alpha^2)(1-(v_1/\alpha)^2)=v_2^2$.
This has a solution exactly when $d=(1+v_1^2-v_2^2)-4v_1^2\ge 0$, which is equivalent with $|v_1|+|v_2|\le 1$.
Then $\alpha^2 = ((1+v_1^2-v_2^2)-\sqrt{d})/2\le v_1^2$, which is what we needed.
For $n>2$ let $x_n=\sqrt{|v_n|}$ and $y_n=\text{sign}(v_n)\sqrt{|v_n|}$.
Let $s=\sqrt{1-|v_n|}$.
By induction (and scaling) there exists vectors $\bar{x},\bar{y}\in\mathbb R^{n-1}$ with $\|\bar{x}\|_2=\|\bar{y}\|_2=s$ such that $\bar{x}_i \bar{y}_i=v_i$ for all $i\in [n-1]$, as long as $\sum_{i=1}^{n-1} |v_i|\le \|\bar{x}\|_2\|\bar{y}\|_2=s^2$.
In our case we have $\sum_{i=1}^n |v_i|\le 1$ so $s^2=1-|v_n|\ge \sum_{i=1}^{n-1} |v_n|$, which completes the proof.

Combined with Cauchy-Schwarz we have proven Michael Grant's conjecture that $\{v : v_i=x_i y_i, i=1\dots n, \|x\|_2=\|y\|_2=1\}$ is exactly the $\ell_1$ ball.
Combined with the proof of convexity of the function given in the question update, we have a complete proof.


How to determine relationship categorical and numerical data

Question: I have two data frames and I would like to determine correlation or another type of relationship between them.
The first data frame is consumption of soft drinks weekly (in liters).
Soft drinks consumption

ID  WEEK1   WEEK2   WEEK3 ......  WEEK 28
1   1.8     2       2.5   ......  5
2   0.7     0.3     0.5   ......  1
.
.
.
1108 1      2       3    ......   1

So I have liters of soft drinks consumed on sample of 1108 people.
Than I have data frame that shows that a same person had an infection in actual week.(1 is infection, 0 no infection)
Infection
ID  WEEK1   WEEK2   WEEK3 ......  WEEK 28
1   1       0       0     ......  1
2   0       0       0     ......  0
.
.
.
1108 1      0       0    ......   0

Could you suggest me some method, test or type of linear regression, which I could use to determine relationship between consumption of soft drinks and infections?
I would like to use R software, so if you could suggest and methodology I would very appreciate that.
Comment: This looks like a time series problem. What you could try is to predict infection/no infection using a logistic regression and t-1, t-2, t-3, etc drinks consumption as features.
Comment: See https://stats.stackexchange.com/questions/102778/correlations-between-continuous-and-categorical-nominal-variables
Answer: You could build what is known as a classifier. Predict 'Infection' from 'Consumption'.
In statistics, we use a capital letter $P$ for probability, as your prior. For probability densities a small letter $p$ is used. Bayes rule is what you should basically compute:
$
\begin{split}
P(Infec \mid Cons) =&
&\frac{p(Cons \mid Infec) P(Infec)}{p(Cons \mid Infec) P(Infec) + p(Cons \mid \neg Infec) P(\neg Infec)}
\end{split}
$
Here, the density $p(Cons \mid Infec)$ can be the normal distribution of Comsumption for the infected cases, the density $p(Cons \mid \neg Infec)$ can be the normal distribution of Comsumption for the cases without infection. The terms $P(Infec)$ and $P(\neg Infec)$ are the prior probabilities of being infected, or not.
The densities may be normally distributed, or follow a different continuous distribution. You can perform a discriminant analysis in the software R, in order to make these calculations. The better the predictions (the accuracy) the stronger the relationship between your two variables.


PHP: preg_match & explode to get some random code from url

Question: I want to get some random code from URL beginning with some word (d_ and r_)
Example:
 1. domain.com/index/book-one-d_123456
 2. domain.com/index/book-one-r_123456

I want to show if the link is "d_123456" show content for "d_123456" and if "r_123456" show content for "r_123456". And explode random code after "d_" or "r_".
I have tried with:
if ($co){
$rand = explode('/',$co);

if (preg_match('/^.*([d_]).*?$/i', $rand[1]))
{
$res = explode("d_",$rand[1]);
some code..........
{
else if (preg_match('/^.*([r_]).*?$/i', $soid[1]))
{
$res = explode("r_",$rand[1]);
some code..........
}

I can get random code from "d_" but I can't get it working for "r_" or seems not detecting.

for I'm sorry I posted to early and Thanks for your help guys :D
already found a solution from this post : https://stackoverflow.com/a/4366744/5118751
I just change :
if ($co){
$rand = explode('/',$co);

if (preg_match('/d_/', $rand[1]))
{
$res = explode("d_",$rand[1]);
some code..........
{
else if (preg_match('/r_/', $soid[1]))
{
$res = explode("r_",$rand[1]);
some code..........
}

and now everthing working perfect ...
Comment: But `$rand[1]` is going to be `index` which is not the delimiter you're looking for. Use `$rand[2]`.
Answer: I'm not sure if this is what you are looking for - the regex is quite crude.
$urls=array(
    'domain.com/index/book-one-d_123456',
    'domain.com/index/book-one-r_123456'
);

$pttn='@(.*)(d_(\d+))|(.*)(r_(\d+))@i';
foreach( $urls as $url ){

    preg_match( $pttn, $url, $matches );
    $matches=array_filter( $matches );
    if( !empty( $matches ) )print_r( array_values( $matches ) );
}

Will output:
Array
(
    [0] => domain.com/index/book-one-d_123456
    [1] => domain.com/index/book-one-
    [2] => d_123456
    [3] => 123456
)
Array
(
    [0] => domain.com/index/book-one-r_123456
    [1] => domain.com/index/book-one-
    [2] => r_123456
    [3] => 123456
)

From the output you can decide which items you wish to process further...
Answer: Given your example URLs, $rand[1] is going to be index which is not the delimiter you're looking for. Use $rand[2] instead of $rand[1].
Answer: I personally hate regex, so I believe there is a lot simpler way of doing what you need to do!
<?php
$url='domain.com/index/book-one-r_123456';
$ex=explode('_',$url);
    if(substr($ex[0],-1)=='d') { //checking if last letter is d
        //do some code, random code is $ex[2];, letter is d
    } elseif(substr($ex[0],-1)=='r') { //checking if last letter is r
        //do some code, random code is $ex[2]; letter is r
    }
?>

Good luck!
Comment: @mario heh, maybe it is! I always had problems with that regexes, so I prefer using this instead :)


Event triggered by condition

Question: I inserted a condition in the event window , this conditions refers to a variable in  my main agent. I dont't understand why the condition is not evaluated by the event . I searched on the help and it suggest to use the onChange function , but i can't understand where and how to use it.
Thanks
Comment: It is generally advisable to stay clear of condition-triggered events and statechart transitions. They are intuitive to understand but can be a pain to ensure they work. And very hard to debug. Luckily, you can *always* reformulate the problem using messages or similar.
Comment: Thank you Benjamin !!
Answer: The onChange is used to make sure the condition is evaluated when it needs to in case AnyLogic missed it, since AnyLogic does not evaluate the conditions every moment in time, instead, it just evaluates them at important time steps.
So, where to put onChange() depends on what your condition is. For example, if you condition is having a queue length of say 10, then I would add the onChange() function on the "On Enter" and "On Exit" of the queue, so that each time an agent enters or leaves the queue, the condition is evaluated.
So again, where to use onChange depends on what your condition is. If this doesn't help, feel free to provide more details on what your condition is.
Comment: Thank you  !! I ' ve decided to avoid the event triggered by condition , I' ve used other tools to achieve the same purpose.

Event triggered by condition


How do you rotate the text in textblock in C# (Code-Behind)~~

Question: Basically I am currently doing final year project in my college whereby i am touching on surface 2.0 WPF.
My project is a game whereby if a user answer a question wrongly,the next question will be rotated to make it more difficult. But I am unsure how to do it. I saw an example in msdn microsoft but it only shows XAML codes. I need the C# codes.
Here's the XAML example.
http://msdn.microsoft.com/en-us/library/ms754028.aspx
The last example
Here's part of my validation codes. I need to activate the animation if user answer wrongly.
 if (surfaceRadioButton1.IsChecked == true)

{

user_answer = (string)surfaceRadioButton1.Content;

            textBlock2.Text = validateAnswer(user_answer, answer);
            retreiveYellowQns();
            if (textBlock2.Text.Equals("Correct"))
            {
                yellow_coord = yellow_coord + 50;
                Canvas.SetLeft(car, yellow_coord);
                Canvas.SetTop(car, 289);
            }
            else
            {
                if (yellow_coord <= 330)
                {
                    yellow_coord = 330;
                    Canvas.SetLeft(car, yellow_coord);
                    Canvas.SetTop(car, 289);
                }
                else
                {
                    yellow_coord = yellow_coord - 50;
                    Canvas.SetLeft(car, yellow_coord);
                    Canvas.SetTop(car, 289);
                }
            }
        }

Any Help will be glad,thanks in advance.
Answer: Try this one. You can use an animation on the RenderTransform:
var rotateAnimation = new DoubleAnimation(0, 180, TimeSpan.FromSeconds(5));
var rt = (RotateTransform) textblock2.RenderTransform;
rt.BeginAnimation(RotateTransform.AngleProperty, rotateAnimation);

In your Xaml, you can add the RotateTransform:
<TextBlock>
  <TextBlock.RenderTransform>
    <RotateTransform Angle="0"/>
  </TextBlock.RenderTransform>
</TextBlock>

Comment: So should i put that code inside the                                else
                {
                    yellow_coord = yellow_coord - 50;
                    Canvas.SetLeft(car, yellow_coord);
                    Canvas.SetTop(car, 289);
Comment: Yes, put this code to the lines where your text should be rotated (Error validation -> error case) .This will animate your text to be rotated with 180 degrees within 5 Seconds. This will give the user a better visual feedback that it is rotated.
Comment: Thanks,it works. Just one last question. How do i forcefully terminate the animation once the user answer the next question correctly?
Comment: You'll have to wrap your Animations within a BeginStoryboard. Once you've given this Storyboard a name, you can call StopStoryboard with the given name in your "CorrectAnswer" - Handler. Check out this one: http://stackoverflow.com/questions/5863722/combining-wpf-datatriggers-and-storyboard-in-code
Answer: You will have to use Transformation for this. Try this answer https://stackoverflow.com/a/8815374/293712
Or You can also try, (I have not tried this) Look at this article for more details
textBlock2.RenderTransform = new RotateTransform(IntegerAngleValue);

Comment: Works like a charm in Winforms! Thank you, this solved my problem.
Answer:             var rotateAnimation = new DoubleAnimation(180, 0, TimeSpan.FromMilliseconds(200));
            UiImage.RenderTransformOrigin = new Point(0.5,0.5);
            UiImage.RenderTransform = new RotateTransform();
            var rt = (RotateTransform)UiImage.RenderTransform;
            rt.BeginAnimation(RotateTransform.AngleProperty, rotateAnimation);


Launching a PHP daemon from an LSB init script w/ start-stop-daemon

Question: I'm writing an lsb init script (admittedly something I've never done from scratch) that launches a php script that daemonizes itself.  The php script starts off like so:
#!/usr/bin/env php
<?php
/* do some stuff */

It's then started like so in the init script:
# first line is args to start-stop-daemon, second line is args to php-script
start-stop-daemon --start --exec /path/to/executable/php-script.php \
  -- --daemon --pid-file=$PIDFILE --other-php-script-args

The --daemon flag causes the php script to detach & run as a daemon itself, rather than relying on start-stop-daemon to detach it.
This is how it's (trying to) stop it in the init script:
start-stop-daemon --stop --oknodo --exec /path/to/executable/php-script.php \
  --pidfile $PIDFILE

The problem is, when I try to stop via the init script, it gives me this:
$ sudo /etc/init.d/my-lsb-init-script stop
 * Stopping My Project
No /path/to/executable/php-script.php found running; none killed.
   ...done.

A quick peek at ps tells me that, even though the php script itself is executable, its running as php


Pass variable from one php file to another

Question: I am currently in file1.php and I want a variable from file1.php to pass to file2.php
How do I pass a variable from one php file to another?
I too want to go from file1.php to file2.php
I did following in file1.php:
session_start();
$_SESSION['akknum']="jkl";
header("Location: file2.php");

and did following in file2.php :
    <?php
    echo "abc";
    echo $_SESSION['akknum'];
    ?>

The file2.php is opening and abc is printing but no value of "jkl" is printing. What am I doing wrong?
Comment: is $_SESSION a must or could you use GET and POST?
Comment: No it's not,nothing must in $_SESSION
Comment: is that case, depending on the way your visitors surf from file1.php to file2.php, you could use $_GET parameters in a link for example: `Link to file2.php`
Answer: You need to add session_start(); in file2.php.
session_start();
echo "abc";
echo $_SESSION['akknum'];

Basic usage.
Comment: Won't super global variables reset when starting a new session?
Comment: You don't start a _new_ session. If you send the same SID, you continue to use the same session data. But if you don't start the session, `$_SESSION` will be always an empty array.
Answer: you need to session_start the second file too.
Answer: If you want to use $_SESSION on a different file,  you'll need to call session_start();
file1.php
<?php
session_start();
$_SESSION['akknum']="jkl";
header("Location: file2.php");
?>

file2.php
<?php
session_start();
echo $_SESSION['akknum'];
//jkl
?>

Read more about php sessions


Question on the interpretation of the predicted results

Question: I would like to understand something that is bothering me. Suppose you have a dataset and a probabilistic model that depends on few parameters $\alpha, \beta  $ etc, and suppose that you find an estimate of these parameters through an MCMC sampler. Such sampler will find the values of the parameters with the highest probability together with an estimate of the uncertainty. In other words, from what I understood, MCMC methods find the configuration that maximize the posterior distributions of the parameters. Now suppose you use a neural network trained through the maximum likelihood method to extend the number of points of your dataset to build up an augmented dataset that extend in an area where the original dataset did not cover. If you apply again the MCMC method with the same model as before, will you get an estimate close or at least compatible with the original dataset or the neural network has the ability to learn a hidden pattern that may cause the likelihood to change and thus, once we apply again  the MCMC method over the extended dataset, leading to  a different set of values of the original parameters?
Answer:
MCMC sampler will find the values of the parameters with the highest
probability together with an estimate of the uncertainty. In other
words, from what I understood, MCMC methods find the configuration
that maximize the posterior distributions of the parameters.

This is not correct. An MCMC sample produces a sample of parameters values (approximately) distributed from the posterior distribution, with obviously a proportion of likely values larger than the proportion of unlikely values. But there is no immediate derivation of the highest posterior (density) value of the parameter or posterior mode. Instead, the sample is treated as an actual simulation from the posterior distribution whose (e.g.) mean and variance can be derived.

you use a neural network trained through the maximum likelihood method
to extend the number of points of your dataset to build up an
augmented dataset that extend in an area where the original dataset
did not cover.

It is unclear (to me) what you mean by this as, in general, learning the distribution of the data leads to a predictive that covers the same area, unless constraints are introduced. The answer to the question thus requires much more detail on the construction and purpose of this neural network.


How do I set an SVG element to my page's favicon?

Question: I have an SVG element on my page. I want to use it as the page's favicon. How do I do this in JavaScript?
Answer: Doing this is astoundingly convoluted. You can see my solution in action here: the methodology is described below (getting the HTML elements, by ID or otherwise, is left as an exercise for the reader).
In the HTML

Make sure your SVG element includes the attribute xmlns="http://www.w3.org/2000/svg", as you're going to need to take the source of the element as its own file, and the XMLNS declaration is required for standalone SVG files. (Also note that this means your SVG will need to be self-contained and can't refer to elements in its parent document with something like <use>.)
Optionally, wrap the element in a
 or , which you may use to get the content of the <svg> element using .innerHTML. (Neither the innerHTML nor the outerHTML attributes are present on SVG elements in the current HTML standard.)
Include a <link rel="icon"> in your page's .

In JavaScript

Get the source of the SVG element you want to set as your favicon by getting the innerHTML attribute of the HTML element you've wrapped it in, or by calling new XMLSerializer().serializeToString() on the SVG element.
Create a DataURL for this element as a document by prepending the string "data:image/svg+xml," to the source. (If most browsers supported SVGs for favicons, we'd be done here, but since, at time of writing, they don't, we must go deeper.)
Create an  element that you'll be routing the image through, add an event listener to it for the load event that will draw the image once control returns to the event loop (as spec-compliant browsers won't let you read the image synchronously - see this crbug), and set the DataURL of your SVG source as its src attribute. (The steps between this and step 8 can happen either in sync now, or as part of the listener callback; they just need to happen before you draw the image.)
Decide what resolution you want to render your favicon to - My examples will use 64x64, for compatibility with high-DPI (Retina and Super Retina) displays.
Create a <canvas> element (heretofore referred to as canvasElement) and set its dimensions (by setting canvasElement.width = 64 and canvasElement.height = 64).
Create a drawing context for the canvas using canvasElement.getContext('2d') (heretofore referred to as ctx).
If you're re-using a canvas you've created beforehand, set ctx.globalCompositeOperation = "copy", or clear it with ctx.clearRect(0, 0, 64, 64).
Somewhere in the execution sequence following from the load listener you added to the  element you created in step 3, draw the image onto the canvas using ctx.drawImage(svgImg, 0, 0, 64, 64) (where svgImg is the  element you set the src to the SVG DataURL).
Create a PNG DataURL from the canvas using canvasElement.toDataURL(), and set that to the href attribute of the <link rel="icon"> element in your HTML.
Comment: Also, you currently need to make sure there are `width` and `height` attributes specified on your `` element, due to https://crbug.com/475009.
Comment: It may also be faster to make a Blob for the canvas using [toBlob](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob), saving the Base64-encoding step.
Comment: Which browsers does this support?
Comment: This *should* work in all current browsers (supporting Canvas, drawImage, and toBlob and/or toDataURL), and at time of writing, it did; however, this appears to be currently broken in Chrome due to [a pretty nasty regression bug](https://bugs.chromium.org/p/chromium/issues/detail?id=755366).
Comment: @ElliotLabs I've updated the post to fix the part that relied on out-of-spec behavior (which triggered the bug I linked in above when Chrome fixed their spec compliance): the procedure described here should work in all modern browsers.
Comment: For older browsers that weren't as consistent in their image loading behavior, you should follow the behavior I describe in step 3 of https://stackoverflow.com/a/34440779/34799 to sniff out whether they make the image accessible synchronously or not.
Answer: I have tried and this worked for me:
<link rel="shortcut icon" href="favicon.svg" type="image/svg">

Change the type="image/x-icon" to type="image/svg".
Answer: I know its already answered but It too much work for such a simple task just store your svg in a svg file and use it as favicon in Head Tag.
<link rel="shortcut icon" href="favicon.svg" type="image/x-icon">

Comment: Even in 2021 support isn't uniform across the different browsers - https://caniuse.com/link-icon-svg
Comment: Yes, its major problem in mobile browsers , this causes ugly UI
Comment: type="image/x-icon" is NOT CORRECT for svg images. One should either remove the incorrect type or replace it with ```type="image/svg"```


Node export module imported node as another node numbers

Question: I used Node Export module to export my nodes.
I exported 3 articles that are node/1, node/2 and node3.
While I imported it into another site, the node became node/4, node/5 and node6.
How do I make it imported as the same node number.
If there is already have that node, it will override it.
Drupal 6
Settings:
Node export
When importing a node that already exists: Create a new revision of the existing node
UUID
Automatic UUID generation for taxonomy:
Answer: You can't, and you shouldn't.
Node Export requires UUID for a reason, and that reason is decoupling database identifier of a node (nid) from it's logical identifier and address. These are supposed to be defined by UUID now, so if you are using UUID module and still have addresses like http://example.com/node/1 then your site is not using modules in a way they are designed to work.
Also, as Node Export project page says, if you need anything fancy on import, you should export in Feeds format, and use Feeds for import. I believe that updating existing nodes is a case where it would be recommended approach.
Comment: How do I export in Feeds format and use Feeds for import?


Colocar input radio disable

Question: Tabela dentro do While para criar a tabela com inputs radio dinâmico:
$y = 0;
while($rows_cursos = mysqli_fetch_array($resultado_cursos)) {
$tabela1 .= '
';
$tabela1 .= ' <input type="text" readonly="true" size="20" name= "Produto['.$y.']" class= "Produto" value="'.$rows_cursos['Descricao'].'">	';
$tabela1 .= ' <input type="radio" name= "Sim['.$y.']" value="Ok" required>	';
$tabela1 .= ' <input type="radio" name= "Sim['.$y.']" value="Não Ok" required>	'
$tabela1 .= ' <input type="radio" name= "DataP['.$y.']" value="Ok" required>	';
$tabela1 .= ' <input type="radio" name= "DataP['.$y.']" value="Não Ok" required>	';
$tabela1 .= ' <textarea type="text" class= "Observacao" name="Observacao['.$y.']" rows="2" cols="30"></textarea>	';
$tabela1 .= '
';
$y++;
}

Mostro na imagem a tabela montada:

Pretendia que nas linhas onde retorna os produtos rodeados a vermelho bloqueasse os inputs radio também rodeados a vermelho, para não ser obrigatório preencher.
Comment: Qual é a condição para identificar os registros destacados? E você precisa bloquear ou deixar opcional?
Comment: @Anderson Carlos Woss, preciso mesmo de bloquear. A condição é, as linhas com os  seguintes produtos(x,x,x,x,x), bloqueia os input radio com o name=DataP.
Answer: Você pode usar um operador ternário preenchendo uma string com o valor required por padrão, mas com o valor disabled quando os campos forem os que você quer desabilitar.
$y = 0;
while($rows_cursos = mysqli_fetch_array($resultado_cursos)) {

$property = ($rows_cursos ["Descricao"]==="x" || $rows_cursos ["Descricao"]==="x2")? "disabled" : "required";

$tabela1 .= '
';
$tabela1 .= ' <input type="text" readonly="true" size="20" name= "Produto['.$y.']" class= "Produto" value="'.$rows_cursos['Descricao'].'">	';
$tabela1 .= ' <input type="radio" name= "Sim['.$y.']" value="Ok" required>	';
$tabela1 .= ' <input type="radio" name= "Sim['.$y.']" value="Não Ok" required>	'
$tabela1 .= ' <input type="radio" name= "DataP['.$y.']" value="Ok" '.$property.'>	';
$tabela1 .= ' <input type="radio" name= "DataP['.$y.']" value="Não Ok" '.$property.'>	';
$tabela1 .= ' <textarea type="text" class= "Observacao" name="Observacao['.$y.']" rows="2" cols="30"></textarea>	';
$tabela1 .= '
';
$y++;
}

Talvez você possa trocar o campo $rows_cursos["Descricao"] por algo como $rows_cursos["Id"], mas como não sei a estrutura coloquei $rows_cursos["Descricao"] mesmo.

Colocar input radio disable


How can I get and process a response from a PHP API

Question: Ok I will try and keep this short. I'm making a request to a simple PHP API which can be done by AJAX through Javascript or JQuery, however I want to make the request using PHP. What is the best way to do this? Using the file_get_contents() function or CURL? If so how do I do it through CURL as the API requires I use GET not POST. Also the response I know is in XML, how do I then process the response once it comes back?
This question may have been asked many times, however when reviewing a lot of the questions and answers they are not specific to my needs on this one so please no answers with "Please see this link" as I can guarantee it won't answer the question in full as a lot of them are making requests from either Facebook API or another API that does not do what the API I am using does.
Comment: http://php.net/manual/en/book.curl.php
Answer: <code>function  getXML()
{

 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, "http://127.0.0.1/index.html");
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 curl_setopt($ch, CURLOPT_USERPWD, "user:password");
 curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
 $res = curl_exec($ch);

 return  $res;

}

    $xml_data = getXML();

    $doc = new DOMDocument();
    $doc->loadXML($xml_data);

    $wms = $doc->getElementsByTagName('WowzaMediaServer');

    $wmstotalactive = $wms->item(0)->getElementsByTagName("ConnectionsCurrent")->item(0)->nodeValue;
    $wmstotaloutbytes = $wms->item(0)->getElementsByTagName("MessagesOutBytesRate")->item(0)->nodeValue;
</code>
so you extracted from xml the value from ConnectionsCurrent key and MessagesOutBytesRate
.
If your link  does not need to auth remove :
curl_setopt($ch, CURLOPT_USERPWD, "user:password");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);


Is this a form of cadence?

Question: I had to harmonize a piece in E major with a given melody. The image below shows the end of the piece, with my harmonization.
Normally, I would write the first beat of the second-to-last bar as B in the bass, B in the tenor, D# in the alto, and F# in the soprano, i.e. the Vth chord of E major.
But, does it make any sense to write the chord depicted in the image, instead of the standard V chord? Does it have a name? To my ear, it sounds like a cadential 6/4 chord, but I think it's not, since it contains F# and not G#. Can I have this form of cadence, or, is this a way to end the piece?
Thank you in advance, and have a happy New Year!
Answer: What you wrote is a perfectly good cadence.
I would describe the E simply as an accented passing-note in the alto between the F# and D#. The Wikipedia definition is

A passing tone (PT) or passing note is a nonchord tone prepared by a
  chord tone a step above or below it and resolved by continuing in the
  same direction stepwise to the next chord tone (which is either part
  of the same chord or of the next chord in the harmonic progression).

It does sound a bit like a 6/4 chord - but there is nothing wrong with writing a harmonic progression which creates a sense of ambiguity for the listener, and then resolves it.
Others may want to call it a suspended 4th chord (even though the E isn't a suspension because it isn't the continuation of an E at the end of bar 1) or a dominant 11th. But if you wrote it because it sounds right, that's more important than giving it a pedantically correct name!
Whether you are "permitted" to do such a thing if you want full marks in an exam is a different issue, of course. "Passing music exams" and "writing music" are not necessarily the same thing!
As a very minor point, it would be more usual to write the F# in the top part as a single dotted-whole-note, not as you did. Most music notation software should be able to handle three "voices" or "layers" with independent rhythms on one stave.
Comment: I tend to agree - accented passing tone it is. The penultimate bar is really just a decorated dominant seventh. The OP could have easily interpolated a G♯ in the descant above the E to make a second inversion tonic chord, so he is right in that what he has done here is much akin to the second inversion: the skip to a second between the descant and alto is perhaps a bit bolder.
Comment: Yup, but how easily the G♯ can be fitted in shows how closely akin to I 6/4 - V7 - I the OP's writing is here (which was the point I was trying to make). I was essentially confirming OP's suspicions about that.
Comment: @Patrx2 "The OP could have easily interpolated a G♯ in the descant above the E" - except that he/she was "harmonizing a given melody", not "composing" ;)
Answer: I think what you want is a note of anticipation in the First beat of that second bar, you are just going about it a little bit wrong. Have your full chord and just go the F sharp on the weak part of the pulse in the manner of a non-chordal note.
Your chord choices are good. You have a Tonic 6/4 going to a Dominant chord with the use of a seventh. Your voice leading just needs to be a little bit better.
This also seems to be a great place to have your Leading Tone note drop by a third. It looks like that will improve the voices tremendously. Remember that in a cadence at the end of a piece the Leading Tone note can drop by a third as long as it features in the Alt or Tenor voices (Not in the outer voices.)
So rather this.
Answer: Shall we call this an 'unprepared suspension'?  Or an 'accented passing note'?  It gives a satisfing alto line, which is probably more important than vertical analysis.  Plenty in common with a cadential 6/4 indeed.

Is this a form of cadence?


using NTP protocol for internal time synchronisation

Question: I have two embedded system that are connected via ethernet. I want them to run synchronously. Using NTP protocol is an option to synchronize them. But this is a isolated system. I don't have an Internet connection. Is it possible to use ntp protocol locally. One of my system will be the master and the other one will be slave.
Kind regards...
Answer: Yes. You need a NTP server on the local LAN. There's two things here - accurate time (e.g. the time is actually correct) and time sync (they all have the same time, whether correct or not).
If you just need the systems to simply be in sync, to agree on what the time is even if they're not using the correct time, you can just install a cheap box with your favourite Linux distro, configure it to act as a time server (example) and tell both these embedded systems to use that as their time source.
If you need accurate time then you need a GPS or radio time clock, which will set time to an external source without needing an Ethernet connection. This is the one I use, for example, but there are others out there.
Comment: @symcbean, This is an embedded system so that I'm able to use only two 600-800Mhz embedded single board computer becouse of system limits. I'm going to use a RTOS like QNX, VxWorks or RTLinux. Would it be use too much resource if I install ntpd to one of my boards? What whould you do?
Comment: @zontragon I think you'd have to test the workload on the system introduced by adding ntpd - this is why i'd favour using a 3rd box (heck it can be something small like a raspberry pi) to handle this kind of misc 'admin' work precisely to keep it off your embedded devices. If they need to use a RTOS then it follows that the extra workload and extra risk of the ntpd process hanging aren't trivial matters in your case in the way they are for most of us working with 'conventional' servers. It might also be that the RTOS implementations of ntpd only function as clients, not servers.
Answer: Even on a single machine which only has intermittent access to a higher stratum time server, NTP can keep the clock correct by tracking the drift of the system clock from actual time (and applying adjustments). It just needs to be connected some of the time so it can learn what the drift is (drift may vary depending on other factors such as ambient temperature, battery status etc, which NTP can't account for).
In your case, with 2 machines, it's perfectly pssible to have one machine taking it's timestamps from another machine - but both machines will become increasingly out of sync with real time.
You can get cheap radio clocks and GPS dongles which will provide accurate time measurement readable by your computer (which with NTP you'd only need to provision on a single system).


Código a funcionar a determinada hora

Question: Eu gostaria de saber como coloco para um código estar ativo entre determinadas horas, que neste caso seria entre as 7h e as 22h do fuso horário Brasília.
Tentei estudar este que já contém essa função, pórem não entendi:
          var horaAtual = (new Date()).getHours();
          var imagem = "";
          if(horaAtual >= horario_inicio["manhã"] && horaAtual < horario_inicio

["tarde"]){
              imagem = imagens["manhã"];
          }else if(horaAtual >= horario_inicio["tarde"] && horaAtual <

horario_inicio["noite"]){
              imagen = imagens["tarde"];
          }else if(horaAtual >= horario_inicio["noite"] || horaAtual < horario_inicio

["manhã"]){
              imagen = imagens["noite"];
          }

          if(imagem_se_repete){
              jQuery(seletor_css).css("background", "url(" + imagem + ") repeat");
          }else{
              jQuery(seletor_css).css({"background-image":"url(" + imagem + ")",

"background-repeat":"no-repeat", "background-size":"cover"});
          }
    });

O código em que quero colocar horário de funcionamento é o seguinte:
$(function() {
$(".post").each(function() {
    if (_userdata.user_level == 2 || _userdata.user_level == 1) {
    return;
    }
if($('.pathname-box:contains(Tarefas), .pathname-box:contains(Redações)').length > 0) {
    var username = _userdata.username;
    if ($(this).has('.staff').length) {
    return;
  }
    if($(this).html().indexOf(username) <= 1) {
          $(this).remove();
    }
    if($(this).html().indexOf(username) >= 1) {
          $(this).remove();
    }
}
    });
    });

Answer: Com Javascript ? É simples:
Peguei apenas as horas e verifiquei se ela se encaixa no horário citado, dentro do if é so colocar a função que você deseja executar.
Exemplo 1:

var d = new Date();
var hora = d.getHours();
if (hora >= 7 && hora <= 22) {
  document.getElementById("demo").innerHTML = hora + ' horario atual';
}

Se você não sabe que horas são para executar a função, você pode usar setInterval() para chamar a sua função que valida o horario e faz o que você precisa.
Exemplo 2:

function validaHorario() {
  var d = new Date();
  var hora = d.getHours();
  if (hora >= 7 && hora <= 22) {
    alert(hora + ' horario atual');
  }
}

setInterval(function() {
  validaHorario()
}, 298000); // executa a função validaHorario() de 5 em 5 min
Comment: Esta correto, só como o AP comentou ele gostaria no horário de brasília, e a função `getHours()` trabalha com a hora local. Ou seja pode haver discrepância, para isso deve se usar `getUTCHours()` que retorna o hora universal, contudo para isso o AP tera que levar em consideração esta diferença em seu horaria também.
Comment: Deu o seguinte erro: Uncaught SyntaxError: missing ) after argument list   / código que estou a utilizar: http://pastebin.com/sD7Y49Ef
Comment: @MaradinhoPH o problema esta no seu console.log você esta passando string sem aspas e não esta concatenando
Comment: ops! não reparei nesse pormenor. tudo okay! obrigado.

Código a funcionar a determinada hora


Get all the orders with filter[limit] rerturns an error WooCommerce REST API

Question: I'm creating a list table in WordPress and I want to fetch the cancelled orders, but I want to fetch all, not for tens.
This is my code:
<code>$pedidos = $wc_api -> get_orders( array( 'status' => 'cancelled'), 'filter[limit]' => 100000 );
</code>
I'm trying to set a big number (following MySQL limit theory) as the parameter for filter to fetch all the rows, but this doesn't work.
Is this actually possible?
Answer: I got it!
The problem was caused because recently I changed the taxonomy for all the products and some products related with cancelled orders do not update their name. So when the API call looked for the name of a product inside a cancelled order do not found it and returns an error.
Simply I deleted all the cancelled orders with old product names and all works perfectly.


Duplicate data analysis using Unix shell

Question: I want to print or show only duplicate data between files. Suppose I have 3 files and their data are as follows:
file 1: man
file 2: man
file 3: female

I want to print using any shell script or awk command or any Unix shell command to show only duplicate data in the files. Like the word "man"" is duplicate in the files so i want only man to be printed on the screen. And when I do the analysis in any order like 1 2 3 or 2 3 1 or 1 3 2 only duplicate data should print on the screen.
Comment: Hint:-  awk 'FNR==NR{a[$1]++;b[$2]++;next} a[$1] || b[$1] {print $1} a[$2] || b[$2]{print $2}' 3 2 1 (but this is not printing the duplicate data when I am starting with 3), (it is printing duplicate data when I am starting with 1 or 2.
Comment: No this is not doing what i want. this is printing all the data from all the files..
Comment: After posting my answer I realize that your question is a bit ambiguous, do you only want to print duplicates shared among several files or should duplicate lines within the same file also be printed?
Comment: You haven't answered my question but I added another solution which only prints duplicate lines shared by at least two files nonetheless.
Answer: sort | uniq -c | awk '$1 > 1'

Comment: This will also print the count and thus skew the output which might or might not be a problem for OP. `uniq` comes with `-d` so there is really no reason to do it like that, but one could do the whole thing with *just* `awk` instead.
Answer: Testdata:
$ grep . file*
file1:man
file2:man
file3:female
file4:duplicate
file4:duplicate

Printing all duplicate lines
1. Using sort + uniq
$ cat file* | sort | uniq -d
duplicate
man

2. Using awk
$ awk '{a[$0]++} END{for (i in a) if (a[i] > 1) print i}' file*
duplicate
man

Printing only duplicate lines shared by two or more files
1. Using GNU awk 4+
$ cat t.awk
#!/usr/bin/awk -f

BEGINFILE { delete a }
{ a[$0]++ }
ENDFILE { for (i in a) b[i]++ }
END     { for (i in b) if (b[i] > 1) print i }

.
$ ./t.awk file*
man