Function Parameter Undefined For Object Array In AngularJS

Question: I've been practicing AngularJS1x doing tutorials from Lynda and Udemy. I did a tutorial that created a multiple choice quiz. I wanted to see if I understood the code by recreating it and then push it farther but trying to make it a fill in the blank quiz.
The questions and answers all pull from a JSON file. The fill-in check works correctly and if the user input matches the string in the JSON object it works fine. I didn't change much but the code does not work when trying to call the $parent.index array. For reference of the original code I used as a multiple choice quiz you can find that link here
I would love it if someone could also explain why I was wrong if I set it up incorrectly so I can get better. I compared it to the original code and could not find where I went wrong.
The problem lies when targeting the array number of the object. I will also show the code below.
Problem
It lies within anything that calls the qIndex parameter like this:
$scope.myQuestions[qIndex].questionState; //Says it is undefined

if I give it a hard coded array number like 0 it works
$scope.myQuestions[0].questionState //If all of them are like this its fine as it calls the first question and finds the correct answer if typed into the input.

Here is the code below:
HTML

Test Your Knowledge:Saturn

 -1) ? 'inactive' : 'active' }}">

Welcome

Click to begin to test your knowledge of Saturn.

Begin

 {{ myQuestion.instructions }}

Check Answer

Correct.

Oops! That is not correct.

 {{ myQuestion.feedback }}

Continue

Results

You Scored {{percentage}}% by correctly answering {{score}} of the total {{totalQuestions}} questions.

Use the links below to challenge your friends.

QUIZ.JS
(function(){
    var codeApp = angular.module('codeApp', ['ngSanitize']);

    codeApp.controller('QuizController', ['$scope', '$http', "$sce", function($scope, $http, $sce){
        $scope.score = 0;
        $scope.activeQuestion = -1;
        $scope.activeQuestionAnswered = 0;
        $scope.percentage = 0;

        $http.get('quiz_data.json').then(function(quizData){
            $scope.myQuestions = quizData.data;
            $scope.totalQuestions = $scope.myQuestions.length;
        });
        $scope.checkAnswer = function(qIndex,aIndex){
            var questionState = $scope.myQuestions[qIndex].questionState;

                if(questionState != 'answered') {

                    var userAnswer = $(".fillin").val();
                    console.log(aIndex); //logs 0
                    console.log(qIndex); //logs undefined

                    var correctAnswer = $scope.myQuestions[qIndex].questionAnswer;

                    $scope.myQuestions[qIndex].questionAnswer = correctAnswer;

                            if(userAnswer === correctAnswer){
                                $scope.myQuestions[qIndex].correctness = 'correct';
                                $scope.score += 1;
                                console.log('Correct!' + $scope.score);
                            }
                            else{
                                $scope.myQuestions[qIndex].correctness = 'incorrect';
                                console.log('Wrong!');
                            }
                        $scope.myQuestions[qIndex].questionState = 'answered';

                }else{
                    console.log('Something is wrong');
                }

                $scope.isCorrect = function(qIndex,aIndex){
                    return $scope.myQuestions[qIndex].questionAnswer === userAnswer;
                }
        }

        $scope.selectContinue = function(){
            return $scope.activeQuestion += 1;
        }

        $scope.createShareLinks = function(percentage){

            var url = 'http://codifydesign.com';
            var emailLink = '<input type="text" placeholder="hi" />Email a friend';
            var twitterLink = 'Tweet your score';
            var newMarkup = emailLink + twitterLink;
            return $sce.trustAsHtml(newMarkup);
        }
    }]).filter('trustAsHtml', [
    '$sce',
    function($sce) {
        return function(value) {
            return $sce.trustAsHtml(value);
        }
    }
    ]);
})();

JSON
[
    {
        "questionId": 0,
        "question" : "Saturn is <input id='guess-input' class='fillin' type='text' name='\"six\"'> many planets from the sun?",
        "questionAnswer" : "six"
    },
    {
        "questionId": 1,
        "question" : "Around Saturn are <input id='guess-input' class='fillin' type='text' name='\"rings\"'>",
        "questionAnswer" : "rings"
    }
]

Answer: In angularjs $parent.$index is $index from the parent scope. It is useful when you have nested loops. Then you can get $index from the parent scope using $parent.$index construction. You code doesn't have nested loops. ng-repeat="myQuestion in myQuestions" is top levele loop. So it doesn't have index in its parent scope. I can guess that in original code there was one loop in another like one ng-repeat in another ng-repeat.


How do I convince Dell blades to PXE Boot

Question: Scenario:
Brand new Dell M610 blades.
Connected to the network with a 10GE uplink into a Dell PowerConnect M6220 blade switch.
DHCP server evidently working, as everything else boots / gets addresses fine.
TFTP server working fine.
Can't seem to get a DHCP address from the server.

Is there something on a blade chassis level interfering? Will I need to set up something special on the chassis? On the switch? On the blade?

Portfast = Enabled.
IP Helper = Points at our DHCP server (BUT! Shouldn't be needed, everything is somewhere on 192.168.0.0/16)
DHCP Relay = Enabled
DHCP Snooping = Disabled

Now What?
Comment: What do the DHCP server logs say? You should see the DHCP exchange (On my ISC DHCP daemon, the exchange steps are DHCPDISCOVER, DHCPOFFER, DHCPREQUEST and then a DHCPACK) so that the client gets an IP address. It looks like your server isn't making it past this step (TFTP occurs after this step, so it's irrelevant for the error above).
Comment: The traffic isn't getting that far.
Comment: You mean there is nothing in the logs at all? Traffic is not making it to the server? That's good to know, because it helps to clarify your question.
Comment: There's not nothing in the logs.. The DHCP works for every other physical device on the network.  There's nothing blade-related there.
Answer: It sounds like you might have an L3 switch in the mix that needs DHCP Forwarding configured on it.
Answer: MDMarra was closest with the suggestion of a L3 switch.
I actually solved this just now (20:20 GMT) by:

