Vuex getters has undefined data when I try to load data from API and use it in multiple components

Question: I have a page component where I am making api call and storing the data in Vuex store through actions. This data has to be used at multiple places but everywhere I'm initially getting undefined data which loads after a few seconds asynchronously from the API. How should I use vuex getters asynchronously ?
Here's the code for my vuex store module :
import axios from 'axios';

const state = {
  all_pokemon: {},
  pokemon_details: {}
};

const getters = {
  getAllPokemon: function(state) {
    return state.all_pokemon;
  },
  getPokemonDetails: function(state) {
    return state.pokemon_details;
  }
};

const mutations = {
  setAllPokemon: function(state, payload) {
    return state.all_pokemon = payload;
  },
  setPokemon: function(state, payload) {
    console.log('Pokemon details set with payload ', payload);
    return state.pokemon_details = payload;
  }
};

const actions = {
  setPokemonAction: function({ commit }, passed_pokemon) {
    axios.get('https://pokeapi.co/api/v2/pokemon/' + passed_pokemon)
      .then((response) => {
        console.log('Response data is : ', response.data);
      });
    commit('setAllPokemon', response.data);
  },
  setPokemonDetailAction: function({ commit }, passed_pokemon) {
    console.log('Action method called..', passed_pokemon);
    axios.get('https://pokeapi.co/api/v2/pokemon/' + passed_pokemon)
      .then((response) => {
        commit('setPokemon', response.data);
      });
  }
};

export default {
  state,
  getters,
  mutations,
  actions,
};

And code for the component where I want to get this data and pass it to other components :

And here's is the code for the template where I'm passing this data to multiple components :

            <ability-component
                    :abilities="getPokemonDetails.abilities"
            >
            </ability-component>

            <sprites-component
                    :sprites="sprites"
            >
            </sprites-component>

            <location-component
                    :location_area="getPokemonDetails.location_area_encounters"
                    :id="getPokemonDetails.id"
            >
            </location-component>

            <stats-component
                    :stats="getPokemonDetails.stats"
            >
            </stats-component>

            <game_index
                    :game_indices="getPokemonDetails.game_indices"
            />

            <moves-component
                    :moves="getPokemonDetails.moves"
                    :pokemon_name="getPokemonDetails.name"
            >
            </moves-component>

As of now, I've adopted a roundabout way of doing this through setTimeout and setting a variable after 2 seconds so that data is available for other  components to use. But, there has to be a more elegant way of handling vuex asynchronous data. Someone please help me in this.
Answer: Your first commit is not in the promise
 commit('setAllPokemon', response.data);

make this :
  axios.get('https://pokeapi.co/api/v2/pokemon/' + passed_pokemon)
      .then((response) => {
        console.log('Response data is : ', response.data);
        commit('setAllPokemon', response.data);
      });

try to use in your vue component
$forceUpdate()

when your request is end for reload the data


JavaScript String Reverse and Capitalized

Question: I am looking for a simple solution to build Javascript a function through which I can reverse a word or a string.
I have gone through .split('').reverse().join('') solution from the community to reverse it correctly but now I am stuck on Capitalizing on Each First Character.
let ar = "looking for opportunities"
const a =(ar)=> {return ar.split('').reverse().join('')}

and then I am stuck. I need a solution that can serve both sentence and word.
Required Output : seitinutroppO roF gnikooL
Answer: Use regex.
let ar = "looking for opportunities"
ar = ar.replaceAll(/\w\S*/g,
    function(txt) {
      return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    }
)
const a =(ar)=> {return ar.split('').reverse().join('')}

This matches all characters after a space, then replaces it with an uppercase version.
Comment: @ArkaBhattacharjee Your code to reverse the string works. Simply capitalize each letter first, then reverse.
Comment: @ArkaBhattacharjee Try `ar.split(' ').map(e => [...(e[0].toUpperCase() + e.substr(1))].reverse().join('')).reverse().join(' ')`, which uses an array-only approach
Comment: Why StackOverflow Bot suggested it as the wrong question? It completely missed the reverse word. It refers https://stackoverflow.com/questions/32589197/how-can-i-capitalize-the-first-letter-of-each-word-in-a-string-using-javascript
Comment: is there any other way to avoid regex and limited it inside string only?


Referencing the constructor function

Question: Im wondering how I can get a reference to a types constructor to pass the function as a value.
Basically, I would like to have a generic type registry that would allow instances to be created by calling a member function of a generic type registry instance.
For example:
class GeometryTypeInfo
{
    constructor (public typeId: number, public typeName: string, public fnCtor: (...args: any[]) => IGeometry) {
    }
    createInstance(...args: any[]) : IGeometry { return this.fnCtor(args); }
    }
}

Later:
class Point implements IGeometry {
    constructor(public x: number, public y: number) { }

    public static type_info = new GeometryTypeInfo(1, 'POINT', Point); // <- fails
    // also fails:
    //    new GeometryTypeInfo(1, 'POINT', new Point);
    //    new GeometryTypeInfo(1, 'POINT', Point.prototype);
    //    new GeometryTypeInfo(1, 'POINT', Point.bind(this));
}

Anyone know if it is possible to reference a classes constructor function?
Answer: You can use the constructor type literal or an object type literal with a construct signature to describe the type of a constructor (see, generally, section 3.5 of the language spec). To use your example, the following should work:
interface IGeometry {
    x: number;
    y: number;
}

class GeometryTypeInfo
{
    constructor (public typeId: number, public typeName: string, public fnCtor: new (...args: any[]) => IGeometry) {
    }
    createInstance(...args: any[]) : IGeometry { return new this.fnCtor(args); }
}

class Point implements IGeometry {
    constructor(public x: number, public y: number) { }

    public static type_info = new GeometryTypeInfo(1, 'POINT', Point);
}

