Predicting a future data value with regression

Question: If I have a list of values throughout time, say a list of values for every minute throughout an hour of monitoring something, can I somehow 'predict' or estimate what the value would probably be in the future, say another 20-30 minute after my last known value?  And if so, how can this be done?
I figure maybe I could do it with just a 'best-fit' to a quadratic and look at the value for x=90 (60 known values + 30 values into the future) but I feel like that probably isn't going to be the most accurate method.  Does anyone have any suggestions for a better way to do this? Just a note, I do have very little statistical experience, so please bare with me if this question is known to be easy (or impossible).
Thanks!
Comment: This is a very general question that no one can answer without more information. It really depends on the nature of your data. Do you have a reason to believe that past behavior can predict future behavior? Do you have other variables you can use to help make predictions (for example, if you are trying to predict future temperature, knowing the pressure could help)?
Comment: Hm. The nature of the data tends to be mostly oscillating, but not entirely and not always. Sometimes it tends to be more linear. No, I don't really have any other variables that could be applied. Predicting this could just be too difficult...
Comment: Hey! did you find an answer to your question? I have the same doubt.
Answer: You might try using ARIMA models making sure that you incorporate any identifiable Level Shifts and/or Local Time Trends culminating in an ARMAX model. Changes in parameters/variance of the errors should also be tested and remedied if necessary. As compared to NN, these approaches challenge the data rather than simply believing/fitting the data.
Answer: Yes, the problem occurs in variety of scenarios for time series prediction thing.
But I would suggest to avoid going through quadratic analysis just by estimating that it might fit.
Go on hitting with Linear multivariate regression, further try a combinations of non-linear series. Plus I have also seen Certain problems of this sort like retweet prediction, stock prices predictions giving nearly accurate results with SOFNN- self of organizing fuzzy and neural network. Try scholar.google search, you would hit upon a previous good work on this.


Lua - "multiple vms detected" while trying to add extension for statically linked Lua

Question: I have application that contain statically linked lua 5.2 inteperpreter (and haven't access to code).
When I trying to write extension with next code:
<code>#define LUA_LIB
#define LUA_BUILD_AS_DLL
#include "lua.hpp"

extern "C"
{
    static int test(lua_State* state)
    {
        return 1;
    }

    static const struct luaL_Reg functions[] = {
        {"test", test},
        {NULL, NULL},
    };

    int __declspec(dllexport) luaopen_test(lua_State* state)
    {
        luaL_newlibtable(state, functions);
        luaL_setfuncs(state, functions, 0);
        return 0;
    }
}
</code>
And compile it with statically linked lua52.lib .
I get "multiple vms detected" error when I trying to require it fromn lua code.
What I can do in this situation?
Answer: You can't compile it with statically linked lua52.lib as the main application loads its own version of lua52.lib and when this module is "required", it loads its own copy, which leads to "multiple VMs detected" message.
With statically compiled VM you have two options (on Windows): (1) include all your modules statically, or (2) compile your modules against Lua52.dll, but instead of the actual DLL include a "proxy" DLL that will forward Lua API calls to the methods in the statically compiled executable (the API methods also need to be exported in the executable).
See this thread for the discussion on how the executable needs to be compiled and LuaProxyDllFour page for the proxy DLL.
On Linux you don't need to have a proxy library, but you still need to avoid linking Lua interpreter into the library and export symbols from the executable by using <code>-Wl,-E</code> linker option; see lhf's answer for details.


Replace text with URL in Word document using Open XML

Question: I have problems with a project where I want to replace som tagged text in a Word document with a clickable URL.
The sample code below uses a word document which only contains the text [Webpage].
Here is the code with the problem:
<code> Imports DocumentFormat.OpenXml
 Imports DocumentFormat.OpenXml.Packaging

 Public Class Form1
     Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

         MsgBox(processDocument("C:\temp\testdoc.docx", "[Webpage]", "Google", "https://www.google.com"), MsgBoxStyle.ApplicationModal + vbOKOnly, "Text replace test")

     End Sub

     Private Function processDocument(ByVal tDocFilename As String, ByVal tagText As String, ByVal replText As String, ByVal replURL As String) As String

         Using doc As WordprocessingDocument = WordprocessingDocument.Open(tDocFilename, True)
             Dim mainPart As DocumentFormat.OpenXml.Packaging.MainDocumentPart = doc.MainDocumentPart

             Dim textPLaceList As IEnumerable(Of Wordprocessing.Text) = mainPart.Document.Descendants(Of Wordprocessing.Text)()

             Try
                 For Each textPlaceHolder As Wordprocessing.Text In textPLaceList
                     Dim parent = textPlaceHolder.Parent
                     If (TypeOf parent Is Wordprocessing.Run) Then
                         If textPlaceHolder.Text.Contains("[") And textPlaceHolder.Text.Contains("]") Then
                             Dim tmpHyperlink As New DocumentFormat.OpenXml.Wordprocessing.Hyperlink
                             tmpHyperlink.Anchor = replText
                             tmpHyperlink.DocLocation = replURL
                             tmpHyperlink.InsertBefore(Of Wordprocessing.Hyperlink)(tmpHyperlink, textPlaceHolder.Parent)
                             textPlaceHolder.Remove()
                             Exit For
                         End If
                     End If
                 Next
                 processDocument = "OK"
             Catch ex As Exception
                 processDocument = "Could not replace text in document (" & ex.Message & ")"
             End Try

         End Using

     End Function

 End Class
</code>
When I try to use InsertBefore or InsertAfter I get an error telling me that the "state" och the object is incorrect.
What does that mean?
Regards Peter Karlström
Answer: This forum wasn't of much help.
After some digging I found the solution myself.
Here is how it was made:
<code>Imports DocumentFormat.OpenXml
Imports DocumentFormat.OpenXml.Wordprocessing
Imports DocumentFormat.OpenXml.Packaging

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        MsgBox(processDocument("C:\temp\testdoc.docx", "[Webpage]", "Google", "https://www.google.com"), MsgBoxStyle.ApplicationModal + vbOKOnly, "Text replace test")

    End Sub

    Private Function processDocument(ByVal tDocFilename As String, ByVal tagText As String, ByVal replText As String, ByVal replURL As String) As String

        Using doc As WordprocessingDocument = WordprocessingDocument.Open(tDocFilename, True)
            Dim mainPart As DocumentFormat.OpenXml.Packaging.MainDocumentPart = doc.MainDocumentPart

            Dim textPLaceList As IEnumerable(Of Wordprocessing.Text) = mainPart.Document.Descendants(Of Wordprocessing.Text)()

            Try
                For Each textPlaceHolder As Wordprocessing.Text In textPLaceList
                    Dim parent As Wordprocessing.Paragraph = textPlaceHolder.Parent.Parent
                    If (TypeOf parent Is Wordprocessing.Paragraph) Then
                        If textPlaceHolder.Text.Contains("[") And textPlaceHolder.Text.Contains("]") Then
                            Dim newParagraph As Paragraph = getURLParagraph(mainPart, replText, replURL)
                            parent.Parent.InsertBefore(Of Wordprocessing.Paragraph)(newParagraph, parent)
                            textPlaceHolder.Remove()
                            Exit For
                        End If
                    End If
                Next
                processDocument = "OK"
            Catch ex As Exception
                processDocument = "Could not replace text in document (" & ex.Message & ")"
            End Try

        End Using

    End Function

    Private Function getURLParagraph(ByVal mainPart As MainDocumentPart, ByVal urlLabel As String, ByVal urlText As String) As Paragraph

        Dim urlExists As Boolean
        Dim hRelation As HyperlinkRelationship = Nothing

        Dim uri As System.Uri = New Uri(urlText)

        For Each hRel As HyperlinkRelationship In mainPart.HyperlinkRelationships
            If (hRel.Uri = uri) Then
                urlExists = True
                hRelation = hRel
                Exit For
            End If
        Next

        Dim relationshipId As String
        If Not urlExists Then
            Dim rel As HyperlinkRelationship = mainPart.AddHyperlinkRelationship(uri, True)
            relationshipId = rel.Id
        Else
            relationshipId = hRelation.Id
        End If

        Dim newParagraph As Paragraph = New Paragraph(New Hyperlink(New ProofError() With {
        .Type = ProofingErrorValues.GrammarStart
    }, New Run(New RunProperties(New RunStyle() With {
        .Val = "Hyperlnk"}), New Text(urlLabel))) With {
        .History = OnOffValue.FromBoolean(True),
        .Id = relationshipId
    })
        Return newParagraph

    End Function
End Class
</code>
Regards
Peter Karlström


Why is this CSS @keyframes rule not cross-fading?

Question: I am trying to create a very simple slideshow that cross-fades between each image. The problem is that the images are fading out before the next image has started to fade in.
I wanted each image to fade in for a duration of 1 second, remain for a further 10 seconds, and then fade out for a duration of 1 second - totalling 12 seconds.
The @keyframes were calculated by dividing the animation-duration by 100, resulting in 1.81% for each second.
The animation-delay is 11s which is causing my confusion as the next image should be fading in as the last images fades out.
If anyone could shed any light on what I've done wrong then I'd be very appreciative.
HTML:
<!doctype html>

CSS:
@keyframes crossFade{
    0%{opacity: 0;}
    1.81%{opacity: 1;}
    18.18%{opacity: 1;}
    19.98%{opacity: 0;}
    100%{opacity: 0;}
}

#cf img{
    position:absolute;
    left:0;
    opacity: 0;
    animation-name: crossFade;
    animation-duration: 55s;
    animation-iteration-count: infinite;
}

#cf img:nth-last-of-type(1){
    animation-delay: 0s;
}

#cf img:nth-last-of-type(2){
    animation-delay: 11s;
}

#cf img:nth-last-of-type(3){
    animation-delay: 22s;
}

#cf img:nth-last-of-type(4){
    animation-delay: 33s;
}

#cf img:nth-last-of-type(5){
    animation-delay: 44s;
}

Link to Codepen:
https://codepen.io/Musicky/pen/YgyOPm
Comment: if you divide the duration by 100 how you get the 1.81%
Answer: I changed your percentages and duration. This will display like you are expecting.
You may want to adjust the length of when the first transitions starts, but your original was not overlapping. It is simpler to time things when they are divisible. Not saying it cant be done, but harder to implement

@keyframes crossFade{
    0%{opacity: 0;}
    10%{opacity: 1;}
    20%{opacity: 1;}
    30%{opacity: 0;}
    100%{opacity: 0;}
}
#cf img{
    position:absolute;
    left:0;
    opacity: 0;
    animation-name: crossFade;
    animation-duration: 60s;
    animation-iteration-count: infinite;
}
#cf img:nth-last-of-type(1){
    animation-delay: 0s;
}
#cf img:nth-last-of-type(2){
    animation-delay: 10s;
}
#cf img:nth-last-of-type(3){
    animation-delay: 20s;
}
#cf img:nth-last-of-type(4){
    animation-delay: 30s;
}
#cf img:nth-last-of-type(5){
    animation-delay: 40s;
}