Resetting the switch to factory defaults.
Double-checking the cables to the fibre core switch and the patch panel.
Swapping the SFP port on the Core Switch
Swapping the SFP port on the Dell Blade Switch (Why this matters is beyond me, unless there's a duff port).
Testing everything one more time.
Answer: Maybe you haven't enable portfast, or the Dell equivalent on the switch?
Comment: Portfast is enabled.


Steiner symmetrization preserves compactness?

Question: I have read " Convexity, H.G.Eggleston, 1958'' and in page 91, theorem 43, it proves that a closed, bounded and convex set $\mathcal{X}$  is  still closed bounded (and convex) under Steiner symmetrization with respect to one plane $\beta$ (or with respect to its normal direction $a$ and I denote the transformation as $S_a$ here). Here I want to know why $S_a(\mathcal{X} )$ is closed (thus compact in $\mathbb{R}^n$)?
More explicitly, in the book, it uses $\limsup_{i\to \infty}\lambda(p_i)\leq \lambda(p)$ as $i\to \infty$, where $\lambda(p)$ is the Lebgesgue measure of the segment whose mid-point at $p$ lies in $S_a(\mathcal{X})$, but I don't know why it is true.
I know the Lebesgue measure is upper semi-continous with respect to the Hausdorff distance but does it works in this situation?
Answer: Recently I've noticed that this question can be done like this:
By one of Blashke's theorem, for a sequence $(p_n)$ with $\lambda(p_n)\to \limsup_i \lambda(p_i)\ (n\to \infty)$, we have a limit $K$ of a subsequence of lines with respect to $p_i$, and we can simply argue that $K$ is contained in the line with respect to $p$ and since Lebesgue measure is upper semi-continous with respect to the Hausdorff distance, it's done.
And a more easy way to prove it is to use the definition of Lebesgue measure and some knowledge of compactness.

Steiner symmetrization preserves compactness？


Break up a long line in a .htaccess file

Question: I am setting a Content-Security-Policy header in my .htaccess file, and it has grown to be an extremely long single line, which is a bother to manage. Is there some way to break up this line into more manageable substrings?
As a trivial example, say I am setting a header like
Header set Content-Security-Policy "deafult-src http://domainA.com; script-src http://domainB.com"

I can (without obvious breaking problems) accomplish my specific case with something like
Header append Content-Security-Policy "default-src http://domainA.com;"
Header append Content-Security-Policy "script-src http://domainB.com"

but that will insert commas into the string, so I was still curious if there was a better answer that could be applied generally, without adding the additional chars to the response.
What would be ideal is if there were some concatenation character that I could use to break the string into smaller parts, like
Header set Content-Security-Policy "default-src http://domainA.com;"
\" script-src http://domainB.com"

or
Header set Content-Security-Policy "default-src http://domainA.com;"^
" script-src http://domainB.com"

or
Header set Content-Security-Policy "default-src http://domainA.com;"
+" script-src http://domainB.com"

Alternatively, if I could set some sort of variable and just dump their contents to do something like
a="default-src http://domainA.com;"
b=" script-src http://domainB.com"
Header set Content-Security-Policy $a$b

that would also be much more managable.
There was a similar topic that came up for nginx and the conclusion was just to live with the long lines (they were dealing with a long regex, so the append solution wouldn't have worked); Is that going to be the case for Apache as well?
Comment: Will Holding shift and pressing enter after each of your substrings do the trick?
Comment: @StixO No, this issue relates to how apache parses strings in conf files. Generally (usually HTML) editors will use such a shortcut to differentiate between line breaks (say, ) and paragraph breaks (). This will depend on the markup format being parsed, and the editor. Apache conf files are pure text, and as such have no differentiation between a line an paragraph (regardless of modifier, enter produces a single, system-dependent carriage-return character like \n or \r).
Answer: The following should work:
 Header set Content-Security-Policy "default-src http://domainA.com; \
      script-src http://domainB.com"

Comment: I applied backslash in a lengthy regular expression pattern in RewriteRule. I worked like a charm but next line auto tab spaces (generated by VS code) must be deleted to get it to work although.
Comment: @kasperd you need to run `a2enmod headers`
Comment: Wow, actually, evidently you can escape any whitespace character this way. Confirmed working with \ as well. .htaccess will never have looked so good!
Comment: Huh, even works to break up regex! @BazzaDP, you might want to go drop this answer on that nginx question I mentioned as well, might work there too.
Comment: I tested this and got `Invalid command 'Header', perhaps misspelled or defined by a module not included in the server configuration`.
Comment: @BazzaDP Interesting! I would expect that this would cause the server to send an escaped newline, but it seems like it concats the way I would want, and is imperceptible from the clients perspective.
Answer: Yes - the backslash works as a line-continuation.  This is buried within the Apache 2.4 documentation on  https://httpd.apache.org/docs/2.4/configuring.html#page-header
Important rules:

Whitespace within a line is fine, ie. any number of tabs and spaces;
The last character on all lines except the final one must be a backslash;<
The final line must not terminate with a backslash;
The Apache comment character (#) cannot be used to comment out a line.
You can not break the [flags]

If these rules are not obeyed, the server will respond with an Error 500.
Note that when editing *.conf files you can use C:\Apache24\bin>httpd -t to check your syntax.
Comment: the problem are the flags, and you can't break the flags


How to rename a column that is an index?

Question: I want to rename a table column but it is an index therefore I get an error. How do I solve this problem?
ALTER TABLE <name> RENAME column <id> TO <newid>;

Error: SQL0478N  DROP, ALTER, TRANSFER OWNERSHIP...
Comment: Please show your code and the error.
Answer: At the shell command line, you can use db2 "? SQL0478N" | more  to see the details of the error and some suggestions.
The error is telling you that the object you want to change has dependent objects, so until you handle the dependencies you cannot complete the alter action.
You can choose between doing the dependency management manually, or use a stored procedure to do it for you.
If you want to do it manually, you have to find the dependent objects, drop them, rename the column(s) , then recreate the dependencies. There can be other dependent objects, not only an index, such as packages.  If your Db2-server runs on Linux/Unix/Windows, you can use the stored procedure DBMS_UTILITY.GET_DEPENDENCY , or you can query the catalog manually. It depends what is easier for you.
Recreating dependencies can be invasive, and if there are static-SQL objects that reference the relevant indexes then they will need to be rebound. For production use this can involve a service outage, which you want to avoid.
So you must be certain that the renaming of the column is essential. Sometimes you can just create a view with the relevant column renamed in the View but the base table remaining unchanged.
If you want try automation, and if your Db2-server runs on Linux/Unix/Windows then you can use the stored procedure SYSPROC.ALTOBJ - there is a learning curve however and this is not suitable for all schema-evolutions.
Answer: Solution:
drop index
alter table
create index


$\int _ { 0 } ^ { L } \left\{ \left( \int _ { 0 } ^ { x } f ( y ) d y \right) \left( \int _ { 0 } ^ { x } g ( z ) d z \right) \right\} d x$

Question: As in the title,
What I wanna do is
$\int _ { 0 } ^ { L } \left\{ \left( \int _ { 0 } ^ { x } f ( y ) d y \right) \left( \int _ { 0 } ^ { x } g ( z ) d z \right) \right\} d x$
Here, functions f and g are arbitrary ones, x is a variable, and L is a constant number.
I can do this numerically. But It takes so much computation costs.
Therefore, I'd like to convert this formula to a simpler form before doing numerical computation. (I think the integral by parts can be a key but I have no idea how/where I should apply it)
Are there any clever ways to do this?
Comment: What numerical algorithm are you using? The formula is already "simple".
Comment: I'm using the Gaussian quadrature. But, I need much more matrix computations than those I needed for solving just normal integral such as int(f(x),0,L).
Comment: I don't see the problem, It's a single for loop unless I'm missing something.
Comment: @SinwooJeong It shouldn't take meaningfully longer than a single integral. Going from $\int_0^x \ldots$ to $\int_0^{x+dx} \ldots$ just requires adding one evaluation of $\ldots$ to the former...
Answer: It seems very straightforward as it is... For general functions $f,g$ there is no way of simplifying the expression. From the numerical point of view, taking a regular decomposition of $[0,L]$ and some numerical quadrature $\int_0^L h(x) dx \approx \sum_{i=1}^n w_i f_i$, you just have to implement the expression
$$
\sum_{i=1}^n \left(w_i \left(\sum_{j=1}^{i} w_j f_j\right)  \left(\sum_{j=1}^{i} w_j g_j\right) \right)
$$


Internal Server Error while sending mail with extended property

Question: I am using EWS Managed API. I just started fiddling with Extended properties. So I wrote simple code to send a simple mail with extended property attached to it.
Forming the mail part I simply copy pasted from this MSDN page. For testing purpose I suppressed certificate validations.
This is my complete code:
1     ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
2     service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
3     service.TraceListener = new TraceListener();
4     service.TraceEnabled = false;
5
6     service.Credentials = new WebCredentials("firstname.lastname@example.com", "password@123");
7     service.Url = new Uri("https://exchng.domain.com/EWS/Exchange.asmx");
8
9     Guid MyPropertySetId = new Guid("{C11FF724-AA03-4555-9952-8FA248A11C3E}");
10
11     // Create a definition for the extended property.
12     ExtendedPropertyDefinition extendedPropertyDefinition = new ExtendedPropertyDefinition(MyPropertySetId, "Expiration Date", MapiPropertyType.String);
13
14     // Create an e-mail message that you will add the extended property to.
15     EmailMessage message = new EmailMessage(service);
16     message.Subject = "Saved with extendedPropertyDefinition of two days";
17     message.Body = "The expiration date is contained within the extended property.";
18     message.ToRecipients.Add("firstname.lastname@example.com");
19
20     // Add the extended property to an e-mail message object named "message".
21     message.SetExtendedProperty(extendedPropertyDefinition, DateTime.Now.AddDays(2).ToString());
22
23     // Save the e-mail message.
24     message.SendAndSaveCopy();

I am getting below exception (with no nested inner exceptions) on line 24:
An internal server error occurred. The operation failed.
   at Microsoft.Exchange.WebServices.Data.ServiceResponse.InternalThrowIfNecessary()
   at Microsoft.Exchange.WebServices.Data.ServiceResponse.ThrowIfNecessary()
   at Microsoft.Exchange.WebServices.Data.MultiResponseServiceRequest`1.Execute()
   at Microsoft.Exchange.WebServices.Data.ExchangeService.InternalCreateItems(IEnumerable`1 items, FolderId parentFolderId, Nullable`1 messageDisposition, Nullable`1 sendInvitationsMode, ServiceErrorHandling errorHandling)
   at Microsoft.Exchange.WebServices.Data.ExchangeService.CreateItem(Item item, FolderId parentFolderId, Nullable`1 messageDisposition, Nullable`1 sendInvitationsMode)
   at Microsoft.Exchange.WebServices.Data.Item.InternalCreate(FolderId parentFolderId, Nullable`1 messageDisposition, Nullable`1 sendInvitationsMode)
   at Microsoft.Exchange.WebServices.Data.EmailMessage.InternalSend(FolderId parentFolderId, MessageDisposition messageDisposition)
   at Microsoft.Exchange.WebServices.Data.EmailMessage.SendAndSaveCopy()

If I comment line number 21, the code works fine and sends the message. So why it fails with extended properties?
Answer: I tried to connect with Microsoft. They gave me one diagnostic utility which captured the internal logs of Exchange Server and uploaded it to the Microsoft servers which were then analysed by Microsoft team. In Exchange Server logs it was realized that there was MapiExceptionNamedPropsQuotaExceeded, which occurs when there is an increase in the default quota what exchange supplies.
The precise exception was as follows:
Mapping 'An internal server error occurred.
The operation failed.' used for exception
'Microsoft.Exchange.Data.Storage.StoragePermanentException:
Cannot get ID from name. ---> Microsoft.Mapi.MapiExceptionNamedPropsQuotaExceeded:
MapiExceptionNamedPropsQuotaExceeded: Unable to get IDs from property names.
(hr=0x80040900, ec=-2147219200)

As a final solution I increased the named properties quota by modifying Windows registries to add dword at HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\MSExchangeIS\<Server Name>\<Database Type-GUID> with name Named Props Quota and setting its value to decimal 16K. This solved the issue.
Detailed steps can be found here.
More information about named properties can be found here.


In C programming macros never do type check? Then what is the difference in defining macro for 0x01 and 0x01u?

Question: They say macros in c never checks for the data type, it simply replaces the left side with the right side. Then why people explicitly define the 0x01u as such they can simply say as 0x01?
Comment: At the place where the macro is used the check will be made
Comment: The macro (preprocessor) doesn't type check; the compiler does when the result of expanding the macro is used.
Comment: Thanks, Bernd Elkemann & Jonathan Leffler. I got your point  so in code where my macro gets replaced by the 0x01u it will be treated as unsigned int whereas for 0x01 it is simply treated as the signed int.
Comment: This question is not too bad. Bernds & Jonathans comments would make a fine answer.
Comment: "...macros never do type check" - this can mean more than one thing. Clarify, what specifically you are asking about.
Answer: At the place where the macro is used the check will be made – Bernd Elkemann
The macro (preprocessor) doesn't type check; the compiler does when the result of expanding the macro is used. – Jonathan Leffler
Answer: It defines an unsigned integer literal. You can also see where they defined a hex literal to be an unsigned long integer by using 0x…UL.
If you would like to know the bit pattern they produce, simply translate the decimal literals to their equivalent hex or binary literals. 1U becomes 0x01U and 01b1 in hex and binary respectively.
Another more commonly seen literal uses the f-suffix, that is a single precision floating point literal like 1.0f.
1. For illustration only; not an actual valid binary literal per the C standard. C++14 supports 0b01 for binary literals (and fun like 0b0000'0001 too, with ' as a grouping character).
Comment: @Rakesh_K I though he was asking what is the purpose of U symbol. So I delete my post. Thanks to notify me.
Comment: Please read the Question again, your answer doesn't seem to help the OP


Android libgdx scene2d - button disappears

Question: I need to create an ever visible in the viewport of the camera button, the camera moves around a tiledmap. Is there any way to add something like a cloak to avoid redrawing the button?
Right now I have another problem with the button, the button is visible when loading the game, but it disappears quickly. I have to create the button whenever the act () event to make this visible, causing problems ugly effects of movements on the button
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.ui.Button;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;

public abstract class GameButton extends Button {

    protected Rectangle bounds;
    private Skin skin;

    public GameButton(Rectangle bounds) {
        this.bounds = bounds;
        setWidth(bounds.width);
        setHeight(bounds.height);
        setBounds(bounds.x, bounds.y, bounds.width, bounds.height);
        skin = new Skin();
        skin.addRegions(AssetsManager.getTextureAtlas());
        loadTextureRegion();
        addListener(new ClickListener() {
            @Override
            public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
                touched();
                loadTextureRegion();
                return true;
            }
        });
    }

    protected void loadTextureRegion() {
        ButtonStyle style = new ButtonStyle();
        style.up = skin.getDrawable(getRegionName());
        setStyle(style);
    }

    protected abstract String getRegionName();

    public abstract void touched();

    public Rectangle getBounds() {
        return bounds;
    }
}

public class PauseButton extends GameButton {
    public int indice;

    public interface PauseButtonListener {
        public void onPause();

        public void onResume();
    }

    private PauseButtonListener listener;

    public PauseButton(Rectangle bounds, PauseButtonListener listener, int ind) {
        super(bounds);
        this.listener = listener;
    }

    @Override
    protected String getRegionName() {
        return GameManager.getInstance().getGameState() == GameState.PAUSED ? Constants.PLAY_REGION_NAME : Constants.PAUSE_REGION_NAME;
    }

    @Override
    public void act(float delta) {
        super.act(delta);
        if (GameManager.getInstance().getGameState() == GameState.OVER) {
            remove();
        }
    }

    @Override
    public void touched() {
        if (GameManager.getInstance().getGameState() == GameState.PAUSED) {
            listener.onResume();
        } else {
            listener.onPause();
        }
    }
}

in the Stage
if(pauseButton != null) {
    pauseButton.remove();
}
Rectangle pauseButtonBounds = new Rectangle((stageCam2.position.x - Constants.APP_WIDTH / 2) + 2f,
        150f, 47f,
        48f);
pauseButton = new PauseButton(pauseButtonBounds, new GamePauseButtonListener(), 0);
addActor(pauseButton);

Comment: In `PauseButton`'s `act`, the button is getting removed if the `GameState` is `OVER`. Can it be that that's why the button is removed all the time? Can you verify the `GameState` isn't `OVER`?
Comment: Thanks! but that wasn't the problem. I posted below how I solved the problem.
Answer: I solved the bug by removing the PauseButton and GameButton classes, and I added to the stage this code:
botonAccion1 = new Button();

Rectangle pauseButtonBounds = new Rectangle(
        getCamera().viewportWidth - 85f,
        getCamera().viewportHeight - 90f,
        45f,
        45f);

botonAccion1.setBounds(
        pauseButtonBounds.x, pauseButtonBounds.y,
        pauseButtonBounds.width, pauseButtonBounds.height);
botonAccion1.setWidth(pauseButtonBounds.width * 1.5f);
botonAccion1.setHeight(pauseButtonBounds.height * 1.5f);

skin = new Skin();
skin.addRegions(AssetsManager.getTextureAtlas());
ButtonStyle style = new ButtonStyle();
style.up = skin.getDrawable("wooditem");

botonAccion1.setStyle(style);

botonAccion1.addListener(new ClickListener() {
    @Override
    public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
        add_action = "wooditem";
        return true;
    }
});