Notice the constructor type literal in GeometryTypeInfo's constructor parameter list, and the new call in the implementation of createInstance.
Comment: in `// <- fails` I suppose as it's the solution, it doesn't fail anymore, if that's correct maybe you can edit it to `// <- doesn't fail anymore` or something similar? Otherwise it's a bit misleading, thx
Answer: typeof YourClass gives you constructor type which can be used in type annotations.
YourClass and this.constructor is constructor itself. So, this code compiles:
class A {}

const B : typeof A = A;

this.constructor is not recognized as value of constructor type by TypeScript (which is funny), so in situations like that you need to use some cheating casting it no any
new (<any> this.constructor)()
That's it.
Comment: But I prefer `typeof Class` whenever possible. It's more specific and handles inheritance chain properly.
Comment: `interface MyCtor { new () : MyInterface }` should do the job then.
Comment: Cause, polymorphic code you would probably write (class factory, as I understand from the context) would expect the same signature from all the subclasses' constructors.
Comment: The issue with this solution is OP wants to reference the type "constructor of a type that implements an interface", and I believe you can't say `typeof IGeometry` when `IGeometry` is an interface. In the case where the passed param is a constructor for a given class or super class this is a great method.
Comment: That wouldn't work in this case, since the constructor's signature is `new (x: number, y: number): Point`. And what happens when each class that implements it has a different constructor signature?
Comment: You will need to find some common signature for the subclasses constructors then. Or the type error TypeScript will report will be perfectly valid.

Referencing the constructor function


nodeJS docker can't connect to redis server

Question: I have a nodeJS-app dockerized. In this, I use a Redis connection.
Redis is running on localhost 127.0.0.1:6379. It's not running as a docker container!
In my nodejs file, I have the following:
client = redis.createClient({
  host: '127.0.0.1',
  port: 6379
});

When I run node index, the connection works. But when I build the docker image and run a container, the nodeJS app cannot connect to the redis server (ECONNREFUSED).
I have also tested it with a managed redis server on GCP, it cannot connect either.
Edit:
I can now connect to the localhost redis client by using the following code in nodeJS:
client = redis.createClient({
  host: 'host.docker.internal',
  port: 6379
});

But I still can't connect to an external IP-address, like this:
client = redis.createClient({
  host: EXTERNAL_IP_HERE,
  port: 6379
});

Comment: From within the container, `127.0.0.1` (or `localhost`) refers to the container itself, not the host. Any reason you're not running the Redis server as a container ? Docker networks are very useful.
Comment: Yes but I'm planning on deploying the docker container on a VM in GCP and I want to use a managed redis server in GCP.
Comment: You could use a dockerized Redis server for local development, this is very common. Does GCP give a public IP address, can you `ping` it from your computer for example ? I never used it but it could be an IP for a private network I guess.
Comment: Yes I can ping it. When I using the code with the external ip and I run ``node index``, it works. But in the docker container I get an "connect ETIMEDOUT" error.
Comment: I'm sorry, I found the solution. I was trying to connect to the INTERAL ip of the redis server through my local setup. An internal IP only works when you upload the code to a google cloud VM. My bad. Thanks anyway for your comments. Have a nice day!
Comment: That's what I was saying by private IP. Thank you, you too !
Answer: Run your docker container with host networking:
$ docker run --network=host mycontainer


How I do text detection from image using google vision api?

Question: I new the Android code side and I have a project.
I want text detection from ımage using google vision api, but I cannot.
I search the internet but I can't find enough information and I know I should use Json(AsynTack).
Just want this not face detection,logo detection.
How can I do this, can you suggest anything?
Answer: The Vision API consists of a single endpoint (https://vision.googleapis.com/v1/images) that supports one HTTP request method (annotate). Here is a sample JSON request:
POST https://vision.googleapis.com/v1/images:annotate
{
  "requests":[
    {
      "image":{
        "content":"change_this_to_the_path_of_your_image"
      },
      "features":[
        {
          "type":"LABEL_DETECTION",
          "maxResults":1
        }
      ]
    }
  ]
}

Answer: Here is the fork of Google sample code, working mainly for text detection.
https://github.com/JackFan-Z/cloud-vision/tree/fda5e83447f9e69cf8a18112e0fced1da928f3d8
Just use Android Studio to open the project in the folder
cloud-vision/android/CloudVision/
Answer: I think this is what you really need:
//Google code labs for mobile vision
https://codelabs.developers.google.com/codelabs/mobile-vision-ocr/#0
Do let me know if this info helps.
Comment: Yeah ı already see that even ı use but this app use Real-Time.I want this;         for example ı send image to Cloud Api and response is  a text.This like https://cloud.google.com/vision/docs/requests-and-responses but ı dont know so much json jobs


Can I train a multi-class linear classifier to output uniform scores for out-of-domain input?

Question: Suppose I train a multi-class classifier with K classes. However, in a practical application, an input can belong to none of the K classes. Thus, the K+1 class is introduced. The training data for this out-of-domain class is needed of course. The training of such classifier and usage is no different than the K-class classifier.
My question is: Why can't we get away with the original K binary classifiers including the case of out-of-domain input?
If an object belongs to one of of K classes, its score (or confidence) is 1.0 for the respective class. And it is zero for other K-1 classes. This is the case of highest certainty or lowest entropy.
If input belongs to none of the K classes, its score is 1/K for all K classes. This is the case of highest uncertainty or maximum entropy.
In a practical setting, I would compute entropy of the discrete distribution (scores/confidences must sum to one). If it is very close to uniform, the decision is "out-of-domain". If entropy is very low, then the classifier's prediction is the class for which the score is the highest (classical usage).
Is it possible to construct such classifier? If not, what are the reasons? A link to a publication would be great.
By extension, would that work for a multiple layer neural network? The last layer in the feed-forward neural network is essentially a linear classifier with a softmax at the end.
Answer: It seems like a reasonable thing to try, but I expect that it will fail in many scenarios.
The problem is the binary classifiers never see out-of-distribution samples during training time, so they might behave arbitrarily poorly on out-of-distribution samples.  It's possible that an out-of-distribution sample might be (wrongly) accepted by one of your binary classifiers as belonging to one of the classes, even though it doesn't actually.  There is nothing in training to prevent this.
Let me give you a concrete example.  Suppose we have $K=2$ classes, and you have a training dataset that comes from the following distribution: each sample lies in a two-dimensional space $\mathbb{R}^2$; class 0 samples are distributed as $(X_0,10)$ where $X_0 \sim \mathcal{N}(5,1)$; and class 1 samples are distributed as $(X_1,10)$ where $X_1 \sim \mathcal{N}(-5,1)$.  If we train a binary linear classifier for each class, the class 0 classifier is likely to accept samples $(x,y)$ where $x \ge 0$ as being in class 0; and the class 1 classifier is likely to accept samples $(x,y)$ where $x \le 0$ as being in class 0.
Now suppose that you receive an out-of-distribution sample, say $(5,-10)$.  What is going to happen?  The class 0 classifier will accept it as being a part of class 0; therefore, you will predict that this sample is "class 0".  That is undesirable -- we wish it would recognize that this should be treated as "unknown".  Unfortunately, your strategy is unable to recognize this sample as "unknown", because during training, the classifier was never trained on anything outside of the normal distribution, so there was no signal or pressure for the classifier to reject points from outside the in-distribution data.
In short, the issue with your scheme is, when we feed an out-of-distribution sample to a discriminative classifier trained only on in-distribution data, arbitrarily bad things can happen.  The classifier is free to do whatever it wants on out-of-distribution data: there is nothing in the training process that forces it to do what you want in that region of the feature space.
Comment: Agreed, that's what I tried to convey with "depending on your problem" and the part about assuming how the unkown class differs. To assume anything about how out-of-distribution detection will work on unseen data will always require assumptions on the unseen data, either from testing or from domain knowledge, and I wanted to complement your answer with the domain knowledge perspective.
Comment: I agree, but would like to add that depending on your problem, it might be reasonable to assume this works. If, for example, you use K one-vs-rest classifiers to achieve multi-class classification, then there is a pressure on each classifier to reject samples which are not similar to its class. Of course, the similarity is then measured in relation to the other K-1 classes, but if the "unknown" class is different from the K classes in the same way that the K classes differ among themselves it is reasonable to expect the one-vs-rest classifiers to still peform well.
Comment: @Erik, there are no guarantees; the example I gave can be adapted to show that such a classifier also isn't guaranteed to work.  In my opinion, it is not reasonable to assume that it works; you have to test it and see whether it actually works or not.  It might work, or it might not, depending on the data you are working with.
Answer: It is worth pointing out that your problem of training a classifier to detect $k$ known classes and 1 "unknown" class can be split into a two-step problem.  We would like a model to 1) classify a point as being "known" or "unknown" and 2) if "known", classify the point into one of $k$ classes.
Since you are apparently familiar with methods to classify things into $k$ classes, your problem has been reduced to classifying points as being "known" or "unknown".  This is what is commonly called novelty detection or anomaly detection.  For continuous input, a popular method is one-class SVM, which, in some sense, tries to find a "soft" convex hull for the training data.  Other methods for anomaly detection abound in time-series and for other types of input.
Comment: The score of 1/K for unknown input is used during training. At the prediction stage, the distribution over K classes in practice will of course almost never be exactly uniform. I am wondering whether such classifier can be trained. If not, what are the clear reasons why it is not even worth setting up and running this experiment?
Comment: "If input belongs to none of the K classes, its score is 1/K for all K classes." This almost never happens for real classifiers.  In my experience neural networks are somehow 90% confident even when you feed them total rubbish.


Scope overlap and cross-posting

Question: Re: When does travel become residency? —
We talked about minimizing the overlap between traveling and expatriating, but the differing opinions on how to do so seemed to widen it (by the fact that they're so different).
At least one person offered some of the reasons cross posting is undesirable.
Is it acceptable to post the question on one site, and on the other put only the title (make sure it's the actual question) with a body like "This question is a duplicate of (URI).  Please answer there."
Then ask a moderator to lock it.
My rationale is that people in group A may be interested in a borderline question but not be following group B.  (Might have a side-effect of getting more people in group B!)
Comment: I think this is just a duplicate of http://meta.stackexchange.com/questions/64068/is-cross-posting-a-question-on-multiple-stack-exchange-sites-permitted-if-the-qu.
Comment: I might add that I think I am in the very center of the overlap by several of the definitions.
Comment: I guess we have different definitions of "duplicate".  That suggests multi-posting; I'm speculating on a way to avoid it.  That claims one site is **always** better than any other for a question; the topic I cited strongly suggests "not always."
Answer: No, such "questions" will be not acceptable, because they are actually not questions, but only references to questions. Technically, the would be link-only questions.
However, there are discussions about strenghtening the relations between sites on Meta.SE, which you can support:

Display other SE site links in the linked questions sidebar
Build and strengthen the Stack Exchange community with "crossover questions" between sites

Scope overlap and cross-posting


Turn a sync method into an async one

Question: I'm trying to turn a synchronous method from some old code into an asynchronous method, but I'm having some trouble understand. From all the videos and tutorials I've read they seem to be creating two methods: one the actual function, the other a wrapper and then it's the wrapper called on the UI.
Here is my code:
private async Task<bool> login(String username, String password)
{
        var tcs = new TaskCompletionSource<RestSharp.IRestResponse>();

        RestSharp.RestRequest request = new RestSharp.RestRequest("/accounts/login/", RestSharp.Method.GET);
        RestSharp.IRestResponse response = client.Execute(request);

        // Make the login request
        request = new RestSharp.RestRequest("/accounts/login/", RestSharp.Method.POST);
        request.AddParameter("username", username);
        request.AddParameter("password", password);

        response = client.Execute(request);

        // Return loggin status
        dom = response.Content;
        return dom["html"].HasClass("logged-in");
}

For some reason when I try to call the method on the UI thread from a button click, it's asking me to make the button event async.
txtLog.AppendText("Before Await");

Task<bool> result = await login("","");

txtLog.AppendText("After Await");
txtLog.AppendText("Result: " + result.toString());

Do I need a wrapper method that is also set to async which makes the call to login?
Answer: To answer your 2nd part first, yes you need to mark the event for the button async, if you want to use the keyword await in your code you must declare the function async.
2ndly if a function uses async without having an await inside of it the code will not be run asynchronously, you either need to create a task and run your synchronous method inside of it or rewrite the method to be asynchronous.
As task method:
private async void button1_Click(object sender, EventArgs e)
{
    txtLog.AppendText("Before Await");

    //Note I changed from "Task<bool>" to "bool", await is like calling ".Result"
    //  on a task but not blocking the UI, so you store the type you are waiting for.
    bool result = await Task.Run(() => login("","")); //You would still use your old login code before you tried to make it async, it requires no modifications.

    txtLog.AppendText("After Await");
    txtLog.AppendText("Result: " + result.ToString());
}

Rewriting the function method:
private async void button1_Click(object sender, EventArgs e)
{
    txtLog.AppendText("Before Await");

    //Note I changed from "Task<bool>" to "bool", await is like calling ".Result"
    //  on a task but not blocking the UI, so you store the type you are waiting for.
    bool result = await login("","");

    txtLog.AppendText("After Await");
    txtLog.AppendText("Result: " + result.ToString());
}

private Task<bool> login(String username, String password)
{
    var tcs = new TaskCompletionSource<bool>();

    // Make the login request
    var request = new RestSharp.RestRequest("/accounts/login/", RestSharp.Method.POST);
    request.AddParameter("username", username);
    request.AddParameter("password", password);

    client.ExecuteAsync(request, (response, handle) =>
        {
            try
            {
                // Return loggin status
                var dom = response.Content;

                //dom["html"] did not have a .HasClass in my tests, so this code may need work.
                tcs.TrySetResult(dom["html"].HasClass("logged-in"));
            }
            catch(Exception ex)
            {
                tcs.TrySetException(ex);
            }
        });

    return tcs.Task;
}

In my "rewrite method" what I am doing is I am using ExecuteAsync witch is part of IRestClient. That function calls a callback method when it completes, in the callback method I call tcs's SetResult to report back the result I wanted.
You could expand this further by taking in a CancellationToken and if the token is raised call Abort() on RestRequestAsyncHandle, however if we do this we need to bring the async back in to the function and await the result so we can clean up after the cancellation token registration.
private Task<bool> login(String username, String password)
{
    return login(username, password, CancellationToken.None);
}

private async Task<bool> login(String username, String password, CancellationToken cancelToken)
{
    var tcs = new TaskCompletionSource<bool>();

    // Make the login request
    var request = new RestSharp.RestRequest("/accounts/login/", RestSharp.Method.POST);
    request.AddParameter("username", username);
    request.AddParameter("password", password);

    var asyncHandle = client.ExecuteAsync(request, (response, handle) =>
        {
            try
            {
                // Return loggin status
                var dom = response.Content;

                tcs.TrySetResult(dom["html"].HasClass("logged-in"));
            }
            catch(Exception ex)
            {
                tcs.TrySetException(ex);
            }
        });

    //if the token is canceled it will call `asyncHandle.Abort()` for us.
    using(cancelToken.Register(() =>
        {
           if(tcs.TrySetCanceled(cancelToken))
               asyncHandle.Abort();
        }))
    {
        return await tcs.Task;
    }
}

Answer: Your button handler uses the await keyword, which requires that it be made async. The await keyword basically partitions the method at the await, turning the part after the await into a delegate that continues when the awaited Task completes. The method returns immediately after encountering the await.
Your login function doesn't use await. It doesn't need the async keyword.

Turn a sync method into an async one


basic java net client returns 400

Question: The following code has been copied out for Horstmann's, Big Java Early Objects 6th edition - Chapter 23.3. The only modification is the package, added by eclipse.
The code:
package zipCodeScrapper;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class client {
    public static void main(String[] args) throws IOException {
        // Get command-line arguments
        String host;
        String resource;

        if (args.length == 2) {
            host = args[0];
            resource = args[1];
        } else {
            System.out.println("Getting / from horstmann.com");
            host = "horstmann.com";
            resource = "/";
        }

        // Open socket
        final int HTTP_PORT = 80;
        try (Socket s = new Socket(host, HTTP_PORT)) {

            // Get streams
            InputStream instream = s.getInputStream();
            OutputStream outstream = s.getOutputStream();

            // Turn streams into scanners and writers
            Scanner in = new Scanner(instream);
            PrintWriter out = new PrintWriter(outstream);

            // Send command
            String command = "GET " + resource + " HTTP/1.1\n" + "Host: " + host + "\n\n";
            out.print(command);
            out.flush();

            while (in.hasNextLine()) {
                String input = in.nextLine();
                System.out.println(input);
            }
        }
    }
}

The code receives a 400 Bad Request. I have tried replacing the host and resources with other values, however I continue to get error 400.
Comment: The line terminator in HTTP is defined as `\r\n`, not just `\n`.
Answer: Firstly , read this documentations. RFC p1 and  RFC2 p2
Line separator of HTTP is not a \n . It must be  \r\n . For more read this thread ;
What is line breaker in HTTP?
Comment: in case this isn't clear to anyone who has the same problem, every \n in my "command" string should be replace by \r\n

basic java net client returns 400


Show that $K_{3,3}-e$ is planar for all $e \in E(K_{3,3})$, and show that $K_{5}-e$ is planar for all $e \in E(K_{5})$.

Question: a) Show that $K_{3,3}-e$ is flat for all $e \in E(K_{3,3})$.
b) Show that $K_{5}-e$ is planar for all $e \in E(K_{5})$.
Attempt:
a) Since we have removed an edge from $K_{3,3}$, it follows that the new graph does not have $K_{3,3}$ as a subgraph. By Kuratowski's theorem, $K_{3,3}-e$ is planar.
b) Since we have removed an edge of $K_5$, it follows that the new graph does not have $K_5$ as a subgraph. By Kuratowski's theorem, $K_5-e$ is planar.
Comment: what is flat? ${}{}$
Comment: With respect to your answer for part a): Note that $K_5$ ddoes not have $K_{3,3}$ as a subgraph yet is not panar. You need to be more complete when using Kuratowski's theorem.
Answer: I think the natural way to prove these specific graphs are planar is to provide an embedding. When trying to give embedding for graphs it usually helps to place the first $3$ of them in a triangle in the outside, and then triangulate when possible. In the case of bipartite graphs you can't have triangles but you can try to get as many quadrilateral faces as possible.
Answer: First, I would say you're better off using Wagner's theorem instead of Kuratowski because Wagner just considers minors, which are easier to show for small graphs such as this.
Second, Wagner/Kuratowski both say that your graph can contain neither $K_{3,3}$ nor $K_5$. So the harder part is not to show that $K_{3,3}-e$ does not contain $K_{3,3}$, but also that it does not contain $K_{5}$. Same for the other.
There are many ways to do this, but the general idea is to find some property of $K_5$ that is not there in $K_{3,3}$ (and therefore not in $K_{3,3}-e$), and vice versa. For example, the latter does not have any vertex of degree $4$, but all vertices of $K_5$ have degree $4$. For the other, simply look at the number of vertices.
Be careful about the kind of property you choose. The strategy I showed implicitly assumed a subgraph-closed property, aka if it is true for $G$, it is true for all subgraphs of $G$. This is not necessarily true (trivial example: if $G$ has an odd number of edges, then there is clearly some subgraph of $G$ with an even number of edges). If you do pick a property that  is not subgraph closed, then you have to show it holds for $K_{3,3}-e$ specifically as well.


Password policy in Active Directory - inactivation of complexity without effect

Question: In my Samba Active Directory Domain, I want to allow passwords that are long (passphrase) and based only on small caps and special characters, i.e. no requirement for large caps and numbers.
In order to do so, I created a new domain wide GPO for authenticated users where I disabled the complexity check (Password must meet password complexity requirement) and instead increased the minimum password length to 10.
I ran gpupdate to make sure the policy was distributed to the computer I'm sitting on. Unfortunately, this didn't have the expected effect, I still get the error message that my new password is not in line with the password policy.
A quick check using gpresult /v reveals the following information:
    Account Policies
    ----------------
        GPO: Default Domain Policy
            Policy:            MaximumPasswordAge
            Computer Setting:  180

        GPO: Default Domain Policy
            Policy:            MinimumPasswordAge
            Computer Setting:  15

        GPO: Default Domain Policy
            Policy:            MinimumPasswordLength
            Computer Setting:  10

    Security Options
    ----------------
        GPO: Default Domain Policy
            Policy:            PasswordComplexity
            Computer Setting:  Not Enabled

What went wrong?

Update: Since a few commenters suggested I should do it via the Default Policy, I did that. The result remains exactly the same. I am attaching a screenshot of the policy just to avoid any doubt.

And here is a screenshot of the local security policy which confirms that the GPO was indeed applied. It looks fine but I can still create 8 digit passwords for domain users and they must include large caps and a number.
Comment: The password policy is set in default domain policy
Comment: Or, more generally, the scope of the GPO does not include the computer or user in question. Also, I'm pretty sure some policies can not be updated with a `gpupdate` and instead require a restart.
Comment: This GPO sits in the domain node, right under the default domain policy (which I never touched). I only have one domain so all users and computers should be affected by the policy. No?
Comment: Btw: Restarting the computer did not change anything.
Answer: Ok, this caught me completely off guard. While a Samba Active Directory domain can be usually fully configured without any issues using RSAT, it seems that the password policy is one of these very few things where this doesn't work, or at least not in its entirety. The solution is to turn off complexity directly on the Samba server, using
# samba-tool domain passwordsettings set --complexity=off

I have not initially declared that I'm using Samba so the other answers and comments are entirely valid for a Microsoft-only domain. I will adapt my question to reflect the use of Samba.
Update for clarification: As Joe pointed out, the GPO for the password settings is applied to the domain controller itself and not the clients like with regular GPOs. And that is the reason why this GPO could not take effect on a Samba DC. Samba can only serve GPOs, not apply them to itself.
Answer: Ignoring FGPP, there can be only one domain Password Policy. This is by default defined in the Default Domain Policy GPO. If you want to use a different Password Policy GPO then you need to link it to the domain and give it a higher precedence than the Default Domain Policy GPO. I suspect that's where your problem lies.
https://blogs.manageengine.com/active-directory/2014/05/16/domain-password-policies-configuring-and-auditing-correctly.html
EDIT:
Something to understand is that the Password Policy affects the local security accounts database. This means that when you're looking at the settings on a member computer you're looking at the settings that are applied to the local security account database on that member computer and will affect local user accounts on that member computer. For Active Directory users the local security account database is the Active Directory database, which is stored on the Domain Controllers. If you want to see what the Password Policy is for the domain then you need to run the Group Policy Results wizard against a Domain Controller, not against a member computer. Run that and post your results in your question.
Comment: Thanks for the interesting link. I'm not using FGPP, by the way. So, I followed these instructions and gave my PasswdPolicy the highest preference. Ran gpupdate, and restarted the computer. Still no change. gpresult /v gives me the same result as above - the 12 character requirement was taken over from the new policy, but not the complexity check. I will check to see what happens if I just unlink this separate policy and do it through the default policy.
Comment: Same situation. See updated question. Seems to me everything is right but it still doesn't work.
Comment: Thanks for the additional information. It doesn't help in my specific situation, see my answer, but you still helped me understand the issue a lot better.


Envio WebService REINF - O servidor remoto retornou um erro: (500) Erro Interno do Servidor

Question: Estou tentando me comunicar com o web service do REINF para enviar o evento de informações do contribuinte (R-1000), entretanto estou recebendo o erro "(500) Erro interno de Servidor", na mensagem subjacente diz "Ocorreu um erro no processamento. Por favor tente novamente. Caso o problema persista, favor entrar em contato através do 'Fale Conosco' da EFD-REINF..., informe o problema e o número [3033699826]"
Alguém já passou por este erro?
Desde já agradeço a atenção.
Abaixo a minha requisição e o retorno:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:xsd="http://www.w3.org/2001/XMLSchema"
   xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
   xmlns:sped="http://sped.fazenda.gov.br/">
   <soap:Header></soap:Header>
   <soap:Body>
      <sped:ReceberLoteEventos>
         <sped:loteEventos>
            <Reinf xmlns="http://www.reinf.esocial.gov.br/schemas/envioLoteEventos/v1_02_00">
               <loteEventos>
                  <evento id="ID1000000032343842018011517062000001">
                     <Reinf xmlns="http://www.reinf.esocial.gov.br/schemas/evtInfoContribuinte/v1_02_00">
                        <evtInfoContri id="ID1000000032343842018011517062000001">
                           <ideEvento>
                              <tpAmb>2</tpAmb>
                              <procEmi>1</procEmi>
                              <verProc>1.0</verProc>
                           </ideEvento>
                           <ideContri>
                              <tpInsc>1</tpInsc>
                              <nrInsc>03234384</nrInsc>
                           </ideContri>
                           <infoContri>
                              <inclusao>
                                 <idePeriodo>
                                    <iniValid>2018-01</iniValid>
                                 </idePeriodo>
                                 <infoCadastro>
                                    <classTrib>13</classTrib>
                                    <indEscrituracao>1</indEscrituracao>
                                    <indDesoneracao>0</indDesoneracao>
                                    <indAcordoIsenMulta>0</indAcordoIsenMulta>
                                    <indSitPJ>0</indSitPJ>
                                    <contato>
                                       <nmCtt>LUCAS VALFRIDO COSTA.</nmCtt>
                                       <cpfCtt>21513643991</cpfCtt>
                                       <foneFixo>(042)32195250</foneFixo>
                                       <email>email@example.com</email>
                                    </contato>
                                 </infoCadastro>
                              </inclusao>
                           </infoContri>
                        </evtInfoContri>
                        <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
                           <SignedInfo>
                              <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
                              <SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" />
                              <Reference URI="#ID1000000032343842018011517062000001">
                                 <Transforms>
                                    <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
                                    <Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
                                 </Transforms>
                                 <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256" />
                                 <DigestValue>KGsEYFOFJVca6JA5MnurDNJOOKXwElCopboz0oXegxg=</DigestValue>
                              </Reference>
                           </SignedInfo>
                           <SignatureValue>DPu5dR...5C1+jgQwbg==</SignatureValue>
                           <KeyInfo>
                              <X509Data>
                                 <X509Certificate>MIIH...E5+J6</X509Certificate>
                              </X509Data>
                           </KeyInfo>
                        </Signature>
                     </Reinf>
                  </evento>
               </loteEventos>
            </Reinf>
         </sped:loteEventos>
      </sped:ReceberLoteEventos>
   </soap:Body>
</soap:Envelope>

Retorno (O servidor remoto retornou um erro: (500) Erro Interno do Servidor) Detalhe:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
   <s:Body>
      <s:Fault>
         <faultcode>s:Client</faultcode>
         <faultstring xml:lang="en-US">Ocorreu um erro no processamento. Por favor tente novamente. Caso o problema persista, favor entrar em contato através do 'Fale Conosco' da EFD - REINF - https://idg.receita.fazenda.gov.br/contato/fale-conosco/empresa/sped/efd-reinf-1 Ao entrar nessa página, clique em 'Indisponibilidade do Sistema', informe o problema e o número [3033699826] e anexe o XML do evento que foi objeto deste erro.</faultstring>
      </s:Fault>
   </s:Body>
</s:Envelope>

Answer: Você está usando o evtInfoContribuinte (R-1000) na versão de leiaute "v1_02_00", mas o ambiente de produção restrita do EFD-Reinf já está na versão 1.3.02:

Ambiente de Produção Restrita da EFD-REINF liberado
http://sped.rfb.gov.br/pagina/show/2641
ESQUEMAS XSD - VERSÃO MAIS RECENTE
http://sped.rfb.gov.br/pasta/show/2270

Provavelmente o problema é esse.
Comment: Obrigado Pedro, havia pegado um exemplo de XML com uma versão anterior a atual,  infelizmente não era isso, peguei outro exemplo na versão atual e permanece o mesmo erro, mas ao menos estou partindo da versão correta agora. Obrigado.
Comment: Jeison, talvez o problema esteja nesse namespace **sped**, e nesses dois elementos, `sped:ReceberLoteEventos` e `sped:loteEventos`, que aparecem antes do primeiro elemento `Reinf`. Veja esse XML de exemplo (também está numa versão super defasada, mas, dá para ter uma ideia de como deveria ser), ele funcionou na época em que foi enviado: http://suporte.quarta.com.br/eSocial/arquivos/R1000_EnvioLote.xml
Answer: Erro 500 normalmente se refere a permissões. Verifique se você possui permissão para acessar as informações, pastas ou diretórios. Veja mais no link:
Erro 500
Comment: Obrigado Cristy, a principio não se trata de permissões. Mas obrigado pelo link.
Answer: NÃO importa qual linguagem de programação, framework ou lib vc usa, faça o debug do XML da requisição usando o Postman.
Nesta pergunta aqui eu explico como configurar e usar o Postman ( super simples ) e tb como usar e configurar o Fiddler.
O Fiddler serve para vc monitorar os dados das requisições que o seu app faz. Ao interceptar as requisições do seu app, vc tem a chance de comparar o que foi enviado contra o que deveria ter sido enviado.
O Fiddler é útil tb para capturar requisições de aplicações que tem a funcionalidade que vc quer implementar no seu app. O Fiddler é basicamente um Inspetor do Google Chrome/Firefox com a vantagem de capturar o request/response de tudo que tá no computador.
Tem também o mitmproxy
OBSERVAÇÕES:

O Fiddler só será útil para monitorar as requisições. Enquanto o Fiddler estiver rodando, todas as requisições irão falhar retornando erro de permissão ( pois o Fiddler intercepta e re-envia a requisição SEM autenticar a comunicação );
Para debuggar a resposta vc tem q desligar o Fiddler e usar o Postman. O Postman tb vai falhar se vc deixar o Fiddler rodando.


Nested arrays to single array in javascript

Question: This could be a silly question but, I´m way too new at javascript. And i´m thinking this more than it should.
I´ll set an example:
I have:
animals['Cat', 'Dog'];

and,
mood['Sad' , 'Happy'];

i want:
animalmood[0]=('Cat', 'Happy')
animalmood[1]=('Cat', 'Sad')
animalmood[2]=('Dog', 'Happy')
animalmood[3]=('Dog' 'Sad')

How can this be achieved?
What would be the correct syntax for it? Any help is welcome.
Comment: What format is this `animalmood[0]=('Cat', 'Happy')`? Do you want it as a string `animalmood[0]='Cat, Happy';` or as an array `animalmood[0]=['Cat', 'Happy']`?
Comment: Possible duplicate of [Cartesian product of multiple arrays in JavaScript](http://stackoverflow.com/questions/12303989/cartesian-product-of-multiple-arrays-in-javascript)
Answer: Use nested for loops, pushing each combination of elements into the output array.

var animals = ['Cat', 'Dog'],
    mood = ['Sad' , 'Happy'],
    animalsMood = [];

for (var i = 0; i < animals.length; i++)
  for (var j = 0; j < mood.length; j++)
    animalsMood.push([animals[i], mood[j]]);

console.log(animalsMood);

Using ES6 in Node.js, you can also take a more functional approach:

let animals = ['Cat', 'Dog'],
    mood = ['Sad' , 'Happy'],
    animalsMood = [];

animals.forEach(a => mood.forEach(m => animalsMood.push([a, m])));

console.log(animalsMood);
Answer: A more advanced answer is using reduce function:
const animals = ['Cat', 'Dog'];
const moods = ['Sad' , 'Happy'];

const animalsMood = animals.reduce((result, animal) =>
  result.concat(moods.map(mood => [animal, mood]))
, []);

console.log(JSON.stringify(animalsMood));

Using spread instead of concat
const animals = ['Cat', 'Dog'];
const moods = ['Sad' , 'Happy'];

const animalsMood = animals.reduce((result, animal) =>
  [...result, ...moods.map(mood => [animal, mood])]
, []);

console.log(JSON.stringify(animalsMood));

Comment: This isn't more advanced, this is just a different programming style. It's functional rather than imperative. I really wish JavaScript had a `.collect()` method instead of forcing us to use `.reduce()` or some other non-traditional function.
Comment: `reduce` or `map` functions are traditional functions which meet all "pure function" criterias of the functional language such as JavaScript. Using and understanding `reduce` will make you use and understand complex operations in NoSQL databases or understanding one of the main concepts of Reducers in `Redux` or ... many other advanced logic constructs or operations
Comment: I would also suggest you to read.... another StackOverflow question (since we are using StackOverflow in the end) http://stackoverflow.com/a/388329/812519  maybe it will give you some ideas
Comment: I just meant that `reduce` is non-traditional when it comes to producing an array. Collecting is a type of reduction, but it would be nice if there wasn't so much boilerplate when using `reduce` in order to `collect`. Purely functional languages have much better alternatives.


Why is a continuous surjective map of the Cantor set not generally a bijection?

Question: It is known that any compact metric space $Y$ is a continuous image under some surjective map $$f: C \to Y,$$
where $C$ is the Cantor set. I want to prove that if $f$ maps $C$ to $([0,1],|\cdot|)$, then $f$ cannot be bijective. So I think the idea is to show that there is some $y\in [0,1]$ such that the pullback of $y$ under $f$, i.e. $f^{-1}(y)$ contains more than one element.
If we look at a proof of the fact that any compact metric space $Y$ is a continuous image under some surjective map $f: C \to Y$, then one approach is to subdivide $Y$ into infinitely many compact sets of diameter zero and then use a ternary sequence mapped by $f$ into $Y$. But I don't yet see what to extract from this.
Is it best to prove this by contradiction? Would appreciate some hints.
Comment: You seem to be leaving out the word "continuous" when discussing these maps.
Comment: $C$ is defined iteratively (its elements are leafs at the end of an infinite binary tree), thus you need to define $f(C)$ iteratively. Keeping track of $\inf, \sup f(C_i)$ could help.
Comment: @zhw. Thanks, updated.
Comment: @zhw.: you changed the title to a phrase that makes no sense. The image of something can't be bijective. The surjection that realizes that image can.
Comment: @symplectomorphic Yes you're right. Thanks. Is it better now?
Comment: Not sets of diameter $0$ but a tree, each layer of which gets smaller and smaller diameter.
Answer: A continuous bijection from a compact space (which the Cantor set is) to a Hausdorff space (which the standard unit interval is) is a homeomorphism.
But $C$ isn't connected and the unit interval is.


system() and CreateProcess() / CreateProcessW()

Question: I want to execute a TEST.exe in a C program. While I use
system( "TEST.exe <input-file> output-file" );

I can get what I expected.
But CreateProcessW() didn't work properly when I use the following code (see How do I run an external program?):
if (CreateProcessW(const_cast<LPCWSTR>(FullPathToExe.c_str()),
    pwszParam, 0, 0, false,
    CREATE_DEFAULT_ERROR_MODE, 0, 0,
    &siStartupInfo, &piProcessInfo) != false)
{
    /* Watch the process. */
    dwExitCode = WaitForSingleObject(piProcessInfo.hProcess,  (SecondsToWait * 1000));
    iReturnVal = GetLastError();
}
else
{
    /* CreateProcess failed */
    iReturnVal = GetLastError();
}

where
FullPathToExe="TEST.exe", pwszParam="TEST.exe <input-file> output-file".

And WaitForSingleObject() returns 258, GetLastError() returns 1813 ("The specified resource type cannot be found in the image file.").
Also, The above CreateProcessW() code works fine when I run my own HelloProcess.exe (print hello, and sleep some seconds determined by the following number, then exit.) with
FullPathToExe="HelloProcess.exe", pwszParam="HelloProcess.exe 10".

Any ideas? Thanks for any hints!
Comment: Is FullPathToExe a string or a wstring?
Comment: It's a wstring. I think the types of variables are OK, since the code runs well with my own *.exe.

I wonder if there is some problem with the "<"/">" in the parameters?
Comment: Title should be changed to "Input/output redirection: system() vs. CreateProcess()" but I'm not allowed to edit it. Also spacing is inconsequential – and hence misleading – in ` output-file`. Characters `<>` are prefixes but OP's spacing implies they are parentheses. Spacing that wouldn't be misleading: `input-file`.
Answer: system actually spawns a cmd instance in which your command is run:

The system function passes command to the command interpreter, which executes the string as an operating-system command. system refers to the COMSPEC and PATH environment variables that locate the command-interpreter file (the file named CMD.EXE in Windows NT). If command is NULL, the function simply checks to see whether the command interpreter exists.
  —Documentation of system

This is why redirection operators such as < and > work. This is not the case for CreateProcess which really just spawns a process instead of a shell that executes another process. Since the redirection operators are a feature of the shell and not the OS you'd have to do input and output to the process manually.
Comment: Thanks so much for your explanation. And I find the solution to my problem now, hooray!!
Answer: I do what CreateProcess and command line arguments
tells me to do, and fix the problem! Thank you guys for your attention!
For your convenience, here is the quotation of the answer:

You cannot use command-line redirection operators with CreateProcess()
  directly. You have to spawn an instance of cmd.exe and pass the
  operators to it instead, eg:
CreateProcess( "C:\\windows\\system32\\cmd.exe", t_str2, ...))

Where
  t_str2 is "/C C:\Temp\sift.exe < C:\img1.pgm > C:\img1.key". The
  actual path to cmd.exe can be determined by reading the %COMSPEC%
  environment variable.
Answer: WaitForSingleObject() returns a wait result, and not the exit code. https://msdn.microsoft.com/en-us/library/windows/desktop/ms687032(v=vs.85).aspx
258 is a WAIT_TIMEOUT. You should retry on this error code until you get the return value of 0 (WAIT_OBJECT_0), or some other error.
After this, use GetExitCodeProcess https://msdn.microsoft.com/en-us/library/windows/desktop/ms683189(v=vs.85).aspx
to get the exit code of the process.


Spare part inventory management calculating safety stock for non-normally distributed demand?

Question: I have a spare part supply chain with 2 echelons in it. Please see attached image for reference.

Currently there is a centralized spare part inventory where ROP is calculated based on outgoing demand.
SS= normsinv(0.99) x Stdeviation x Sqrt(Lead time demand + review period).
Based on Shapiro-Wilk test and due to applicability of Central limit theorem the demand distribution at the centralized inventory point seems to fit with normal distribution.
Because of this, in theory I would be able to decrease the safety stock required by considering local DC and service centre demand variaiblity. However, this is where I face my biggest roadblock.
The spare part demand in service centres is not normally distributed, while the demand at the central location is. The z-score currently used does not seem to be reliable. This is further backed up by the fact that the spare part availability is between 85% to 87% at the service centres
I would like to propose an alternative method to ensure that the spare part availability is between 95 to 99% at the service centres. As such, I was looking into applying poisson probability distribution when calculating the requirements for ROP. However, I do not fully understand how to go about doing it.
Any help or advice on what is the best approach in this situation would be greatly appreciated.
Answer: To tackle that problem of non normality i used block bootstrapping for the sales time series. Having n simulations you can just make percentiles in the required amounts (eg 90% service level)


In jQuery UI sortable, how do I get the element undernearth a dragged element

Question: Let's say you have 5 elements, labeled item 1,..,5.
Here is sample code illustrating this:

Item 1

Item 2

Item 3

Item 4

Item 5

If I drag item 1 over item 2, what event can I hook into to get the element under item 1 (which is item 2 in this case, but could be item 3 or 4 or 5.)
Note: Mouseover event gives me the item I am dragging (in this case item 1) and not the item under it (in this case, item 2.) So, that is not an option AFAIK.
I have included a jsFiddle:
http://jsfiddle.net/H6f2S/2/
Comment: Maybe you could get it from a mouseover event?
Comment: @kehrk: Good observation but unfortunately mouseover does not help (and was my first thought). Mouseover event give me the item I am moving, not the one under it (in my illustration, item 1)
Comment: I've never worked with jQuery draggable before so that's probably the best I'll be able to contribute. Good luck.
Comment: @kehrk: Thanks. Plus, you did help me update the question to make it clear.
Answer: I don't think the jQuery UI draggable API provide such a method.
I wrote a quick'n'dirty solution:
$("#sortable .ui-sortable-helper").live('mousemove', function(e) {
    var x = e.clientX;
    var y = e.clientY;

    var hoveredElement;
    // Iterate through all draggable elements (not the current one, not the helper)
    $("#sortable > li:not(.ui-sortable-helper, .ui-sortable-placeholder)").each(function(_, li) {
        var $li = $(li);
        var liOffset = $li.offset();
        var height = $li.outerHeight();
        var width = $li.outerWidth();
        // Test if mouse is in block bounds
        if (y >= liOffset.top &&  y <= liOffset.top + height
            && x >= liOffset.left && x <= liOffset.left + width) {
            hoveredElement = $li;
            return false;
        }
    });
    console.log(hoveredElement);
});

Working Fiddle
Please note few things:

You can cache jQuery selector in order to improve performance
Since your fiddle use jQuery 1.6.4 (!), I have used .live(), which is deprecated as of jQuery 1.7. You should use .on() instead.
This code does not take currently dragged element size. Thus, only the mouse position is checked, not the whole
 element bounds.
Comment: There is one, `elementFromPoint(x, y)`, but it will only returns the top-most element (i.e. the element *visible* at a given `(x,y)`).
Comment: Brilliant. I will experiment with this and resolve this question if your suggestion works. I thought about a similar approach but approached it wrong.  I was looking for an jQuery API or DOM API that gives me all documents in range of pageX and pageY. It failed to dawn on me that it may not exist and there is probably no reason why it should.


How hard is it to build CMS driven websites in WSS/MOSS?

Question: We build CMS's with ASP.NET using tools such as Umbraco and DotNetNuke etc
A client is asking us if we can build a site in WSS which I think is Windows Sharepoint Services.
Are there any experienced MOSS people out there who can tell me how hard we would find this?
Would it be just like learning another CMS?
Or will it be a nightmare?
Also, what software do we need to build the site in house for testing?
We don't have a MSDN subscription and use free Microsoft tools (Visual Studio Express and SQL Server Express)
Answer: Sharepoint is great for use with its own document management features, and it integrates well with Office products.
It's not such a good platform for development.  The API is a nightmare, web parts are incomprehensible, and the database has a terrible structure (fields are named NumericField1, TextField2, etc.  Yuck).
If you eventually need a web-facing server, MOSS is very expensive.
Answer: I will preface this by saying I am currently finally wrapping up a more-than-2 3-year project building one of the largest WCM sites deployed on MOSS in the world. We're talking thousands and thousands of content editors, nearly a million pages, millions of hits per day.
Depending on what you need, it could be moderately painful or extremely painful. MOSS is never a pleasure to use, so at the very least it will be an unpleasant exercise to deploy an out-of-the-box WCM site and make it look kinda like the design you want. However it should not be too terribly time-consuming or overly difficult.
If your needs look more like ours - do you need complex cross-loaded content on your pages? Content syndication and connected content? Flexible editor-controlled layouts? XHTML-compliant markup? Pixel-perfect design? If so, trying to use MOSS will absolutely be a nightmare.
Answer: Take note that WSS is not MOSS. WSS is the free version of SharePoint and MOSS is the paid version. MOSS is also the version designed for public facing CMS web sites.
With a bit of reading you should find MOSS relatively straight forward to develop a CMS site on top of. JP's link is a good one and I also recommend reading Andrew Connell's book Professional SharePoint 2007 Web Content Management Development: Building Publishing Sites with Office SharePoint Server 2007.
Depending on your requirements, in most cases you can work out-of-the-box with MOSS and SharePoint Designer. If you find you need more than what these can provide your learning curve will jump by quite a lot so tread carefully!
For development you will need at least a MOSS and SharePoint Designer license (as JP suggests MSDN is better and also gives you the option of using Visual Studio). Your client is going to need to fork out the licensing costs for MOSS. I think there are additional costs for public facing web sites but check with your Microsoft account manager.
See some cool stuff you can with public-facing web sites for the product at Top SharePoint.
Answer: It's not that hard.  I don't find it as easy as DotNetNuke, but it's still fairly straight forward once you have some of the concepts down.  There is a really great intro to CMS on MOSS at Web Content Management with SharePoint MOSS 2007.  You are going to need least the lowest level subscription to MSDN because CMS is part of MOSS not WSS.  Search around for deals on MSDN.
Answer: Actually if you are aware of the share point technology , then wont find it difficult to built CMS using it. Designing content management system using share point is actually possible.


Windows Clients: Windows or Linux Domain Controller?

Question: I'm planning to set up a domain controller for our small computer laboratory. I'm a little confused as to what operating system to use for our domain controller.
What's in the lab:

The lab has 25 units running a mix of Windows 7 and Windows XP.
The domain controller will only have 2GB of RAM running a C2D E7200. (Is this enough?)

What we want:

The Domain Controller will also be running a git server.
The Domain Controller will also be used as a general development machine (mostly Java, PHP).
A way to centralize the updates for the windows clients, so that they won't have to download the same patches from the remote site. The machines would just query them from the local domain controller and get the updates from there.

Our head recommended that I virtualize a Windows Server 2008 system under a Linux host and use the former as a domain controller and the latter for development or the other way around.
A comparison of the advantages and disadvantages of using a Linux distribution or Windows Server 2008 in this situation would also be appreciated.
As you may have noticed by now, I'm kinda new to setting up a domain so I hope you guys will be able to help me. Thank you.
Answer: If you are building a Windows environment, run a Windows domain controller.  You will save yourself an infinite number of headaches and drastically reduce your setup time.  Plus if/when something goes wrong competent MS folks are easier to find than competent *nix folks with domain controller hackery experience :)
You can run a Domain Controller on a very lean system (or even a VM as you mention above) IF you resist the temptation to tack a bunch of other services onto your DC.  Running WSUS on it is probably OK, but  It should NOT be a git server and it should NOT be a development machine.  Dedicate another box for these tasks (it can even be a unix system, which will make git easier to wrangle).
ideally nobody should be logging in to your DC locally, especially in a lab-type environment.
If you are not married to using Windows clients there are a number of ways to implement the lab environment using BSD or Linux systems...
Comment: +1 for not cluttering up the server with other crap. Windows domain servers can cause untold havok if weird things are running on them.
Comment: +1 for running Windows if you're running Windows.


Seguir link com Enter baseado em entrada de usuário

Question: Com a ajuda da comunidade, criei um arquivo para redirecionar um usuário que digitou seu login para uma página na web que recebe o usuário dessa forma:
https://site.com.br/usuario=LOGIN&empresa
O problema é que geralmente o usuário aperta Enter ao digitar o texto, então tentei adequar o código para que ao apertar essa tecla fosse redirecionado, mas aparentemente o link não está recebendo a variável.
Poderiam me auxiliar a, ao apertar Enter ou clicar em Entrar depois de inserir seu login, o usuário seja direcionado?
Segue o meu código:
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />

<title>Redirecionamento</title>

       Insira os números do seu

login ou CPF e clique em Entrar

    <input type="text" id="username" name="username" size="20">
    <input type="button" id="BotaoLogin" value="Entrar" onClick="redirecionar()">

Answer: function redirecionar() {
  var username = document.getElementById("username").value;
  if (username != "") {
    window.location = "https://site.com.br/usuario"+username+"&empresa";
  }
}

Falto capturar o valor do elemento.
Comment: Perfeito! Deu certo! Obrigado.


Is it correct to say that $\int e^{-x^2}dx=\sum_{n=1}^{\infty} (-1)^n\frac{x^{2n+1}}{n!(2n+1)}$

Question: Is it correct to say that:
$$\int e^{-x^2}dx=\sum_{n=0}^{\infty} (-1)^n\frac{x^{2n+1}}{n!(2n+1)}$$
I know that the stuff inside the summation is used as a formula for finding the n-th term in the series that equals $e^{-x^2}$ (the first bit of the series I speak of is: $C+x-\frac{x^3}{3}+\frac{x^4}{10}-...)$.
Since that's the case, wouldn't it be correct to say that the integral of $e^{-x^2}$ is indeed equal to that summation? Just wanting to be sure because I've never seen this explicitly stated anywhere.
Edit: to clarify, what I've done here is apply term-by-term integration to the power series representation of $e^{-x^2}$, which you can easily find by replacing $x$ with $-x^2$ in the power series for $e^x$.
Comment: You are allowed to integrate the power series to get an antiderivative (just make sure to start at $n=0$). [Here](https://math.stackexchange.com/questions/2159110/antiderivative-of-ex2-correct-or-fallacy) is a similar question.
Comment: Your question could use some more clarification.
Comment: Are you sure about the summation starting at $n=1$?
Comment: @mrtaurho That was a typo, thanks!
Comment: @NoChance could you clarify what I need to clarify?
Answer: Up to a constant factor this is precisely the series representation of the so-called Error Function which is defined as

$$\operatorname{erf}(z):=\frac2{\sqrt \pi}\int_0^z e^{-x^2}\mathrm dx$$

Expanding the exponential within and integrating termwise afterwards $($make sure that this can be justified here!$)$ yields to the the result you gave. Note that for the indefinite integral we have to add a constant of integration.
Thus, it is indeed correct to state that
$$\int e^{-x^2}\mathrm dx~=~\sum_{n=0}^\infty (-1)^n\frac{x^{2n+1}}{n!(2n+1)}+C$$
But more common, since the Error Function itself is widely used, to say that
$$\int_0^z e^{-x^2}\mathrm dx~=~\sum_{n=0}^\infty (-1)^n\frac{z^{2n+1}}{n!(2n+1)}$$
Matching the aforementioned definition of the Error Function omitting the constant factor for a moment.
Comment: I'd heard of the error function but hadn't looked into it deeply; I had no idea this was it! It's also insightful to see the definite integral from $0$, nice to know that the error function is actually pretty simple. Thanks for the help!
Comment: @JamesRonald No problem, glad to help! Feel free to accept the answer to show that you are satisfied; if not, tell me what I possible could improve further.
Comment: apologies, I had no idea that feature existed haha. Done now, thanks again


Subqueries podem diminuir a performance? Mito ou verdade?

Question: Bem, costumo trabalhar apenas com frameworks. Eu trabalho com frameworks MVC e costumo utilizar os ORMs para fazer consulta ao banco de dados.
No meu caso eu utilizo Laravel, mas já usei outros frameworks, e tive a oportunidade recente de conhecer o Entity Framework.
Alguns usuários experientes quanto ao uso do Entity Framework me mostrou que o ORM do mesmo costuma gerar uma SQL para consulta diferente da que estamos acostumados (algo que alguém sismado demais poderia dizer que diminui a performance).
Da mesma forma já constatei isso no framework Laravel.
O que quero dizer é que, em alguns casos, esses frameworks costumam gerar algumas consultas com subqueries, ao invés de usar um JOIN.
Por exemplo, eu já vi uma query que, para identificar se um usuário possui alguma publicação, estava sendo gerada dessa forma:
select * from
    usuarios
where
    (select count(*) from `posts` where `usuarios`.`id` = `posts`.`usuario_id`) >= 1

Mas creio que a mesma consulta poderia ser feito com JOIN.
Bem, agora eu explico por que estou falando dos frameworks antes de entrar no assunto. É porque já ouvi vários comentários da boca de "programadores", que dizem que subqueries causa problema de performance. Porém o que não dá pra entender é porque os frameworks então insistiriam em fazer algo que fosse prejudicial (diminuir a performance é prejudicial, quis dizer nesse contexto).
Porém, se vejo sendo usado  nos frameworks, logo vem à mente que "não tem problema nenhum" usar subqueries. E sem tem algum problema, não entenderia então o por quê de os desenvolvedores dos frameworks, que teoricamente teriam experiência suficiente para saber o que estão fazendo.
Eu um ISSUE no Github, onde havia alguém reportando o problema de performance por causa das subqueries geradas, observei que o desenvolvedor da biblioteca perguntou: "Mas as suas tabelas contém os índices definidos corretamente?", o que me levou a entender que o problema as vezes pode estar mais na maneira errada de usar do que propriamente na subquery.
Então, baseado em todos os meus argumentos acima, pergunto:

Subqueries sempre causam problema de performance, ou pode ocorrer esse problema dependendo de um contexto específico?
É verdade que a definição de índices para uma tabela pode melhorar o desempenho de uma subquery ou isso é baboseira?
A consulta mostrara acima, no exemplo, se fosse feita de outra forma (como por exemplo, usando JOIN), teria melhoria de performance?
Comment: só um detalhe que não responde a sua pergunta, mas que contribui para você melhorá-la. O SQL mostrado não é um exemplo válido de subquery. Não há como fazer isso em SQL, pelo menos nos SGDBs que conheço.
Comment: Em relação aos frameworks (e a alguns projetos em OO que usam bastante OO) as vezes, manter o padrão não é o melhor caso de performance. Escrever orientado a objeto de forma a obter performance é por si só uma tarefa dificil. Muitas vezes, você tem um programador experiente que escreve um código pouco performantico por causa do Design ou da cultura. Um ponto importante em relação aos frameworks é que eles não tem como prever todas formas que serão usados, mas, tentam gerar código baseado em padrões de comportamento e boas práticas de design, logo, podem gerar código de baixa performance.
Comment: Obrigado @cantoni, boa observação
Comment: Fiquei surpreso em saber que o laravel gera uma query "porca" dessas. Se eu quero saber publicações de um usuário faria apenas: SELECT COUNT(POST_ID) FROM POSTS WHERE PUBLISHER_ID = 100 por exemplo. Contaria por um campo só, reduzindo a quantidade de bytes por tupla eliminando obviamente o *. Não precisaria nem de join pois quero saber a quantidade de posts de usuários ativos e não ativos, qualquer coisa só passar um atributo a mais no where e tudo resolvido. Incrível como complicam aquilo que deveria ser tão simples!
Answer:
Subqueries sempre causam problema de performance, ou pode ocorrer esse problema dependendo de um contexto específico?

"Sempre" é uma expressão muito pesada, depende muito do caso. E aí não só do código gerado, mas também depende do otimizador do banco de dados, a forma como a execução se dá, e é claro, do conjunto de dados e modelo que está trabalhando, e mais um fator que falo abaixo.
Tem que analisar cada caso, sempre tem que medir.

É verdade que a definição de índices para uma tabela pode melhorar o desempenho de uma SubQuery ou isso é baboseira?

Total verdade, índices podem ser a salvação da lavoura se forem definidos corretamente. Esse pode ser o fator que realmente fará a diferença. Eles não podem salvar tudo e podem trazer alguns pequenos malefícios também (as atualizações ficam mais lentas, há mais consumo de espaço em disco e memória, etc.). Novamente, depende do que está fazendo e fornecedor usado.

Quais as vantagens e desvantagens do uso de índices em base de dados?
Como aplicar indexes para melhorar a performance das queries?
Índices desnecessários no banco são um problema?
Use the index, Luke

A consulta mostrara acima, no exemplo, se fosse feita de outra forma (como por exemplo, usando JOIN), teria melhoria de performance?

Esse exemplo especificamente eu não sei dizer, mas em exemplos mais comuns posso dizer que depende do banco de dados e como seria esse JOIN, em alguns pode ser que haja alguma otimização (bem comum). Em outros o JOIN é só açúcar sintático para a expressão comum.
Coloquei no GitHub para referência futura.
Comment: vc mitou... hehehe
Answer:
SubQueries podem diminuir a performance?

Em resumo, podem. Mas não é sempre assim.

Subqueries sempre causam problema de performance, ou pode ocorrer esse problema dependendo de um contexto específico?

Não. Tudo depende do motor de consulta do banco de dados e da estatística compilada em cima do esforço da consulta. Índices podem sim prejudicar o desempenho se mal formulados, mas a maior penalidade de desempenho normalmente vem de um design pobre de esquema de banco de dados.
Se o motor de banco de dados suporta executar subqueries em paralelo, o resultado pode até ser mais rápido que na execução usando joins. Há farto questionamento disso até mesmo no SO. O que responde adequadamente a isto é o estudo do plano de consulta. Cada banco de dados tem a sua maneira de obter este estudo.

É verdade que a definição de índices para uma tabela pode melhorar o desempenho de uma SubQuery ou isso é baboseira?

É verdade, dependendo do banco em que estamos falando. No Oracle, por exemplo, um TABLE SCAN pode ser mais rápido que uma busca por índices.
Novamente, vale a pena aplicar o índice e estudar a sentença.

A consulta mostrada acima, no exemplo, se fosse feita de outra forma (como por exemplo, usando JOIN), teria melhoria de performance?

E mais uma vez, depende. No SQL Server, por exemplo, normalmente JOINS são mais rápidos que subqueries, mas isto pode variar.
Aqui há um artigo sobre como obter o plano de execução da sua consulta no SQL Server.
Answer: Wallace, isto vai dependendo muito da engine do Banco de Dados, tendo como exemplo as duas consultas abaixo:
--Query A
SELECT
    A.TabelaAID,
    A.Descricao as DescricaoA
    (SELECT Descricao FROM TabelaB B WHERE A.TabelaBID = B.TabelaBID) as DescricaoB,
    (SELECT Descricao FROM TabelaC C WHERE A.TabelaBID = C.TabelaBID) as DescricaoC,
    (SELECT Descricao FROM TabelaD D WHERE A.TabelaBID = D.TabelaBID) as DescricaoD
FROM TabelaA A

--Query B
SELECT
    A.TabelaAID,
    A.Descricao as DescricaoA
    B.Descricao as DescricaoB,
    C.Descricao as DescricaoC,
    D.Descricao as DescricaoD
FROM TabelaA A
LEFT JOIN TabelaB B ON A.TabelaBID = B.TabelaBID
LEFT JOIN TabelaC C ON A.TabelaBID = C.TabelaBID
LEFT JOIN TabelaD D ON A.TabelaBID = D.TabelaBID

No SqlServer 2005 a Query A era exponencialmente mais lenta que a Query B, isto tudo por que a engine não conseguia traduzir a subquery em um join. como resultado, caso a TabelaA tivesse 1000 registros, a Query A iria executar 3001 consultas e a Query B apenas 1.
No SqlServer 2014, ainda existem algumas diferenças de desempenho, mas nada extraordinario, dependendo da consulta a subquery vai ser até mais rápido que o join.
Agora quanto ao seu exemplo, acredito que teria um melhor desempenho se usa-se EXISTS(SELECT 1 FROM post WHERE post.usuario_id = usuarios.id) ao invés de um COUNT com *.
O seguinte artigo possui uma ótima comparação que envolve uma tipo particular de subquery, que é bastante semelhante à do seu exemplo:
Should I use NOT IN, OUTER APPLY, LEFT OUTER JOIN, EXCEPT, or NOT EXISTS
Comment: Toby, o seu comentário sobre trocar Exists por Count é interessante. Recentemente, notei que o Framework Laravel substituiu o SELECT do meu Exemplo para um semelhante ao que você fez (usou o Exists)


Twilio Alphanumeric Sender ID and multiple phone numbers

Question: I have difficulties understanding the Twilio API.
It is specified that to send text messages with alphanumeric ID, you need to replace the "From" attribute with the text to be displayed. It works perfectly for me as I have bought only a single number. But it makes me wonder how Twilio selects the phone number to be used to send the text message if you are using an alphanumeric ID with multiple numbers attached to your account.
Regards,
Answer: Twilio developer evangelist here.
The message is not actually sent from a number. It's identifying sender is that string that you used. So the messages are not actually attached to any number. You can, in fact, release the number you have in Twilio and still send messages from an alphanumeric ID.
This highlights the drawbacks to an alphanumeric sender ID though. As the message never came from a real number, the receiver cannot respond to it.
So, don't worry about buying more numbers, they won't be a part of messages you send from alphanumeric IDs.
Comment: Okay! But I thought the pricing was depending on the country of the phone the message originated from. So it is actually not true? Buying a number is mostly useful to receive calls/messages then?
Comment: Pricing is dependent on the country (and sometimes phone network) that you're sending to, not from. Numbers are useful for receiving calls/messages, yes, but alphanumeric IDs won't work in every country either, so you may still need a number.
Comment: Okay, this is all very logic. I don't know why but the documentation confused me!


Least degree polynomial with integer coefficient and having one root $\sqrt{8+\sqrt 6 +4\sqrt 3+ 3\sqrt 2}$

Question: Find Least degree polynomial with integer coefficient and having one root as $\sqrt{8+\sqrt 6 +4\sqrt 3+ 3\sqrt 2}$
I tried doing square again and again is there any simpler method
Comment: $ x^8 - 32 x^6 + 240 x^4 - 320 x^2 - 368 $ according to Wolframalpha
Comment: The unpleasant fact is that such polynomial factors over any finite field, since at least one number among $2,3,6$ is a quadratic residue $\pmod{p}$, so we cannot conclude the irreducibility of such polynomial over $\mathbb{Q}$ from the irreducibility over a finite field.
Comment: Yes I got same just by doing squaring. Now how to prove it is minimal such polynomial?
Comment: @Makar: you already have a solution below. The polynomial $x^4-32 x^3+240 x^2-320 x-368$ is irreducible since $b_{00},b_{01},b_{10},b_{11}$ provided by dan_fulea are algebraic conjugates over $\mathbb{Q}(\sqrt{2},\sqrt{3})$.
Answer: Let us ask a computer algebra system, sage, about this:
<code>sage: a = sqrt(8+sqrt(6)+4*sqrt(3)+3*sqrt(2))
sage: a.minpoly()
x^8 - 32*x^6 + 240*x^4 - 320*x^2 - 368
</code>
So the "blind result" is telling us that we have to "square three times". The first squaring is simple, so let us consider $b={8+\sqrt 6 +4\sqrt 3+ 3\sqrt 2}$ instead of the above $a=\sqrt{8+\sqrt 6 +4\sqrt 3+ 3\sqrt 2}$. Then a possibility to do the job as a human is to consider the Galois conjugates of $b$, working in the field $\Bbb Q(\sqrt 2,\sqrt 3)$ where $b$ lives in:
$$
\begin{aligned}
b=b_{00} &=8+\sqrt 6 +4\sqrt 3+ 3\sqrt 2\ ,\\
b_{10} &=8-\sqrt 6 +4\sqrt 3- 3\sqrt 2\ ,\\
b_{01} &=8-\sqrt 6 -4\sqrt 3+ 3\sqrt 2\ ,\\
b_{11} &=8+\sqrt 6 -4\sqrt 3- 3\sqrt 2\ ,
\end{aligned}
$$
and building the polynomial $(X-b_{00})(X-b_{10})(X-b_{01})(X-b_{11})$. Now it is easy to see the coefficient in $X^3$, which is $-\sum b_{jk}=-(8+8+8+8)=-32$. The free coefficient can by also computed in a few lines,
$$
\begin{aligned}
&b_{00}b_{10}b_{01}b_{11}
\\
&\qquad=(b_{00}b_{10})\cdot(b_{01}b_{11})
\\
&\qquad=
\Big(\ (8+4\sqrt 3)^2 - (\sqrt 6 + 3\sqrt 2)^2\ )
\Big(\ (8-4\sqrt 3)^2 - (\sqrt 6 - 3\sqrt 2)^2\ )
\\
&\qquad=
\Big(\ (112+64\sqrt 3) - (24+12\sqrt 3)\ )
\Big(\ (112-64\sqrt 3) - (24-12\sqrt 3)\ )
\\
&\qquad=
\Big(\ 88+52\sqrt 3\ )
\Big(\ 88-52\sqrt 3\ )
\\
&\qquad=-368\ .
\end{aligned}
$$
Yes, we have a match of the free coefficient.
Let us do the job also for the coefficient of $X^2$ in the minimal polynomial of $b$, it is
$$
\begin{aligned}
&b_{00}b_{10}+(b_{00}+b_{10})\cdot(b_{01}+b_{11})+b_{01}b_{11}
\\
&\qquad=
(88+52\sqrt 3)+2(8+4\sqrt 3)\cdot 2(8+4\sqrt 3)+(88-52\sqrt 3)
\\
&\qquad=
88+88+4(64-48)
\\
&\qquad= 240
\ .
\end{aligned}
$$
The last coefficient can be computed along the same lines, grouping
$b_{00}b_{10}\cdot(b_{01}+b_{11})+
(b_{00}+b_{10})\cdot b_{01}b_{11}$, and the half of the computations are already done.
Note:
The indices $jk$ have the meaning
$$
b_{jk}=
8 + (-1)^j 3\sqrt 2 +(-1)^k 4\sqrt 3+ (-1)^j \sqrt 2\cdot (-1)^k \sqrt 3
\ ,
$$
corresponding to the Galois automorphism sending $\sqrt 2\to(-1)^j\sqrt 2$ and $\sqrt 3\to(-1)^k \sqrt 3$.


Testing Logistic Regression Classifier in R

Question: I am testing the logistic regression classifier in R. I created some test data like this:
x=runif(10000)
y=runif(10000)
df=data.frame(x,y,as.factor(x-y>0))

basically I am sampling the 2D unit square [0,1] and classifying a point belonging to class A or B depending on which side of y=x it lies.
I generated a scatter plot of the data like below:
names(df) = c("feature1", "feature2", "class")
levels=levels(df[[3]])
obs1=as.matrix(subset(df,class==levels[[1]])[,1:2])
obs2=as.matrix(subset(df,class==levels[[2]])[,1:2])
# make scatter plot
dev.new()
plot(obs1[,1],obs1[,2],xlab="x",ylab="y",main="scatter plot",pch=0,col=colors[[1]])
points(obs2[,1],obs2[,2],xlab="x",ylab="y",main="scatter plot",pch=1,col=colors[[2]])

it gives me below graph:

Now I tried running LR (logistic regression) on this data using code below:
model=glm(class~.,family="binomial",data=df)
summary(model) # prints summary

here are the results:
Call:
glm(formula = class ~ ., family = "binomial", data = df)

Deviance Residuals:
     Min        1Q    Median        3Q       Max
-0.11832   0.00000   0.00000   0.00000   0.08847

Coefficients:
              Estimate Std. Error z value Pr(>|z|)
(Intercept)  5.765e-01  1.923e+01   0.030    0.976
feature1     9.761e+04  8.981e+04   1.087    0.277
feature2    -9.761e+04  8.981e+04  -1.087    0.277

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 1.3863e+04  on 9999  degrees of freedom
Residual deviance: 2.9418e-02  on 9997  degrees of freedom
AIC: 6.0294

Number of Fisher Scoring iterations: 25

I also get these warning messages:
Warning messages:
1: glm.fit: algorithm did not converge
2: glm.fit: fitted probabilities numerically 0 or 1 occurred

If I try plotting the ROC curve using a varying threshold, I get following graph (AUC=1 which is good):

Could someone please explain why the algorithm does not converge and coefficient estimates are not statistically significant (high std. error in coeff estimates)?
I also compared to LDA:
lda_classifier=lda(class~., data=df)

gives:
Call:
lda(class ~ ., data = df)

Prior probabilities of groups:
 FALSE   TRUE
0.5007 0.4993

Group means:
       feature1  feature2
FALSE 0.3346288 0.6676169
TRUE  0.6710111 0.3380432

Coefficients of linear discriminants:
               LD1
**feature1  4.280490
feature2 -4.196388**

Answer: As you note, the standard errors are huge and the estimation algorithm doesn't really converge. There's two related things going on.

you have a two-dimensional predictor (two features), but a single linear combination of them is essentially perfectly related to the response. The relationship as a function of that linear combination (x-y) is very strong. The orthogonal direction is not at all determined.
you have complete separation in that ($x-y$) linear combination; that causes unstable estimates, since the fit of the model can be made "better" by inflating the magnitude of the coefficients to make the logistic curve increase more and more sharply:

--
While the parameter estimates for the two features individually are neither stable nor well-determined, the model still classifies perfectly. Performance of the fitted model on some new data:
Comment: i did not use it to predict new data. from what i have the AUC is less than 0.5 and it wasn't able to classify the training data itself.
Comment: i made a mistake in plotting the ROC curve. i will edit my post. i guess the question then is why does the algorithm not converge? the data does not look ill conditioned. also if you look at the std error of coefficient estimates, they are very large
Comment: Okay, I've recast my answer in light of your new question. You can read more about this issue in other answers on the site.


How do the parts of an '80's Pearl Export snare strainer come together?

Question: I play an 80's Pearl Export kit and today, while tuning, I accidentally undid the parts of the snare strainer. I'm not sure if I found all parts that got loose and I certainly am not sure how to put it together.
This is how it looks now, and the parts I have:

I found three washers:

smaller hole
bigger hole
curved washer (looks like some kind of lock washer)

As seen in the picture there's also a nut (the one to tighten the snares) and a "screw" that looks different in either end.
How do the parts of an '80's Pearl Export snare strainer come together? Do I have all parts? A picture of an assembled one would be great!
Comment: Google Pearl export snare strainer - there are plenty of pics to look at.
Comment: Good idea @Tim, and yes there are plenty of pics but if you could find one that show the position of the screws and washers (seen from the backside) point it out to me :P
Comment: What about looking for videos/blogs/etc... of people that make percussion instruments (if there are). You might find an idea of what screws are usually used.
Comment: I submitted this question to Pearl support, but their reply was to look for an instructional video on YouTube. I did find one for assembly of a Trick strainer. Even though it's different hardware, I wonder if it would give you enough clues to reassemble yours. [How To Assemble A Trick Unassembled Strainer](https://www.youtube.com/watch?v=0xKD289VWf0).
Comment: Here's another candidate video. It involves a Pearl marching snare, so at least the brand is the same  (but you might need to watch it backwards). [Disassembling snare throw off and strainer!](https://www.youtube.com/watch?v=-zWbJyhcmTs).
Comment: Unfortunately the older Pearl Export is of a totally different (and much simpler) construction.
Answer: One nut was gone in my original setup (or got lost when it disassembled itself :). All washers but the spring washer seems to have been put there by someone else than the manufacturer (since they where of odd sizes and also not fitting the screw).
This is what it looks like assembled:

Steps:

The screw goes with the fully threaded end into the block, so that the partially threaded end is pointing upwards when the strainer is in place.

The screw is screwed into the block until there enough play for the strainer to be adequately adjusted when the strainer is in place. You have to put the strainer in place and check that this is ok -- then take it out from the rail again, put on the spring washer and lock the screw with the nut.

Then slide the strainer upwards on the rails again, and put on the adjustment nut that is used to adjust the snare.

Done!
Comment: @Aaron, Unfortunately just trial and error ... There are many ways to put it together, but this is the only way it works as far as I've tried :) Oviously the screw can't be loose (as it would be without the nut), since it would then unscrew itself when the snare is adjusted with the adjustment nut/dial whatever you call it (this is what happened in the first place).

I haven't been able to find a video or pictures of this particular model.
Comment: How did you find the solution?
Answer: Most snare strainer mechanisms rely on a sort of knee joint. Imagine a limb where the hip joint is attached to the snare wires and the ankle is attached to the snare drum shell. When the knee joint is bent the hip and ankle are close together and the snare is off, and when you straighten the knee joint the hip moves away from the ankle and tightens the snare across the drum head. The other detail is that, like an actual human knee, when you straighten the knee, it goes just past the fully-straightened alignment, and then locks. This prevents your snare suddenly popping off - you have to turn it off deliberately.
The double-ended screw in your photo is part of a fine tensioner. The partially-threaded end screws into that silver knob, and the other fully-threaded end screws into the barrel nut in the photo.
From the photo I can't identify the parts of the knee joint, but you should be able to work it out. The washers are there to spread the load and reduce friction so the adjuster knob can be turned easily.
If you attach a photo taken facing the mech rather than from above, I could add more suggestions if you really need them.
Comment: All your thoughts are good to hear, and they make sense, but my problem is how to assemble the parts in the right place. It turned out that a nut was missing.


Show that $\cos(2X)$ is equally distributed to $\cos(X)$

Question: For $X \sim U[0,2\pi]$, I have tried to show that the MGFs of $\cos(X)$ and $\cos(2X)$ are equal but this does not appear to be working. My next attempt was
\begin{align}P\left(\cos(X) < x\right) &= P\left(X < \cos^{-1}(x)\right) + P\left(X < \cos^{-1}(-x)\right) \\[0.4cm]&= \frac{\cos^{-1}(x)}{2\pi} + \frac{\cos^{-1}(-x)}{2\pi}\end{align} for $x \in [-1,1]$ and
\begin{align}P(\cos(2X) < x) &= 2\left[P\left(X < \frac{\cos^{-1}(x)}{2}\right) + P\left(X < \frac{\cos^{-1}(-x)}{2}\right)\right] \\[0.4cm]&= 2\left[ \frac{\cos^{-1}(x)}{4\pi} + \frac{\cos^{-1}(-x)}{4\pi}\right] = \frac{\cos^{-1}(x)}{2\pi} + \frac{\cos^{-1}(-x)}{2\pi}\end{align} for $x \in [-1,1]$, which seems to work.
Thea idea here is that $\cos(x)$ is 1:1 on $[0,\pi]$ and $[\pi,2\pi]$ (hence two seperate terms in the first calculation) while $\cos(2x)$ is 1:1 on $[0,\pi]$ and $[\pi,2\pi]$ and $[2\pi,3\pi]$ and $[3\pi,4\pi]$.(Hence the factor 2 in the second calculation). Is this correct, and if so is it correctly argued?
Comment: Your arguments are not fine. You should discuss wether $x<\pi$ or not (for the first case). Note also that $\arccos (x) + \arccos(-x) = \pi$ for $ x \in [-1,1]$. A more straightforward (not necessarily less involved) way to go about this is to look at charateristic functions.
Comment: @ Math-fun Thank you! I will look into this.
Answer: Hint:
If $A=\left\{ x\in\left[0,2\pi\right]\mid\cos x\in B\right\} $
then:
For $x\in\left[0,\pi\right]$ we find: $$\cos2x\in B\iff2x\in A$$
For $x\in\left[\pi,2\pi\right]$ we find: $$\cos2x=\cos\left(4\pi-2x\right)\in B\iff4\pi-2x\in A$$
So if $X\in[0,2\pi]$ then: $$\cos2X\in B\iff X\in\frac12A\cup(2\pi-\frac12A)$$
It remains to prove that: $$\Pr(X\in A)=\Pr\left(X\in\frac12A\cup(2\pi-\frac12A)\right)$$
Comment: Thanks! How am I to interpret $\frac{1}{2}A$?
Comment: As $\{\frac12a\mid a\in A\}$ wich is a subset of $[0,\pi]$. And $2\pi-\frac12A$ as $\{2\pi-\frac12a\mid a\in A\}$ which is a subset of $[\pi,2\pi]$.


How to write and show something on Delphi IDE status bar

Question: I want to know how can I write a module to show something like clock or other thing on Borland Delphi 7 IDE status bar, because I know it's possible but I couldn't find how!
Comment: Why so many downvotes? Question looks perfectly clear and reasonable for me, and it did so since very first revision. @user3615169, I feel quite lazy today, sorry, so I'm going to ask you *what did you try, what you researched so far, in other words, **what did you know already?***
Comment: IIUYC you have to write an IDE expert. Check out ToolsAPI/OTA. See [this FAQ](http://www.gexperts.org/open-tools-api-faq/) for a start.
Comment: possible duplicate of [Create a Simple Delphi IDE Expert](http://stackoverflow.com/questions/4488873/create-a-simple-delphi-ide-expert)
Answer: To insert a text in a StatusBar, you have to insert a panel first.
Just select your statusbar, find the property "Panels" (or perform double click over the statusbar) and click in "Add new".
After that, you can write what you want inside the panel in the property "Text" (you can insert one or more panels).
To do it programmatically, you can do something like this:
procedure TForm1.Timer1Timer(Sender: TObject);
begin
  StatusBar1.Panels[0].Text := 'Today is: ' + FormatDateTime('dd/mm/yyyy hh:nn:ss', Now);
end;

Comment: Actually, I'm not understanding exactly what you want, sorry. Try to give us more details about it.
Comment: Your answer is not my answer because I want to write on Delphi7 status bar not on my own form of application but thanks for your attention
Answer: Since OP didn't replied with more details, I'm going to post a little demonstration how to reach a status bar of Delphi's edit window. I had no success with adding new distinct status panel w/o disturbing layout, so I'm just changing the text of INS/OVR indicator panel.
Disclaimer: I still do not have access to the machine with Delphi 7 installed, so I've done that in BDS ("Galileo") IDE. However, differences should be minor. I believe what main difference lies in the way how we locate edit window.
Key strings are: 'TEditWindow' for edit window class name and 'StatusBar' for TStatusBar control name owned by edit window. These strings are consistent across versions.
{ helper func, see below }
function FindForm(const ClassName: string): TForm;
var
  I: Integer;
begin
  Result := nil;
  for I := 0 to Screen.FormCount - 1 do
  begin
    if Screen.Forms[I].ClassName = ClassName then
    begin
      Result := Screen.Forms[I];
      Break;
    end;
  end;
end;

procedure Init;
var
  EditWindow: TForm;
  StatusBar: TStatusBar;
  StatusPanel: TStatusPanel;
begin
  EditWindow := FindForm('TEditWindow');
  Assert(Assigned(EditWindow), 'no edit window');
  StatusBar := EditWindow.FindComponent('StatusBar') as TStatusBar;
  (BorlandIDEServices as IOTAMessageServices).AddTitleMessage(Format('StatusBar.Panels.Count = %d', [StatusBar.Panels.Count]));
  //StatusPanel := StatusBar.Panels.Add;
  StatusPanel := StatusBar.Panels[2];
  StatusPanel.Text := 'HAI!';
end;

initialization
  Init;

finalization
  // nothing to clean up yet

Another note: As you see, I use Open Tools API to output debug messages only, to interact with IDE I do use Native VCL classes. Therefore, this code must be in package.

The code above is a relevant part of the unit which should be contained in package. Do not forget to add ToolsAPI to uses clause as well as other appropriate referenced units (up to you).
Package should require rtl, vcl and designide (important!).
Since I run the testcase directly from initialization section, installing the package is enough for testcase to run and produce some result.
Comment: @user3615169, I updated the answer. But I strongly suggest you to step back to the basics, because writing IDE add-ins is rather complex field for a novice. Feel free to request more details, tho.
Comment: Dear Free Consulting , Thanks for your answer, I want to test your answer, but I couldn't find where and in which module, may you help me for thisthis


Rails STI: invoking child method

Question: I've got something like this
class Reply < AR::Base
end

class VideoReply < Reply
  def hello
    p 'not ok'
  end
end

class PostReply < Reply
  def hello
    p 'ok'
  end
end

...

So when I am creating object:
# params[:reply][:type] = "VideoReply"
@reply = Reply.new(params[:reply])

How can I invoke child method (in this case VideoReply::hello)?
UPD:
I can imagine only very stupid solution:
@reply = Reply.new(params[:reply])
eval(@reply.type).find(@reply.id).hello

But it is not cool, I think :)
Answer: When you're dealing with STI-based models, you'll have problems creating them if you're not careful. Retrieving them should be done automatically so long as you use the base class to find.
What you need is to create the proper kind of model in the first place and the rest will be fine. In your model or controller define a list of valid classes:
REPLY_CLASSES = %w[ Reply VideoReply PostReply ]

Then you can use this to verify the type before creating an object:
# Find the type in the list of valid classes, or default to the first
# entry if not found.
reply_class = REPLY_CLASSES[REPLY_CLASSES.index(params[:reply][:type]).to_i]

# Convert this string into a class and build a new record
@reply = reply_class.constantize.new(params[:reply])

This should create a reply with the proper class. Methods should work as desired at this point.
Comment: it looks hacky, but why not? thx! By the way to create REPLY_CLASSES array we can use `Reply.subclasses.map{|s| s.to_s} << "Reply"`
Comment: The temptation is there to use `Reply.subclasses` but the catch is that only indicates which classes are loaded. When your app spins up that will be empty. Rails is able to auto-load subclasses on-demand, but it can't predict which subclasses can be loaded in advance without actually trying to load them. If you want to get fancy, you can manually load all of `app/models/reply/*.rb` to force them in if you want, but you'll have models called `Reply::Video` and `Reply::Post` instead. You could also try force-loading `app/models/*reply*.rb` as well.
Comment: In production Rails will load all classes. In development we can use static REPLY_CLASSES array
Comment: I think things are auto-loaded even in production, so you might want to validate that your sucblasses array will be fully populated.

Rails STI: invoking child method


CSS cross-browser pelo JavaScript

Question: No CSS exitem algumas propriedades que precisam de um prefixo para alguns navegadores, por exemplo:
-webkit-transition: all 4s ease;
-moz-transition: all 4s ease;
-ms-transition: all 4s ease;
-o-transition: all 4s ease;
transition: all 4s ease;

Se eu quiser alterar essas propriedades de um elemento pelo JavaScript, uso:
document.querySelector('#myElment').style.transition = 'all 4s ease';

Ao mudar a propriedade style.transition é o suficiente para que funcione em todos navegadores?
É necessário aplicar algum prefixo? Quais são?
As propriedades que precisam aplicar esses prefixos são as memas que precisam aplicar os prefixos do CSS?
Preciso aplicar esse prefixo em todos os navegadores (assim como no CSS) ou apenas o de cada navegador?
Devo alterar essas propriedades de forma que o último seja sempre sem prefixo para que tenha prioridade sobre os demais (quando disponível) ou tanto faz?
Comment: Como a pergunta é um pouco ampla, o JavaScript tem também a função de alterar as propriedades CSS de forma dinâmica, sendo assim, o que vc usa no CSS deve ser o mesmo no JS, o que muda é apenas a sintaxe _camelCase_ que o JS trabalha, sem hífens. Por ex.:, `.style.webkitTransition`, `.style.mozTransition` etc... Se a propriedade `transition` necessita de um prefixo para certo navegador, só `.style.transition` não vai fazer efeito.
Comment: Relacionado: https://pt.stackoverflow.com/questions/3674/%C3%89-necess%C3%A1rio-adicionar-prefixos-em-algumas-propriedades-do-css/
Comment: Relacionad 2: https://pt.stackoverflow.com/questions/245870/ordenar-estilos-com-prefixos-no-css
Answer:

Ao mudar a propriedade style.transition é o suficiente para que funcione em todos navegadores?

Não. Se uma propriedade necessita de prefixo em um determinado navegador, deve-se colocá-lo no JavaScript também. A diferença é que no JavaScript utiliza-se a sintaxe camelCase. Ex.: .style.mozTransition, .style.webkitTransition etc.

É necessário aplicar algum prefixo? Quais são?

Mesma resposta da pergunta anterior. Os prefixos comuns são os mesmos que você utilizou na pergunta.

As propriedades que precisam aplicar esses prefixos são as mesmas que precisam aplicar os prefixos do CSS?

Sim. Quando você altera propriedades CSS via JavaScript, as regras são basicamente as mesmas.

Preciso aplicar esse prefixo em todos os navegadores (assim como no CSS) ou apenas o de cada navegador?

Você deve fazer assim como no CSS, colocando todos os prefixos, porque o navegador automaticamente irá assumir o que lhe for compatível. Não tem como colocar de cada navegador porque, em tese, você não sabe qual navegador o usuário está usando para poder escolher qual prefixo usar. Logo, colocando todos, você não precisa se preocupar com isso.

Devo alterar essas propriedades de forma que o último seja sempre sem prefixo para que tenha prioridade sobre os demais (quando
  disponível) ou tanto faz?

Há um tempo eu fiz uma pergunta a respeito da ordem dos prefixos no CSS, e constatei que a ordem pode influenciar em alguns casos. Sendo assim, é recomendável manter essa ordem mesmo quando feito via JavaScript, ou seja, a propriedade sem prefixo vir por último.

CSS cross-browser pelo JavaScript


Are people allowed to mention paying somebody?

Question: This question originally had a comment about paying somebody for help, I removed the comment as I'm not sure if it's allowed or not.
What are the rules for this?
I feel it shouldn't be allowed, the answers here should be public for all to see.
Comment: Related discussion on main meta: [Edit out an offer of financial reward. Right or wrong?](https://meta.stackexchange.com/q/42767)
Answer: Job hunting and developer fishing are not allowed