Comment: @WillHammond If this reply fixed your problem mark it as the accepted answer so others who find this will also know how to fix their problem


Convert a vector> into a vector

Question: I've got a
std::vector<std::vector<char>> and want to fill a std::vector<string> with its content.
I just can't get my head into thinking how to access the inner vector of and put the chars into a string vector.
Maybe I'm wrong, but I think a std::vector<char> is like a string.
So it should not be hard to do and I'm just stuck somewhere in my mind.
I've seen this:
vector<string> or vector< vector<char> >? but it didn't got me far.
Thanks for your help.
Answer: Here's an algorithm version
std::vector<std::vector<char>> a;
std::vector<std::string> b;

std::transform(a.begin(), a.end(), std::back_inserter(b),
[](std::vector<char> const& v) -> std::string {
  return {v.begin(), v.end()};
});

Answer: The naive solution should work well enough:
std::vector<std::string>
chars_to_string(std::vector<std::vector<char>> const & in)
{
    std::vector<std::string> out;
    out.reserve(in.size());
    for (auto const & v : in)
        out.emplace_back(v.begin(), v.end());
    return out;
}

Comment: For the naive solution, I would not even bother with `resize`; amortized constant back insertion and all that.
Answer: This should work
std::vector<string> vec;
for(std::vector<std::vector<char>>::iterator itr = source.begin();
    itr != source.end(); ++itr) {
    vec.push_back(std::string(itr.begin(),itr.end()));
);

Comment: Since you are using C++11, I would advise: `for (auto const& e: source)` it's so much more readable. Also note that repeatedly computing `source.end()` at each iteration of the loop is not particularly "nice".
Answer: I think you can just do:
std::vector<char> v_char;
std::string my_string(v_char.begin(), v_char.end());

or also (requires C++11 and the vector of char must be NULL terminated):
std::string my_string(v_char.data());

Once you have the std::string, filling a vector is easy.
Comment: The first is definitely the way to go; it's also extremely efficient since the `std::string` can compute the expected length in O(1) as the difference between the two iterators and thus pre-reserve memory once and for all.

Convert a vector> into a vector


Ranking the Outputs of Statistical Models

Question: I have the following question about Ranking the Outputs of Statistical Models.

In the case of a regression model with a continuous response variable : Suppose the model makes predictions on 3 new observations (e.g. failure time for these 3 observations : observation #1 expected to fail in 10 days plus minus 5 days, observation #2 expected to fail in 50 days plus minus 20 days, observation #3 expected to fail in  200 days plus minus 100 days) - based on the confidence intervals of the predicted values of these 3 observations, are we allowed to rank these times? For example, could we say that observation #3 is likely to fail after observation #1?

In the case of a classification model with a categorical response variable: Suppose the model predicts that observation #1 belongs to "class 1" with a probability of 0.9 and that observation #2 belongs to "class 0" with a probability of 0.53 - based on the confidence intervals, are we allowed to rank these probabilities? For example, could we say that the prediction made for observation #1 is more "certain" than the prediction made for observation #2?

My Question: Can the predictions made by statistical models be ranked as the way I described?
Thanks!
Comment: Hm... You keep saying "confidence intervals" but your rank based on point estimates. Also CIs are probabilities are pretty sketchy... But to state the obvious, these predictions not only *can* be ranked but they is literature on *ranking* in particular look at ranking measurements like Discounted cumulative gain (DCG) and its associated measures. If you think of your regression as movie rating that is exactly what movie recommenders try to do. Finally to state the obvious, AUC-ROC is a ranking measure.
Comment: @  usεr11852 : Thank you so much for your reply! Can you recommend any references which show how to do this for an example similar to mine using the R programming language? Thank you so much!
Comment: I haven't seen something good with R, sorry; generally I think that ranking is a bit unloved compared to other stats applications. The obvious pick is to try and get some introduction to recommender systems/information retrieval. An interesting curated list on IR is this: https://github.com/harpribot/awesome-information-retrieval.
Answer:
based on the confidence intervals of the predicted values of these 3 observations, are we allowed to rank these times? For example, could we say that observation #3 is likely to fail after observation #1?

The marginal distributions can give you some idea about which variable is larger but you do not know everything. Below you see an example with two different joint distributions for a pair of variables x,y. The marginal distributions are the same but the number of times that you have $x>y$ is not the same.
In the example you get that more often $x>y$ than $x<y$. But in some situations it might be possible that the mean or median of one distribution $x$ is larger than the the mean or median of the distribution of $y$ but that you get more often $y>x$.

For example, could we say that the prediction made for observation #1 is more "certain" than the prediction made for observation #2?

You could indeed say that the predictions are more "certain" if the values are closer to zero or one. A related concept is information entropy which would be computed as
$$H = \sum_{\text{for all classes $i$}} p_i \log p_i = p \log(p) + (1-p) \log(1-p)$$
This means that the model makes a more 'certain' prediction. But, the model could be bad and make a lot of false positive or false negative errors. We may not be certain about the model.
Answer: Your question has two separate aspects - one is the interpretation of the outputs of statistical models and the other one is the ranking of random variables based on their probability distribution.
It is easiest to answer the kind of questions you are describing in a Bayesian framework, since in that case you can describe everything probabilistically - that is, you actually get a probability distribution for every prediction (as depicted in your plot). so for example if $t_1$ and $t_2$ are the failure times of two observations you can use those distributions to calculate for example $P(t_1 > t_2) = \int_{t_1>t_2}f_1(t_1)f_2(t_2)dt_1dt_2$ which will tell you how likely it is for $t_1$ to happen after $t_2$.
However just as with any random variables there is no unique way of ranking the outputs. You could also calculate for example the expected values $\mathbb E[t_1]$ and $\mathbb E[t_2]$, and it is possible to have at the same time $\mathbb E[t_1] > \mathbb E[t_2]$ and $P(t_2 > t_1) > 1/2$, that is, the expected value of $t_1$ can be larger but $t_2 > t_1$ is more likely than $t_1 > t_2$. So, you will have to decide based on which criterion you want to rank them (this is somewhat similar to the analysis of risk vs. expected value in
finance, see e.g. Mean-variance analysis).
In a classification case where the model outputs probabilities this is more straightforward, and it does makes sense to rank based on the level of certainty. However keep in mind that usually those models don't perform a full Bayesian calculation so there can be issues with the Calibration of those probabilities.


Signed URL vs serve through script for serving images or files

Question: Signed URLs are paths like below, is that the correct name for those?
    http://mydomain.tld/<randomhash>.<extension>

They mostly protect access to an image and are often only available a certain amount of time. If you know the path and filename, you get access.
This seems to be acceptable user access restriction for many webmail and other web application and it seems to be a common pattern.
Alternatively you could serve files or images through a script that checks access for each request, which allows tracking and user credential check on each access as described in here: Serve image with PHP script vs direct loading an image
So the trade of between the two would be, and here I would like to know if that is complete or if there is more to consider:

signed urls need to be generated, served, discarded after t
the longer t the more insecure
the shorter the path the more insecure
even when served via https sniffing the url gives anyone access during timeout of t
access after generation is

While serving through php has the issues:

each time accessed generating load on script engine checking user and serving image, not allowing web server a direct file path access

What would be the better approach in general? If that cannot be said, which other perspectives/issues are to be considered?
Answer: Using PHP (or any other language) is a good option here with no much overhead. What I would do:

using Nginx or other webserver with X-forward capabilities (see e.g. mod_xsendfile on Apache)
using the hash in GET parameter not be able to sniffed on a https channel (e.g.: http://mydomain.tld/image?hash=<randomhash>)
on page load PHP can check if the given hash is right (even without a database with a simple file_exists call to the <hash>.png/jpeg/etc.) and give back the required headers with the X-forwarded image
delete/remove unneeded images from protected folder after duration of time
Comment: I started using elFinder and it works with hashes as you explained.


When is it a remix, and when is it a cover?

Question: This question might not be fit for this stack, but I didn't find any other. My apologies to music students out there :)
When is a song a remix, and when is it a cover?
Lets take Corona - The Rhythm of the Night as an example.
The cover by Bastille (which is also a mashup) is clearly a cover? No original sample has been used in this one.
But there are remixes (remakes?) where they only keep the lead singers voice, and everything else is new: Simon from Deep Divas - The Rhythm of the Night. Is this a cover or a remix? And this one actually has remixes of itself too.
Comment: This type of questions will be a perfect fit for the Music Fans SE, which is in commitment phase currently. Sign up at http://area51.stackexchange.com/proposals/61574/music-fans.
Comment: +1 Nice question! Seems to me that new versions of songs are often going to be on a *spectrum* between obvious covers (new artists, new recording, old song) and simple remixes (at their most basic, a remix of the originally recorded material). I think you've probably hit-the-nail-on-the-head by mentioning "the lead singer's voice", but I'm looking forward to seeing how other users respond to this question.
Comment: It can also be sampling. For instance when Timbaland used Glenn Rune Gallefoss' cover of "Acidjazzed Evening" as basis for Nelly Furtado's "Do It". He muted the bass line and added a beat and song on top if it and called it sampling.
Answer: I think the difference is in the context, methods, tools, and limitations.
1) "Cover" is often used in a singer/band context, where the artist performs a song from another artist, most commonly associated with pop/rock. "Remix" is used in a production context, where the reconstruction is made using DAWs, effects, synths, edits, etc, most commonly associated with electronic music.
2) In general, a cover remains similar to the original in many ways. Melodies, structure, harmony, lyrics, etc, most elements will remain the same. If there are any changes, they'll tend to be in the arrangement. A remix, in the other hand, can drastically change the source work: different harmony, structure, add/remove/change lyrics, etc. The remix can hold no resemblance to the original, while the cover tends to try to resemble the original.
3) The remix uses material from the original (recordings, sequences, synth patches, etc). The cover doesn't (or tends not to).
4) Because of the above, generally, a cover implies performance and can be done without sound edit tools. A remix implies sound edit tools, and can be done without performers.
5) There's also difference in how the work is presented. Cover performers tend to replace the original author in the work's presentation: Morris Albert - Feelings, The Offspring - Feelings. Remix authors tend to present the work with the original and remix authors included, separately: Nathan Fake - The Sky was Pink, Nathan Fake - The Sky was Pink (James Holden remix).

Lets take Corona - The Rhythm of the Night as an example. The cover by Bastille (which is also a mashup) is clearly a cover? No original sample has been used in this one.

"No original sample" can mean different things. No sample from the original track? It doesn't fit the remix description. No original sample as in no originally created sample as in all samples are from the source track, then it fits the remix description. If structurally it resembles the original (harmony, melody, lyrics, rhythm, etc), it is on the cover area.

But there are remixes (remakes?) where they only keep the lead singers voice, and everything else is new: Simon from Deep Divas - The Rhythm of the Night. Is this a cover or a remix? And this one actually has remixes of itself too.

