Verification of an R-Module isomorphism between $R^n$ and its dual

Question: With one step at a time, I am getting slightly more used to $R$-Modules.

Let $R$ denote a commutative Ring with $\mathbb{1}$ and $n$ a natural number. For the tuple $a:= (a_i)_{i=1}^n \in R^n$ we have the mapping: $$\varphi_a: R^n \to R ,\  (x_i)_{i=1}^n \mapsto \sum_{i=1}^n a_i x_i $$

It is easy to see that the above mapping is $R$ linear, which means that for scalars $r,s \in R$ and 'vectors' $x,y$ we have $\varphi_a(rx + sy)= r\varphi_a(x) + s\varphi_a(y)$
I now want to show that the following mapping $$\psi : R^n \to \text{dual}(R^n), \ a \mapsto \varphi_a $$
is an $R$-Module isomorphism. Here dual$(R^n)$ just denotes linear mappings from $R^n \to R$

My approach:  First I want to show that $\psi$ is a homomorphism. I did that as follows.
Let $r,s \in R$ and $a,b \in R^n$ be arbitrary. Then it follows that $$\psi(ra + sb) = \varphi_{ra + sb} \tag{*} $$
By definition. So lets take $x \in R^n$ arbitrary and continue from there $$\varphi_{ra + sb}(x) =\sum_{i=1}^n (ra_i + sb_i)x_i = r\sum_{i=1}^n a_ix_i + s\sum_{i=1}^nb_i x_i = r \varphi_a(x) + s\varphi_b(x) = (r\varphi_a + s\varphi_b)(x) $$
Since $x \in R^n$ was arbitrary it follows that $\varphi_{ra + sb} = r \varphi_a + s \varphi_b$ which means for the above calculation at (*) that  $$\psi(ra + sb) = \varphi_{ra + sb}= r \varphi_a + s \varphi_b = r \psi(a) + s \psi(b) $$
Which means that $\psi$ is R-linear.

Injectivity: I want to show that the kernel of $\psi$ is trivial. Choose $a \in \ker \psi$ arbitrary. Thus I have $\psi(a) = \varphi_a = 0$. I want to show that my 'vector' $a$ is the zero vector.
I thought choosing an arbitrary $x \in R^n$ would be the next thing to do but then I ran into troubles. So instead I choose $x \in R^n \setminus \ker \psi$ and continue my calculations from there.
$\varphi_a(x)=x\varphi_a(1)= x(a_1 + \dots + a_n ) =0 \implies a_1 + \dots + a_n =0, \text{ because } x \neq 0$
And here I am stuck again. I somehow want to argue that it must follow that $a_1 = a_2 = \dots = a_n =0$ but I don't see a rigorous statement for that yet, so I assume my entire approach was flawed.
Surjectivity: I didn't come up with a good idea here yet, I might must give it some more thought or maybe you could provide me a hint here as well.
Answer: Given $\varphi\colon R^n\to R$ you want to find $a=(a_1,a_2,\dots,a_n)\in R^n$ such that $\varphi=\varphi_a$. In particular, you want that
$$
\varphi(e_1)=\varphi_a(e_1)=a_1
$$
where $e_1=(1,0,\dots,0)$.
Can you go on from here?
A similar idea can be used for injectivity.
The rest is maybe a bit too verbose, but correct.
Comment: Thanks @egreg, do I deduce correctly that I could use my calculations for injectivity above and rather than choosing an arbitrary $x \in R^n$ I would just choose $x=e_1=(1, 0, \dots ,0)$ which readily suggests that $\varphi_a(e_1)=a_1=0$ ?
Comment: @Spaced Rightly so: the elements $e_1,e_2,\dots,e_n$ generate $R^n$, thus a homomorphism is determined by the action on them. It is also defined univocally, because $R^n$ is free with those elements as basis.


What is the difference between creating fields programmatically and by exporting settings?

Question: We are developing a custom app with decoupling approach. There are going to be many custom entities with fields. What is your preferred way to create fields programmatically, so we have all information in the code and can build our custom logic on it? So far I have identified three ways how to do it:

using the BaseFieldDefinition::create in the entity class.
using .yaml files in the modules config/install directory
using Features