addActor(botonAccion1);

and in the draw() method I added this code before super.draw();:
botonAccion1.setPosition((stageCam2.position.x + Constants.APP_WIDTH / 2) - 85f, botonAccion1.getY());


How to configure Nginx to serve a variety of back-ends via multiple FCGI processes?

Question: I've seen a lot of tutorials showing one how to set up PHP/Python/Perl/RoR on nginx via various FCGI processes.
None of the tutorials that I found show one how to serve multiple FCGI services off one server.
How would one configure the stable nginx (nginx-0.7.64) to serve multiple FCGI processes (one for each of the above languages)?
Example addresses for each FCGI process are as follows:
127.0.0.1:8080 - PHP
127.0.0.1:8081 - Python
127.0.0.1:8082 - Perl
127.0.0.1:8083 - Ruby on Rails

An example configuration file that shows one how to implement multiple FCGI's off one server is really what I need. Perhaps others will benefit as well.
Answer: Just change:
location /
{
FCGI..PARAMETERS (find on the web)
}

To:
location /python/

{
python FCGI..PARAMETERS (find on the web)
}

location /php/
{
php FCGI..PARAMETERS (find on the web)
}

location /perl/
{
perl FCGI..PARAMETERS (find on the web) - although nginx supports it embedded.
}

location /ror/
{
ror FCGI..PARAMETERS (find on the web)
}

Make the above folders, python/php/perl/ror under /var/www/nginx-default/ -> each will be served by a different FCGI process as per your FCGI configuration -> just place the files that need to be executed in their an run the fcgi process + restart nginx.


Let $R$ be a PID and $a \in R$ is non-invertible,then $\exists$ some prime element $p$ such that $p|a.$

Question: I tried this and i don't know , if there is any fallacies in my arguement.
If $a$ is prime then it is easy to show.
If $a$ is not prime the $<a>$ is cannot be a maximal ideal of $R$, since $R$ is PID.
$\implies \exists$ a maximal ideal of $R$, say M,which contain $<a>$.
since $R$ is a PID then $M=<p>$ , where p is prime.
$\implies$ $<a> \subset <p>$ hence $a=pr$ for some $r \in R \implies p|a$
Comment: PID implies UFD
Comment: It isn't even necessary to do cases for "$a$ is prime or not". You simply note that $(a)\subseteq M=(p)$ for some maximal ideal $M$ and that the generator $p$ is necessarily prime.
Comment: @rschweib Ohh yes u r right
Comment: @lhf i fell dumb after that
Answer: Your argument is good. As an alternative: PID $\implies$ UFD and in this is just one of the definitions of an UFD.


Maximal area covered by two triangles in unit circle

Question: What is the maximal area covered by two triangles in a unit circle? There are no restrictions other than that. They can overlap, touch the circle, not touch the circle etc.
So far I have shown

In an optimal solution all six vertices have to lie on the unit circle.
If the two triangles are not overlapping, the optimal solution has area $2$.
Using two equilateral triangles, the maximal area is $\sqrt 3\approx 1.7320508$.

Explanations
AD 1: This is true since any triangle with not all vertices touching the unit circle will be entirely contained in a larger triangle where all three vertices lie on the unit circle.
AD 2: The optimal non-overlapping solution is a square formed by two triangles meeting in a diameter of the circle. This can be derived from a few simple principles:

(a) Given a triangle with all vertices on the unit circle we can always increase the area by fixing two vertices using their distance as base and then move the third vertex to the middle of the circular segment between the other two to maximize the height with out changing the base. This makes optimal non-overlapping solutions consist of isosceles triangles.
(b) Any non-overlapping triangle contained within one half  of the circle can be enlarged by a parallel displacement of one side until it either meets the diameter of the circle or a side of the other triangle. This effectively makes the two triangles share one side so they form a 4-gon.
(c) The optimal 4-gon with vertices on a circle is a square which can be obtained by applying principle (a) four times namely to each of the triangles formed by dividing the 4-gon by a diagonal.