It depends. How was the structure and harmony changed? Do they try to resemble the original or are they trying to do their own thing? If only the voice is preserved, if really "everything else is new" as in harmony, melody, key, structure and everything else was changed, then it hardly fits the cover description and is more on the remix grounds.
Reinterpretations can be both covers and remixes (and neither), at least as defined by this answer.
Comment: I'm just a music fan, so a few of the technical terms are a bit over my head. But in the EDM-realm where I mostly live you often see titles like "Original Artist - Original name (Remix Name)" and the new piece incorporates almost nothing of the original piece. The main tune, maybe only the chorus, is kept, and everything else has changed. Is that really a remix then? Or is it a cover?
Answer: A remix uses source material from an existing, recorded piece of music, which has been re-arranged with technology, changes made to that sound and extra material added.
A cover is a new performance of the same piece, usually with some changes to instrumentation, styling and approach.
Basically, a remix is the same sound, and a cover is the same song.
A different singer, singing the song over exactly the same recording is known as karaoke.
Comment: Would you say the RunDMC/Aerosmith version of *Walk this Way* is a cover or a remix?
Comment: @BobBroadley The original being an Aerosmith song, they will probably have played the instrumental parts again. There's some scratches in there, but they're almost certainly extra material instead of using the original track.

Basically, it's a cover.
Answer: In the purest form, a cover is played all out by an artist and recreated musically through practice and memory of the song and introducing and showing their influence by this specific song and/or artist.
A remix is all done after recording in a studio or on a live Mixing table with LPs and or computer technology. The recorded parts are split up and rearranged to form different sounds and different riffs. It can also be spliced with another song or two to signify the relationship between the two songs and compliment it.
you can liken this to someone remaking a movie (cover) and/or producing a parody and/or misheard lines videos (placing funny/different words in a section of the original film for comic affect) (Remix)
Answer: I would say that a cover pertains more to the performance aspect of a song and a remix pertains more to the recording aspect of a song.
Using one of the comments by a user in another answer, he asks what about Run DMC's version of Walk This Way.  Performance-wise, you could say that Run DMC covered Walk This Way.  Recording-wise it was a remix because it used pieces of the original recording by Aerosmith.
Another point to make is that a remix incorporates the original recording in a different recorded arrangment. A cover is an actual performance of an existing song (whether recorded or not) by a separate artist.


Binding datasource to an html  tag

Question: Is there any way to bind a datasource to an html select tag with runat=server attribute.
<select runat="server" onchange="showdistrict();" class="textbox" id="DpCity" name="DpCity">
    <option value="0">unknow</option>
</select>

Comment: Then why can't you use Dropdownlist?
Comment: because I'm binding my dropdown listboxes using Jquery Ajax and for preventing Enable validation error I use  tag
Answer: I found the answer myself so I'll share it.
by using runat="server"  attribute and assigning an id to control it will be accessible in code behind.
for example DpCity is my html select tag so I can use below code for binding datasource:
DpCity.DataTextField = "title";
        DpCity.DataValueField = "val";
        DpCity.DataSource = SrCity;
        DpCity.DataBind();

as like as an asp dropdown list box

Binding datasource to an html  tag


Unable to cover the code using Jasmine Spy

Question: I am writing test cases for code coverage using typescript. I am using Jasmine spyOn, but it is not covered. But some of the methods are covered and I am not getting any error. I need your guidance to resolve this. I provide below the actual code.
import {IncomingMessage} from "http";
import * as https from "https";
import * as logger from "winston";

export class ApiUtil {
    public static async authenticate(params: object): Promise<string> {
        let response: Promise<string> = null;
        response = new Promise((resolve) => {
            try {
                const req: any = https.request(params, (res) => {
                    ApiUtil.getAuthResponse(res).then((resstr) => {
                        resolve(resstr);
                    })
                        .catch((error) => {
                            logger.info("Internal unexpected authentication error: ", error);
                            if (error === "NOT_FOUND") {
                                resolve("NOT_FOUND");
                            } else {
                                resolve("Error");
                            }
                        });
                });
                req.on("error", (error: any) => {
                    logger.info("Internal unexpected authentication error for unknown host:  ", error);
                    resolve("Error");
                });
                req.end();
            } catch (error) {
                logger.info("Unexpected Authentication Error: ", error);
                logger.info("To DO");
            }
        });
        return response;
    }

    public static getAuthParams(host: string, userName: string, pwc: string): object {
        const base64Credential = ApiUtil.getBase64EncodeCredential(userName, pwc);
        logger.info("Base64 Credential successfully received");
        const params: object = {
            agent: false,
            headers: {
                Authorization: base64Credential,
                accepts: "application/json",
            },
            hostname: host,
            method: "POST",
            path: "/LOGIN_REST_URI",
            rejectUnauthorized: false,
        };
        return params;
    }

    public static async getAuthResponse(res: IncomingMessage): Promise<string> {
        return new Promise((resolve, reject) => {
            ApiUtil.getRestAPIResponseText(res).then((resstr) => {
                resolve(resstr.value);
            })
                .catch((e) => {
                    logger.info("Unexpected error while getting authentication response: ", e);
                    reject(e);
                });

        });
    }

    public static async getRestAPIResponseText(res: IncomingMessage): Promise<any> {
        return new Promise((resolve, reject) => {
            if (res && res.statusCode === 200) {
                res.on("data", (dataChunk: string) => {
                    logger.info("Actual API call response");
                    const body = JSON.parse(dataChunk);
                    logger.info("Actual Body received");
                    resolve(body);
                });
            } else if (res && res.statusCode === 404) {
                reject(res.statusMessage);
            } else {
                reject(null);
            }
        });

    }

    public static getBase64EncodeCredential(userName: string, pwc: string): string {
        let b64Encvalue: string = null;
        b64Encvalue = "Basic " + new Buffer(userName + ":" + pwc).toString("base64");
        return b64Encvalue;
    }

    public static getApiParams(vmwareSessionId: string, host: string, restApiURI: string): object {
        logger.info("vCenter Session Id received");
        const options: object = {
            headers: {
                "vmware-api-session-id": vmwareSessionId,
            },
            hostname: host,
            method: "GET",
            path: restApiURI,
            rejectUnauthorized: false,
            requestCert: true,
        };
        return options;
    }

    public static async getApiResponse(vmwareSessionId: string, host: string, restAPIURI: string): Promise<any> {
        let doesExist: Promise<any> = null;
        const params: object = ApiUtil.getApiParams(vmwareSessionId, host, restAPIURI);
        doesExist = new Promise((resolve, reject) => {
            try {
                const req: any = https.request(params, (res) => {
                    ApiUtil.getRestAPIResponseText(res).then((resstr) => {
                        resolve(resstr);
                    })
                        .catch((e) => {
                            logger.info("Inner Unexpected error while calling  getApiResponse(): ", e);
                            reject(null);
                        });

                });
                req.on("error", (error: any) => {
                    logger.info("Internal unexpected authentication error for unknown host:  ", error);
                    resolve(null);
                });
                req.end();
            } catch (error) {
                logger.info("Outer Unexpected error while calling  getApiResponse(): ", error);
                reject(error);
            }
        });
        return doesExist;
    }

    public static async getVersionApiResponse(vmwareSessionId: string, host: string, restAPIURI: string):
        Promise<string> {
        let versionDetails: Promise<string> = null;
        const params: object = ApiUtil.getApiParams(vmwareSessionId, host, restAPIURI);
        versionDetails = new Promise((resolve, reject) => {
            try {
                const req: any = https.request(params, (res) => {
                    ApiUtil.getRestAPIResponseText(res).then((resstr) => {
                        resolve(resstr.value.version);
                    })
                        .catch((e) => {
                            logger.info("Internal Unexpected Error while calling getVersionApiResponse(): ", e);
                            resolve(null);
                        });

                });
                req.on("error", (error: any) => {
                    logger.info("Internal unexpected authentication error for unknown host:  ", error);
                    resolve(null);
                });
                req.end();
            } catch (error) {
                logger.info("Unexpected Error while calling getVersionApiResponse(): ", error);
                reject(error);
            }
        });
        return versionDetails;
    }

    public static async getVersionNBuildApiResponse(vmwareSessionId: string, host: string, restAPIURI: string):
        Promise<any> {
        const versionNBuild: any = {version: null, build: null};
        let versionInfo: Promise<any> = null;
        const params: object = ApiUtil.getApiParams(vmwareSessionId, host, restAPIURI);
        versionInfo = new Promise((resolve, reject) => {
            try {
                const req: any = https.request(params, (res) => {
                    ApiUtil.getRestAPIResponseText(res).then((resstr) => {
                        versionNBuild.version = resstr.value.version;
                        versionNBuild.build = resstr.value.build;
                        resolve(versionNBuild);
                    })
                        .catch((e) => {
                            logger.info("Internal Unexpected Error while calling getVersionApiResponse(): ", e);
                            versionNBuild.version = null;
                            versionNBuild.build = null;
                            resolve(versionNBuild);
                        });

                });
                req.on("error", (error: any) => {
                    logger.info("Internal unexpected authentication error for unknown host:  ", error);
                    versionNBuild.version = null;
                    versionNBuild.build = null;
                    resolve(versionNBuild);
                });
                req.end();
            } catch (error) {
                logger.info("Unexpected Error while calling getVersionApiResponse(): ", error);
                reject(error);
            }
        });
        return versionInfo;
    }
}

I am writing below the spec code.
import { ApiUtil } from "./api.util";

describe("API Utility", () => {

    it("should not validate authentication", ((done) => {
        // spyOn(https, "request").and.returnValue(Promise.resolve("someValue"));
        spyOn(ApiUtil, "getBase64EncodeCredential").and.returnValue("someValue1");
        spyOn(ApiUtil, "getAuthParams").and.returnValue(Promise.resolve("someValue"));
        spyOn(ApiUtil, "getRestAPIResponseText").and.returnValue("clusterName");
        spyOn(ApiUtil, "getAuthResponse").and.returnValue(Promise.resolve("someResponse"));
        spyOn(ApiUtil, "getApiResponse").and.returnValue("[]");
        const params: object = {};

        ApiUtil.authenticate(params).then( (response) => {
            expect(response).toBe("Error");
            done();
        });

    }), 30000);
});

I also provide below the screenshot which is not covered.
Answer: You maybe should have a look here => Code Coverage issue when spyon is used
That said, I'm going to replicate the content here and anticipate a little bit to make it easier.
"Because the spy actually replaces the function call. You have to make two tests : the first will test if the function is actually called (what you did), and the second will test your onNext function" By – user4676340.
So, do ApiUtil.YouFunction() to let it have been called indeed.


Show page content on another page using views