With the first option, there is a problem that Workflow modules, which would be helpful, does not support the creation of the entity fields in the code (see https://www.drupal.org/project/workflow/issues/2960185). However, we can still replace Workflow module with custom entities and logic.
With other two options I am not entirely sure what are the pros and cons of using them. They just seem to me quite difficult to add custom logic, and/or methods to entities or create new field types (plugins).
Any suggestions will be much appreciated.
Answer: For modules common practice is to define base fields with the first option and bundle fields with the second option. Concerning option 3 most use cases of Features are now covered by the configuration management, which you can use to synchronize fields configured in UI to a cloned site. Not only those fields created in UI , but also base fields from option 1 in case they are overridden or bundle fields installed by option 2 if they are modified in UI.


App quiz angularjs não aparece quando a página está online

Question: Eu tenho essa app em AngularJS é um Quiz só que quando eu coloco ela online, subo para o servidor, a aplicação não aparece. Alguém pode me ajudar? Obrigada.
HTML
<!DOCTYPE html>

  <meta charset="utf-8" />
  <title>QuizApp</title>
  <link rel="stylesheet" href="style.css" />

QuizApp

    <quiz/>

App.js
var app = angular.module('quizApp', []);

app.directive('quiz', function(quizFactory) {
    return {
        restrict: 'AE',
        scope: {},
        templateUrl: 'template.html',
        link: function(scope, elem, attrs) {
            scope.start = function() {
                scope.id = 0;
                scope.quizOver = false;
                scope.inProgress = true;
                scope.getQuestion();
            };

            scope.reset = function() {
                scope.inProgress = false;
                scope.score = 0;
            }

            scope.getQuestion = function() {
                var q = quizFactory.getQuestion(scope.id);
                if(q) {
                    scope.question = q.question;
                    scope.options = q.options;
                    scope.answer = q.answer;
                    scope.answerMode = true;
                } else {
                    scope.quizOver = true;
                }
            };

            scope.checkAnswer = function() {
                if(!$('input[name=answer]:checked').length) return;

                var ans = $('input[name=answer]:checked').val();

                if(ans == scope.options[scope.answer]) {
                    scope.score++;
                    scope.correctAns = true;
                } else {
                    scope.correctAns = false;
                }

                scope.answerMode = false;
            };

            scope.nextQuestion = function() {
                scope.id++;
                scope.getQuestion();
            }

            scope.reset();
        }
    }
});

app.factory('quizFactory', function() {
    var questions = [
        {
            question: "Which is the largest country in the world by population?",
            options: ["India", "USA", "China", "Russia"],
            answer: 2
        },
        {
            question: "When did the second world war end?",
            options: ["1945", "1939", "1944", "1942"],
            answer: 0
        },
        {
            question: "Which was the first country to issue paper currency?",
            options: ["USA", "France", "Italy", "China"],
            answer: 3
        },
        {
            question: "Which city hosted the 1996 Summer Olympics?",
            options: ["Atlanta", "Sydney", "Athens", "Beijing"],
            answer: 0
        },
        {
            question: "Who invented telephone?",
            options: ["Albert Einstein", "Alexander Graham Bell", "Isaac Newton", "Marie Curie"],
            answer: 1
        }
    ];

    return {
        getQuestion: function(id) {
            if(id < questions.length) {
                return questions[id];
            } else {
                return false;
            }
        }
    };
});

Template

{{question}}

                    <input type="radio" name="answer" value="{{option}}">
                    {{option}}

        <button ng-click="checkAnswer()" ng-show="answerMode">Submit</button>

            <button ng-click="nextQuestion()" class="next-question">Next</button>
            That is correct!
            Sorry, that is an incorrect answer.

Quiz is over

        <button ng-click="reset()">Play again</button>

        Score: {{score}}

Welcome to the QuizApp

    <button id="startQuiz" ng-click="start()">Start the Quiz</button>

Comment: Esse servidor tem firewall ou proxy? Repare que você está carregando o angular e Jquery por CDN.
Answer: Não faz diferença se estiver usando CDN. A primeira pergunta é: o seu app funciona localmente? A segunda pergunta é: que tipo de servidor? Se for algo como o Heroku, você tem que ter um servidor de frontend porque o Heroku não vai servir só páginas HTML. Por exemplo, você pode usar um servidor simples que serve só páginas estáticas usando Node.js (Express) ou outra linguagem como o Ruby ou Python.


dgtsv - LAPACK not returning answer

Question: I'm trying to solve a simple tridiagonal system of equations using LAPACK library. The code below explains it all.
I'm getting an array full of zeros (initialized ones), not the correct answer.
I checked the inputs, tried to compile with two compilers and everything seems fine. What is wrong?
The compilation line is:
ifort -L/usr/local/lib/ -llapack -lblas tLapack.f90 -o tlapack
gfortran -L/usr/local/lib/ -llapack -lblas tLapack.f90 -o tlapack

the code is:
program lapackT

  implicit none

  ! dgtsv( integer(4) :: N,
  !        integer(4) :: NRHS,
  !        real(8)    :: DL[],
  !        real(8)    :: D [],
  !        real(8)    :: DU[],
  !        real(8)    :: B [],
  !        integer(4) :: LDB ,
  !        integer(4) :: info )

  ! [A][x] = [b]
  ! N    - The order of matrix [A]
  ! NRHS - Number of coluns in [b]
  ! DL   - Array with the subdiag.
  ! D    - Main diagonal.
  ! DU   - Upper Diagonal.
  ! B    - Answer !!
  ! LDB  - length of array [B].
  ! INFO - If = 0 .. Uhul !!.

  real(8), dimension(3) :: mainDiag
  real(8), dimension(2) :: lowerDiag
  real(8), dimension(2) :: upperDiag
  real(8), dimension(3) :: unknow
  real(8), dimension(3) :: equalty

  integer(4) :: info = 0
  integer(4) :: i = 0

  integer(4) :: N    = 3
  integer(4) :: NRHS = 1
  integer(4) :: LDB  = 3

  mainDiag(1) = 2.0d0
  mainDiag(2) = 2.0d0
  mainDiag(3) = 2.0d0

  upperDiag(1) = 3.0d0
  upperDiag(2) = 3.0d0

  lowerDiag(1) = 1.0d0
  lowerDiag(2) = 1.0d0

  equalty(1) = 1.0d0
  equalty(2) = 1.0d0
  equalty(3) = 1.0d0

  unknow = 0.0d0 ! answer

  call dgtsv(N,NRHS,lowerDiag,mainDiag,upperDiag,equalty,LDB,info)

  write(*,*) info

  do i = 1,size(unknow)
    write(*,*) unknow(i)
  end do

  ! Correct answer: unknow = (/-1,1,0/)    ! real(8) values
  ! Answer Im getting: unknow = (/0,0,0/)  ! real(8) values

end program lapackT

Answer: If you look at the documentation you'll see the answer is returned in your equalty argument (i.e. it overwrites the RHS) - as unknow is not passed how can it be affected by the call? And I agree, I'm bot convinced this is the greatest design ever ...
While I'm here please learn about kinds, some of what you are doing is so quarter of a century ago. Please look at Fortran 90 kind parameter . Anyway here's how I would write your program (which some would say it also slightly out of date nowadays), and the answer it gives:
ian-admin@agon ~/test/stack $ cat dt.f90
program lapackT

  implicit none

  Integer, Parameter :: wp = Selected_real_kind( 13, 70 )

  real(wp), dimension(3) :: mainDiag
  real(wp), dimension(2) :: lowerDiag
  real(wp), dimension(2) :: upperDiag
  real(wp), dimension(3) :: unknow
  real(wp), dimension(3) :: equalty

  integer :: info = 0
  integer :: i = 0

  integer :: N    = 3
  integer :: NRHS = 1
  integer :: LDB  = 3

  mainDiag(1) = 2.0_wp
  mainDiag(2) = 2.0_wp
  mainDiag(3) = 2.0_wp

  upperDiag(1) = 3.0_wp
  upperDiag(2) = 3.0_wp

  lowerDiag(1) = 1.0_wp
  lowerDiag(2) = 1.0_wp

  equalty(1) = 1.0_wp
  equalty(2) = 1.0_wp
  equalty(3) = 1.0_wp

  unknow = 0.0_wp ! answer

  call dgtsv(N,NRHS,lowerDiag,mainDiag,upperDiag,equalty,LDB,info)

  write(*,*) info

  do i = 1,size(unknow)
    write(*,*) equalty(i)
  end do

  ! Correct answer: unknow = (/-1,1,0/)    ! real(8) values
  ! Answer Im getting: unknow = (/0,0,0/)  ! real(8) values

end program lapackT
ian-admin@agon ~/test/stack $ gfortran -Wall -Wextra -fcheck=all -O -std=f95 dt.f90  -llapack
ian-admin@agon ~/test/stack $ ./a.out
           0
  -1.0000000000000000
   1.0000000000000000
   0.0000000000000000E+000
ian-admin@agon ~/test/stack $

Comment: Thank you so much.
Answer: Unless dgtsv operates through side-effects, this sequence of statements (your code, without empty lines):
  unknow = 0.0d0 ! answer
  call dgtsv(N,NRHS,lowerDiag,mainDiag,upperDiag,equalty,LDB,info)
  write(*,*) info
  do i = 1,size(unknow)
    write(*,*) unknow(i)
  end do

does not update unknow.  How could it not be all 0.0s ?
Isn't the result returned through equalty in your call to dgtsv ?

dgtsv - LAPACK not returning answer


Sync two web views

Question: I have a need to sync two web views, so that anything that happens in one web view happens simultaneously in the other.
I have tried various ways, without success, and the more I try the more convoluted and likely bug ridden this is getting.
I feel there maybe a very simple way to do this, but can not figure it out.
One of the things that I note is not allowed is having the same NSTextField as the "takeStringURLFrom"
override func controlTextDidEndEditing(obj: NSNotification) {
    webViewLeft.takeStringURLFrom(hiddenTextField)
    webViewRight.takeStringURLFrom(urlField)
}

override func webView(sender: WebView!, didCommitLoadForFrame frame: WebFrame!) {
    if frame == sender.mainFrame {
            urlField.stringValue = sender.mainFrameURL
            hiddenTextField.stringValue = sender.mainFrameURL
            webViewRight.takeStringURLFrom(urlField)
            webViewLeft.takeStringURLFrom(hiddenTextField)
            printLn("realised just creating an infinite loop here")
    }
}

Comment: Please explain, what you mean by synchronization in this context. I.e. is it also for user interactions? And *what* did you try so far?
Comment: Yes, I'd like to sync everything between the two web views. So user interactions as well as the two views sharing the takeStringURLFrom from a single NSTextField. I tried using 2 NSTextFields bound together from a var in the app delegate which takes care of that aspect, but if i then try and call takeStringURLFrom for each web view in the web view delegate (the app delegate) inside didCommitLoadForFrame it breaks.
Comment: updated code sample above
Answer: I don't like this but it appears to work as needed. I think it needs some refinement. Using a hidden text field to mimic the url for the second web view and tie each web view to there respective text fields via the web view's referenced action "takeStringUrlFrom"
override func webView(sender: WebView!, didStartProvisionalLoadForFrame frame: WebFrame!) {
    if frame == sender.mainFrame {
        urlField.stringValue = sender.mainFrameURL
        hiddenTextField.stringValue = sender.mainFrameURL
        window.makeFirstResponder(nil)
        window.makeFirstResponder(hiddenTextField)
        window.makeFirstResponder(nil)
        window.makeFirstResponder(urlField)
        window.makeFirstResponder(nil)
    }
}

Sync two web views


Textarea name given back undefined

Question: Getting back $message is undefined. I've tried switching $_POST['message'] to $_POST['send']. it works, but for some reason it won't work with the text-area. I even tried to switch the button type from button to submit. It didn't help. This mistake's given me a real headache.
<?php
$message = $_POST['message'];
?>

<form action="chat.php" method="POST">
<textarea name="message" id="type" placeholder="Type your message"></textarea>
<input name="send" id="send" type="button" value="send" onclick="sendmsg()"/>
</form>

Comment: have you tried isset() and what is sendmsg() is doing
Comment: Give something else in place of type id="type" because type is library keyword.
Answer: Do one thing:
print_r($_POST); die;

And check whats coming from form . It will help you to find out the problem.
Comment: This is not a solution.
Comment: bt your code doesn't have any error .. so you can check if "message key coming or not "
Answer: I've remove sendmessage() and replace button type to submit. Keeping it simple.
<?php
if(isset($_POST['send'])){
echo "
";
print_r($_POST);
$message = $_POST['message'];
}
?>

<form action="" method="POST">
<textarea name="message" id="msgtype" placeholder="Type your message"></textarea>
<input name="send" id="send" type="submit"/>
</form>

Try it. Hope it'll work.
Comment: returns array() but the undefined problem is still there
Comment: @Bryan: Post your array. Let me check what its returning.
Comment: i copy and pasted what u wrote. it returned Array
(
)

Notice:  Undefined index: message in C:\Users\meansnail24\Desktop\project_w\SocialNetwork\htdocs\Creation\testing100.php on line 4
Comment: Modified the answer. Please check now.
Comment: nvm, i fixed it. i was missing the if(isset($_POST['send']))
Answer: if you are getting Post in same page .. keep you action blank

Textarea name given back undefined


Wordpress Plugin -> Is there an API call to get what the URL will be of an article?

Question: I'm writing a wordpress plugin and I have a hook for everytime the publisher publishes an article. I'm sending some of that data to a server. Is there an API in wordpress I can call that will tell me what the URL of the article would be?
for example....
I'll know what the article ID is and can craft a URL like
http://thedomain.com/?p=1234
however that won't be the URL that the users sees, it would be more like http://thedomain.com/news/this-is-an-article
Is there a way in wordpress to get the final URL?
gracias
Answer: Sure. <code>$link = get_permalink(1234);</code>
Comment: Do you have the permalink feature enabled and configured properly? Are you giving it a post ID that doesn't exist yet?
Comment: worked, didn't have permalink set right on my local machine, thanks :)


dynamically select an excel element

Question: guys,
I want to select an element from a column based on column name. This column changes its place time to time and that's why I want to achieve this dynamically. I couldn't post an image here so I'll try my best to explain it in words.
In the excel sheet I'm trying to select an element located at B2 dynamically based on column name of B2. For sake of simplicity lets say the column name of B is column2.  Since my column2 would not always be on B place I want to select that dynamically.I also want this to achieve without VBA code if possible.
Really look forward for your help. Thanks!
Comment: Sounds like something `INDEX` & `MATCH` would solve.  What have you tried?  Where does the column change its place to - same sheet, same workbook, same range?  _select an element located at B2 dynamically based on column name of B2_ - not sure what this is getting at.  Surely the column name of `B2` is column `B`?
Comment: If you are trying to get some range dynamically then you can use INDIRECT function, for eg: if cell B2 is a range 'A2:A2000' and you need to get sum of the range, then you can use =SUM(INDIRECT(B2)). INDIRECT returns a range based on the reference text.
Comment: So I've used MATCH function to find the index of the column from column row but then I don't know how to use INDEX because this function asks for lookup array and my lookup array [column B] would change its place. By the way, the column would change its place in the same sheet.

There is a header row in my excel sheet. So the first row holds column names for an example Age, DOB, Address.
Comment: My ultimate goal is to use INDEX function where I can pass the lookup array [Desired Dynamic Column] and get the value at certain index.
Comment: @Anees Hameed, So I used INDIRECT function within my INDEX function following way. My B2 cell holds a range A2:A6 and I want to get the third element in the range A2:A6. So I used INDEX(INDIRECT(B2), 3, 0) but that returns #REF!.
Comment: Could you layout some sample data in your question please.  What range does your data table cover?  What value is held in `B2`? Would the `B2` value be found in the data table, or is it the name of a column header in the data table?  Is it an actual data table - you can reference the headers as `=Table1[#Headers]` or just a range of cells and the headers would be referenced as `=Sheet1!A1:C1`?
Answer: Below formula may help you in this,
Explanation:
MATCH will return the column position of "DOB", if DOB is in column C, MATCH will be returning 3.
ADDRESS will the row 1 address of column C, $C$1 hence; which is a text in fact.
Pass this text to INDIRECT function so that it gets converted to range. Now INDIRECT function will be pointing to cell C1.
Use cell C1 as reference and return 3 item in that colum.
<code>=OFFSET(INDIRECT(ADDRESS(1,MATCH("DOB",1:1,0))),3,0)
</code>
Formula is expecting row 1:1 as header. You can pass B2 in place of "DOB".

dynamically select an excel element


Why is my theme library load on every page?

Question: I'm beginning with D8, but I work a lot with D7 and Magento. I follow the developer documentation to add a library in my theme, and I don't understand why it's loading it on every page. I only want attach it to a brunch of page with a preprocess hook. Could you help me please?
In my theme.libraries.yml I add this at the end:
hover3d:
  js:
    js/hover3d.js: {}

In my theme.info.yml I add under libraries "theme/hover3d".
Here is specific information:

I deactivated JavaScript/CSS compression in the back office and in my settings.local.php file
My theme is a sub theme of bootstrap_barrio
My Drupal version is 8.6.3
There is no custom / contrib modules yet
I discover it by inspecting my page

I don't really understand how JavaScript parts are loaded, but I suppose it's with lazy builders which are called placeholder and in D8 for rendering JavaScript there are two (or more) which are js-placeholder and js-bottom-placeholder. I see in my HTML structure that in the js-placeholder is only loaded modernizer and in the js-bottom-placeholder all the others. I don't know if this is a correct JavaScript rendering procedure, so I keep it here if it can help you.
Answer:
In my theme.info.yml i add under libraries "theme/hover3d".

That's why it's loaded on every page. libraries in the theme info file is:

A list of libraries (which can contain both CSS and JavaScript assets) to add to all pages where the theme is active.

To add it contextually, attach it to a relevant render array. For example:
function MYTHEME_preprocess_node(&$variables) {
  // Library will only be loaded when a node is rendered on the page.
  $variables['#attached']['library'][] = 'theme/hover3d';
}

See Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme for more information.
Comment: Oh that's why ! I thinked that only global-styling and global-js was globally loaded i misunderstands the docs. Thanks
Comment: Yeah `global-*` is quite confusing


How to compare current array element to next array element in JavaScript

Question: I have color templates that users can choose between and also change the individual colors if they want. I have two arrays: one with all the templates, and each template containing a color palette of 8 total colors and a string of the template name. Most of my templates have white backgrounds, so I don't want the user to have to click 12 times or however many it takes to get to another index where the background color is different. My idea was to use a "for" statement to check the next element in my array, and compare it to the current element to see if they are identical. If the elements are identical, then I increment the array and the "for" statement checks again, effectively skipping any duplicate indices until a new value is found.
To do this, I use a "for" statement like this:
( ; array[index][colorSlot] == array[index+1][colorSlot]; index++)
This works perfectly until I get to the last array index and it looks for the next index which obviously doesn't exist, thus completely breaking my function. Is there a way to prevent it from looking into an array index that doesn't exist? Should I use something other than a "for" statement?
Comment: Go up to array.length -2 in the for loop. Also why do you have a loopcount and use index.
Comment: @arundeepchohan, how do I do that?
Comment: Your for-statement looks some confusing: initialize of `loopcount`,condition with `array` and increment of `index`. Are you sure this is the right way?
Comment: @Sascha, sorry, I guess I don't need any initialization. Edited it out.
Answer: You'd prob want to go up to the second last array index and skip all repeats.
for(let index=0; index<array.length-2; index++)
{
    if[index][colorSlot] != array[index+1][colorSlot]
    {
    }
}

Answer: You can try it with a while loop it's better choice than a for-loop in your case.

let index = 0;
while (index < array.length -2 && array[index][colorSlot] != array[index+1][colorSlot] ) {
    ...
    index++;
}
Answer: Ok, I figured it out.
In my for loop, I check for two conditions: FIRST, I check to see if [index+1]!=array.length and THEN I check to see if the current array value is equal to the next (as written above). If checking the next value of the index would cause it to search an index that does not exist, it exits the for statement and resets my index.


NSXMLParser error, how to get rid of invalid chars inside XML tags?

Question: Hi everyone and thanks in advance for your help.
This is the situation:
I'm consuming a webservice that returns me a soap message in the following way:
    <?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 <soapenv:Body>
  <getMessagesResponse xmlns="urn:DefaultNamespace">
   <getMessagesReturn xmlns="">
    <?xml version="1.0" encoding="ISO-8859-1" ?>
<contact>
A message with escaped values like & < >
</contact>
</getMessagesReturn>
  </getMessagesResponse>
 </soapenv:Body>
</soapenv:Envelope>

I use NSUTF8StringEncoding to read the getMessagesReturn child and it generates me the following:
<?xml version="1.0" encoding="ISO-8859-1">
        <contact>
        A message with escaped values like & < >
        </contact>;

My problem is that it also unescape the & < > inside the contact tag, and of course the NSXMLParser throws an error because these are invalid characters inside a XML tag.
My Question is, How can I avoid this? Is there a way to escape back only the tags message contents before passing the info to the Parser?
Any help would be greatly appreciated.
Edit I use:
[NSString stringWithCString:(char*)elementText encoding:NSUTF8StringEncoding];

Comment: I don't know what you are using to convert your data to UTF8, but NS-apis does not escape entities if I remember well...
Answer: Do you control the web service? The correct way to pass getMessageReturn is with a CDATA. Otherwise, the correct encoding would be like this (note the message itself and the extra &amp's)
<getMessagesReturn xmlns="">
    <?xml version="1.0" encoding="ISO-8859-1" ?>
<contact>
A message with escaped values like &amp; &lt; &gt;
</contact>
</getMessagesReturn>

But CDATA is much easier, and this is what it's for. If nothing else, you can use string substitution to insert the CDATA before parsing.
Comment: Thanks for your answer Rob, but if the content of the getMessageReturn is an entire XML, I need to parse it anyway or write some code to find the info inside the CDATA string. I guess that maybe I can talk with the webservice provider and see if they can encapsulate every tag contents inside a CDATA block, in that way I would be able to read the XML properly and capture the data inside every tag with the foundCData method of the NSXMLParser right?
Comment: If you're embedding XML inside of XML, then you should use CDATA. You don't have to make every tag contents CDATA. You would use foundCData for this particular tag. The result would be a string that you would then need to start over with (since it's a completely different document). BTW, to inject the CDATA by hand, you can use an NSScanner to find the right places in the string, and then insert it. It's better to fix the original XML, though; it's invalid.
Comment: Thanks Rob, your answer leads me to found the solution that was asking the WS provider to encapsulate every tag contents inside a CDATA block and use the foundCDATA from the NSXMLParserDelegate to get the info.


Regression followed by a t-test?

Question: I am new to statistics so basic answers are appreciated. I am a psychology student and am looking at dark triad traits and endorsement for lying. So I have carried out a regression to investigate whether any of the three traits predict endorsement for lying. I then had hoped to see if there was any difference between male and female participants. I ran a t-test but realised that I have only ran it on whether there was a difference between males and females and their endorsement of lying.  This is not good to me as I specifically want to look at whether there was a difference between males and females based on the outcome of the regression - if that makes any sense at all.  My question is - how would I do that?  if it is possible at all.
Thanks
Comment: Welcome to cross validated. I am not sure what you mean with "based on the outcome of the regression". I guess you are interested whether there is a significant relationship betwen participants' sex and and endorsement of lying which is not explained by narcissism, psychopathology, and machiavellianism? In that case, I would recommend to add participants' sex (dummy coded) as another independent variable in your analysis.
Comment: thank you - what does dummy coded mean in regards to spss?
Comment: just coding one of them with zero the other one with 1
Answer: If you are not familiar with statistics, I think it would be a mistake to jump right into running statistical tests. First, plot your data in various ways, and clarify what question you want statistics to answer. In detail. Once you have an unambiguous question, you can seek help to answer it with stats.
Comment: Shouldn't the question be asked before having the data? But checking your data visually is indeed important to avoid false statistical claims
Comment: I dont have an option of not running a statistical test as the research is for an assignment I am doing.  I decided on - does dark triad traits predict endorsement for lying on a dating profile - this was decided based on a thorough literature review.  My hypothesis is that each trait would predict endorsement for lying.  Because the research says there are differences between men and women I also wanted to see if there would be any significant difference between men and women. I  thought a t test to look at differences between genders but realise that will only tell me about one construct.
Answer:
I then had hoped to see if there was any difference between male and
  female participants.

That depends what is being different as implied by your statement above.
If it's "does endorsement differ by sex, after adjusting for trait," then add sex into the regression as another independent variable. Like this:
$$Lying = \beta_0 + \beta_1 traitYes + \beta_2 Male$$
If it's "does the relationship between trait and endorsement differ by sex," then add sex and the interaction between trait and sex into the model. Like this:
$$Lying = \beta_0 + \beta_1 traitYes + \beta_2 Male + \beta_3 traitYes \times Male$$
Suppose Male = 1 for male and Male = 0 for female, for female, the association would be just $\beta_1$, and the association for male would be $\beta_1 + \beta_3$. If $\beta_3$ is different from 0, the association between trait and endorsement differs by sex.
Comment: @rach1981 Maybe you should watch Andy Fields videos about regression. They might be a good start for you current level of statistical knowledge [see here](https://www.discoveringstatistics.com/statistics-hell-p/antevorta-predicting-continuous-outcomes/applying-the-linear-model/)
Comment: I appreciate your answers but  I really don't understand what you have just said - i have only just been introduced to statistics and only know the basics of SPSS.  I am specifically trying to see if relationship between trait and endorsement differs by sex.  I hope this clarifies.
Comment: Thank you.  I will look at that.  Weve only had one short lesson on regression and then expected to do a research paper in 3 weeks including analysing data etc.

Regression followed by a t-test?


Slow address translation in small business network

Question: Here at my office we've started to experience a slow down for browsing websites due to our router becoming bogged down by the the traffic. I've narrowed it down to the router as the problem goes away temporarily anytime the router is unplugged and plugged back in.
Current network configuration
Comcast SMB cable modem
Linksys consumer grade router
Win2k3 Server Domain Controller + DNS
30-50 connected workstation clients
The router was originally added to the equation due to the previous modem that was from comcast not being able to support the address translation workload back then before we upgraded our internet and received the new SMB modem.
My question is what is the most appropriate solution for this, is it worth investigating whether the current modem is powerful enough to be the router itself, should we just buy a business class router, or is there a role available for Win2k3 to handle this?
Answer: You might want to find out if the router is just being overburdened, in which case you should investigate getting a higher end router from Cisco instead of a SOHO-class router, or configuring a Linux system to act as your router, or finding out if there's something flooding your network that is killing your router's available memory for routing.
I'd suspect with up to 50 machines if this seems to happen periodically that you're simply pumping too much traffic through it for a SOHO router to handle.
I personally might look at getting a spare machine with a couple NIC's and turning it into a router/firewall. Either a custom linux job so that you could run NTOP on it for monitoring network usage (and possibly track abuse) and other such tools, or something like Smoothwall as a dedicate "router/firewall appliance". This should alleviate your routing headaches as well as give you a large number of options for tracking and troubleshooting issues, plus it's cheaper than a cisco solution for a small to medium 50-machine business.
Answer: I've seen this exact same issue on a Soekris router we once used.  Rebooting it always fixed our issue in the short term but then it would slow down again.  Your router definitely can't keep up. You're network is probably fine, it's your router that is the bottleneck.
We use a Cisco ASA 5505 for one of our remote offices that supports about 80 users.  We've been very happy with this device.  Cisco has come a long ways with their support as well.  This device has a GUI if you don't have experience with ssh/telnet for configuring them.
What's more, Cisco techs will set up the device for you within the first 90 days of purchase.  The extended support isn't much if you want to go longer (we did).  You'll probably want to get an unlimited user bundle for that device.  It'll run you around $600 but seriously, the Cisco techs will save you a ton of heartbreak since they'll set it up for you.  ROI on the support will pay off.
FYI, I have a Cisco certification and still use tech support from time to time.
Comment: Do you have to buy this directly from cisco for them to set it up or specific vendors? I haven't seen any mentions of that online yet since the more I've read about it I clearly don't have the capability to set it up. Also it seems somewhat slow to limit throughput to 150mbps doesn't that effectively kill a gbit lan?
Comment: I purchased through CDW but I'm sure you could use another retailer.  Them important thing to do would be to consider purchasing the extended support.  One year would be enough since you can always extend the support when it's about to expire (because it's software support rather than hardware support).  The retailer will surely know what the default support time is that comes with the device if you don't purchase additional support (I think it's 90 days).


Access field on relation from rule

Question: I am using the Drupal 7 Rules and Relation modules. I have a relation between a user entity and a node content type (membership). The relation has an added field (relationship type). I was able to define a rule to create a new relation entity and set the relationship type field when creating a new membership node.
Now I am trying to write a rule with a condition that checks the value of the relationship type field at the time some event referencing a user or membership entity fires. The Relation module provides actions to fetch endpoint entities, but I cannot find a way to fetch the relation entity itself. What I'm searching for is a way to load that relation entity, tell Rules the relation type to expect, then be able to access the field (relationship type) on that relation.
Thanks in advance for any advise.
Answer: I believe Rules lets you write custom php. Relation has an API. You can query for a relation directly using relation_load and giving it a relation_id. You can also search for a relation by supplying 1 endpoint and the type of relation you are looking for (or empty to return all relations of that endpoint, using the relation_query() function.
/**
 * Returns a query object to find related entities.
 *
 * @param $entity_type
 *   (optional) The entity type of one of the endpoints.
 * @param $entity_id
 *   (optional) The entity id of one of the endpoints. Can also be an array of
 *   entity IDs.
 * @param $r_index
 *   (optional) The index of the search entity in the relation to be found
 *   (0 = source, 1 = target).
 *
 * @return RelationQuery
 *   The query object itself.
 */
function relation_query($entity_type = NULL, $entity_id = NULL, $r_index = NULL) {
  return new RelationQuery($entity_type, $entity_id, $r_index);
}

The RelationQuery is simply a small custom extension of the core EntityFieldQuery. You can use relation_query() and pass it a UID and a NID as the endpoints -- relation_query will return the Relation ids (RIDs) for those objects. You can inspect the relations further by calling relation_load($rid).
You can then do whatever you need to with the relation(s). A small example. In my app students have surveys assigned to them to complete; using Relations. When they're done with a survey I want to change a flag on the Relation that the survey is completed ...
function _mark_student_survey_as_completed($user_id, $survey_id) {
  // using relation query we want to search for a $user and a
  // specific survey they should have been assigned. Many arguments
  // to relation_query are optional, you can more results; like
  // if you just supply a UID, you'll get all relations that use
  // that UID as an endpoint.
  $relation_ids = relation_query('user', $user_id)
      ->related('custom_survey',$survey_id)
      ->execute();
  $relations = entity_load('relation', array_keys($relation_ids));
  if (count($relations) == 1) {
    $relation = reset($relations);
    // survey_is_completed is an attached field, to the Relation;
    // not an endpoint.
    $relation->survey_is_completed[LANGUAGE_NONE][0]['value'] = 1;
    // Save our field change on the parent relation.
    relation_save($relation);
  } else {
    watchdog('survey_check', 'Duplicate Survey!'.$user_id.'::'.$survey_id.'::'.print_r(array_keys($relation_ids), TRUE), WATCHDOG_ERROR);
 }

Lastly, since RelationQuery is just a class ... I've seen people extend it to make custom "relation logic" more easy, or even Views-like listing easily. Look at this blog post for such ideas (not my blog post):
http://www.phase2technology.com/blog/building-energy-gov-without-views/

Access field on relation from rule


Chopin - Étude in A minor, Op.25 No.11 "Winterwind" Pedalling Discrepancies Between Sheet Music and Performances

Question: The nub of the question is: why are there pedalling discrepancies that most performers I listen to follow identically, but are almost universally not listed in any variations of scores and how could I come to the same conclusions myself when just looking at a score like this? I feel the sheet music isn't telling the whole story and I don't know what I'm missing...
Here's a little more detail. I definitely understand pedalling is fairly subjective, but I don't think I've ever seen it performed so consistently differently from what is written. Instances:

All the scores at imslp for the first page show that pedalling stops half way through through the phrase, but when watching performances they all continue a "pedal-release" for distinct chords in the left hand for the entire duration of the fast right hand scales. (See image example)

I think I heard most performers pedal for the duration of these two parts as well, but pedalling is not indicated on the sheet music at all. (See image example)

Performers examples:

Josh Wirgh (most obvious example with a view of the pedals)
Evgeny Kissin
Rousseau
Others too!
Answer: Just because modern professional performers play something a certain way doesn't mean you should feel compelled to come to similar conclusions about the execution.
Your own example is illustrative of this point. Chopin used to lambast people who would substitute damper pedal for a true finger-legato. That's exactly what Kissin and Wright are doing; they're playing the etude too SLOW (check with the metronome if you don't believe me) and using damper pedal to maintain the big slurs instead of the indicated finger-legato, which would suffice at indicated speed.
My own interpretation of that passage on a modern piano would use sostenuto pedal for the single bass note alone and finger-legato in both hands. That would give maximum clarity to the dotted rhythm in the left hand.
Answer: ONE: Pedaling generally has less to do with sustaining pitches or creating legato and more to do with tone color. A note played with pedal has a warmer, richer sound than one played without.
TWO: @ttw makes a critical point that Chopin's piano had less power that a modern piano. It did not produce as loud a sound, and the sound decayed more quickly. Also, the key depth, and even the length and width of the keys, were less on Chopin's piano than the modern instrument. This, too, has an impact on both the power, the tone, and the "legato-ness".
The pedal markings in the first sample posted in the question, I interpret in this way:

m. 5: the first indication, below the low A, is Chopin letting us know he wants that low pitch sustained until the harmony change on beat four.1 This is best accomplished by half-pedaling through the next two beats.
m. 6: there is no pedal indicated, because there's no particular pitch that Chopin needs to indicate as sustaining.
m. 7: this measure is essentially a repeat of the first, and again Chopin want the performer to allow the low A to continue as long as manageable until the harmonic shift.

However, none of this precludes pedaling, or not, wherever the performer feels the need. This Etude begs to be played all out, which on a modern piano means reinforcing the tone as much as possible with the pedal. But the right hand (or left hand, as in the second example in the question) will get muddy very quickly if the pedal is held down, so at minimum, pedaling every beat is a necessity. The technique to apply is sometimes called "flutter" pedaling.
On the other hand, the opening measures can be very effective with no pedal, creating a "dry" sound before the onslaught.

"The more I play, the more I am convinced the pedal is the soul of the pianoforte!"
---Arthur Rubinstein

1 This begs the question of why Chopin didn't write a dotted half-note. I believe that, first, the low A is still part of the left hand "melody", not a separate voice. Second, Chopin doesn't want the sound literally held for three beats. He's allowing for natural decay, he just wants to make clear that the sound has to be gone by beat 4.
Comment: Chopin (unlike Liszt) was, for the most part, *scrupulous* in writing note values that could *actually be held down with the fingers for the indicated value*.  The low A is not only a quarter note, but ask yourself Why is it staccato? You have to move your hand quickly, so holding it full value is impractical and Chopin lets you know. Chopin uses pedal marks to lengthen notes that can't be held; Liszt usually writes the values to be heard and leaves it up to practicality as to how you achieve this--pedal, fingers, both.
Comment: See the left hand in this [Chopin Waltz](https://music.stackexchange.com/questions/52501/how-to-play-two-voices-with-a-large-range-in-the-same-hand/120212#120212), The pedaling remains the same, but  Chopin writes  values that can actually be held down for the low bass notes. There is no other reason they aren't dotted half notes as in the other measures.
Answer: I think the best answer is "Pedalling is subjective" as mentioned in the OP. In this case, there are at least three reasons I can think of that performers apply pedal differently from the written music. There is a difference in modern pianos and those available to Chopin and the performers try to make their performance sound musical. Also, the printed version may not be Chopin's actual writing; editors do make changes and suggestions, even in pedalling. The locale of the performance may be different; this can affect tempo, dynamics, and pedalling for most pieces (even true for a country dance band as I have found out from experience.)


500 Internal Server Error can't access

Question: I am using Odoo 8 on Windows 7, things were going all right untill I tried to make the fleet.vehicle class inheriting another class (inheritance by prototyping) :
_name = 'fleet.vehicle'
_inherit = 'another.class'

since then, I have this error when trying to access to my http://localhost:8069/web :

Internal Server Error
The server encountered an internal error and was unable to complete
  your request. Either the server is overloaded or there is an error in
  the application.

this is the openerp-server.log's repport :
2016-03-14 13:59:31,033 1904 INFO Odoo8_DB openerp.modules.loading: loading 1 modules...
2016-03-14 13:59:31,058 1904 INFO Odoo8_DB openerp.modules.loading: 1 modules loaded in 0.02s, 0 queries
2016-03-14 13:59:31,239 1904 INFO Odoo8_DB openerp.modules.loading: loading 53 modules...
2016-03-14 13:59:31,266 1904 CRITICAL Odoo8_DB openerp.modules.module: Couldn't load module fleet
2016-03-14 13:59:31,267 1904 CRITICAL Odoo8_DB openerp.modules.module: unindent does not match any outer indentation level (fleet.py, line 313)
2016-03-14 13:59:31,279 1904 INFO Odoo8_DB werkzeug: 127.0.0.1 - - [14/Mar/2016 13:59:31] "GET /favicon.ico HTTP/1.1" 500 -
2016-03-14 13:59:31,293 1904 ERROR Odoo8_DB werkzeug: Error on request:
Traceback (most recent call last):
  File "werkzeug\serving.py", line 177, in run_wsgi

  File "werkzeug\serving.py", line 165, in execute

  File "D:\MesDocuments\Les_prog\Odoo 8.0-20160118\server\openerp\service\server.py", line 290, in app
    return self.app(e, s)
  File "D:\MesDocuments\Les_prog\Odoo 8.0-20160118\server\openerp\service\wsgi_server.py", line 216, in application
    return application_unproxied(environ, start_response)
  File "D:\MesDocuments\Les_prog\Odoo 8.0-20160118\server\openerp\service\wsgi_server.py", line 202, in application_unproxied
    result = handler(environ, start_response)
  File "D:\MesDocuments\Les_prog\Odoo 8.0-20160118\server\openerp\http.py", line 1290, in __call__
    return self.dispatch(environ, start_response)
  File "D:\MesDocuments\Les_prog\Odoo 8.0-20160118\server\openerp\http.py", line 1428, in dispatch
    ir_http = request.registry['ir.http']
  File "D:\MesDocuments\Les_prog\Odoo 8.0-20160118\server\openerp\http.py", line 346, in registry
    return openerp.modules.registry.RegistryManager.get(self.db) if self.db else None
  File "D:\MesDocuments\Les_prog\Odoo 8.0-20160118\server\openerp\modules\registry.py", line 339, in get
    update_module)
  File "D:\MesDocuments\Les_prog\Odoo 8.0-20160118\server\openerp\modules\registry.py", line 370, in new
    openerp.modules.load_modules(registry._db, force_demo, status, update_module)
  File "D:\MesDocuments\Les_prog\Odoo 8.0-20160118\server\openerp\modules\loading.py", line 351, in load_modules
    force, status, report, loaded_modules, update_module)
  File "D:\MesDocuments\Les_prog\Odoo 8.0-20160118\server\openerp\modules\loading.py", line 255, in load_marked_modules
    loaded, processed = load_module_graph(cr, graph, progressdict, report=report, skip_modules=loaded_modules, perform_checks=perform_checks)
  File "D:\MesDocuments\Les_prog\Odoo 8.0-20160118\server\openerp\modules\loading.py", line 143, in load_module_graph
    load_openerp_module(package.name)
  File "D:\MesDocuments\Les_prog\Odoo 8.0-20160118\server\openerp\modules\module.py", line 315, in load_openerp_module
    __import__('openerp.addons.' + module_name)
  File "D:\MesDocuments\Les_prog\Odoo 8.0-20160118\server\openerp\modules\module.py", line 80, in load_module
    mod = imp.load_module('openerp.addons.' + module_part, f, path, descr)
  File "D:\MesDocuments\Les_prog\Odoo 8.0-20160118\server\openerp\addons\fleet\__init__.py", line 21, in <module>
    import fleet
File "D:\MesDocuments\Les_prog\Odoo 8.0-20160118\server\openerp\addons\fleet\fleet.py", line 313
    LogFuel = self.pool['fleet.vehicle.log.fuel']
                                                ^
IndentationError: unindent does not match any outer indentation level

even after deleting the line I added I am still receiving the same error,
I tried to restart the odoo-server, postgreSQL-server and refreshing the DB but in vain..
  I would be gratful for any help
edit : line 313 , fleet.py
Comment: Any chance you have edited `fleet.py` from fleet module while examining its code for inheriting it? Also if you want to customize fleet module then you probably need `_inherit = 'fleet.vehicle'` and `_name = 'your_class'`. Not the other way around like you are doing.
Comment: thanks for replying, but I have canceled all editings before asking the question
Answer: That's python-related : you have some trailing (before or after) indent.
Open your file within your IDE, and display indents. In python, each block should be on the same indent level.
EDIT : as the stack says it, that's probably near: D:\MesDocuments\Les_prog\Odoo 8.0-20160118\server\openerp\addons\fleet\fleet.py", line 313
Comment: Remember : python and trailing spaces / indents. Double check the line before AND after. Error is pretty clear : you have trouble with indents. I'm not a Windows user, but if I remember well, Notepad++ has some option to show invisible characters; use it to find what is causing trouble here.
Comment: thanks for replying, but I think this is not the real problem (I have added a screenshot of the line 313 )
Comment: There is no such thing as a "trailing indent", and Python does not care about whitespace at the *end* of a line. However, these problems can easily occur when mixing spaces and tabs. Depending on the IDE it may not display in a way that highlights the problem.

500 Internal Server Error can't access


Prove that a Galois group is isomorphic to matrix group

Question: This was a problem in a test:
Prove that the Galois group of $x^p-2$ (where $p$ is a prime)  over $\mathbb Q$ isomorphic to the following matrix group under multiplication:
$$\begin{pmatrix}
a & b \\
0 & 1\\
\end{pmatrix}$$
where $a \in \mathbb F_{p}$ and $b \in \mathbb F_{p} \backslash \{0\}.$
I don't know why the Galois group is not simply the order $p$ cyclic group (since the roots of the polynomial over $\mathbb C$ are $\sqrt[p]{2}\epsilon_{i}$ where the $\epsilon_{i}$ are the $p$-th roots of unity),
Can someone help me?
Comment: The splitting field over $\Bbb{Q}$ will need to contain the $p^{th}$ roots of unity.  Hence the $\Bbb{F}_p\backslash \{0\}$
Comment: Complex conjugation will also be an automorphism, which fixes some roots but not others.  On the other hand, the $\sqrt[p]{2} \mapsto \sqrt[p]{2}\zeta$ automorphism, which would generate that cyclic group, moves all the roots.
Comment: What we want to prove is $\sigma \in Gal(\mathbb Q(\sqrt[p]2, \zeta)/\mathbb Q)$ iff $\sigma(\zeta^k\sqrt[p]2) = \sigma(\zeta^k)\sigma(\sqrt[p]2)=\zeta^{nk}\zeta^m\sqrt[p]{2}$  for some $n \in \mathbb{F}_p^\times, m \in \mathbb{F}_p$.

Thus $$\sigma_{n',m'} \circ \sigma_{n,m}(\zeta^k\sqrt[p]2) = \sigma_{n',m'} (\zeta^{nk}\zeta^m\sqrt[p]2) = \zeta^{n'(nk+m) + m'}\sqrt[p]2 = \sigma_{n'n,n'm+m'}(\zeta^k\sqrt[p]2)$$
Comment: Hint: Map that matrix to the automorphism that is determined by $\zeta\mapsto \zeta^a$, $\root p\of2\mapsto \zeta^b\root p\of 2$.
Comment: [Related](https://math.stackexchange.com/q/463671/11619).
Answer: Let $\zeta = e^{\frac{2\pi i}p}$, a primitive $p$-th root of unity and let $K$ be the splitting field of $x^p-2$ over $\mathbb Q$. Then claim that $K = \mathbb Q(\sqrt[p]2, \zeta)$ and $[K:\mathbb Q] = p(p-1)$. Since $x^p -2$ is an separable polynomial over $\mathbb Q$ (why?) it follows that $K/\mathbb Q$ is Galois and so the Galois group has order $p(p-1)$. Following the comments one can show that $Gal(K/\mathbb Q)$ is isomorphic to the matrix group you state above, which is also isomorphic to the nonabelian group $C_p \rtimes C_{p-1}$
Proof of claim: As you said $\sqrt[p]2\zeta^k$ for $k = 0, 1, \dots, p-1$ are the roots of $x^p - 2$; so clearly $K \subset \mathbb Q(\sqrt[p]2, \zeta)$. Now note that $\sqrt[p]2 \in K$ and also $\zeta = \frac{(\sqrt[p]2\zeta)^{p+1}}{2\sqrt[p]2} \in K$; hence $\mathbb Q(\sqrt[p]2, \zeta) \subset K$. Now note that $K$ contains the subfields $\mathbb Q(\sqrt[p]2)$ and $\mathbb Q(\zeta)$, which have degree $p$ and $p-1$ resp. over $\mathbb Q$. Since $\gcd(p, p-1) = 1$, by a basic field theory result it follows that the compositum field $\mathbb Q(\sqrt[p]2)\mathbb Q(\zeta) = K$ has degree $p(p-1)$ over $\mathbb Q$. $\square$


Prove for all subsets $M$ of $A$ the following $M \subseteq f^{-1}(f(M))$.

Question: I'm doing a past exam as preparation for the upcoming exam. It contains the following problem
Let $f: A \longrightarrow B$ be a mapping.
(a) Prove for all subsets $M$ of $A$ the following
$M \subseteq f^{-1}(f(M))$.
I have spent a good hour thinking about this... nothing substantial has come to my mind, sorry.
Which theorems, definitions, corollaries etc. should I use?
I will probably try to study these harder because I probably do not have a sufficient understanding.
(b) Give an example which shows that $f^{-1}(f(M))$ do not have to be equal to $M$.
This one I can probably solve if I get sufficient help with (a).
Thank you in advance.
Kind regards,

X
Comment: How about the definition of $f^{-1}(X)$: $a\in f^{-1}(X)$ iff $f(a)\in X$? So $a\in f^{-1}(f(M))$ iff $f(a)\in f(M)$.
Comment: also, put $f:\mathbb{R} \rightarrow \mathbb{R}$, $f(x)=x^2$. then for M={2}. we have $f(M)={4}$, and $f^{-1}(f(M))=f^{-1}(\{4\})=\{x \in \mathbb{R}: x^2=4\}=\{2,-2\}$
Comment: Thanks for your fast reply! This is the definition of a inverse mapping, right? But $f$ does not have to be invertible ?
Comment: Thanks. Seems like an easy and understandable example.
Answer: Remember that for a function $f:A\to B$, for any $M\subseteq A$ and $N\subseteq B$ we have  $$f(M)=\{f(x)\mid x\in M\}\\f^{-1}(N)=\{x\in A\mid f(x)\in N\}$$
Let $M\subseteq A$ be given.  Let $x\in M$ be given.  Then $f(x)\in f(M)$ from the first definition.  Therefore, $x\in f^{-1}(f(M))$, again from the second definition because $f(x)\in f(M)$.  Since $x$ was arbitrary, $M\subseteq f^{-1}(f(M))$
Remember that $f^{-1}(f(M))$ is the set of all members of the domain whose output under $f$ is the output under $f$ from some member of $M$.  So, of course any member of $M$ would satisfy that.  This is one of those problems that is so easy that you can get bogged down by all the notation.
For your second question, imagine that $f:\mathbb R\to \mathbb R$ is the constant function $f(x)=0$.  Let $M=\{1\}$.  Then $f(M)=\{0\}$ because $f(1)=0$.  But $f^{-1}(\{0\})=\mathbb R$, because every element maps to $0$.  Therefore, this is a case where $f^{-1}(f(M))\neq M$.
Comment: Thanks, now I understand fully!
Why do you use $\subset$ instead of $\subseteq$ ?
Comment: @Xenusi because half of mathematicians think that extra line is a waste of pencil lead and we use $\subsetneq$ in the rare cases when we want to talk about proper subsets.  ^_^  I should have noticed it and adapted -- it is now edited.
Comment:
Once again, thanks.


drupal_is_front_page can't recognize arguments

Question: I have a view display as a drupal site's front page. And that view has a path (like "/myview". Also that view takes several arguments from url (like "/myview/arg1/arg2"). I also have some extra code to be called on the front page only. But it seams that drupal_is_front_page function can't recognize a view page with arguments as a front page. For example, drupal_is_front_page returns:

1) "mysite.com/" - >true
2) "mysite.com/myview/" - >true
3) "mysite.com/myview/arg1" - >false
4) "mysite.com/myview/any-text-here" ->false

In any of these cases a view display returns correct data, but drupal_is_front_page - not. Is there any way to check if its a frontpage in my case?
Answer: When looking at the drupal_is_front_page function you see it performs a check on
<code>($_GET['q'] == variable_get('site_frontpage', 'node'));
</code>
So it only returns true if there is an exact match.
You can recreate the function and use something this instead, to check if the frontpage url is a part of the request url:
<code>(strpos($_GET['q'], variable_get('site_frontpage', 'node')) !== false)
</code>
All other code in drupal_is_front_page is for static caching. You want to copy that if you intend to call this function often. If it is for one check you can do with this simple function:
<code>function drupal_is_front_page2() {
  $is_front_page = (strpos($_GET['q'], variable_get('site_frontpage', 'node')) !== false);
  return $is_front_page;
}
</code>


Python plot points on the same scatter plot using a for loop

Question: I have a list of objects. I want to plot two particular attributes from each of these objects on to a scatter plot. I want to do this WITHOUT creating a list of x and y data points before plotting.
I tried the following but it plots a new graph for each data point instead(somehow the datapoint isn't visible either):
for i in config:
    plt.scatter(i.timestep, i.totalCalcAtoms)
    plt.pause(0.05)

plt.show()

Comment: Try `fig, ax = plt.subplots()` and `ax.scatter()`.
Answer: Using the change suggested by @Ynjxsjmh worked. The following was the finally used code:
fig, ax = plt.subplots()
plt.title(f'cutoff(Angstron)={cutoff}')
for i in config:
    ax.scatter(i.timestep, i.totalCalcAtoms,color="blue")
    ax.scatter(i.timestep, i.proton_count,color="red")

plt.show()

Comment: I ran your original code and everything went fine, a single plot… so it was a different, probably non-recurrent problem.  Anyway, now it works for you too…
Comment: @gboffi I was running it in a jupyter notebook. Can that be any different?
Comment: I was running it in the terminal, probably the notebook was the reason


Finding an impulse response to an inverse system of that of which an impulse reponse is given

Question: I need to solve a bunch of these questions and would appreciate a solid direction.
I have an impulse response $h[n]=\left(\frac{1}{5}\right)^nu[n]$.
 Firstly we are to find a whole number A which satisfies $h[n]-A h[n-1]=\delta [n]$.
After it is found we need to find the impulse response of the inverse system to the original one.
I dont know how to find the original system from the data given.
In regards to the first part, I know that the discrete unit impulse is 1 when n=0 and 0 otherwise and I gathered that A should be such that it satisfies this structure but have failed to find it.
Thank you for your attention.
Comment: If $H(z)$ is a filter, $1/H(z)$ is its inverse filter. $H(z)$ is the z-transform of $h[n]$.
Comment: The second part is about the inverse system, not an inverse filter. Also, must be done without Laplase (dont know if it is called for here but in any case)
Answer: Well regarding the first part, just solve for $A$:
$A = (h[n]-\delta[n]) / h[n-1]$
Ok, in general case you would not know that the right hand side is independent of $n$. But since the question is already tells us, that such an $A$ exists, it will be found by just solving. When you plug everything in, $n$ cancels out and you obtain $A=1/5$.
For the second part, on how to find the inverse, just recall that the inverse to $h[n]$ is defined by
$h[n] * g[n] = \delta[n]$
So the task is to find $g[n]$. We notice that this equation looks already very similar to the equation in your question (i.e. $h[n] - A h[n-1] = \delta[n]$) so we should think how to convert it to the form.
The answer is easily found by noticing that $h[n] = h[n] * \delta[n]$ and $h[n-1] = h[n] * \delta[n-1]$. So by plugging this in and rearranging, we get
$h[n] * (\delta[n] - A \delta[n-1])  = \delta[n]$
which yields the inverse
$g[n] = \delta[n] - A \delta[n-1]$
Maybe a word of interpretation: The system in your original question resembles a first order lowpass, because it just has a exponentially decaying impulse response. The inverse system is just a first order highpass, which is just given by the system $g[n]$. Since a first order highpass amplifies the detail of a signal, while ignoring the average value (i.e. the opposite of a lowpass), it makes sense that the $g[n]$ outputs the difference of consecutive input samples with some weighting.
Comment: A brilliant and well formed answer and interpretation. Thank you for your time and answer.
Comment: one problem though. For the solution of A, n doesnt cancel out plus A is supposed to be an integer (whole) number. When plugging in, the equation is $A=\frac{\left(\frac{1}{5}\right)^nu[n]-\delta [n]}{\left(\frac{1}{5}\right)^{n-1}u[n-1]}$.. Although $u[n]-\delta [n]=u[n-1]$ There is a coefficient to $u[n]$
Comment: @SteelSoul: of course n cancels out! Check your math. For $n > 0$, we have $A = (1/5)^n / (1/5)^{n-1} = 1/5$. For $n=0$ we get $0/0$ which essentially means $A$ can be arbitrary. So $A=1/5$ is a solution. This is easily verified by plugging in: $\left(\frac{1}{5}\right)^n u[n] - \left(\frac{1}{5}\right) \left(\frac{1}{5}\right)^{n-1} u[n-1] = \left(\frac{1}{5}\right)^n (u[n] - u[n-1]) = \left(\frac{1}{5}\right)^n \delta[n] = \delta[n]$! Please check your math!
Comment: Maybe the point you did not realize is that $(1/5)^n \delta[n] = \delta[n]$. This is just because $\delta[n]$ is zero almost everywhere (so the equation is correct at $n \neq 0$). And at $n=0$ we have $(1/5)^0 = 1$, which makes it correct also for $n=0$.
Comment: Thank you for the clarification. You are very observant.


Otimização de código R

Question: Gostaria de saber se alguém tem alguma sugestão para que eu possa otimizar o código abaixo.
A ideia eu retirei desse site. Você tem uma permutação de n cartas, por exemplo [2, 4, 1, 3] (onde o 2 é a carta que está no topo). Em cada rodada, a pessoa deve reverter as m primeiras cartas, onde m é a carta do topo. As rodadas são repetidas até que a permutação final seja [1, 2, 3, ..., n].
Exemplificando:
[2, 4, 1, 3]
[4, 2, 1, 3]
[3, 1, 2, 4]
[2, 1, 3, 4]
[1, 2, 3, 4]

Utilizei a função perm da biblioteca Deducer para obter todas as permutações possíveis de um determinado vetor.
#retorna a quantidade de mudanças necessárias para obter o vetor de 1 até n
topswops <- function(x){
  i <- 0
  while(x[1] != 1){
    primeira <- x[1]
    if(primeira == length(x)){
       x <- rev(x)
    } else{
      x <- c(x[primeira:1], x[(primeira+1):length(x)])
    }
    i <- i + 1
  }
  return(i)
}

library(Deducer)

inicio <- Sys.time()
resultado <- NULL
for(i in 1:10){
  A <- perm(1:i)
  A <- data.frame(A)
  A$flips <- apply(A, 1, topswops)
  resultado <- rbind(resultado, c(i, max(A$flips)))
}
fim <- Sys.time()
fim - inicio

O tempo de processamento foi 3,74 minutos. Suspeito que a parte das permutações A <- perm(1:i) seja a que mais leva tempo, mas não consegui pensar em nenhuma outra forma.
Answer: Pelo que analisei do teu código, a tua suspeita está correta: a função perm é o que está deixando o código lento. Eu cheguei a esta conclusão testando o tempo de execução da função topswops:
library(rbenchmark)
benchmark(topswops(sample(1:i, 10)), replications = 100000)
                       test replications elapsed relative user.self sys.self user.child sys.child
1 topswops(sample(1:i, 10))       100000   2.388        1     2.253    0.107          0         0

Repetir topswops cem mil vezes em vetores aleatórios de tamanho 10, com os elementos de 1 a 10, levou 2.388 segundos. Ou seja, o gargalo não é aqui.
Isto posto, procurei outras maneiras de gerar todas as permutações possíveis para uma sequência de números. Além do Deducer, os pacotes combinat e gtools também conseguem gerar todas as permutações de uma sequência de números. Os resultados do meu teste foram os seguintes:
library(Deducer)
inicio <- Sys.time()
resultado.Deducer <- NULL
for(i in 1:10){
  A <- perm(1:i)
  A <- data.frame(A)
  A$flips <- apply(A, 1, topswops)
  resultado.Deducer <- rbind(resultado.Deducer, c(i, max(A$flips)))
}
fim <- Sys.time()
fim - inicio
Time difference of 4.131159 mins

library(combinat)
inicio <- Sys.time()
resultado.combinat <- NULL
for(i in 1:10){
  A <- as.data.frame(matrix(unlist(permn(1:i)), ncol=i, byrow=TRUE))
  A$flips <- apply(A, 1, topswops)
  resultado.combinat <- rbind(resultado.combinat, c(i, max(A$flips)))
}
fim <- Sys.time()
fim - inicio
Time difference of 2.371664 mins

library(gtools)
inicio <- Sys.time()
resultado.gtools <- NULL
for(i in 1:10){
  A <- permutations(i, i, 1:i)
  A$flips <- apply(A, 1, topswops)
  resultado.gtools <- rbind(resultado.gtools, c(i, max(A$flips)))
}
Warning messages:
1: In A$flips <- apply(A, 1, topswops) : Coercing LHS to a list
2: In A$flips <- apply(A, 1, topswops) : Coercing LHS to a list
3: In A$flips <- apply(A, 1, topswops) : Coercing LHS to a list
4: In A$flips <- apply(A, 1, topswops) : Coercing LHS to a list
5: In A$flips <- apply(A, 1, topswops) : Coercing LHS to a list
6: In A$flips <- apply(A, 1, topswops) : Coercing LHS to a list
7: In A$flips <- apply(A, 1, topswops) : Coercing LHS to a list
8: In A$flips <- apply(A, 1, topswops) : Coercing LHS to a list
9: In A$flips <- apply(A, 1, topswops) : Coercing LHS to a list
10: In A$flips <- apply(A, 1, topswops) : Coercing LHS to a list
fim <- Sys.time()
fim - inicio
Time difference of 1.849558 mins

Portanto, uma maneira de otimizar o código é, justamente, melhorando a geração das permutações. Nos meu teste, a função que melhor se saiu foi gtools::permutations, levando 1.849558 minutos para rodar. Isto equivale a 44% do tempo utilizado pela função original.
Talvez seja possível melhorar ainda mais este desempenho otimizando a geração das permutações. Como são milhões de replicações, acredito que qualquer melhora na geração das permutações seja algo que conte muito no final.
Se a procura é pelo menor tempo de execução e não necessariamente o melhor algoritmo, também é possível diminuir o tempo de execução paralelizando o código. Mas aí eu deixo este exercício para o leitor : )
Comment: A ideia de paralelização é boa, mas como foi um código de brincadeira, nem vou me preocupar tanto com isso. Consegui achar um outro pacote que reduziu o tempo de execução para 1,58 minutos - `iterpc`. Rodei novamente meu código inicial e, o tempo gasto foi 3,25 minutos. Então, o ganho, foi mais de 50%.

Otimização de código R


Why do I get different heteroscedasticity robust standard errors in R when using the plm package?

Question: I am now writing my bachelors thesis and I have come across some difficulties. I am about to do some panel regressions with time and entity fixed effects and I would therefore like to use the plm package. But when I do add fixed effects and want to have heteroscedasticity robust standard errors they seem to be incorrect.
Does anyone know why the HC standard errors differ?
Here is my code
# Load data
load(file="panel")
attach(panel)

# Load packages
library(lmtest)
library(plm)

# Create two models. The lm.model is a linear model and as the
# LAND variable is a factor variable representing countries
# (Land = Country in Swedish) this model will have entity fixed
# effects. In the plm.model the plm package is used and
# individual effects and within model is turned on (which is
# the same as entity fixed effects)
lm.model<-lm(NETTOSPARANDE ~ EURO + LAND, data=panel)
plm.model<-plm(NETTOSPARANDE ~ EURO, index=c("LAND","ÅR"), effect="individual", model="within", data=panel)

# When looking at the coefficents without heteroscadisity robust
# standard errors they are identical. They do also have the same
# value in stata.
coeftest(lm.model)[1:2,]
coeftest(plm.model)

# But when looking at the coefficents using heteroscadisity
# robust standard errors the lm.model and the plm.model produces
# different standard errors.
coeftest(lm.model, vcov.=vcovHC(lm.model, method="white2", type="HC1"))[1:2,]
coeftest(plm.model, vcov.=vcovHC(plm.model, method="white2", type="HC1"))

If you want to test the data it can be found here (the panel file)
  [1]: https://sourceforge.net/projects/emumoralhazard/files/ R-data
And here is my output
1> # Load data
1> load(file="panel")

1> attach(panel)

1> # Load packages
1> library(lmtest)
Loading required package: zoo

1> library(plm)
Loading required package: kinship
Loading required package: survival
Loading required package: splines
Loading required package: nlme
Loading required package: lattice
[1] "kinship is loaded"
Loading required package: Formula
Loading required package: MASS
Loading required package: sandwich

1> # Create two models. The lm.model is a linear model and as the
1> # LAND variabel is a factor variable representing countries
1> # (Land = Country in swedish) this model will have entity fixed
1> # effects. In the plm.model the plm package is used and
1> # individual effects and within model is turned on (which is
1> # the same as entity fixed effects)
1> lm.model<-lm(NETTOSPARANDE ~ EURO + LAND, data=panel)

1> plm.model<-plm(NETTOSPARANDE ~ EURO, index=c("LAND","ÅR"), effect="individual", model="within", data=panel)

1> # When looking at the coefficients without heteroscedasticity robust
1> # standard errors they are identical. They do also have the same
1> # value in Stata.
1> coeftest(lm.model)[1:2,]
             Estimate Std. Error   t value     Pr(>|t|)
(Intercept) -3.731024  0.7731778 -4.825570 1.726921e-06
EURO1        2.187170  0.4076720  5.365024 1.112984e-07

1> coeftest(plm.model)

t test of coefficients:

      Estimate Std. Error t value  Pr(>|t|)
EURO1  2.18717    0.40767   5.365 1.113e-07 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

1> # But when looking at the coefficients using heteroscedasticity
1> # robust standard errors the lm.model and the plm.model produces
1> # different standard errors.
1> coeftest(lm.model, vcov.=vcovHC(lm.model, method="white2", type="HC1"))[1:2,]
             Estimate Std. Error    t value     Pr(>|t|)
(Intercept) -3.731024  0.3551280 -10.506138 5.102122e-24
EURO1        2.187170  0.3386029   6.459395 2.009894e-10

1> coeftest(plm.model, vcov.=vcovHC(plm.model, method="white2", type="HC1"))

t test of coefficients:

      Estimate Std. Error t value  Pr(>|t|)
EURO1  2.18717    0.33849  6.4615 1.983e-10 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Answer: Though numerically both of your model coefficients estimates coincide, you are actually fitting two different models: least square dummy variables and fixed effects.
They differ on their assumptions, so the robust standard errors are calculated differently.
Function vcovHC is a wrapper function, different functions are actually used in case of lm model and plm. In the first case the function vcovHC comes from the sandwich package, in the second from the plm package.
The difference in results arises because  vcovHC for lm object does not exploit panel data structure. Comparing
plm:::vcovHC.plm

and
vcovHC.default

reveals that for panel data there is additional argument cluster = c("group", "time").
Look into Wooldridge book for more explanation why least squares dummy variables and fixed effects regressions differ. It has whole chapter dedicated for that.
Comment: Thank you for the answear.
But is the first model pooled? I have added the LAND term wich is the entity dummy variable (as it's a facor variable.
And as I can se the parameter estimates (EURO) are identical?
Comment: @Skolnick, I've missed that at first, so I changed my answer accordingly
Comment: I have tried to get reach of that book but the library has a copy that's not available for the moment. But I can perhaps ask which model that has the most accurate standard errors when HC-robust, LSDV or within?
Answer: @Skolnick -
After an admittedly quick look at your problem, it seems that plm() truncates and/or rounds results to less digits than lm().  I think this is the most likely cause of the differences in your heteroscedasticity-robust standard error estimates.  Explore summary(plm.model) and summary(lm.model) for differences in residual quantiles.


Conditional Probability of not events

Question: If the probability of A is 0.25, the probability of S is 0.15 and the probability of A AND S is 0.1, what is the probability of;
(a) NOT S given A
(b) NOT A given NOT S
Comment: you can try to solve this by using venn diagram
Comment: Do you know how conditional probabilities are computed?
Answer: $$P(S'|A)=1-P(S|A)=1-\dfrac{P(A\cap S)}{P(A)}=0.6$$$$P(A'|S')=\dfrac{P(A'\cap S')}{P(S')}=\dfrac{1-P(A\cup S)}{1-P(S)}=\dfrac{0.7}{0.85}=\dfrac{7}{85}$$
Comment: So in your answer, P(A AND S) is equal to 0.06? Why is that, when the intersection is 0.1?
Answer: I think it's also nice to get a visual feel too. Below is a Venn diagram representation of your problem.

In a) you require $\text{Pr}(\bar{S}|A)$.Lets think of our probabilities as areas for a moment. Notice that this is then the same as asking,

"What proportion of $\bar{S}$ sits inside of $A$".

What is the area of $A$? Well it's going to be the blue bit plus the purple bit, which is $0.25$.
Now, what is the area of $\bar{S}$ in $A$? Well, it's just the blue bit, which is $0.15$.
Therefore, the proportion of $\bar{S}$ that sits inside of $A$ is just $\frac{0.15}{0.25} = 0.60$.
You can carry the same ideas through to the next part of the question too.

Conditional Probability of not events


Dirac Delta special case

Question: How can we define a generalized function, very similar with Dirac Delta, that is zero on the real line but 1 at 0 (origin), instead of "infinity"?
Something without using piecewise notation?
I'm looking for something that I can use with Mathematica to inspect some properties on the real numbers.
If possible I would some help to define this function on Mathematica too.
Answer: Mathematica has a function called DiscreteDelta for such purposes:

DiscreteDelta[0] gives $1$; DiscreteDelta[n] gives $0$ for other numeric $n$.

Dirac Delta special case


Comparing slopes between different regression lines in the same sample

Question: I have two models:
mod1 <- glm(y ~ A + CONTROL1 + CONTROL2, data = dat,family=binomial(link="logit"))
mod2 <- glm(y ~ B + CONTROL1 + CONTROL2, data = dat,family=binomial(link="logit"))
I'm trying to determine if slope A in mod1 is significantly different from slope B in mod2.
I'll give a reproducible example here:
mydata <- read.csv("https://stats.idre.ucla.edu/stat/data/binary.csv")
mydata$sat<-rnorm(400, mean=1350, sd=100) # randomly generate SAT scores
m1 <- glm(admit ~ gre + gpa + rank, data = mydata, family = "binomial")
m2 <- glm(admit ~ sat + gpa + rank, data = mydata, family = "binomial")
I am interested in finding out if the slope associated with gre in m1 is significantly different from the slope associated with sat in m2.
What are some tests in R that can help me get there?
Thanks in advance!
Comment: Possible duplicate of https://stats.stackexchange.com/questions/252325/is-there-a-statisical-method-for-comparing-slopes-of-logistic-regressions.  Especially the first comment and the corresponding link.
Comment: I'm not sure if it's a duplicate. The questions in the two threads are quite a bit different. I'm not asking about how slopes might vary by subgroups.
Comment: That's why I indicated they are possible -- admittedly they may not apply -- I just scanned them because I remember a similar question before.  I guess one question I'd have is why are you fitting separate models?  Can you update the question a bit to tell us why you are doing separate models as opposed to fitting a single model with an interaction term?
Comment: Thanks for your follow up. I'm not fitting a single model with an interaction term because there's no theoretical reason for doing so. In the example, there's no reason to think that the effect of "gre" on the likelihood of admittance varies by "sat" scores. I'm only trying to see if there's a different effect between "gre" and "sat" on the outcome variable. m1 and m2 aren't nested models.
Comment: Have you tested that theory?  Couldn't you just include gre and sat in the same model and test contrasts?  It seems you'd want to account for both of these since both influence admission.  I'm not sure you can have one without the other in any admission process that I know of.
Comment: the test scores are generally highly correlated. I don't want to include them in the same model due to multicollinearity. Anyways, I simply want to see if the slope associated with "gre" is different from the one associated with "sat".
Comment: OK. Can you tell us what the end goal of your analysis is?  Is it to obtain the best prediction possible or is it only to determine if gre or sat is a better predictor, perhaps?
Comment: Yes, the end goal simply is to determine is "gre" or "sat" is a better predictor
Comment: See: Comparing Coefficients of Nonlinear Multivariate Regression Models Between Equations Survey Research Methods. 2015;9(3):159-167 DOI 10.18148/srm/2015.v9i3.6211.  You might also consider computing standardized coefficients for comparison purposes.  In addition, I think you are better off creating some sort of a composite function of gre and sat (think PCA scores) since, in real world admissions processes, admission staff don't have one or the other.
Comment: Also, another helpful CV link:  https://stats.stackexchange.com/questions/8718/comparing-logistic-regression-coefficients-across-models
Answer: You mentioned in the comments that your goal is to determine if GRE or SAT does better at predicting.  Given that this is your goal, and that all other variables in your model appear to be identical, I'd suggest the following approach.
Simply test your GRE model on a hold-out sample of data and compute the mean squared predicted error (MSPE).  Do the same thing with the SAT model.  Then, select the model that has the lowest mean squared predicted error as this model does the best job of predicting.  You could even perform cross-validation or jackknife estimates with these methods and compare the averaged MSPEs.
That being said, in the real world, rarely do school admissions offices receive only a GRE or only and SAT (I believe).  As you've provided in your example, both factors likely contribute to the admission decision.  As a result, I think you are better off creating a composite index of both GRE and SAT (perhaps by using a PCA score of GRE and SAT) and placing it in your model.


Shouldn't log likelihood always be normalized by data size in bayesian estimation?

Question: This is very interesting problem. I wonder if the whole bayesian statistics is neglecting it or if I am super confused. I will illustrate it on a bayesian Maximum a Posteriori (MAP) estimation and later we can discuss how would it be when full distribution is considered (using e.g. MCMC).
We are looking for MAP estimate for parameters $\theta$:
$$\theta_{MAP} = \mathrm{argmax}_\theta \ \ p(\theta|y) = \mathrm{argmax}_\theta \ \ {p(y|\theta)  \cdot p(\theta)  \over p(y)} = \mathrm{argmax}_\theta \ \ p(y|\theta)  \cdot p(\theta) =  \mathrm{argmax}_\theta \ \ \mathrm{log}(p(y|\theta)  \cdot p(\theta)) = \mathrm{argmax}_\theta \ \ \mathrm{log} \ p(y|\theta) + \mathrm{log} \ p(\theta)$$
a
$p(y|\theta)$ is the log likelihood, $p(\theta)$ is prior. Now, this is interesting: the magnitude of the log likelihood $p(y|\theta)$ will vary very much based on data size: I get values like -4414.6 for N=7576 and -59.4 for N=59. But the magnitude of the prior stays the same.
So, just based on data size, the log prior will get different weight in the estimation compared to the log likelihood! Which looks like a different model. Question 1: Am I right in this conclusion?
So (Question 2), wouldn't it make more sense to "normalize" the log likelihood according to data size, like this? :
$$\mathrm{argmax}_\theta \ \ {1 \over N} \mathrm{log} \ p(y|\theta) + \mathrm{log} \ p(\theta)$$
For example, in Yi et al (2011), they do this:

I already tried this approach and found that different values of $\lambda$ will yield different cross-validation results (which doesn't yet imply that the likelihood should be normalized by data size, but it shows that the relative scale of the prior to the likelihood is important).
There are some approaches like Regularization where this has been consciously taken care of. But, surprisingly, when I look at the papers and current practice in my area (in the context of Gaussian Processes), taking care of this important issue (like in the above paper) is very rare and most studies don't care about that at all and just stay with the bayesian MAP approach. Which is confusing me, because:
(Question 3) Isn't the MAP approach a priori wrong, because the weight of the log prior (i.e. penalization, regularization, however you interpret the prior) relative to log likelihood will change with data size?
And the interesting discussion would be whether problem does apply in the case when we don't just care about the maximum of the distribution as in MAP, but study the whole posterior distribution as e.g. in MCMC, so shouldn't we be looking at this instead? :
$${p(y|\theta)^{1 \over N}  \cdot p(\theta)  \over p(y)}$$

Mentioned references: Yi, G., Shi, J. Q., & Choi, T. (2011). Penalized gaussian process regression and classification for high-dimensional nonlinear data. Biometrics, 67(4), 1285–1294. doi: 10.1111/j.1541-0420.2011.01576.x
Comment: That the influence of the prior vanishes as we collect more and more data is a well known result and makes intuitive sense.  This property allows prior beliefs to change with enough data.
Comment: What gets published and what gets used in, say, industry, can be two very different things.  When you have access to domain experts, as I do - and have for most of my career - informative priors become the norm, not the exception.  One does have to be wary of the trap of the experts' opinions being partially based on the same data that goes into the likelihood function, however!  For publication, though, people prefer uninformative priors, because it makes it clear to the reader that the results were driven by the data, not by the prior.
Comment: @DemetriPananos wow, thanks for interesting comment! But let's be realistic about how priors are used: most of the people do not have any "prior beliefs" (as priors are commonly advertised); most people use the priors in fact to penalize model compexity, which will **shrink** the parameters towards simple model. When you start thinking about priors like this, it becomes less intuitive; why should the weight of penalization term change with data size?
Comment: I'm not sure if that is how "most" people use priors, and frankly that seems like a sweeping generalization.  Regularization certainly is a use of priors (a la Bayesian ridge regression for example), but priors are and certainly should be used to impart valuable information to the model prior to seeing data.
Comment: @DemetriPananos I read tens, maybe well over a hundred of papers and I've seen maybe just one or two which would actually have prior beliefs and used priors to model them... most of the people have no "beliefs" about the value of $\rho$ parameter of their PC Matérn prior should be... Most of the studies use weakly informative priors which have shrinkage properties, i.e. which have the only function of penalizing model complexity (whether the authors know it or not :-))
Answer: Before answerinig you quesion, let's first make clear the Bayesian mindset:
All about Bayesian is to use posterior distribution to summarize everything we know about a certain random entity (such as $\theta$ in your case).
Where "everything we know" contains two parts:

part1: the prior information about $\theta$, which is represented by the prior distribution $p(\theta)$.
part2: the information from the observations, which is represented by the likelihood $p(y|\theta)$

To combine two parts of information, of course you need to assign a weight to each of them. There has to be one that is more pronouncing than the other.
And as you have noticed, sample size $n$ plays as the information weight for part2, which make sense because the more samples you observe, the more convincing the samples say about $\theta$, thus they should play a bigger role in the posterior (keep in mind that posterior is just a way to represent the combined information of part1 and part2).
As for part1, there will always be a prior strength been assigned when defining the prior (for example when using inverse-wishart distribution as the prior of a covariance matrix, the degree-of-freedom of the inverse-wishart distribution is the prior strength). And prior strength plays as the information weight for part1.
What if you assigin weight $1/n$ to the observations, by multiplying a $1/n$ to the log-likelihood as you did in the question. Then the weight for part1 will not increae with new data been observed, which means no matter how many samples you observe, your total knowledge about $\theta$ won't change.
For example:
If I want to model a coin toss, and using $Beta(2,2)$ as the prior distribution of the probability of getting a head(here the prior strength is $2$).
After 10 observations, say there are 4 heads and 6 tails, then the posterior distribution will be
$$
\theta \sim Beta(4+2,6+2)
$$
The variance of $\theta$ is $Var(\theta) = 0.0163$. The variance shows how uncertain you are about the distribution of $\theta$, the MAP estimate in this case is $\theta=0.4167$.
If you increase your sample size to 1000, there are 400 heads and 600 tails, then the posterior will be
$$
\theta \sim Beta(400+2,600+2)
$$
The variance is $\theta$ is $Var(\theta) = 0.0002$, the MAP estimate in this case is $\theta=0.3998$.
You can see that the variance is much smaller with more samples been observed. This is because increasing samples will increase the amount of information you gained in the posterior, the more information result in less uncertainty. Also, the MAP esitmate will be closer to the MLE when sample size is increased, this is because observations plays more weight in the posterior, thus has more say to the estimate.
But if you set weight to $1/n$, for no matter 10 or 1000 samples, the posterior will be the same:
$$
\theta \sim Beta(0.4+2,0.6+2)
$$
The variance is $Var(\theta)=0.0416$ and won't reduce when more samples are observed.The MAP esitimate will be $0.4667$ and won't show a tendency to MLE.


Aptana 3 - Setup PHP Executable

Question: I'm trying to use an Aptana plugin that requires a PHP executable with a certain name. Everywhere online people just say to go to Window > Preferences > PHP > PHP Executables.
There is no "PHP Executables" menu in my Aptana 3 though.
Is there another way to setup PHP Executables in Aptana 3?
Answer: For debugging/running, there is a way if you get the latest nightly build (preview.appcelerator.com/studio).
Once you are on the nightly, the debugger feature that includes the support for PHP executable will add this preference page under Window > Preferences > Aptana Studio > Editors > PHP > Debugger

Aptana 3 - Setup PHP Executable


array_merge removes my duplicates

Question: I am adding several arrays to a $result array.
Find below my example what I am currently doing:
$res = array();

$arr1 = array("key1" => array("10","12"));
$arr2 = array("key2" => array("1","11"));
$arr3 = array("key1" => array("10","12"));
$arr4 = array("key2" => array("1","11"));

$res = array_merge($res, $arr1);
$res = array_merge($res, $arr2);
$res = array_merge($res, $arr3);
$res = array_merge($res, $arr4);

print_r($res);

// OUTPUT:
// #######
Array
(
    [key1] => Array
        (
            [0] => 10
            [1] => 12
        )

    [key2] => Array
        (
            [0] => 1
            [1] => 11
        )

)

However, I would like to have the following output:
Array
(
    [key1] => Array
        (
            [0] => 10
            [1] => 12
        )

    [key2] => Array
        (
            [0] => 1
            [1] => 11
        )
    [key1] => Array
        (
            [0] => 10
            [1] => 12
        )

    [key2] => Array
        (
            [0] => 1
            [1] => 11
        )

)

As you can see I would like to add the duplicated arrays to my result array.
Any suggestions why array_merge replaces the duplicated merges and how to turn this behavior of?
I appreciate your replies!
Comment: You can't have two or more identical keys in the same array. The last one will overwrite the others.
Comment: @Anna.Klee Think about it this way, how would you reference/access them individually?
Comment: @Mehdi Thank you for your reply! Is there another function to have two or more identical arrays in an array?
Answer: As commented the answer is no.  A key is inherently unique.  PHP uses the key to locate the associated value.
You can not accomplish the structure you want, but if all you want is to have all the values in one array structure you could accomplish that simply with this code:
$res = array();

$res[] = array("key1" => array("10","12"));
$res[] = array("key2" => array("1","11"));
$res[] = array("key1" => array("10","12"));
$res[] = array("key2" => array("1","11"));

var_dump($res);
// You'll see all your arrays in one structure

Answer: This was meant to be a comment but ended up being too long.
You need to understand how arrays work, this is just a brief small explanation.
Let's say you have an array:
$array = array(
    'key1' => 'Hello ',
    'key2' => 'World',
    'key1' => 'Foo ',
    'key2' => 'Bar',
);

Now we try to use it like this:
echo $array['key1'].$array['key2'];

If we can use identical keys, which one will be printed?
Hello world or Foo bar? or a mix?
The real output is Foo bar because the last two will overwrite the first ones.
Here is a more detailed (and advanced) article explaining how PHP handles arrays.

array_merge removes my duplicates


ngResource GET with filter values

Question: I'm writing a small test application where I can retrieve my customers from a parse.com database.
I have the following form in html
...

        <button ng-click="getCustomers()">Get customers</button>

{{ customer.name }}

...

My angular app is the following:
Module
var app = angular
    .module('myApp', ['ngResource'])
    .constant('myConfig', {
        'api_url': 'https://api.parse.com/1/classes/',
        'parse_application_id': 'xxxxxxxxxxxxx',
        'parse_rest_api_key': 'xxxxxxxxxxxxx'
});

Factory
app.factory('CustomersService', function($resource, myConfig) {
    return $resource(myConfig.api_url + 'Customer', {}, {
        query: {
            method: 'GET',
            isArray: false,
            headers: {
                'X-Parse-Application-Id': myConfig.parse_application_id,
                'X-Parse-REST-API-Key': myConfig.parse_rest_api_key
            }
        },
        create: {
            method: 'POST',
            headers: {
                'X-Parse-Application-Id': myConfig.parse_application_id,
                'X-Parse-REST-API-Key': myConfig.parse_rest_api_key
            }
        }
    })
});

Controller:
app.controller('CustomerController', function($scope, CustomersService, CustomerService) {
     $scope.getCustomers = function() {
         CustomersService.query().$promise.then(function(result) {
            $scope.customers = result.results;
         });
     };
 });

So when I click my button, everything works like it should.
But I also want to add a filter by name when I want to retrieve customers from the database.
When I execute the following in Postman
https://api.parse.com/1/classes/Customer?where={"name":"aaaaa"}

this works and only gets the customer with the name "aaaaa". So I know that the syntax is OK.
So I will add a textbox where the user can enter a customername and after that I want to click on the search button.
But how can I manage the ?where={"name":"aaaaa"} into the angular stuff when I click the button? I also want to expand the filter with other columns from that customer.
Answer: Something like this should work (assuming everything goes in the where object)
Add some search fields that bind to a scoped object's properties. We'll call it search
Name
<input type="text" ng-model="search.name" name="name" id="search_name">

City
<input type="text" ng-model="search.city" name="city" id="search_city">

Then you can execute the query action with
CustomersService.query({where: $scope.search}).$promise...

That should create a query param like
?where=%7B%22name%22%3A%22aaaaa%22%2C%22city%22%3A%22London%22%7D

which is the URI encoded value
?where={"name":"aaaaa","city":"London"}

Comment: Thank you, that did the trick! Happy that it's a clean solution and not a special workaround to accomplish this! :)

ngResource GET with filter values


standby only at login screen?

Question: I have 10 computers running Windows 7 connected to Active Directory.  I would like to setup the computers so that they go into standby if no one logs in for 15 minutes, BUT I want the computers NOT to go into standby ever if someone is logged in.
This would involve the changing of Power Plans.  Is there a way to have one Power Plan loaded when the computer is not logged in and a different Power Plan loaded when a user is logged in?
UPDATE: Using jscott's suggestions I think I have what I want working. I made a Power Plan called Logged_In for the User Configuration and Logged_Out for the Computer Configuration.  The last glitch I had to fix was that Logged_In was applied after logout until the next policy refresh.  I made the following script to run at logout based on code I found >here<:
<code>Set objShell = WScript.CreateObject("WScript.Shell")
Set objWshScriptExec = objShell.exec("powercfg.exe -list")
Set objStdOut = objWshScriptExec.stdOut

While Not objStdOut.AtEndOfStream
   strLine = objStdOut.ReadLine
   If InStr(strLine,"Logged_Out") Then
      strGuid = Mid(strLine,20,37)
   End If
Wend
objShell.run "powercfg.exe -setactive " & strGuid
</code>
Answer: The best way to do this is to create a GPO.  You'll want to look under Computer Configuration, Preferences, Control Panel Settings, Power Option.  Then right click and select New, Power Plan.  From there you can specify all the power settings you want.  Here is a technet article.
http://technet.microsoft.com/en-us/library/dd759141.aspx
Comment: @Joseph - Via group policy.
Comment: @joseph Assign a computer configuration Power Plan for the computer settings. Assign a user configuration Power Plan for the user settings.  When nobody is logged in, the Computer Power Plan will be used.
Comment: But how do you automate the changing of the Power Plan?
Comment: @jscott How do you change it back to the Computer Configuration after a user has logged out?
Comment: @Joseph Both the computer and user will have their own Power Plans -- that is you configure one under Computer Configuration, the other under User Configuration. When a user is logged on, the User Configuration GP settings are active. When a user logs off, the User Configuration settings will fall out-of-scope and the Computer Configuration GP will be the active settings.
Comment: @jscott How long does that usually take? The Computer Configuration Power Plan works perfectly on bootup if a Group Policy update was applied and the User Configuration Power Plan works perfectly on logon, but the computer is not switching to the Computer Configuration after logoff or reboot until the Group Policy is applied again.
Comment: @Joseph [It depends](http://technet.microsoft.com/en-us/library/cc757597(WS.10).aspx). You can reduce the refresh time if you don't want the computer to have to wait for the default refresh to come around and update the Power Plan.
Comment: @jscott Make your comment into an answer, and I'll give you the points. I've made a logout script that might fix my last issue which I will post when I've confirmed it works.

standby only at login screen?


Geometric intuition for harmonic conjugate functions

Question: It is known that given a harmonic function $u$ of class $C ^ {2}$ defined in a simply connected subset of $\mathbb{C}$ , we can find a function $v$ also harmonic, such that $f = u + iv$,  is a holomorphic function.

What does this definition mean geometrically?
Would there be applications of this in physics?

Comments or references, are very welcome!!
Comment: One physics application is that for irrotational 2D fluid flow, the flow can be characterized by either a stream function or a velocity potential, which are harmonic conjugates of each other.
Answer: Contours of constant $u(x,y)$ and $v(x,y)$ will be crossing orthogonally. For example, the harmonic conjugate of $x$ is $y$.