So the optimal non-overlapping solution will be an inscribed square of area $2$.
AD 3: I wrote a "dirty" equation for the area as a function of the radian distance between a vertex from each triangle and found that the area was maximized when the six vertices where evenly spread out forming a hexagram (star of David).
Remark
I suspect the optimal solution is actually $2$ so that the triangles do not need to overlap. In other words, we gain nothing from allowing the triangles to overlap, if I am right. I hope someone can provide a nice and clear way to either prove or disprove this conjecture.
Comment: @String Draw $5$ vertices along the outside of the circle. The lines $1-4, 4-3, 3-1$ make the first triangle and $5-4, 4-2, 2-5$ make the second. What I was saying about the evenly spaced vertices is true for the case in which the triangles share two vertices (square) and zero vertices (hexagram,) but for the case where they share one vertex (pseudo-pentagram) I realized that it may not be. However, there is one minor simplification which is that the shape must be symmetric about a line passing through vertex $4$ and the center of the circle so you only need to consider one half.
Comment: Assuming no conditions other than "two triangles in unit circle",  you might as well solve "one triangle in unit circle", and then make two copies of that one triangle. For if in the ideal solution the two triangles had different areas, you'd replace the smaller with a copy of the larger, right?
Comment: @John: I do not understand how solving "one triangle in unit circle" helps. The optimal solution to that is an *equilateral triangle* and two such triangles can only cover an area of $\sqrt 3$ because $2/3$ of their areas overlap. This is less than what is covered by two *right isosceles (and non-overlapping) triangles* with a diameter as common side which form a square of area $2$. Each of those *right isosceles triangles* are far from optimal solutions to the "one triangle in unit circle" problem.
Comment: There's no reason for the vertices to be in any orientation other than evenly spaced, so the only real candidate shapes are the square, the pseudo-pentagram created when the triangles share one vertex and the hexagram. The pseudo-pentagram may have a larger area than the square but I sort of doubt it.
Comment: I misunderstood the problem as "find the pair of triangles in the unit circle for which the sum of the areas of the interiors is maximal", rather than "for which the area of union of the two interiors is maximal." The latter is, of course, a much more interesting problem, but one on which I have essentially no insight. :(
Comment: @John: OK, no problem!
Comment: @Mr.G: Thanks! Can you substantiate your claim theoretically? And what should the pseudo-pentagram look like, I have not considered such thing yet.
Comment: @Mr.G Note there is a second kind of pseudo-pentagramm: $1-4,4-2,2-1$ and $5-4,4-3,3-5$
Answer: I whipped up a quick Matlab program that computes area stochastically (generate 20000 points; count how many are inside either triangle), and then ran it on 10,000 randomly generated triangle pairs (i.e., 6 random points on the unit circle; the first 3 define one triangle; the next three define the other. WLOG, I made the first angle be 0). Each time a new "largest area" was found, I printed out the triangles. It instantly found an area of ~1.25; then steadily improved this to 1.87 over the next couple of minutes. A previous instance of the program reached 1.97 or so...and this one just jumped to ~1.92, with a solution that's very nearly the  two 45-90-45 triangles erected on a diameter.
That suggests to me that the correct answer is indeed this pair of triangles, with area 2 as the optimum.
<code>>> testCircles
area = 1.2587; angles are [0 4.13265878886387 1.69578766384379 2.78030964099446 4.4988452659303 2.81878425776269]
area = 1.4833; angles are [0 1.03997694447012 4.97128628805005 5.53558413650189 4.31034051247746 2.03741390656017]
area = 1.5065; angles are [0 2.583714405482 3.95028117360417 3.41185810372066 4.81492678793123 1.47312279640955]
area = 1.8173; angles are [0 4.99055083947817 1.93427156493409 1.86260140259647 3.04043013930809 5.0276959720494]
area = 1.8517; angles are [0 3.01875721392096 1.30210531664363 4.12564514448203 2.38462146306761 5.8391459560257]
area = 1.87; angles are [0 1.78060248058588 4.66075033844476 2.08372315689924 5.4697587833186 3.76689571284346]
area = 1.9184; angles are [0 4.43108946197308 1.4092884007527 4.31113371053254 2.84429076671212 1.32017294630991]
</code>
Here's a picture of the most recent success:

The associated angles/area are
<code>area = 1.9428; angles are [0 1.51926494165392 3.23093144636552 0.0773804130776986 3.34779844425289 4.92681116635565]
</code>
Comment: Very interesting!
Answer: Here's an approach to a proof.
We know the six vertices lie on the circle. Now divide into three cases.

The two triangles are disjoint.
The two triangles have overlapping interiors
The two triangles meet along their boundaries, either by sharing one vertex or sharing two.

CASE 1:
In case 1, consider a chord of the circle that separates the two triangles but doesn't meet either of them. This chord will be longer than at least one of the two nearby edges. Replacing that edge with the chord will increase the area, proving that the original configuration was not optimal.
Case 3:
In case 3, consider the case where the triangles share just one vertex. WLOG, suppose this vertex, $S$, is at the bottom of the circle. Reading clockwise from it, we have vertices $W$, $N_1$, $N_2$, and $E$ forming two triangles $SWN_1$ and $SN_2 E$, where the letters are informally meant to suggest "west,", "north", and "east".
subcase 1: If the two edges $SN_1$ and $SN_2$ are equal length, then one lies west of north and one lies east of north; replacing both $N_1$ and $N_2$ by $N = (0, 1)$ will increase the area, showing this case is not optimal.
Subcase 2: If the x-coordinates of $N_1$ and $N_2$ have opposite signs, we can increase the areas of both triangles by replacing N_1$ and $N_2$ by $N$, again showing this situation is not optimal.
Subcase 3: WLOG, suppose the $x$-coordinates $x_1$ and $x_2$ of $N_1$ and $N_2$ are both non-negative, with $N_2$ being strictly to the right of $N_1$. Then the perpendicular distance from $N_2$ to the edge $SE$ is less than the perpendicular distance from $N_1$ to $SE$. [Proof: some trig/geometry stuff I don't feel like working out :)  ] Replacing $N_1$ with $N_2$ therefore would increase the area of the right-hand triangle, showing this situation is also not optimal.
Conclusion, so far: the optimal solution either involves two interior-disjoint triangles that share an edge, or two overlapping triangles. In the first of these cases, I'm pretty sure a gradient argument will show that if you fix the shared edge, the area is optimized by having each triangle be isoceles. You then compute the exact areas as a function of the location of the shared edge's second vertex (assume the first is at the south pole) and find it's optimal when the other vertex is at the north pole, and you're done.
What about the overlapping triangles case? In this case, the total area is a smooth function of the five vertex locations (I'm still fixing the sixth at the south pole). That means you can compute the derivative with respect to each of the six angles and show that the gradient's always nonzero. So following the flow of this gradient field must lead you to a point NOT in the "overlapping interiors" domain, i.e., one of the other cases. And the only one that can conceivably be the optimum is (by prior argument) the "two triangles erected on a chord that turns out to be a diameter" situation.
I haven't computed the gradients; I haven't done the geom/trig proof in the middle of one of the cases...but it least it's a sketch of how one might get to the end result.
Comment: I have to read this answer a bit more carefully, but it seems quite interesting! BTW I already proved that if the triangles do not overlap then a square is optimal. So it all comes down to excluding the overlapping cases.


Help finding ALL the critical points of this function

Question: $$f(x)=x^{2/3}(5-x)$$
So I derived the function and came up with:
$$f'(x)=\frac{10-5x}{3x^{1/3}}$$
I then made it equal to 0:
$$0=\frac{10-5x}{3x^{1/3}}$$
multiply both sides by the denominator and got:
$$0=10-5x$$
$$-10=-5x$$
$$x=2$$
Then I sub it into f(x) to get the y value.
I feel like there are more critical points though. If so then how do i find them? i feel like I should do more with the $3x^{1/3}$ part.
Answer: Your work is correct and you can easely see that $x=2$ is a maximum. But note also that the derivative is not defined for $x=0$ and we have $\lim_{x\rightarrow 0}f'(x)= \infty$.
Comment: oh so x=0 is also a critical point as well as x=2?
Comment: Yes, by classical definition: https://en.wikipedia.org/wiki/Critical_point_(mathematics)
Answer: You found all critical points. The expression $$\frac{10-5x}{3x^{\frac13}}$$
is only equal to $0$ if $x=2$.
To be extra sure, you can plot the function in Wolfram alpha


What is the best way to define the tangent space of a manifold?

Question: I have some questions about the definition of tangent space that arose after reading the book Differential Geometry of Curves and Surfaces of Manfredo do Carmo.
First, what's the best way to define tangent space? Using tangent vector to curves or derivations?
I've researched about the concept of derivation but it seems to require knowledge of abstract algebra, is is possible to understand derivations without knowing anything of abstract algebra?
Can someome recommend some material about this topic? And if it's really needed to understand derivations, can someone recommend also some material about derivations?
Thanks in advance.
Comment: There is no *best* way to do it. Like with all useful things, what is best is to know many ways to construct it. You do not need to know *any* abstract algebra to know what a derivation is in the context of manifolds—as usual, the more you know the better, of course, but with nothing more than the definition of what a derivation is you are good to go. In fact, if you are studying manifolds, as you seem to be, then the best plan is probably to not further your knowledge of derivations and "their theory" at this point and instead concentrate on, well, manifolds!
Answer: For smooth manifolds the tangent space given by equivalence classes of smooth curves and the set of derivations on smooth functions is equivalent. You can give an isomorphism between these constructions. Each has its advantages.

For example, in the equivalence class of curves set-up the differential is really simple; $dF(\gamma) = F \circ \gamma$ the mapping $F: \mathcal{M} \rightarrow \mathcal{N}$ pushes the curve on $\gamma$ on $\mathcal{M}$ to the curve $F \circ \gamma$ on $\mathcal{N}$. To show $d(F \circ G)=dF \circ dG$ for manifolds we can argue
$$ d(F \circ G)(\gamma) = F( G (\gamma)) = F( dG(\gamma)) = dF(dG(\gamma)) = (dF \circ dG)(\gamma) $$
I think the proof in the derivation view is less slick.
Derivations naturally arise from coordinates systems as the partial derivatives with respect to the manifold coordinates. The differential again pushes vectors from one manifolds tangent space to another. Or from the manifold to itself, but where the coordinate system has two overlapping charts. Believe it or not, you've already done this calculation in multivariate calculus. Changing coordinates from cartesian to polar for example:
$$ \frac{\partial}{\partial x} = \frac{\partial r}{\partial x}\frac{\partial}{\partial r}
+\frac{\partial \theta}{\partial x}\frac{\partial}{\partial \theta} = \cos(\theta)\frac{\partial}{\partial r}-\sin(\theta)\frac{\partial}{\partial \theta}$$
This can be understood as the vector $\frac{\partial}{\partial x}$ being pushed forward to the vector $\cos(\theta)\frac{\partial}{\partial r}-\sin(\theta)\frac{\partial}{\partial \theta}$ by the differential of the transition map. In other words, there are constructions for which the derivation formulation of tangent space nicely dovetails. Usually the derivation is sold as a sort of directional derivative like object. The formula $X(f) = \sum_{i=1}^n X^i \frac{\partial f}{\partial x^i}$ is like $D(f)(\vec{X}) = (\nabla f) \cdot \vec{X}$.

In either case, it is a bit unsettling to trade seemingly static objects like geometric vectors for classes of curves or differential operators. There is at least one other popular view, the contravariant vector formulation of tangent vectors.

a contravariant vector is typically described in physics by saying something like $v^{\mu}$ is a contravariant vector because under a change to barred coordinates we find $\bar{v}^{\mu'} = \sum_{\nu=1}^n\Lambda^{\mu'}_{\nu} v^{ \nu}$ where the coordinates transform via $\bar{x}^{\mu'} =\sum_{\nu=1}^n\Lambda^{\mu'}_{\nu} x^{ \nu}$. This is the rule underwhich $X^i$ of the derivation changes. That fact follows from the chain rule for manifolds. This viewpoint has great advantages for those folks who do detailed calculations in one particular system of coordinates; a.k.a. physicists.

It should be commented that when we consider $C^k$ manifolds this correspondence breaks down.See page 49 in Conlon's 2nd edition of Differentiable Manifolds. In his Lemma 2.2.20 he builds functions which are used to frame the isomorphism between curves and derivations. The construction fails for $C^k$ manifolds. Moreover, the reason for this is that the space of derivations on $C^k$-germs of functions is infinite dimensional.
I'd love to say you can pick one to understand. However, the nature of the subject of differential geometry requires you to be conversant in all these views.
Comment: James S. Cook, thanks a lot for your answer, I think I understood the difference, but can you recommend good material where the author explains the construction using smooth curves and another material where the author explains using derivations? I'd like to go more deep into that to aquire a good knowledge in both views. I didn't studied any abstract algebra as I told you. This book Differentiable Manifolds that you recommended has both views? Thanks very much again.
Comment: @user1620696 yes Conlon has both views and explains the connection between them. However, if you want more on the topic then many other books also work. For example, the text by Warner mentioned by Andrew is also very careful. The advice found here: http://mathoverflow.net/questions/7834/undergraduate-differential-geometry-texts is probably helpful to your inquiry.
Answer: I think the best way depends on your goals. One reason derivations are so important is that they are general enough to be used in contexts other than manifolds (they are crucial for doing algebraic geometry).
There is a nice description on p.12 of Warner's text in the real manifold context.
For the algebraic theory you can look at chapter 16 of Eisenbud.
Answer: I am just trying to add my understanding to the mix. As in one of the books I used, the author remarks that the definition of tangent vectors and ergo the tangent space is much more intuitive and "pleasant" when curves are employed.
However as the answers already given so neatly tell, it is much more beneficial in a general context to look at tangent vectors as derivations.
And though it helps to know abstract algebra to understand derivations better, a derivation is in essence just a linear map that satisfies the familiar Leibniz product rule seen in usual derivatives.
That it is defined on an Algebra over a ring or a field can be neglected if you are studying it from the point of view of Differential Geometry atleast at this juncture.
I think Loring Tu's book on manifolds and tensors has a nice way of introducing derivations without delving much into abstract algebra. He does mention modules , but explains the background himself and that suffices in that context.


Hypothesis test for a parameter when only the upper and lower bounds of the parameter are estimable

Question: Consider a null hypothesis:
\begin{align*}
H_0:\;\beta=0
\end{align*}
Here, we can estimate only the upper and lower bounds of $\beta$.
To be clear, let the upper and lower bounds of $\beta$ be $\alpha_u$ and $\alpha_l$, respectively, then what we can get is the estimate $[\widehat{\alpha}_l,\widehat{\alpha}_u]$.
I am wondering whether is it possible to test the null hypothesis only using the estimates $\widehat{\alpha}_l$ and $\widehat{\alpha}_u$.
Is there a reference that deals with this kind of problem?
Answer: $\beta$ is a parameter (not a random quantity), it has some true scalar value, therefore it does not have an upper and lower bounds.
Sometimes we use confidence intervals which are random (since they are based on the random sample), which we have a level of confidence (usually denoted by $1 - \alpha$) that indeed covers the parameter.
The (parametric) CI is equivalent to an hypothesis testing at significance level $\alpha$.


Easiest way ti implement SOAP WS client

Question:
I'm about to iplement WS service
client
I have wsdl description
Client itself is Spring 3.0.2
application running in jetty
(I'm doing some changes)
Application is build by maven

WHAT IS THE SIMPLEST WAY TO IMPLEMENT THE CLIENT FROM WSDL?
(I'm thinking of some code generation from wsdl)
I don't want to add huge amount of dependencies.
Answer: WSDL2Code Plug-in to generate client is I found easier to use.
Comment: What additional dependencies must I add after generating sources?
Comment: Genrated sources have ant build? what the hell is that if I'm using the Maven
Comment: @Hundra Maven is far better than ant. you can  check the link provided to get answer for both of your questoins
Comment: life.java - I followed link did exactly what was there - run mvn axis2-wsdl2code:wsdl2code and all i got is generated code in target/generated-sources with ant build.xml - can you please elaborate on usage (like 10 steps to use this)

Easiest way ti implement SOAP WS client


How to rename address labels on Address field module?

Question: I wanted to know if it's possible to change the input labels on the address field module 'Address 1' and 'Address 2' without using the string overrides module?
I want to be able to change them to say 'Address line 1' and 'Address line 2'.
Can this be done in a template preprocess function?
Answer: This can be done with hook_form_alter:
<code>function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {

    //drupal_set_message("Form ID is : " . $form_id);

    switch($form_id) {

        case 'MY_FORM_ID':

            // dpm($form);

            // $form['NAME_OF_YOUR_FIELD'] - this is the field you want to edit

            // check that the field is set before looping over values
            if(isset($form['NAME_OF_YOUR_FIELD'][LANGUAGE_NONE])) {
                // loop over each values passing $item by reference
                foreach($form['NAME_OF_YOUR_FIELD'][LANGUAGE_NONE] as &$item) {
                    if(is_array($item) && isset($item['street_block'])) {
                        $item['street_block']['thoroughfare']['#title'] = 'Address Line 1';
                        $item['street_block']['premise']['#title'] = 'Address Line 2';
                    }
                }
            }
            break;
    }

}
</code>
I found the path to the variable I wanted to change by outputting the $form array to the message area using devel's dpm function, and then searching though the array for the value "Address 1" using the search krumo module.
Comment: Form alters can be done in themes (I think any alter can).  You just have to make sure the theme is in use on the form you are altering, especially on admin forms.
Comment: Hi Felix, thank you for your help. I have added this to my template file, changed MY_MODULE to my theme name and changed 'MY_FORM_ID' to 'order-form-entityform-edit-form' but the changes are not happening. I have flushed caches. What am I doing wrong?
Comment: Arr - that is code for a custom module, not a template file. See [Creating Drupal 7.x modules](https://drupal.org/developing/modules/7) if you need any help with that.
Comment: I did not know that - cheers MPD.
Comment: Ok, thanks guys. I've looked into hook form alter and have come up with this code but it's not working. Can you help?

/**
 * Implements hook_form_FORM_ID_alter().
 */
function my_theme_form_order_form_entityform_edit_form_alter(&$form, &$form_state) {

// Change labels for the 'Address 1' and 'Address 2' elements.
  $form['street_block']['thoroughfare']['#title'] = t('Address line 1');
  $form['street_block']['premise']['#title'] = t('Address line 2');
}
Comment: I actually tested the code in my answer so I know it should work. Have you made sure that you have put the correct form id where it says MY_FORM_ID? You can un-comment the line with drupal_set_message to find out the correct form ID to use.
Comment: You want to be changing values in $form['field_address'] - $form['street_block'] does not exist. Note how I'm looping over the field_address field passing each item by reference to update the values if there are multiple addresses.
Comment: Yes I changed 'MY_FORM_ID' using the form id displayed when uncommenting the line. But I got this error: Warning: Invalid argument supplied for foreach() in my_theme_form_alter() (line 142 of C:\wamp\www\mysite\sites\all\themes\my-theme\template.php).
Comment: So check that $form['field_address'][LANGUAGE_NONE] is set before looping over values. I've updated my answer.
Comment: Ok, used the new code, the error has gone but the labels are not updated Felix
Comment: Ok, you need to install the devel module as then you can use the dmp function to inspect the form array and figure out why it's not working. Try putting one call to dmp($form) before you make any changes, and then another after your code so you can see what effect it is having. Those labels are part of the array - you just need to find out what value to change and update it. Like I said my code is tested and working on my sandbox site so your already 99% of the way there.
Comment: Ar ha - also on my site my field is called field_address - it may not be called that on your site. Again using dmp will allow to to find out the correct name of your field. Alternatively you can get the name of the field by looking at your node structure page.
Comment: Ah that was it! my field was called field_postal_address. Changed that and it works great!! Thank you very much Felix :)


How to escape special chars when sending mail via PHPmailer while keeping Polish characters?

Question: I'm making a simple contact form for a site, and I've come across a slight problem - when sending mail via PHPmailer, i can pass HTML tags, curly braces and other special characters in my form, which probably isn't really a good idea...
Problem is - I need to keep spaces and Polish characters (ąćęłńóśźż), and I'm an absolute newbie in regular expresions and php.
I resorted to using preg_replace doing basically this:
function clean($string) {
    return preg_replace('/[^A-Za-z0-9\-]/', '', $string);
}

As you might expect, that leaves me with this kind of garbage:
Before preg_replace: https://i.stack.imgur.com/E7u4J.jpg
After preg_replace: https://i.stack.imgur.com/UOzRK.jpg
All help is appreciated!

Problem solved: Summary
Ended up following Álvaro González's suggestion of using the zendEscaper component to escape HTML tags. Did so by doing this
$inputFieldName = $escaper->escapeHtml($_POST['inputFieldName']);

every time I need to make sure there can't be any HTML used, where inputFieldName is your <input name=""> attribute.

If for some other reason you really need to do what I asked to do in the first place, which is removing some characters entirely, but leaving English and Polish letters, numbers and spaces, then Toto's answer suits your needs:
function clean($string) {
    return preg_replace('/[^A-Za-z0-9ąćęłńóśźżĄĆĘŁŃÓŚŹŻ\s-]/u', '', $string);
}

Again, thanks everyone for help!
Comment: What's wrong with Polish chars and HTML tags? Even if you app is not using UTF-8, you can configure PHPMailer to use whatever encoding you need. Your `clean()` function looks like a bad idea: you are just corrupting user input.
Comment: You're right, didn't think about that really... Maybe it's time to stop coding at 4 am :P I just wanted to get rid of HTML markup that would make XSS possible. Is it enough then if I instead use `strip_tags`?
Comment: You haven't really shared any code and I'm not sure of what problem you're trying to solve. If you're generating email in HTML format and you're injecting plain text then you need to [escape it properly](https://framework.zend.com/blog/2017-05-16-zend-escaper.html), rather than damage it.
Comment: Thank You! That was exacly what I was looking for but didn't really know how to phrase it correctly! I'm using ZendEscape now and it's just what I needed. Cheers!
Answer: Just add spaces and Polish characters inside the character class:
function clean($string) {
    return preg_replace('/[^A-Za-z0-9ąćęłńóśźż\s-]/u', '', $string);
}

The /u flags is mandatory to deal with unicode characters.
Comment: You probably also need the `u` flag for this to be processed properly.
Comment: Thank you for your answer, unfortunately Alvaro in the comments above showed me that it's really a bad practice to do what I tried to do and I ended up using zendEscape instead. Anyway, in case someone tries to reference this in some case, for your answer to be completely right it should include uppercase characters aswell, so `'/[^A-Za-z0-9ąćęłńóśźżĄĆĘŁŃÓŚŹŻ\s-]/u'`


Azure Search highlights not returned for every result

Question: I recently encounter an issue with the azure search, where the highlights are not populated on every result item.
View the results returned by Azure Search Explorer
The same thing happens on both '2015-02-28' and '2015-02-28-Preview' search API versions.
Thanks.
Answer: The issue was in broad wildcard search query. For performance, Azure Search internally uses a filter when a wildcard search query expands to too many (a few hundreds) terms, or matches more than a certain percentage of the document set. In such cases, not all the result items contain the highlight hits. The customer was hitting the known case. To workaround the issue, we recommend trying a query with higher selectivity. I apologize for the inconvenience.
Please let me know if you have any further questions.
Nate


Simplify $x/(x-2)+(x-1)/(x+1)=-1$ step by step

Question: Simplify $$x/(x-2)+(x-1)/(x+1)=-1$$ step by step.
So I clear the fractions by multiplying by the common denominator of $(x-2)(x+1)$ and you have
$$x(x+1) + (x-1)(x-2) = -(x-2)(x+1)$$
$$x^2 + x + x^2 - 3x + 2 = -x^2 + x + 2$$
$$3x^2 - 3x = 0$$
$$x(x-1) = 0$$
$$x = 0,1$$
I feel this is wrong. It there a simpler way to solve this equation?
Comment: @CodeVista Welcome to Math SE. Note each of your steps is reversible, i.e., you could start at the bottom and work your way to the top.
Comment: Well, $x=0$ and $1$ are indeed solutions of the original equation. Why do you feel it is wrong?
Comment: I think you right maybe I am over thinking this.
Comment: You just have to substitute either $0$ or $1$ to the left-hand side of the original equation and check that it simplifies to $-1$.
Answer: There is nothing wrong with your approach.
You just have to bear in mind the proposed transformations are not equivalent.
Having said that, you can keep your solution and check the results to know if they satisfy the original equation as suggested by @Gary.
Alternatively, you could consider to proceed as follows:
\begin{align*}
\frac{x}{x - 2} + \frac{x - 1}{x + 1} = -1 & \Longleftrightarrow
\begin{cases}
x(x + 1) + (x - 1)(x - 2) = -(x - 2)(x + 1)\\\\
(x - 2)(x + 1) \neq 0
\end{cases}
\end{align*}
which leads to the obtained solutions.
Hopefully this helps!
Answer:
Comment by Gary

You just have to substitute either 0 or 1 to the left-hand side of the original equation and check that it simplifies to −1.

It is important to understand the consequences of the OP's (i.e. original poster's) analysis.
You started with a specific constraint, C-1.
Then in effect, you deduced that any value for $x$ that satisfies C-1, must also satisfy equation E-1, which was the first equation that you originated.
Then, your analysis deduced that if equation E-1 is satisfied, then equation E-2 must also be satisfied.
....
This process was continued until you reached the point of saying
If equation E-n is satisfied, then $x$ must be an element in the set $S$ of $\{candidate-value-1, candidate-value-2, ...\}$.
In this particular problem, $S$ had two candidate values.

So, what has been accomplished (so far) is that if $x$ satisfies C-1 then $x$ is an element in the set $S$.
This does not imply that every element in the set $S$ will satisfy C-1.  However, it does imply that no other value for $x$ can satisfy C-1, besides the elements in the set $S$.
This explains the comment of Gary, that I excerpted at the start of my answer.

This is where the dissection of the situation gets interesting.  The question is being begged: under what circumstances will every value in the generated set $S$ automatically satisfy C-1?  Alternatively, under what circumstances will the set $S$ contain extraneous candidate values that do not satisfy C-1?
To answer this question, you have to dissect the each step of the analytical process.  When, for example, it was reasoned that
C-1 implies E-1
was this analysis a one-way implication or a two-way implication
(i.e. C-1 if and only if E-1).
In the present problem, as it turns out, each step was an if and only if step.  This explains why the set $S$ contained no extraneous values.
You get a feel for when you are generating a one-way implication, rather than two-way (if and only if) implication.
The typical example is $x = 3 \implies x^2 = 9.$

However, this type of dissection is actually unnecessary.  If you always regard the set $S$ as a set of candidate values, each of which must be manually verified, then you never have to worry about whether the set $S$ has extraneous values.
This means that this approach relieves you of ever having to worry that one of your implications was not a two-way implication.


defining regions in bitmap (java)

Question: I have a graphics application in JAVA, which is made up of many different shapes (lines, circles, arcs, etc, which are drawn via the Graphics.drawLine(), drawArc()... methods).  I would like to create mouse-over events on many, if not all of the drawn objects.
What I was thinking was to store some sort of bitmap with metadata in it, and use that to figure out which object the mouse is over.  Is there a way to do this in Java?  (looping through all the objects per mouse move doesn't seem viable).
Thanks,
John
Comment: I would try key colors and off-screen surface (like BufferedImage). Draw your objects at off-screen image buffer: Each object with it's own color. Then read image buffer (example here http://stackoverflow.com/questions/6524196/java-get-pixel-array-from-image ) and determine your object index by color at mouse position.
Comment: You can use java shapes contains http://docs.oracle.com/javase/1.4.2/docs/api/java/awt/Shape.html#contains%28double,%20double%29
Comment: Thanks for the suggestions.  Drawing twice -- once to an off screen buffer, and once to an on-screen buffer seems to make the most sense.  I can reuse the drawing code for that, and then create a hash function to convert color to object.
Comment: @John, I have moved my comment to a separate answer.
Answer: Key-color solution
(moved from comment)

Create an off-screen graphics buffer (like BufferedImage), same size as subject image.
Draw all objects into this buffer. Each object with one own color. Depending on object count you can optimize image buffer: For example use 8-bit graphics.
Read resulting image buffer by pixel (example Java - get pixel array from image). Determine pixel color at current mouse position, and map color index (or RGB value) to the source object.

Pros:

The solution is "pixel-accurate": Object boundaries are exact - pixel to pixel.
Easy to solve overlapping objects problem. Just draw them at the desired order.
Object complexity is not limited. Theoretically bitmaps are also possible.

Cons:

To move one object, the complete off-screen buffer must be repainted
Number of objects can be limited when using low-bit image buffer
Answer: It depends on your specifications. You do not mention if those shapes are allowed to overlap, to move, how many of them can exist etc.
Solution a) The easiest approach that comes to mind is to implement each shape as a JComponent descedant (e.g. JPanel). So you would have a CirclePanel, an ArcPanel etc that extend JPanel and each one of them paints itself in the same way it is being done now.
Having the shapes as a JComponent allows you to add a MouseListener to each panel that would then handle the mouseEntered(), mouseExited() events.
Solution b) If on the other hand you need to draw all the shapes on a single component's area (as I understand is the case now) then you still do not need to iterate over all the shapes. You just need to introduce an algorithm to categorize the shapes based on their position, to be able to exclude them fast inside your "isMouseOver(Shape s)" test procedure.
For example lets say you divide the area to 2 equal sub-areas left and right (let's call them tiles). When you create each shape you test which tile they intersect to, and you store this information both in the shape and in the corresponding tile.
Now when you need to test if the mouse is over a shape, you decide which tile the mouse is over. This way you only have to check shapes that intersect either the left or the right tile. Assuming that your shapes are distributed uniformly on the screen, you have just rejected 50% of the shapes with one test.
Depending on how many shapes you have, you could use 4 or 8 tiles, or you could even create/delete tiles dynamically (e.g. based on how many objects tend to gather in one area of the screen or not).
I would suggest to try the first solution because it is easier and a cleaner approach. If you decide that it does not fit your needs, you could then go for an approach similar to the second one.
Comment: Thanks for the suggestions.  The shapes are indeed allowed to overlap, they may move, and I will have potentially hundreds of them.  Solution b) does not work simply because it creates a lot of overhead to the program itself, which would make it hard to maintain.  Solution a) essentially loops through all of the shapes as well, so it would not work.   I think I will go with DRCB's suggestion, and draw to an off-screen buffer, and then do a color hash to get the object.
Comment: Perhaps I did not correctly understand your problem. Solution a) loops all the objects for drawing only. You would still have to loop at least once to draw them all right? The only additional thing it does, is to add mouse over capabilities. It is rather easy to implement and check the performance. At least this is what I would try first.
Comment: It might amount to the same thing, in that the MouseEntered and mouseExited events may use a raster in the background.  As far as performance goes, during animation, I only need to update the 'mouse over raster' every five or so frames, which significantly reduces the overhead.  Plus, with the raster solution, I can just call all of my current drawing methods with a different Graphics object, and just adjust the output colors (some of these drawing methods are somewhat involved, so this would significantly reduce coding and maintenance).

defining regions in bitmap (java)


Invalid parent values in JAGS

Question: I read through some other forums with the same error but have not yet been able to figure out my case. When I run the model:
y <- Fairfield$incidents
n <- Fairfield$population
N <- nrow(Fairfield)
jData <- list("y", "n", "N")

model <- function()
{

for(i in 1:N)
{
 y[i] ~ dbin(theta[i], n[i]) #y is incidents, n is population, theta is probability
 logit(theta[i]) <- logit.theta[i] # initialize for MCMC
 logit.theta[i] ~ dnorm(mu, inv.omega.squared) # logit to connect thetas under one hyper-parameter
}
inv.omega.squared <- 1/pow(omega,2)
omega ~ dunif(0,100)
mu ~ dunif(-100,100)
alpha[3] ~ dnorm(2*alpha[2]-alpha[1],1000000*tau.a)
alpha[4] ~ dnorm(2*alpha[3]-alpha[2],1000000*tau.a)
alpha[5] ~ dnorm(2*alpha[4]-alpha[3],1000000*tau.a)
alpha[6] ~ dnorm(2*alpha[5]-alpha[4],1000000*tau.a)
alpha[7] ~ dnorm(2*alpha[6]-alpha[5],1000000*tau.a)
alpha[8] ~ dnorm(2*alpha[7]-alpha[6],1000000*tau.a)
alpha[9] ~ dnorm(2*alpha[8]-alpha[7],1000000*tau.a)
alpha[10] ~ dnorm(2*alpha[9]-alpha[8],1000000*tau.a)
alpha[11] ~ dnorm(2*alpha[10]-alpha[9],1000000*tau.a)
alpha[1] ~ dnorm(0,1000000*tau.a)
alpha[2] ~ dnorm(0,1000000*tau.a)
beta[3] ~ dnorm(2*beta[2]-beta[1],1000000*tau.b)
beta[4] ~ dnorm(2*beta[3]-beta[2],1000000*tau.b)
beta[5] ~ dnorm(2*beta[4]-beta[3],1000000*tau.b)
beta[6] ~ dnorm(2*beta[5]-beta[4],1000000*tau.b)
beta[7] ~ dnorm(2*beta[6]-beta[5],1000000*tau.b)
beta[1] ~ dnorm(0,1000000*tau.b)
beta[2] ~ dnorm(0,1000000*tau.b)
gamma[3] ~ dnorm(2*gamma[2]-gamma[1],1000000*tau.g)
gamma[4] ~ dnorm(2*gamma[3]-gamma[2],1000000*tau.g)
gamma[5] ~ dnorm(2*gamma[4]-gamma[3],1000000*tau.g)
gamma[6] ~ dnorm(2*gamma[5]-gamma[4],1000000*tau.g)
gamma[7] ~ dnorm(2*gamma[6]-gamma[5],1000000*tau.g)
gamma[8] ~ dnorm(2*gamma[7]-gamma[6],1000000*tau.g)
gamma[9] ~ dnorm(2*gamma[8]-gamma[7],1000000*tau.g)
gamma[10] ~ dnorm(2*gamma[9]-gamma[8],1000000*tau.g)
gamma[11] ~ dnorm(2*gamma[10]-gamma[9],1000000*tau.g)
gamma[12] ~ dnorm(2*gamma[11]-gamma[10],1000000*tau.g)
gamma[13] ~ dnorm(2*gamma[12]-gamma[11],1000000*tau.g)
gamma[14] ~ dnorm(2*gamma[13]-gamma[12],1000000*tau.g)
gamma[15] ~ dnorm(2*gamma[14]-gamma[13],1000000*tau.g)
gamma[16] ~ dnorm(2*gamma[15]-gamma[14],1000000*tau.g)
gamma[17] ~ dnorm(2*gamma[16]-gamma[15],1000000*tau.g)
gamma[1] ~ dnorm(0,1000000*tau.g)
gamma[2] ~ dnorm(0,1000000*tau.g)

tau.a ~ dgamma(.001,.001)
tau.b ~ dgamma(.001,.001)
tau.g ~ dgamma(.001,.001)
}

require(R2jags); invisible(runif(1))
fit <- jags(model=model, param=c("n","theta","mu","omega","alpha",
"beta","gamma","tau.a","tau.b","tau.g"),
data=jData, n.iter=10000, n.thin=1)

I get the error:
Error: Error in node gamma[2]
Invalid parent values
I thought the issue might be in my tau's, as other answers have involved either accidentally having 0 as a gamma parameter or landing negative values for variance in normal distributions, but I can't figure out the issue with mine. Any help is greatly appreciated, I'm not great with JAGS (or Bayesian methods in general).
***EDIT, updated the variance (or precision, technically) in the models and still get the error.
***EDIT 2, removed the loop and expanded, still get invalid parent error with beta[2].
Answer: This is just a guess, but one of the distributions might be receiving invalid values.
For example you have the line:
 gamma[i] ~ dnorm(2*gamma[i-1],gamma[i-2]*1000000*tau.g)

The variance (or precision as is the case in JAGS) of a normal distribution must be greater than zero. So if you are getting a negative number ever in gamma[i-2]*1000000*tau.g then you're going to get an error. Given that gamma is sampled from a normal distribution, it seems likely that you might get a negative variance.
So for example, if you have a variance parameter like gamma, you need to make sure that it respects the requirements of the distribution. For example, this is why we often use a gamma distribution or a uniform distribution with lower limit equal to zero when sampling variance parameters. It ensures that you don't get negative variances.
Comment: whoops. I had edited the model so that, for instance,
gamma[i] ~ dnorm(2*gamma[i-1],gamma[i-2]*1000000*tau.g)

became

gamma[i] ~ dnorm(2*gamma[i-1]-gamma[i-2],1000000*tau.g),

so that the variance (or precision) was always greater than 0 and still have the error. The update is an edit in the main post
Answer: This part of your code is incorrect:
for (i in 3:17){
gamma[i] ~ dnorm(2*gamma[i-1]-gamma[i-2],1000000*tau.g)
}
gamma[1] ~ dnorm(0,1000000*tau.g)
gamma[2] ~ dnorm(0,1000000*tau.g)

you have only gamma[1] and gamma[2] declared, while you refer to values from 1 to 17. "For-loops" in BUGS and JAGS are not for-loops as known from programming languages, they do not allow you to do operations sequentially. JAGS/BUGS are declarative languages, you use them only to declare structure of your model, rather then the procedure that is to be followed for estimating it. So what for-loop in BUGS/JAGS means is only the declaration that something is applied to cases i in 1:n and not that it is applied sequentially.
Quoting Plummer (2003) himself

3.2  For loops
  The existence of "for" loops in the BUGS language is somewhat incongruous, since it is a declarative language, not a
  procedural one. For loops can be thought of as a kind of macro that
  succinctly describes repetitive structures. For example, the loop:
for (i in 1:2) {
mu[i] <- alpha + beta*(x[i] - x.bar);
Y[i]   ~ dnorm(mu[i], tau);
}

can be thought of as expanding to
mu[1] <- alpha + beta*(x[1] - x.bar);
Y[1]   ~ dnorm(mu[1], tau);
mu[2] <- alpha + beta*(x[2] - x.bar);
Y[2]   ~ dnorm(mu[2], tau);

Plummer, M. (2003, March). JAGS: A program for analysis of Bayesian graphical models using Gibbs sampling. In Proceedings of the 3rd international workshop on distributed statistical computing (Vol. 124, p. 125). Technische Universit at Wien.
Comment: Sorry but code debugging questions are off-topic on this site, please also do not edit your question so to change it -- additional question should be posted as new question. Your question probably better suites to https://codereview.stackexchange.com/ where it would be more on-topic.
Comment: @src471 Did you figure out the error? I am having the same problem.
Comment: I expanded all of the alphas, betas, and gammas and still have the same issue (though now it decides that parent values for beta[2] are invalid. I've edited the question to include the update

Invalid parent values in JAGS


What are the consequences of using a t-test in a U-Shaped Distribution?

Question: What are the consequences of using a t-test in an heavily U-shaped distribution (in both groups). Does the result tend to underestimate or overestimate the significance?
Is there a good citable study for the consequences?
I am aware that there are better tests for this case, I am interested in evaluating existing results that have used the t-test for group differences in a U-shaped distribution.
Comment: @Dave Why not go all the way and explore the limiting distributions "Beta$(0,0)$"? By taking the limits carefully these are just Bernoulli$(p)$ distributions. As you know, for $p=1/2,$ a t-test works pretty well even in samples as small as $n=5.$ That gives us insight into how U-shaped distributions might affect a t test generally. The bottom line is that we have to worry about skewness and extreme kurtosis, but in cases where the moments are bounded--as in all Beta distributions--and there's little skewness, t tests work very well indeed.
Comment: I'd be curious to know what happens in a simulation study that compares two U-shaped beta distributions, say $\text{Beta}(0.1, 0.1)$ and $\text{Beta}(0.1, 0.1) + \Delta\mu$.
Answer: One distribution family that contains U-shaped distributions is
$\mathsf{Beta}(\alpha, \beta)$ with $\alpha, \beta < 1.$ The support
for the beta family is $(0,1),$ so an optimal test to distinguish
one beta population from another with a shifted-beta distribution
would look at maximum and minimum values.
However (as Commented by @Dave), it may be of interest to see what happens when we try to
use a t test to distinguish between a population distributed
$\mathsf{Beta}(.1,.1)$ and population distribution with the same
beta distribution shifted to the right by $0.23.$ Both distribution
have SD about $0.46.$ (So the shift is about half a standard deviation.)
For comparison, we start by using R to approximate the power (about 94%) of a two-sample Welch t test
to distinguish a shift in mean of $0.23$ of normal populations with samples of size $n_1 = n_2 = 100.$
set.seed(609)
pv.norm = replicate(10^5, t.test(rnorm(100,10,.46),
                            rnorm(100,10.23,.46))$p.val)
mean(pv.norm <= .05)
[1] 0.94108

Then we find the power (about the same) of this test for a roughly analogous situation
for a shift in beta populations.
set.seed(610)
pv.beta = replicate(10^5, t.test(rbeta(100,.1,.1),
                            rbeta(100,.1,.1)+.23)$p.val)
mean(pv.beta <= .05)
[1] 0.94528

The similarity in powers is hardly a surprise because t tests use means
of samples of size $n$ and, by the Central Limit Theorem, means of large samples
from a beta distribution (even an aggressively bimodal one)
are very nearly normally distributed.
set.seed(2020)
a = replicate(10^5, mean(rbeta(100, .1, .1)))
mean(a);  sd(a)
[1] 0.4998844
[1] 0.04569338
hist(a, prob=T, br=40, col="skyblue2",
     main="n=100, Means of Beta Samples")
  curve(dnorm(x, mean(a), sd(a)), add=T, col="red", lwd=2)

A Shapiro-Wilk test of normality on the first 5000 sample means (as many as the test will accommodate) shows no departure from normal.
shapiro.test(a[1:5000])$p.val
[1] 0.3998924

Comment: Perhaps a more relevant alternative hypothesis would be a Beta distribution with the same variance as the null but a shifted mean. For instance, the alternative to a Beta$(0.1,0.1)$ with a shift of $+0.23$ would be a Beta$(0.691, 0.255).$ Generally, when the null is a Beta$(\alpha,\beta),$ a shift of $\epsilon$ gives a Beta$(\alpha^\prime,\beta^\prime)$ where $$\alpha^\prime=\lambda^\prime(\mu+\epsilon),\ \beta^\prime=\lambda^\prime-\alpha^\prime$$ where $\lambda=\alpha+\beta$ and $$\lambda^\prime=(1+\lambda)(\mu+\epsilon)(1-\epsilon-\mu)/(\mu(1-\mu)) - 1.$$
Comment: How would Slutsky's theorem play into this?
Comment: It seems more directly relevant to explore optimal tests for distinguishing between sample from beta and shifted beta. For example, what is the probability that all 100 treatment values stay in $(0,1)?$ I get very nearly $0$ for that, which means pwr of optimal test with $n_1=n_2=100$ is nearly 100%.// t test may not be technically inappropriate, but it avoids sufficient statistics and so wastes great gobs of relevant information.


Draw A Tree Data Structure in Java

Question: Given a tree how one could approach to draw the same using Java Swing that what we draw in a simple piece of paper to understand a tree ? i.e. drawing all the nodes an values inside the node circle as well as threads to join the parents with the child and so on .The Structure will be like this :

From https://en.wikipedia.org/wiki/Tree_%28data_structure%29#/media/File:Binary_tree.svg
Comment: As an [example](http://stackoverflow.com/questions/15455739/animate-change-of-color-of-nodes-in-insertion-of-binary-search-tree/15458451#15458451)
Answer: You can use JavaFX for that:
https://en.wikipedia.org/wiki/JavaFX
http://docs.oracle.com/javase/8/javase-clienttechnologies.htm
That's the newest Java GUI technology!
Comment: Here is the same in Swing: http://stackoverflow.com/questions/10126695/how-to-draw-a-tree-representing-a-graph-of-connected-nodes
Comment: Can  you mention any tutorial or like that?
Comment: I've read an book. But in German. ;) So I unfortunately don't know a good online tutorial. sorry
Comment: Given the [tag:swing] tag, the suggestion of Java-FX is off topic and irrelevant. Swing will be around for a long time yet.

Draw A Tree Data Structure in Java


what are Major triads with an added minor 6th called?

Question: Im researching types of 6th chords & have not come across any site referencing such a chord. Does a Major triad with an added m6/b6 not exist?
Comment: I'm genuinely surprised I can't find this question having already been asked. Lots of minor triad with minor sixth, but not major triad with minor sixth.
Comment: @Aaron - checking over some bigband orchs, just found Cb6/9 in an arrangement of Smoke Gets in Your Eyes by Michael Philip Mossman - bars 17, 20, 25, all with different bass notes (pno parts), none of which sound to me like they're any 'C' chord. And they're not Cb 6/9, but C b6/9!
Answer: The question should not be if it exists, of course it does. Regardless of whether or not it has much practical usage I believe the real issue here is spelling it out in a way that makes it completely clear and unambiguous.
Sometimes major chords with a b6 use the designation b13 but I advise against that because some might think a chord symbol with a 13 implies including other extensions.
Using C as an example I believe the best option is this:
C(add b6)
This indicates a C triad with one additional note, nothing else.
Answer: It's basically a maj7#5 chord (forte class 4-19B). To see it, just look at Cmaj7#5 in first inversion--it looks like E with a flat 6 added.
Answer: It's a rather unusual sounding chord. So unusual, it hardly ever gets to be played.The minor flat6 chord is more usually found as a major seventh version of the chord whose root is 4 semitones below that of the m♭6 chord's. And sounds good as such.
Playing a M7 chord with root right next to the M7 usually doesn't sound good - one semitone between sets up vibrations - beats - which don't help.
And it's the same with major flat 6: the P5 and ♭6 are similarly one semitone apart. There could be a case for calling it ♭13, but John gives good reason for not calling it that.
So, basically because it will hardly ever get used as such, why would it have a special name? And, if indeed, it does need one, C(♭6) works.
Answer: A major triad with a minor sixth doesn't have a special name associated with it.
The presence of the minor sixth makes the chord generally too ambiguous to be used as a coloration on a major triad. More likely that ambiguity would be used in the context of a major seventh chord with a raised fifth, but in first inversion. It might be used at the end of a song in which an ambiguous finish is desirable.
Played without additional context, I hear it as the upper portion of a minor-major seventh chord with an added ninth. That chord can be found at the end of the theme song of every detective show ever.
Answer: It exists theoretically.  C(add♭6) is a legitimate chord name.   If you like the sound, go ahead!
Answer: Every chord exists. Any group of notes, even 2(generally called intervals) is a chord. Hell, even 1 note is a chord. A chord is a color, a sound. It represents a harmonic implication. There are many names for chords just like there are many names for paint colors. You have many types of greens and some times the same green is called by different names.
You are asking about nomenclature.
A Mm6 does exist. It's a Mm6.
Typically a very common usage is the Phrygian Dominant usage as this is the most natural context. The usage of the b6 will generally be more of a passing tone(used melodically or in extended form as a b13) although it doesn't really matter how you label it, what matters is that it sounds good and you have some way to describe the general idea.
For example, one can find such a chord on the tonic of a Mixolydian b6 scale, an Ionian b6, a Lydian b6, a Lydian Augmented(depending on precisely how you interpret the b6), etc.
It's not used much in common music because common people generally don't know how to use "complex" chords or don't like them.
Any combination of notes can be thought of as a chord. If you think of chords like this and that they are just colors then things will make more sense. The naming scheme of chords is just to communicate with words what one hears in sounds. Just like the word BOOM is to communicate an aural thing and red is to communicate a visual thing. Don't expect nomenclature to be complete though. Music notation is the notation used to precisely, well mostly, communicate musical sound.
The simplest way to state a Mm6 chord is a Mm6 chord. Or you could use something like Mb6. Generally these chords are known as b13 chords and are quite common in more advanced music(more advanced than pop and childrens songs). b13 major chords usually have some additional extensions to fill in the sound but music is context dependent. Learn the nomenclature as just a way to name things and don't confuse naming with the actual music.
Comment: Calling it a Lydian augmented chord is wrong, because of the perfect fifth in the major triad. In a Lydian augmented chord you don't have a perfect fifth.
Comment: OP says there is a major triad. In a Lydian augmented chord the fourth is raised, otherwise it wouldn't be Lydian, and the fifth is raised or otherwise it wouldn't be an augmented chord. There is no way to explain this so that a Lydian augmented chord would have a perfect fifth.
Comment: It has a b6 which is enharmonic to a #5. The n5 could be non-harmonic. Everything depends on it's usage, context, and emphasis. There is only one chord in 12-tet and that is the chromatic 12-note chord.
Comment: @piiperiReinstateMonica Wrong, it depends context. If he means out of context then yes, you can't have a major triad be an augmented triad else you would just say augmented triad. But in context, and what really matters, the p5 may not be the actual 5 of the chord that is dominants the sonority. For example, the P5 may actually be a pedal tone or suspension and actually not part harmony but which may look to be on paper. If one is not aware that context they will blindly try to apply the nomenclature and forever be confused by what actually happens in practice.


Calculating the cohomology of projective varieties

Question: I have a question about the following method of calculating the cohomology of a projective variety. Fix a field $k$, and let $f\in k[x_0,\ldots,x_n]$ be homogeneous and prime of degree $d$, so if we let $X\subset\mathbb{P}_k^n$ be the codimension $1$ subvariety cut out by $f$, if we consider the very ample sheaf $\mathscr{O}_X(1)$, people seem to calculate the cohomology $H^i(X,\mathscr{O}_X(a))$ by using the short exact sequence $$0\to\mathscr{O}_{\mathbb{P}^n}(a-d)\xrightarrow{f}\mathscr{O}_{\mathbb{P}^n}(a)\to\mathscr{O}_X(a)\to 0$$ but my question is, how can we consider $\mathscr{O}_X(a)$ as a sheaf on $\mathbb{P}^n$, and if we do consider this as a sheaf on $X$, then how do we use the long exact sequence of cohomology?
Comment: $\mathcal O_X(a)$ should be $i_* \mathcal O_X(a)$, which is a sheaf on $\mathbb P^n$, but it is an abuse of notation. For compute $H^i(X, \mathcal O_X(a))$ you need to know the so-called "Serre's computation" which computes $H^i(\mathbb P^n, \mathcal O(k))$.
Comment: I'm familiar with $H^i(\mathbb{P}^n,\mathscr{O}_{\mathbb{P}^n}(a))$. What I'm less familiar with is how cohomology interacts with pushforward and pullback.
Answer: [Edited to incorporate some of the comments.]
We define $\mathcal O_X (a)$ to be $$ \mathcal O_X (a) \cong i^\star O_{\mathbb P^n} (a),$$ where $i : X \hookrightarrow \mathbb P^n$ is the natural closed immersion.
Note that the cohomology of $\mathcal O_X (a)$ (considered as a sheaf on $X$) is the same as the cohomology of the push-forward $i_\star \mathcal O_X(a)$ (considered as a sheaf on $\mathbb P^n$)!
[For example, cohomology can be computed using flabby resolutions, and under the closed immersion $i$, a flabby resolution of $\mathcal O_X (a)$ on $X$ pushes forward to a flabby resolution of $i_\star \mathcal O_X(a)$ on $\mathbb P^n$. Alternatively, we could use the fact that cohomology can be computed by Cech cohomology on an open affine cover: if $\{ U_\alpha\}$ is an open affine cover for $\mathbb P^n$, then $\{ i^{-1}(U_\alpha) \}$ is an open affine cover for $X$, since $i$ is a closed immersion.]
So we may as well compute the cohomology of $i_\star \mathcal O_X(a)$, since this is easier!
To do this, first note that
$$ i_\star \mathcal O_X (a) \cong i_\star( i^\star O_{\mathbb P^n} (a)) \cong i_\star (O_X \otimes i^\star O_{\mathbb P^n} (a) ) \cong i_\star O_X \otimes O_{\mathbb P^n}(a),$$
by the push-pull formula.
Next, observe that, since $X$ is the vanishing locus of $f$, where $f$ is a degree $d$ homogeneous polynomial, there is a natural short exact sequence,
$$ 0 \to \mathcal O_{\mathbb P^n} (-d) \overset{f}{\to} \mathcal O_{\mathbb P^n} \to i_\star \mathcal O_X \to 0.$$
Tensoring this SES with $O_{\mathbb P^n} (a)$, you get the SES,
$$ 0 \to \mathcal O_{\mathbb P^n} (a-d) \overset{f}{\to} \mathcal O_{\mathbb P^n} (a) \to i_\star\mathcal O_X \otimes O_{\mathbb P^n} (a) \to 0.$$
Finally, the LES associated to this SES contains portions that look like:
$$ \dots \to H^i(\mathcal O_{\mathbb P^n} (a)) \to H^i (\mathcal O_X (a)) \to H^{i+1} (O_{\mathbb P^n} (a-d) )\to \dots $$
[Remember, $H^i (\mathcal O_X (a)) = H^i(i_\star \mathcal O_X(a)) = H^i (i_\star \mathcal O_X \otimes O_{\mathbb P^n}(a))$.]
But we know what $H^i(\mathcal O_{\mathbb P^n} (a))$ and $H^{i+1} (O_{\mathbb P^n} (a-d) )$ are: they are given by the standard formula for the cohomology of line bundles on projective space, in Hartshorne Chapter III.5! And they are quite often zero. This will help you determine (or at least restrict the possibilities for) $H^i (\mathcal O_X (a))$.
For instance, if $X$ is a quartic K3 surface embedded in $\mathbb P^3$, you should be able to use this trick to show that $h^{0,1}(X) = h^1(\mathcal O_X) = 0$.
Comment: What do you mean by $\mathcal{O}_X\otimes i^*\mathcal{O}_{\mathbb{P}^n}(a)$ by the way? Isn't $i^*\mathcal{O}_{\mathbb{P}^n}(a)$ already an $\mathcal{O}_X$-module?
Comment: But when you write $\mathcal{O}_X\otimes i^*\mathcal{O}_{\mathbb{P}^n}(a)$, on what sheaf of rings are you tensoring?
Comment: Yeah, you're absolutely right - $i^\star \mathcal O_{\mathbb P^n}(a)$ is already an $\mathcal O_X$ module, so tensoring by $\mathcal O_X$ does nothing. However, by writing it as a tensor product, it's easier for you to apply the push-pull formula!
Comment: Ok, I understand now.


Log Linear Models: Interpretation when None Fit

Question: This is question 9.6 from Categorical Data Analysis by Alan Agresti (Wiley, 2013).
The question asks us to find a Log Linear with the best fit for a 2x2x2 contingency table. The following are the explanatory variables.

A: Abortion should be legal for any reason (yes or no)
T: Willing to pay higher taxes to help the environment (yes or no)
P: Political party affiliation (Democratic, Republican)

Here is my output from R.
                G^2      x^2 DF  p-value G^2  p-value X^2
(A,T,P)    44.95596 45.47235  4 4.060666e-09 3.171144e-09
(TP,A)     26.11294 25.39128  3 9.031946e-06 1.278875e-05
(AP,T)     32.81293 31.65649  3 3.526977e-07 6.182630e-07
(AT,P)     39.46998 34.14721  3 1.380028e-08 1.844369e-07
(AT,AP)    27.32695 25.30322  2 1.164201e-06 3.202402e-06
(AT,TP)    20.62696 19.11921  2 3.318271e-05 7.052056e-05
(AP,TP)    13.96991 13.56004  2 9.257053e-04 1.136252e-03
(AT,AP,TP) 11.61972 10.94716  1 6.525633e-04 9.374717e-04
(ATP)       0.00000  0.00000  0 1.000000e+00 1.000000e+00

How do we interpret this result?
What do we do when none of all of the possible log linear models fit?
My hunch is that the model (ATP) does fit, but can I justify that assumption given the model is saturated?
Would it be valid to make up a dummy variable to show the model (ATP) does fit well?
Thanks for your feedback.
Answer: ATP fits. This is trivially true. We could have known this without looking at the data. This is because it is a saturated model, so it can exactly reproduce your data. The problem with ATP is not the fit, but whether or not it is a model. A model is a simplification of your data, and ATP does not simplify but just exactly reproduce your data.
You can see this in another way. The null hypothesis of the tests you report is: There is no difference between the model you test and a fully saturated model. Again it is trivially true that the we cannot reject that null hypothesis for the model ATP, though that is not a very informative finding...
You can also question whether statistical tests are the right tool for choosing models. Again, a model is supposed to simplify your data. Simplify means being (somewhat) wrong. So the fact that we reject the null-hypothesis for the other models is in itself not a problem for that model. It would become a problem if the difference between the model and the data is so large that the model is no longer useful. The $p$-value is not a measure of usefulness, so it cannot be used to make that judgement call. Instead you need to interpret the models, compare them and see if you find the differences too big or not for your purpose.
Comment: I guess I should have clarified that I understand the saturated model fits in the trivial sense. I'd like to know in the context of the social situation analysis, can we say that in the true population three-way interaction exist between A T P . Also, I don't quite understand your point about the p-value, how would we assess the differences between the models without the p-value? To me, the p-value seems pretty usefull for assessing (or measuring) fit. Thanks for your feedback.
Answer: Here's the contingency table used in this question:
surv.gss <- structure(list(A = c(1L, 1L, 1L, 1L, 0L, 0L, 0L, 0L), E = c(1L, 1L
, 0L, 0L, 1L, 1L, 0L, 0L), P = c(1L, 0L, 1L, 0L, 1L, 0L, 1L,
0L), count = c(50L, 5L, 28L, 30L, 32L, 27L, 50L, 61L)), .Names = c("A",
"E", "P", "count"), class = "data.frame", row.names = c(NA, -8L
))

Print data:
> surv.gss
  A E P count
1 1 1 1    50
2 1 1 0     5
3 1 0 1    28
4 1 0 0    30
5 0 1 1    32
6 0 1 0    27
7 0 0 1    50
8 0 0 0    61

Fit the saturated model:
require(car)
mod.gss <- glm(count ~ A * E * P, poisson, surv.gss)
Anova(mod.gss)

Which outputs Type II Anova (i.e. conforming to the marginality principle):
> Anova(mod.gss)
Analysis of Deviance Table (Type II tests)

Response: count
      LR Chisq Df Pr(>Chisq)
A      11.5595  1  0.0006740 ***
E      10.7574  1  0.0010386 **
P       4.8513  1  0.0276248 *
A:E     2.3502  1  0.1252675
A:P     9.0072  1  0.0026891 **
E:P    15.7072  1  7.394e-05 ***
A:E:P  11.6197  1  0.0006526 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

With higher-order terms in the model, we need to look at the Anova table from bottom to top. We reject the null for A:E:P (i.e. the "three-way interaction"), which means that the partial association between each pair of variables varies over the levels of the third variable.
As mentioned in the other answer, the model fits the data perfectly, as shown by the lack-of-fit test (based on residual deviance) with a very large p value:
> mod.gss

Call:  glm(formula = count ~ A * E * P, family = poisson, data = surv.gss)

Coefficients:
(Intercept)            A            E            P          A:E          A:P          E:P
     4.1109      -0.7097      -0.8150      -0.1989      -0.9767       0.1299       0.3687
      A:E:P
     2.0028

Degrees of Freedom: 7 Total (i.e. Null);  0 Residual
Null Deviance:      72.12
Residual Deviance: 2.687e-14    AIC: 57.81

> pchisq(0, df=0, lower.tail=FALSE)
[1] 1


Nginx save file to local disk

Question: My case is:

In our China company, we have to access one web server in USA
  headquarter through Internet. But network is too slow, and we download
  many big image files. All our developers have to wait.
So we want to setup a Nginx which acts as reverse proxy, its upstream
  is our USA web server. Question is can we make Nginx save the image
  files from USA web server into its local disk? I mean let Nginx act as
  one cache server.
Answer: Yes, nginx can be used as reverse cache and cache files to disk. Here is example configuration: http://wiki.nginx.org/ReverseProxyCachingExample

Nginx save file to local disk


Create new column in dataframe using if {} else {} in R

Question: I'm trying to add a conditional column to a dataframe, but not getting the results I'm expecting.
I have a dataframe with values recorded for the column "steps" across 5-minute intervals over various days. I'm trying to impute missing values in the 'steps' column by using the mean number of steps for a given 5-minute interval on the days that do have measurements. n.b. I tried using the MICE package for this but it just crashed my computer so I opted for a more manual workaround.
As an intermediate stage, I have bound an additional column to the existing dataframe with the mean number of steps for that interval. What I want to do next is create a column that returns that mean if the raw number of steps is NULL, and just uses the raw value if not null. Here's my code for that part:
activityTimeAvgs$stepsImp <- if(is.na(activityTimeAvgs$steps)){
  activityTimeAvgs$avgsteps
} else {
  activityTimeAvgs$steps
}

What I expected to happen is that the if statement would evaluate as TRUE if 'steps' is NA and consequently give 'avgsteps'; in cases where 'steps' is not NA I would expect it to just use the raw value for 'steps'. However, the output just gives the value for 'avgsteps' in every row, which is not much use. I also get the following warning:
Warning message:
In if (is.na(activityTimeAvgs$steps)) { :
  the condition has length > 1 and only the first element will be used

Any ideas where I'm going wrong?
Thanks in advance.
Comment: If you wanted to use an if{} statement in that way, you would have to iterate down the rows with a for loop, or something similar. The ifelse() function proposed by janos works better on your problem.
Answer: The if statement is not suitable for this. You need to use ifelse:
activityTimeAvgs$stepsImp <- ifelse(is.na(activityTimeAvgs$steps), activityTimeAvgs$avgsteps, activityTimeAvgs$steps)