Question: I have a 'presentation' page where I would like an image gallery where all the uploaded images that users upload to the site are displayed.
So far these images are being displayed only on the 'upload' page as default.
(users are effectively modifying the same page when adding content)
I want to keep the 'upload' only as means to upload the images but I want all the images to be displayed ONLY on the 'presentation' page!
How do I do it with views?
Answer: Not sure if I'm understanding you correctly, but you can create two view modes for the node that contains all the images that users upload, one for 'presentation' and one for 'upload' using Display Suite (see tutorial on view modes). If you don't want the upload version to show the images, simply hide the Image field in the 'upload' view mode.
Additionally, you can use a module like Juicebox to create a nice-looking and easy to navigate Javascript gallery in the 'presentation' view mode - just select "Juicebox Gallery" as the formatter for the Image field (instead of the default Image formatter) in your 'presentation' view mode.
Answer:
Create a view block
Create custom page or your defined page.
Open views block configuration select option show block on specific page


Transform PHP script into executable

Question: I am trying to create a script to upload my file to Google Drive. When I run it, it works perfectly. Here's the working code:
public function uploadToDrive()
{
    $client = new Google_Client();
    $client->setClientId(Mage::getStoreConfig('mtm_google/drive/client_id'));
    $client->setClientSecret(Mage::getStoreConfig('mtm_google/drive/client_secret'));
    $client->setRedirectUri(Mage::getStoreConfig('mtm_google/drive/redirect_uri'));
    $client->setScopes(array('https://www.googleapis.com/auth/drive.file'));

    session_start();

    if (isset($_GET['code']) || (isset($_SESSION['access_token']) && $_SESSION['access_token'])) {
        if (isset($_GET['code'])) {
            $client->authenticate($_GET['code']);
            $_SESSION['access_token'] = $client->getAccessToken();
        } else {
            $client->setAccessToken($_SESSION['access_token']);
        }

        $service = new Google_Service_Drive($client);

        $file = new Google_Service_Drive_DriveFile();
        $file->setName('analysis.csv');
        $file->setDescription('A test document');
        $data = file_get_contents('temp.csv');

        $service->files->create($file, array(
            'data' => $data,
            'mimeType' => 'text/csv',
            'uploadType' => 'multipart'
        ));
        echo 'SUCCESS!';
        unlink('temp.csv');
    } else {
        $authUrl = $client->createAuthUrl();
        header('Location: ' . $authUrl);
        exit();
    }
}

This script should be executable from console, and not executed from certain URL. When I try to execute this from console, nothing happens because session variables and redirects are something it can't handle. How can I modify this script in order to be executable from console?
Comment: eliminate any dependencies on things that'd only be available in a web environment? kill off $_SESSION, kill off `header()`, blah blah blah.
Comment: give me full code, i'll try it on my localhost
Comment: @Monty I already solved it (with different script), but truly appreciate effort. Thank you!
Answer: Simply define/set variables : $_GET, $_SESSION, ....
Those variables can be passed like an arguments from console using $argv[]
Comment: But how can i automate them, when token is different every time? I cant hardcode its value?

Transform PHP script into executable


MySQL Workbench - Criar Base de Dados com base no Modelo EER (Opções do Forward Enginner)

Question: Dúvida:

No WorkBench criei a tabela no EER Diagram e agora quero connectar ao Hostname 127.0.0.1.
O caminho que faço é Forward Engineer -> Next -> e depois tenho uma serie de opções, tenho de selecionar quais?

Opções:

Drop object before Each Create
Object Generate DROP SCHEMA
(...)
Comment: Pode colocar a imagem na qual tela parou?
Answer: É essa tela aqui?

Vamos lá, uma por uma:

DROP Objects Before Each CREATE Object: exclui as tabelas antes de criá-las novamente
Generate DROP SCHEMA: exclui o banco de dados/schema antes de criá-lo novamente
Skip creation of FOREIGN KEYS: não cria as chaves estrangeiras
Skip creation of FK indexes as well: não cria os índices para as chaves estrangeiras (só se você marcar a opção anterior)
Omit schema qualifier in object names: não prefixar os objetos com o nome do esquema
Generate USE statements: usar afirmações do tipo USE
Generate Separate CREATE INDEX statements: não criar os índices dentro dos comandos de geração de tabelas
Add SHOW WARNINGS after every DDL statement: selecione essa opção para a adicionar os comandos de SHOW WARNINGS no output; com isso exibe-se eventuais avisos quando o output for executado, o que é bom para fins de debugging
Don't create view placeholder tables: ¯\_(ツ)_/¯
Do not create users. Only create privileges (GRANTs): não cria nenhum usuário, apenas garante os seus acessos às tabelas necessárias (presume-se que os usuários já estejam criados)
Generate INSERT statements for tables: marque essa opção se você edicionou linhas às tabelas geradas e deseja que elas sejam inseridas
Disable FK checks for INSERTs: desabilita a checagem de chaves estrangeiras para os INSERTs.

Referências:
http://dev.mysql.com/doc/workbench/en/wb-forward-engineering-sql-scripts.html
http://docs.oracle.com/cd/E17952_01/workbench-en/workbench-en.pdf
Answer: Vou seguir os menus do Wizard que me aparecem na minha máquina (Fedora com Worbench em Inglês):

[Connect Options]  Deves definir o host onde te vais ligar. No
teu caso, localhost ou 127.0.0.1; Define o nome do utilizador e
password e clica em "Next".
[Options] À partida, deves fazer Next, sem qualquer problema.
Todas as opções que lá estão servem para usares como migração - no
caso de já existir a base de dados/tabelas e quereres modificar
porque fizeste modificações no modelo ER. "Next"
[Select Options] Nesta janela podes escolher se queres
exportar/criar só as tabelas, Vistas (View Objects), Stored
Procedurs (Routine Objects), Triggers e Objectos de Utilizadores
(User Object); "Next"
[Review SQL Script] - podes rever as alterações que vão ser
feitas na BD. Podes alterar alguma coisa que pretendas mas não é de
todo necessário. "Next"

E deverás ter a base de dados criada no host/base de dados que definiste.
Espero que ajude!
Answer: Eu faço assim: crio o bd no mysql ai depois abro o workbench e crio meu EER diagrama, dou um ctrl+shift+z e vou avançando... Uma coisa que gosto de fazer é copiar o sql que é gerado, pois se der algum erro eu abro o phpmyadmin seleciono meu bd e insiro o sql que copiei e analiso o erro pra corrigir la mesmo( mas isso é um caso a parte)


Integrate $\int_{-\infty}^{\infty} \frac{dx}{1+x^{12}}$using partial fractions

Question: How do I integrate the improper integral  $$\int_{-\infty}^{\infty} \frac{dx}{1+x^{12}}$$ using partial fraction decomposition?
I am restricted to use only the principles taught in Calculus 2, which entails partial fraction decomposition. I have tried factoring the denominator but was quickly stumped at the complicated roots. I am unsure of how to proceed. I even thought of looking at it as a series but I don't think I can do that.
Thank you very much for your help. I greatly appreciate it.
Comment: This doesn't have any roots over $\Bbb R$ so a partial fraction decomposition is going to be pretty challenging. Wolfram Alpha gives the solution in terms of a product of gamma functions as well.
Comment: Parentheses, please.  What you wrote is the integral of $1+x^{12}$, but I am sure you meant $1/(1+x^{12})$  If you know where the roots of $-1$ are, you can group them in conjugate pairs to get a factorization of $1+x^{12}$ into real quadratics
Comment: Using half-angle identities one can compute the complex roots $e^{ik\pi/12} = \cos(k\pi/12) + i\sin(k\pi/12)$ to get the roots over $\Bbb C$, then combine the conjugate terms to get the factorization of the denominator over $\Bbb R$.  This is ugly and I don't see any nicer way off the top of my head.
Comment: [the factorization](http://www.wolframalpha.com/input/?i=%28x%5E2%2Bsqrt%282%29x%2B1%29%28x%5E2-sqrt%282%29x%2B1%29%28x%5E2%2B%28sqrt%283%29-1%29%2Fsqrt%282%29*x%2B1%29%28x%5E2-%28sqrt%283%29-1%29%2Fsqrt%282%29*x%2B1%29%28x%5E2%2B%28sqrt%283%29%2B1%29%2Fsqrt%282%29*x%2B1%29%28x%5E2-%28sqrt%283%29%2B1%29%2Fsqrt%282%29*x%2B1%29) is $(x^2\pm\sqrt{2}x+1)(x^2\pm\frac{\sqrt{3}-1}{\sqrt{2}}x+1)(x^2\pm\frac{\sqrt{3}+1}{\sqrt{2}}x+1)$ ($\pm$ are for short, every parenthesis counts 2 times, for $+$ and for $-$) @Sam
Comment: Someone edit this question
Comment: Residues using a pie slice :)
Answer: Apply the partial fractions
$$ \frac{6}{1+x^{12}}
=\frac2{x^4+1}-\frac{\sqrt3x^2-2}{x^4-\sqrt3x^2+1}
 + \frac{\sqrt3x^2+2}{x^4+\sqrt3x^2+1} $$
to integrate
$$\int_{-\infty}^{\infty} \frac{dx}{1+x^{12}}
=\frac23 J(0) +\frac{2+\sqrt3}3 J(\sqrt3)+ \frac{2-\sqrt3}3 J(-\sqrt3)$$
where
\begin{align}
J(a) &= \int_{-\infty}^{\infty} \frac{dx}{x^4+ax^2+1}
=\frac\pi{\sqrt{2+a}}\\
\end{align}
Evaluate $J(a)$ with $a=0, \pm \sqrt3$ to obtain
$$\int_{-\infty}^{\infty} \frac{dx}{1+x^{12}} = \frac{(\sqrt3+1)\pi}{3\sqrt2}$$
Comment: @Ercanayan which is equal to $\frac{\sqrt3+1}{3\sqrt2}\pi$
Comment: @Ercanayan it's overlooked; will fix.
Comment: I am getting $\frac{1}{6} (\pi cosec \left(\frac{\pi}{12}\right))$
Comment: your answer doesnt involve $\pi$
Comment: I'm a little confused: why is there no $6$s in the denominator in the RHS of the line just after "to integrate"? And why can you ignore $x^2$ in the numerator? Thanks.
Comment: @BenjaminWang - These particular partial fractions happen to exclude the 6s in the denominator. Also note that $$\int_{-\infty}^{\infty} \frac{dx}{x^4+ax^2+1}
= \int_{-\infty}^{\infty} \frac{x^2\ dx}{x^4+ax^2+1}
$$
Answer: To help you get started:
$u^4 + 1 =
u^4 + 2u^2 + 1 - 2u^2 $.
Then write as a difference of squares and factor.
Answer: Hint:
$\frac{1}{x^{12}+1}=\sum_{k=0}^{5}\left(\frac{A_k}{x-x_k}+\frac{\bar A_k}{x-\bar x_k}\right)$
where $x_k=\exp\left(\frac{(2k+1)\pi i}{12}\right)$ gives
$A_k=-\frac{x_k}{12}$ and hence that
$$\int_{-\infty}^{\infty}\frac{dx}{x^{12}+1}=\left(\sum_{k=0}^{5}\frac16\sin\left(\frac{(2k+1)\pi}{12}\right)\right)\pi$$


whay Laravel jetstrem logout 419 problem?

Question: when logout from dashboard has logout successfully but click back button then enter dashboard,

logout from dashboard
then browser back button click
and enter dashboard without email and password
then turn click logout show error page expired 419
Comment: Because you already logged out, and the back button throw you the page from browser cache
Comment: Probably because of the CSRF token being mismatched because of @sta's comment.
Answer: The same happens when the user's session expires (they have been gone a while) and then tries to logout.
You can prevent this by excluding the csrf token when the (now) guest user tries to logout.
I wrote it up here https://talltips.novate.co.uk/laravel/csrf-and-expired-logout-forms
A solution to the problem is relatively simple, and requires a small addition to the VerifyCsrfToken middleware;
<code>use Closure;

//

    public function handle($request, Closure $next)
    {
        if(!Auth::check() && $request->route()->named('logout')) {

            $this->except[] = route('logout');

        }

        return parent::handle($request, $next);
    }
</code>


get value from xml with r by attribute

Question: I'm trying to get values from xml that looks like this:
<data>
    <result name="r">
        <item>
            <str name="id">123</str>
            <str name="xxx">aaa</str>
        </item>
        <item>
            <str name="id">456</str>
            <str name="xxx">aaa</str>
        </item>
    </result>
</data>

So far, I can get the id value in the following way:
xmlfile <- xmlParse(url)
data <- xmlRoot(xmlfile)
result <- xmltop[["result"]]
for (i in xmlSize(result)) {
  print(xmlValue(result[[i]][[1]]))
}

This seems highly inefficient and only works if "id" is stored in the first child element. So, is there a way to get the value of an element (123, 456) by searching for the attribute (name) and value (id)?
Answer: The xml2 package is very good for solving this type of problem.
library(xml2)
page<-read_xml('<data>
    <result name="r">
               <item>
               <str name="id">123</str>
               <str name="xxx">aaa</str>
               </item>
               <item>
               <str name="id">456</str>
               <str name="xxx">aaa</str>
               </item>
               </result>
               </data>')

#find all str nodes
 nodes<-xml_find_all(page, ".//str")
#filter out the nodes where the attribute name=id
 nodes<-nodes[xml_attr(nodes, "name")=="id"]
#get values (as character strings)
 xml_text(nodes)

Update
Using Xpath selectors everything can be accomplished in 1 line
#R verison >4.0
xml_find_all(page, ".//str[@name='id']") |> xml_text()

Here is a link to a handy xpath path cheat sheet:
https://www.red-gate.com/simple-talk/development/dotnet-development/xpath-css-dom-and-selenium-the-rosetta-stone/

get value from xml with r by attribute


Hide conditionally hidden fields from custom node template

Question: Case: I am using conditional fields module to hide some dependent fields based on the value of its dependee field. I have created a custom node--content-type.tpl.php template for my content type.
Field1

Field2

Here, Field2 is dependent on the value of Field1. Suppose in this case, Field2 is rendered only if Field1 has value 'jobs'. Otherwise, it is hidden from both node edit form and node page.
When using seven theme and its display(default or teaser) to view node, if the Field2 is hidden or the dependency was not triggered the Field2 is not rendered on the node page, which is correct.
But, when using my custom template, I am not been able to prevent the rendering of Field2 on my node. It is shown with its default value on the node.
Please help.
template code:
<?php if(isset($content['field_job_type'][0]['#markup'])):?>

Job Type: <?php print $content['field_job_type'][0]['#markup'];?>

            <?php endif;?>

Comment: please show the template code
Comment: I used devel module to get variables.
Comment: well, if the default template doesn't show it, but the code you presented does, then the if statement is always true, so you either need to change the if statement, or use some other mechanism for determining it. I would wager a guess that it is only hide() ing the field not unset() ing it, meaning your if statement WILL always be true since it doesn't remove the actual data, just tags it as hidden - this can be found in the field array
Comment: Yes true, I found something 'content['field_job_type']['#access']' which is a boolean value. It worked :)
This will surely help others who will face the same situation.
Answer: Based on the comments:

generic template works, but custom does not

custom template overrides visibility rules

I would surmise that the problem is with the visibility, since the conditional field is likely only hidden, and not actually being removed - this would cause the code to execute every time, while in a standard render() it would remain hidden
Using Devel and specifically the dpm() function, I would find the element in the field array that manages the visibility of the field and use that as the basis for the if statement.

A suite of modules containing fun for module developers and themers


Complex numbers multiplication

Question: I know how to multiply complex numbers (with formula ), but i can't figure out what is really happening on them , I was able to understand that if $z_1z_2=z_3$ then $z_3$ will have the argument of $z_1$ + argument of $z_2$ (its kind of rotation). My question is, what is happening with modules of this $z_3$. I want an intuitive answer not mathematical proof , wanted to understand the phenomenon.
Comment: Think about rotation matrix $R_a.R_b=R_{a+b}$ Does it make a sense ?
Comment: In my experience Rotation matrix doesn't change the length (If not send me to reference)
Comment: You are right , it doesn't change the length ,but add the angles .
Answer: Denote by $|z|$ the modulus of the complex number $z$. Let $z,w\in \mathbb{C}$. Then $|zw|=|z||w|$ and $\text{arg}(zw)=\text{arg}(z)+\text{arg}(w)$. This completely determines a complex number of you think in terms of the polar coordinates of such a number.
So multiplication by a complex number can be seen as first rotating and then rescaling.
Comment: Hm, should I consider this operation of rotating - rescaling an axiom (the way it was defined ) or it has some relation with $\mathbb{R}$ multiplication.
Comment: Multiplication in $\mathbb{R}$ rescales stuff, the argument of a complex number determines the rotation.

Complex numbers multiplication


How to change div styles after showing/hiding with slideToggle()

Question: I'm using .slideToggle() to show and hide some divs on my portfolio page. When the divs are shown, I want to apply a box-shadow and background that makes it look like they're sitting on a tray.
Here's a jsFiddle that shows what I'm trying to do. It works perfectly there, but for some reason the same code isn't working on my site. The box-shadow appears for a moment when I click to show the div but quickly disappears when the slideToggle animation is complete. Any idea why? I feel like there must be a style somewhere that's overriding the box-shadow but I can't figure out what it may be.
Here's the Jquery code:
$('.portfolioToggle').click(function(e) {
    var toggle = $(this),
        divId = toggle.attr('href');

    $(divId).slideToggle('slow');
    $(divId).toggleClass('portfolioSectionVisible', $(this).is(":visible"));

    var toggleState = toggle.text() == "-" ? "+" : "-"; //change icon
    toggle.hide().text(toggleState).fadeIn("fast");

    e.preventDefault();
    event.preventDefault();
});

And here's the CSS:
.portfolioSection{
    clear:left;
    float:left;
    width:80%;
    margin-left:10%;
    margin-right:-90%;
    padding-left:20px;
    padding-right:21px;
    -moz-box-sizing:border-box;
    -webkit-box-sizing:border-box;
    -ms-box-sizing:border-box;
    box-sizing:border-box;
    word-wrap:break-word;
    _display:inline;
    _overflow:hidden;
    _overflow-y:visible;
    padding-left:0;
    padding-right:0;
    margin-bottom:2.25em;
    margin-top:1.5em;
    text-shadow:0 2px 0px rgba(255,255,255,0.9)}

.portfolioSectionVisible{
    -moz-box-shadow:inset 0 0 5px #888;
    -webkit-box-shadow:inset 0 0 5px #888;
    box-shadow:inner 0 0 5px #888}

Answer: Missing a ';' on the last property of each class may mean the browser is mis-reading the CSS
box-shadow:inner 0 0 5px #888}

Change to:
box-shadow:inner 0 0 5px #888;}

Answer: Well seems you need to insert a clear div after the last portfolioItem. I tried following in  chrome and it is working on your site as well:
$("
").css({'clear':'both','height':'1px !important','width':'99%'})
    .insertAfter($("#portfolioContainer1").find(".portfolioItem3"))

Answer: The problem on your page is that your individual portfolio items are floated left, and their parent container .portfolioItemContainer is not expanding vertically to contain them.
One way to solve the problem is by inserting an empty div below the floated divs, and setting it to clear: both. But that is not a good solution because you must insert extraneous markup.
Instead, apply a clearfix technique to the parent container to solve the problem. Here is a nice one:
.portfolioItemContainer:before,
.portfolioItemContainer:after {
    content: " ";
    display: table;
}

.portfolioItemContainer:after {
    clear: both;
}

Or you could just abstract this into a clearfix class which you apply here and anywhere else needed. See this: http://nicolasgallagher.com/micro-clearfix-hack/
Answer: You can change your element style by applying css() function to your element once the effect is done. like:

$(divId).css("background-color", "#ffe");
  $(divId).css("border-left", "5px solid #ccc");

or

document.getElementById('divId').style.-moz-box-shadow = 1px 1px 1px #000;


SAS ARIMA forecast estimate statement

Question: Im trying to forecast a timeseries (daily intervals) but I am unsure of the syntax of the estimate statement. I know p is for autoregression and q is for moving averages, but what do the (2)(12) and (1 3) mean, and what values should they be if the interval = day?
proc arima data=daily;
 i var=SUM_of_Total_Revenue2;
run;
e p=(2)(12) q=(1 3);
 f lead=365
    out=daily2
    id=Order_date
    interval=day
    noprint;

Comment: Be aware the questions about code are generally off-topic here. This one is borderline, IMO, as there is a statistical question behind the code. It would help however, if you could make the *statistical* aspect of your Q more prominent. It might also help (ironically) if you could provide the full code, eg what PROC is that?
Comment: I meant what proc is the `e... noprint;` in? AFAIK, you couldn't run that code in SAS on its own.
Comment: I have been involved several daily forecasting tasks, but I have not come across any model like yours, can you please post the series ? its strange to have a seasonality of 12 for a daily forecasting its usually 7 or 365.
Comment: I think it shoul be 365 instead of 12. here is the series.http://imgur.com/G0sUM8d
Answer: SAS has extensive documentation on all their procedures. Please see here for the syntax for PROC ARIMA.
As you noted p is for autoregressive and q is for moving average in an arima model. In proc arima if p or q is separated by a bracket then it means that there is a seasonal autoregressive model.For your example, what p = (2)(12) means is that current day of SUM_of_Total_Revenue2 is related to 2 days (nonseasonal ar) before and also related to 12 days (seasonal ar) before the current day.
Mathematically using back-shift notation this could be represented as follows. I'm following the notation used in Makridakis et al:
$(1-\phi_1B^2)(1-\Phi_1B^{12}) Y_t = (1-\theta_1B-\theta_1B^3)e_t$
Left hand is non seasonal and seasonal ar(p) and right hand side is the nonseasonal ma(q).
Hope this helps.
Answer: My experience tells me that the analysis of daily data would never lead to the ARIMA model that you propose. How did you go about identifying such a model for daily data (7 days in a week) ?  Are you analysing daily data that has 6 readings per week ? A more appropriate model might include daily fixed effects, weekly or monthly effects , holiday effects and perhaps an ARIMA structure or order 1 or 7 or perhaps 6 if the data is 6 periods per week . Care should be taken to deal with and identify and incorporate pulses, level shifts and perhaps trends.

SAS ARIMA forecast estimate statement


Projection as Affine Transformation

Question: $S \subseteq \mathbb{R}^m \times \mathbb{R}^n$ is projected onto some of its coordinates: $$T = \{x_1 \in \mathbb{R}^m | \ (x_1,x_2)\in S \text{ for some } x_2 \in \mathbb{R}^n \}. $$
Can I show this projection as an affine map?
Comment: This does not make sense. Where is the map? Do you want to show that the set $T$ is affine (for affine $S$)?
Comment: tbh I just want to show that if $S$ is a convex set, then $T$ is. I know projection on coordinates of a convex set gives another convex set. I want to prove this inequality by the fact that affine maps present convexity..
Answer: This projection is a linear map of the type
$$
F(x_1,x_2) = x_1.
$$
Then $T = F(S)$ is convex if $S$ is convex.

Projection as Affine Transformation


How to asymptotically estimate a lower bound of this function?

Question: The function is given as
$$f(x)\geq \sum_{i=1}^{[x/2]}f(i)+1$$
The boundary condition is $f(0)=0$.
What I can get is this function grows faster than any polynomial function, and grows slower than any exponential function.
Apparently this function is monotonic, estimate in the integral form gives
$$f(x)\geq \int_{i=0}^{x/2-1}f(t)dt+1$$ must be satisfied.
I also tried put $\geq$ as equality and solve the ODE obtained, which looks like $f(x)=2f'(2x)$. But I could not go any further.
So is there some way to estimate the growth of this function? More specifically, I would like know how to find some asymptotic lower bound which is better than polynomials. Thanks
Comment: Doesn't $f(x) = e^{x/2}$ satisfy the equation?
Comment: It satisfies the inequality, not the version that is an equation.
Answer: With $\ge$, this does not define the function uniquely.  It might grow exponentially or faster, e.g. $2^x$ satisfies the inequality.
For the version with $=$, see http://oeis.org/A018819
EDIT: This is the version of http://oeis.org/A000123 with terms repeated.  Precise
asymptotics are given in  N. G. de Bruijn, "On Mahler's partition problem", Indagationes Mathematicae, vol. X (1948), 210-220.
Comment: Sorry I was not clear enough before. Actually I was looking for some good lower bound for this function.


syntax error: invalid syntax when trying to comment

Question: I am a total beginner here, not familiar with any type of code at all and I thought python would be a good start.
So when I try commenting multiple lines I get a syntax error.
I added in the code, please help me and forgive me for obvious mistakes. I apologise for my action.
print ("no comment")
'''
print ("this is a comment")
print ("so is this")
'''
print (" not a comment")

Comment: That's not commenting.
Comment: @kindall It is effectively a comment. (See [reference](https://twitter.com/gvanrossum/status/112670605505077248))
Comment: Are you sure? I tried running your code (after removing the indents), and it ran fine. Try posting the rest of your code, and the specific error you have. (You can add info to your post by pressing "edit" in the lower-left of the question)
Comment: Please show actual code that causes the error, and the actual error with traceback instead of just a description of it.
Comment: Depending on the context, such a "comment" may be treated as a docstring. Take some time to learn how to use your text editor to comment out multiple lines at once.
Answer: I'm python doing the ''' you are specifying a long string that can span across many many lines  and return the value that you placed in the ''' for example
print(""" Hello

 World
 how are you""")

Would be printed out like so
 Hello

 World
 how are you

Comments are done with hashtags for example if you wanted to make a comment in your code you would do print('hello world') #This will print hello world to the console would comment out the part of the code that says #This will print hello world to the console and it will still run your print('hello world') code just would not print out the other lines that you have commented out.
Unfortunately, there is no way to comment out several lines of code (like in HTML) at a time unless you're are using the IDLE or another good python editor like Sublime text to do mass comments if you are in the IDLE you can press Alt-3  on your keyboard to comment out the region to uncomment that region you do Alt-4 but if your in Sublime text you do Control+/ or if your on a MAC you can do Command+/ and that will comment out and/or uncomment out that region.
I hope this made things a bit more easy for you! I wish you the best with your future in python. You will find that it is a very versatile language!
Answer: Your problem does not exist in your code, but possibly in your interpreter.
The interpreter is the system that runs your code (interprets it) and decides how to make sense of the functions you write into it.
However, there is a big change between Python Interpreter 2.7.x and Python 3.x, where the syntax for print used to be
`print "here is your text"`

And now it is
`print("here is your text")`

The reasons for this are a tad ambiguous, but in short print has become a function. These are a very simple concept and are very important to master. But hopefully my explanation has helped you understand.
Also, when other people here talk about comments, multi-line comments, and docstrings, all you need to know is that comments work for one line, multi-line comments or block comments work for many lines, and docstrings are for proper developers, and is a standard way to document your code to make it easier for others to understand and work on.
At this phase you shouldn't worry about it when someone talks about docstrings.
Answer: def hello():
    """
    This is a doc string
    It has some information about what
    the function does
    """
    print("Hello")

hello() # Calling hello. This is a comment. Prints "Hello"

Maybe you are typing this outside any function and you might be getting something like this:
print("This is not a comment")
'''
    print('This is a comment')
'''

And may be you are getting something like this:
'\n\tprint("This is a comment")\n'

Its not an error its perfectly fine.
Answer: Whatever it is, first of all its not a simple commenting, but while developement people use
'''text''' or """text"""

or
'''
line 1
line 2
and so on
'''

but here nothing is wrong to raise an SyntaxError
first check your Python Interpreter version, and do accordingly
Answer: I am with @iCodez on IndentationError.
According to this page: http://docs.python.org/release/2.5.1/ref/indentation.html
The first line of code cannot be indented.
I ran the code on ideone for checking and it gives error: http://ideone.com/YTuqaG
    print ("no comment")
    '''
    print ("this is a comment")
    print ("so is this")
    '''
    print (" not a comment")

Try removing the leading spaces/ tabs from each line.
Comment: Well, I originally thought that.  But then he said it was a `SyntaxError`, so I deleted my comment.  I bet you though it _is_ an `IndentError` and the OP meant "syntax error" as in "error", not the literal `SyntaxError`.
Answer: What you have posted does not generate a syntax error, but do be careful with spaces. This generates IndentationError: unexpected indent:
print ("no comment")
 '''
^ note leading space
print ("this is a comment")
print ("so is this")
'''
print (" not a comment")

And this generates the same error because of the uniform indent:
    print ("no comment")
    '''
    print ("this is a comment")
    print ("so is this")
    '''
    print (" not a comment")

But this has no error at all:
print ("no comment")
'''
print ("this is a comment")
print ("so is this")
   '''
#^^ leading spaces
print (" not a comment")

Answer: Comments are not done with ''' or """ that is a way to have a string go across multiple lines how you comment is by doing # for example
#print ("hello world")
#this is a comment
#so is this
#I am a comment
print('I still work')

If you have multiple lines to comment out what you would have to do is use your IDE highlight the text and dependent on your keyboard or computer you press CONTROL+/ or COMMAND+/ I know that works for sublime text 2 but I am not sure about python's default IDLE
Good luck with your future coding !


Erro no Captcha com Magento: Call to a member function getBlockName

Question: Gerencio uma loja virtual, o site está fora do ar e quando vou acessar o administrador dá este erro:

Call to a member function getBlockName() on a non-object in /var/www/html/app/code/core/Mage/Captcha/Block/Captcha.php on line 43
Comment: Você instalou algum plugin recentemente? Está usando algo que não usou antes? Já conseguiu acessar antes
Comment: nada de novo foi feito (pelo menos não foi solicitado), sou leiga nisso e estou sem suporte da agencia responsável ou seja, desesperada! Isso é só com programador mesmo, ne?
Comment: Sim, mas nenhum programador será capaz de resolver com tão pouca informação, de qualquer maneira vou pesquisar ver se houve algum problema semelhante. Tente as respostas abaixo por enquanto.
Comment: brigada Guilherme!
Comment: me diz uma coisa, você tem APC instalado no seu servidor?
Answer: Tente limpar os diretórios var/cache e var/session
Answer: Certifique-se que sua pasta /var tem permissão adequada.
Quando os captcha são criados eles primeiro são armazenados na pasta var. Devido a permissão imprópria não será salva. Isto irá retornar um objeto NULL, portanto, esse erro.
Comment: realmente é interessante verificar o permissionamento desses diretorios sem isso não adiantaria limpa-los


How to understand the notation $S(-3)$?

Question: I asked a question about linear maps between free modules. I have a related question.
Let $S=k[x_1, \ldots, x_n]$ where $k$ is a field. Then $S$ is a graded ring with usual grading given by $\deg x_i = 1$. By definition, $S(a)$ is a graded module defined by $S(a)_d = S_{a+d}$. What is the basis of $S(a)$? For example, what is the basis of $S(-3)$?
Thank you very much.
Answer: The basis of $S(a)$ is formed by all monomials $x^i = x_1^{i_1}\cdots x_n^{i_n}$, but the degree of $x^i$ is equal to $i_1 + \dots + i_n - a$.
Comment: Sure. As an $S$-module the basis is given by one element (monomial 1) in degree $-a$.
Comment: This is a basis as a $k$-vector space, right? Because as an $S$-module, $S(a)$ has rank $1$.

How to understand the notation $S(-3)$?


How to convert a text variable to a python dataframe column and split rows by "\n"?

Question:  fruit='Food\nName/Category\nApple\nFruit\nBanana\nFruit\nBread\nGrain\nTomato\nVegetable'

Hi folks, I have a text variable as above and I want to convert it to pandas dataframe column and split by "\n". I can transfer it to the df but don't know how to split rows based on "\n".
Expected results:

Any thoughts are greatly appreciated!
Thank you!
Comment: Use `pd.DataFrame({'Col':fruit.split('\n')})`
Comment: `pd.Series(fruit.split('\n'))`?
Comment: also `fruit.splitlines()`
Comment: Thank you all for the help!
Comment: @piRSquared even better indeed!
Answer: You can use the split method to split the fruit string based on the '\n' string pattern:
fruit_list=fruit.split('\n')

You can then load fruit_list into a dataframe:
import pandas as pd
df=pd.DataFrame(fruit_list)

Answer: Code:
import pandas as pd

fruit='Food\nName/Category\nApple\nFruit\nBanana\nFruit\nBread\nGrain\nTomato\nVegetable'

df = pd.DataFrame({'fruit':fruit.split("\n")})

Output:
           fruit
0           Food
1  Name/Category
2          Apple
3          Fruit
4         Banana
5          Fruit
6          Bread
7          Grain
8         Tomato
9      Vegetable

Comment: Thank you for the help!
Answer: Just use split.
pd.DataFrame(fruit.split())


Manipulando com Update Panel

Question: Estou trabalhando com asp:button e asp:Listbox utilizando o evento do click do asp:button para popular os listbox. Estou tentando gerenciar para que não ocorra mais postBack no evento do click do botão, porém da forma como estou implementando não está surtindo efeito com o updatePanel, gostaria de uma colaboração para poder sanar e aprender com o caso. O código segue abaixo:
HTML:
<%@ Register Src="../Modelos/Cabecalho.ascx" TagName="Cabecalho" TagPrefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Lysis</title>

Tratamento com o UpdatePanel:
<asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:UpdatePanel ID="updProcesso" UpdateMode="Conditional" runat="server" ChildrenAsTriggers="true">
        <%--<asp:UpdatePanel ID="updProcesso" runat="server" >--%>
            <ContentTemplate>

                            Campos Disponíveis

                            <asp:ListBox ID="lstOrigem" CssClass="DropDownlist" runat="server" Height="200px"
                                Width="250px" SelectionMode="Multiple"></asp:ListBox>

                            <asp:Button ID="btnAcima" CssClass="Botao" runat="server" Text="Mover para Cima"
                                Width="110px" />

                            <asp:Button ID="btnAbaixo" CssClass="Botao" runat="server" Text="Mover para Baixo"
                                Width="110px" />

                            <asp:Button ID="btnSelecionar" CssClass="Botao" runat="server" Text="Selecionar"
                                Width="110px" />

                            <asp:Button ID="btnDesfazer" CssClass="Botao" runat="server" Text="Desfazer Seleção"
                                Width="110px" />

                            Campos Selecionados

                            Ordem

                            Operação

                            <asp:ListBox ID="lstDestino" CssClass="DropDownlist" runat="server" Height="200px"
                                Width="250px" SelectionMode="Multiple"></asp:ListBox>

                            <asp:ListBox ID="lstOrdem" CssClass="DropDownlist" runat="server" Height="200px"
                                Width="50px"></asp:ListBox>

                            <asp:Button ID="btnMudaOrdem" CssClass="Botao" runat="server" Text="Mudar Ordem"
                                Width="95px" />

                            <asp:ListBox ID="lstOperacao" CssClass="DropDownlist" runat="server" Height="200px"
                                Width="115px"></asp:ListBox>

                            <asp:Button ID="btnMudaOperacao" CssClass="Botao" runat="server" Text="Mudar Operação"
                                Width="110px" />

            </ContentTemplate>
        </asp:UpdatePanel>

Exemplo do tratamento de um Button:
Protected Sub btnSelecionar_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSelecionar.Click

        Try

            ScriptManager1.RegisterPostBackControl(CType(sender, Control))

            If lstOrigem.SelectedIndex <> -1 Then

                If lstOrigem.SelectedIndex <> -1 Then

                    For item As Integer = lstOrigem.Items.Count - 1 To 0 Step -1

                        If lstOrigem.Items(item).Selected Then

                            Dim origem As New ListItem
                            origem.Text = "----"
                            origem.Value = lstOrigem.SelectedItem.Value

                            lstDestino.Items.Add(lstOrigem.SelectedItem)
                            lstOrdem.Items.Add(origem)

                            Dim operacao As New ListItem
                            operacao.Text = "----"
                            operacao.Value = lstOrigem.SelectedItem.Value

                            lstOperacao.Items.Add(operacao)
                            lstOrigem.Items.RemoveAt(lstOrigem.SelectedIndex)
                            lstDestino.ClearSelection()

                        End If

                    Next

                End If

                btnSelecionar.Focus()
                updProcesso.Update()

            End If

        Catch ex As Exception

            Session("erro") = ex
            Response.Redirect("../Paginas/Erro.aspx")

        End Try

    End Sub

Comment: Venho aqui informar que eu resolvi tratando a proprieadade
Answer: Dentro desse cenário eu não saberia como trabalhar, entretanto poderiamos abordar de uma maneira diferente.
Crie uma div com runat=server, dessa forma, no onload da página voce consegue oculta-la via codebehind, ou se voce preferir, pode não utilizar o runat=server na tag e oculta-la via jQuery.
Então voce poderia criar uma variavel global que guardaria o status de bind dos dados. Ela iniciaria em false, e após o primeiro bind das informações ocorrerem, ela seria setada para true.
Sempre que clicar no botão para carregar as informações, antes de carregar ele faz um check da variavel que quarda o status do bind, e só carrega se o status dela for false, sendo assim, ela só carregaria uma unica vez, pois ao fim do primeiro carregamento ela seria setada para true.
Answer: Você pode fazer esse tratamento via javascript o código abaixo é um exemplo de como evitar um novo postback(ajax) do mesmo "objeto" antes que o atual termine.
Inserir após o form runat="server"
<asp:ScriptManager ID="ScriptManager1" runat="server" />

Answer: Você pode usar uma Trigger no botão, um exemplo abaixo de um problema que resolvi com esse recurso por causa do postback:
Veja no exemplo que Trigger dentro do UpdatePanel, essa trigger está referenciando meu botão para disparar a ação Onclick.
 <asp:UpdatePanel runat="server" ID="fl_upload" UpdateMode="Conditional">
                            <ContentTemplate>

                                    <asp:FileUpload runat="server" ID="fl_arquivos" CssClass="btn btn-primary" AllowMultiple="true"/>

                                    <asp:Button runat="server" ID="btn_upload" OnClick="btn_upload_Click" Text="Enviar" CssClass="btn btn-primary"/>

                            </ContentTemplate>
                            <Triggers>
                                <asp:PostBackTrigger ControlID="btn_upload" />
                            </Triggers>
                        </asp:UpdatePanel>

Depois que eu clicar no meu botão, chamo a ação do meu botão :
protected void btn_upload_Click(object sender, EventArgs e)
{
            //AÇÃO DO MEU BOTÃO
            //E para finalizar atualizo o UpdatePanel
            fl_upload.Update();

}

Comment: Fiz as adaptações como orientado, porém o postback continua a acontecer. O fato de minha ação do botão é popular as listbox não afetaria no funcionamento do UpdatePanel?

Manipulando com Update Panel


Communication redundancy

Question: I have a device that is connected to a switch and is then connected to a customer controller. I have been asked to make the connection to the controller redundant because they are very far apart from one another. In the case of one connection failing there would be another to take over that is routed through a different area. I do not want the increased throughput, only the fail over protection.
I only have access to my device and the managed switch. I have no access to the controller and the customer will not have access to the switch. I have read about LACP and LAG but I'm a programmer not a network admin so I'm not quite sure how this process works. The switch to buy is being based off this decision so I have no hardware to work with. It seems to me that the configuration would have to be done on the controller OS and then also I would have to configure the two ports on my switch to reflect that configuration. Is this the proper way to achieve this setup?
EDIT: To clarify what I'm asking.
If its something that can be setup on just the switch, then we would probably do it. If it requires messing with the switch and the controller NICs, then we would probably tell the customer to buy their own switch.
Comment: No offense @rawbus, i know this comment is not going to answer your question but seriously hire someone, you don't need a top-notch engineer for this nor expensive at all :)
Comment: What model of managed switch?  What Operating System is the "controller" running?  Is the controller a Windows/Linux server?  Does it have multiple network interfaces?  If so what is the model of the Ethernet controllers?
Comment: More information. Is this industrial equipment? How far is the switch from the controller?
Comment: @msemack the switch is to be determined.
Comment: @ewwhite yes it is industrial and you could say across the plant floor. I don't know say a 100 yards.
Comment: Your "controller" needs two Ethernet ports, and they will both need to be configured properly.  Either that or you have managed switches at both ends and just do a redundant uplink between the two switches.
Comment: I'm assuming their controller would or he wouldn't be asking me about link layer level redundancy.
Comment: And I'm guessing the device only has one Ethernet port?
Comment: Correct that is why the switch is involved.
Answer: If you really don't need the added throughput of LACP you just need the configure the controller to use a master/slave (the terminology differs depending on brand/driver) or Adaptive Load Balancing. Neither of these configurations require any configuration on the switch side,but provide L1 redundancy. You can also provide L2 redundancy here by having the lines run into two separate switches.
Answer: I have industrial and production equipment like this in my environments. Unless you have existing cabling or other hardware issues, I wouldn't go out of my way to provide connection resiliency. We don't in our configurations (except for that location with the rodent-chewing-through cables problem).

Do you happen to know what type of controller this is?
What Operating System does it run?
What are the manufacturer's best-practices or recommendations regarding managing the network interfaces?
Can you elaborate on the application. That will help us understand the tolerance for failure/downtime and possible workarounds.

Think about your potential issues and steps to remediate them...

Switch failure: Replace switch. Keep cold-spare.
Cable failure: Replace cable. Run additional cabling as a precaution.
Controller interface failure: Use another available interface(?)

Am I missing any potential issues here?
Comment: I'm not going to get any information on the controller it could be anything. But it is safe to assume it has two ports and supports some type of redundancy or he wouldn't be asking me if the switch does. The application is controlling a motor. If the link goes down the motor control goes down. The main worry is cable failure because of the distance. We are not worried about switch or controller interface.
Comment: Initially the redundancy was going to be done in software by treating the two connections from the controller as separate interfaces. But the customer inquired about handling the redundancy in the switch.
Answer: Ok, based on the comments, here is what I would do.  It is crude, but will work and is really simple to configure.
Use a Cisco switch with the switchport backup interface configuration command.  Designate one port on the switch to be the primary uplink, and another one to be the secondary uplink.
http://www.cisco.com/c/en/us/td/docs/switches/lan/catalyst3750/software/release/12-2_55_se/commmand/reference/3750cr/cli3.html#wp3269214
As long as the primary interface has a link, the backup interface will be kept offline (no link LED).  If the primary interface goes down (cable is cut), it will be placed in an offline state, and the backup interface will be brought online.
Now, the controller will need to be connected to the the primary and backup interfaces of the switch, and the network interfaces on the controller will need to be configured to use the other port in the case of a link down event.  If this is not practical, put another switch in front of the controller so it only has to deal with one link.  (No special configuration of the controller-side switch will be needed.  Could be an unmanaged switch.)
             |      |----------------------------|      |
Controller---|Switch|                            |Switch|---Device
             |      |----------------------------|      |

Communication redundancy


Would Wrapping Rockwool in Plastic Ruin its Sound Absorption?

Question: I bought enough 3-inch-thick Rockwool to sufficiently treat my studio's walls, but building (ideally) 11 wood frames does not sound fun. If I were to wrap each piece in a thin but sealed plastic (to keep it from shedding) and hang that on the wall, would its absorption be adversely affected in any significant way?
It's a 9' by 9' room with 8' ceilings. I'm sitting 3' away from my monitors (speakers).
Answer: The answer to your immediate question is no, wrapping Rockwool in plastic doesn't adversely affect sound absorption at all.(1)
But I'd like to also answer a more general question you didn't ask, i.e. how to do a good job in your studio, and my suggestion would be that before you start your work you should read as much as possible, and watch as many videos as possible, on the subject of fixing up a good home studio.
Once you start the work, it'll be difficult to change things. But if you invest some time in advance in study and research, you'll almost certainly get a better result and avoid a lot of mistakes. These days there are many good youtube videos on the subject, and if I were you I'd probably watch everything that I could find on the subject, before finalizing my own project and getting started with the work.
(1) For the record, thin plastic (or thin anything) has a modest absorption effect on the highest frequencies, and no effect at all on medium and low frequencies.
Comment: Thank you for you're answer. I have watched many videos on the subject before deciding which insulation product to buy and how to position the panels. I'm just lazy :)


Erro de Charset UTF-8 ao retornar do banco de dados

Question: O meu sistema está com erro de charset, porém são apenas com os dados retornados do banco de dados. O meu charset no HTML está certo, o do banco de dados também está certo, e no php.ini também está certo.
Como consigo resolver o problema? Os caracteres especiais estão retornando ?.
Comment: Não da pra dizer que o problema é apenas com o mysql ou mariadb, estas dicas devem lhe ajudar com o php, html e o banco: http://pt.stackoverflow.com/a/43205/3635
Comment: você esta usando PDO ?
Comment: Relacionada: http://pt.stackoverflow.com/questions/77491/incluir-charset-utf-8-na-conx%C3%A3o-mysqli/77494#77494
Answer: Defina o charset desejado em tempo de execução.
Se estiver usando PDO, faça:
$pdo->exec('SET NAMES utf8');

Em Mysqli:
mysqli_query($mysql, 'SET NAMES utf8')


Desenhar apenas com o "pincel" e apenas "círculos" quando clicar nos determinados botões

Question: Estou construindo um programa simples para desenhar no canvas no qual você consegue desenhar um círculo e desenhar com o pincel clicando nos determinados botões Desenhar círculo (clicando no canvas é desenhado o círculo) e Pincel (movendo o mouse por cima do canvas é feito o desenho com o pincel):

let btnCircle = document.querySelector('#btn-circle');
let btnBrush = document.querySelector('#btn-brush');
let canvas = document.querySelector('#canvas');
let ctx = canvas.getContext('2d');
let mouseX, mouseY;

canvas.onmousemove = () => {
    mouseX = event.offsetX;
    mouseY = event.offsetY;
}

btnCircle.onclick = () => {
    canvas.onclick = () => {
        ctx.beginPath();
        ctx.arc(mouseX, mouseY, 40, 0, 2 * Math.PI, false);
        ctx.stroke();
    };
}

btnBrush.onclick = () => {
    canvas.onmousemove = () => {
        mouseX = event.offsetX;
        mouseY = event.offsetY;

        ctx.fillStyle = 'red';
        ctx.fillRect(mouseX - 10, mouseY - 10, 20, 20);
    };
}
canvas {
    display: block;
    margin: 10px 0;
}
<button id="btn-circle">Desenhar círculo</button>
<button id="btn-brush">Pincel</button>
<canvas id="canvas" style="border: 1px solid #000;" width="500" height="500"></canvas>

Até ai parece que está funcionando bem, mas se, por exemplo, eu clicar no botão Desenhar círculo eu consigo desenhar de boa os círculos e se eu clicar no botão Pincel eu também consigo desenhar com o pincel, mas clicando nos dois botões acaba acontecendo um problema eu consigo desenhar ao mesmo tempo com o pincel e os círculos o que acaba gerando uma bagunça:

O que era para acontecer é quando eu clicar no botão Desenhar círculo eu desenho apenas círculos e quando eu clicar no botão Pincel eu desenho apenas com o pincel, mas não está acontecendo isso, porque isso está acontecendo? e como eu posso resolver esse problema?
Answer: Basta setar uma flag (booleana) ou remover o evento canvas.onclick = () => { quando for pincel e remover o evento canvas.onmousemove = () => { quando for circulo, em programação esse é o básico: o que não é usado deve ser desabilitado ou removido.
Exemplo removendo os eventos:

let btnCircle = document.querySelector('#btn-circle');
let btnBrush = document.querySelector('#btn-brush');
let canvas = document.querySelector('#canvas');
let ctx = canvas.getContext('2d');
let mouseX, mouseY;

function circulo()
{
    //Substitui o onmousemove para usar com o circulo
    canvas.onmousemove = () => {
        mouseX = event.offsetX;
        mouseY = event.offsetY;
    };

    //Aplica o click
    canvas.onclick = () => {
        ctx.beginPath();
        ctx.arc(mouseX, mouseY, 40, 0, 2 * Math.PI, false);
        ctx.stroke();
    };
}

btnCircle.onclick = circulo;

btnBrush.onclick = () => {
    //Remove o click
    canvas.onclick = null;

    //Substitui o onmousemove para usar com o pincel
    canvas.onmousemove = () => {
        mouseX = event.offsetX;
        mouseY = event.offsetY;

        ctx.fillStyle = 'red';
        ctx.fillRect(mouseX - 10, mouseY - 10, 20, 20);
    };
}
canvas {
    display: block;
    margin: 10px 0;
}
<button id="btn-circle">Desenhar círculo</button>
<button id="btn-brush">Pincel</button>
<canvas id="canvas" style="border: 1px solid #000;" width="500" height="500"></canvas>

Ou com flags booleanas:

let btnCircle = document.querySelector('#btn-circle');
let btnBrush = document.querySelector('#btn-brush');
let canvas = document.querySelector('#canvas');
let ctx = canvas.getContext('2d');
let mouseX, mouseY, circulo = false, pincel = false;

canvas.onmousemove = () => {
    mouseX = event.offsetX;
    mouseY = event.offsetY;

    if (pincel) {
        ctx.fillStyle = 'red';
        ctx.fillRect(mouseX - 10, mouseY - 10, 20, 20);
    }
}

canvas.onclick = () => {
    if (circulo) {
        ctx.beginPath();
        ctx.arc(mouseX, mouseY, 40, 0, 2 * Math.PI, false);
        ctx.stroke();
    }
};

btnCircle.onclick = () => { circulo = true; pincel = false; }
btnBrush.onclick = () => {  circulo = false; pincel = true; }
canvas {
    display: block;
    margin: 10px 0;
}
<button id="btn-circle">Desenhar círculo</button>
<button id="btn-brush">Pincel</button>
<canvas id="canvas" style="border: 1px solid #000;" width="500" height="500"></canvas>
Comment: Valeu, @Guilherme Nascimento! verdade eu não tinha pensado nisso ♂


Display content type images using taxnomy

Question: In a drupal block view that I have created I am currently displaying the images and title of a certain content type. On that content type I have two taxonomy term fields one is a multi-select box
My question is this, I want to filter the title and images according to the taxonomy multi box field when a node is displaying, how?
For example if I have a multi list
<code>water
coffee
tea
drupal
views
</code>
On creating the node I select water and drupal so when the node displays it will show all the images and titles that have the same taxonomy term in the block view
Below I have an image of a view that is trying to displaying an image and title according to the taxonomy terms save on a node that a user is currently looking at

It is not working of course. Do I have the right idea what am I missing?
Comment: were you able to solve this? or are you still looking for a solution?
Comment: Use "Content: terms on node" relationship in the "term" relationship. Choose the "term" relationship on fields
Answer: I would try removing your Content: Related Products filter criteria.
Make sure your contextual Content: Nid filter is setting the default from the content ID in the url, and under "More" this filter is set to exclude.
Add another contextual filter for Content: Has Taxonomy Term ID. Select "Provide default value" and use type PHP Code:
<code>$node = menu_get_object();
$terms = array();
if (empty($node->field_related_products)) return;
foreach ($node->field_related_products[LANGUAGE_NONE] as $term) {
  $terms[] = $term['tid'];
}

return implode('+', $terms);
</code>
Under "More" for this filter, enable "Allow multiple values"
Under "Other > Query Settings" select "Distinct"
Answer: I would recommend using Views. You can choose to make it a block or page.

You need Views if
You like the default front page view, but you find you want to sort it
  differently. You like the default taxonomy/term view, but you find you
  want to sort it differently; for example, alphabetically. You use
  /tracker, but you want to restrict it to posts of a certain type. You
  like the idea of the 'article' module, but it doesn't display articles
  the way you like. You want a way to display a block with the 5 most
  recent posts of some particular type. You want to provide 'unread
  forum posts'. You want a monthly archive similar to the typical
  Movable Type/Wordpress archives that displays a link to the in the
  form of "Month, YYYY (X)" where X is the number of posts that month,
  and displays them in a block. The links lead to a simple list of posts
  for that month. Views can do a lot more than that, but those are some
  of the obvious uses of Views.

Setup a new View, naming it whatever you want
set it to content, of the content type you want to show
you probably want it set to Table to determine which fields are presented

Filtering it really depends on how you want to setup the node display. You could use a contextual filter (url parameter) or Filter by the field and expose it allowing the user to change what is displayed.  The rest of the answer depends too much on your vision for the page.
Comment: OP is using a view already.
Comment: @Darvanen the original question didn't specify the Views module - it has been edited since
Comment: Sorry Geoff but the first words of the first unedited version are "In a block view"
Comment: that means nothing, I've seen people use 'units' as nodes, 'pages' as content types and 'div' meaning a block - obviously the original question wasn't specific enough for me to assume that. Op will ignore it given the edits made, so what does it matter now...
Answer: You should use a taxonomy contextual filter. It will filters all nodes that have the same taxonomy terms as your current node.
If I understand well your issue, i think there is no need to use any PHP here.
In "Contextual Filters" add "Content: Has taxonomy term ID". Then select "Provide default value" and select the "Taxonomy term ID from URL". It opens a few checkbox options. Select "Load default filter from node page". There is a Vocabulary selection list if you want to restrict your query to specific vocabularies.
With those settings selected, the view will list all nodes containing terms that are selected in the current node. You can then add the title and picture field as usual in the Fields.


Alternative argument in Fisher's exact test in R

Question: Can anyone please tell me what the alternative argument is in fisher.test() in R? What do greater and less imply?
fisher.test(x, y = NULL, workspace = 200000, hybrid = FALSE,
            control = list(), or = 1, alternative = "two.sided",
            conf.int = TRUE, conf.level = 0.95,
            simulate.p.value = FALSE, B = 2000)

I tried the help section and all it says is that alternative hypothesis must be one of "two.sided", "greater", or "less". When should I use each one? I'm looking at over-representation in my set against a control set.
Answer: This is the alternative hypothesis, commonly denoted by $H_1$.
For example if you type or=1 and alternative=less, the $H_1$ hypothesis is $\psi<1$ where $\psi$ is the odds ratio (or).
Comment: You have to learn the basic principles of hypothesis testing ! If you want to prove that the odds ratio is significantly greater than 1 then you must use "greater" for the alternative hypothesis.
Comment: I'm working on finding over-representation of a motif in my DNA sequences as compared to a background set. Let's say hypothetically that or=1 what should my alternative hypothesis be?from what I understand I want to know that this motif is enriched in my sequences but the null hypothesis would be that it is the same in both my set and background set. What do I use as an alternative in that case? do we select less or greater when we want to see over-representation? I'm confused in that part. In other words is there a need to select alternative or can the test be performed without it?Many thanks