Retrieving data from multiple tables through Get() method in web API

Question: I have just started with web API and got my first Get method successfully implemented. I was able to retrieve the data and show it to the client. Now I have to retrieve data from two tables through a single Get method which I am not able too. Here's my code for retrieving data from a single table.
public HttpResponsemessage Get(string Login, string Password)
{
  using (Accord_BMHEntities entities = new Accord_BMHEntities())
  {
    Login = Login.Trim();
    EncryptDecrypt EncryptDecryptObj = new EncryptDecrypt();

    string EncryptedPassword =
            EncryptDeccrypt.Encrypt(Login.Trim().ToUpper(), Password);

    var userLogin = entities.ITPLUsers.firstOrDefault(e => e.Login == Login
                & e.Password ==  EncryptedPassword

   if (UserLogin == null)
   {
     return Request.CreateErrorResponse(HttpStatusCode.NotFound)
   }
   else
   {
     return Request.CreateResponse(HttpStatusCode.OK , UserLogin)
   }
  }
 }

EmpMaster.cs
public partial class EmpMaster
{
  [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", n
  CA2212:DoNotCallOverridableMethodsInConstructors")]

  Public EmpMaster()
  {
    this.EmpPersonal = new HashSet<EmpPersonal>();
  }

  Public int EmployeeID { get; set; }
  Public int DivisionId { get; set; }
  Public int ResumeId { get; set; }
  Public int GroupId { get; set; }
  Public int DepartmentId { get; set; }
  Public int WorkplaceId { get; set; }
  Public int DesignationId { get; set; }
  Public int Code { get; set; }
  Public int DesignationId { get; set; }

  [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", n
  CA2227:CollectionPropertiesShouldBeReadOnly")]

  public virtual ICOllection<EmpPersonal> EmpPersonals { get; set; }
}

EmpPersonal.cs
Public partial class EmpPersonal
{
  Public int EmployeeID { get; set; }
  Public int DivisionID { get; set; }
  Public short Gender { get; set; }
  Public short BloodGroup { get; set; }
  Public string FlatNo { get; set; }
  Public string Premises { get; set; }
  Public string Street { get; set; }
  Public string Area { get; set; }
  Public string City { get; set; }
  Public string StateId { get; set; }
  Public string CountryId { get; set; }

  Public virtual EmpMaster EmpMaster { get; set; }
 }

Please note : there are many more properties in both the class. Just to save time i have mentioned some of it.
Comment: Why can't you have 2 methods and call them both on the client?  It's also pretty unclear what you're asking here and where the problem is
Comment: you got data from ITPLUsers, what is the second table that you want to retrieve data?
Comment: @p3tch: I'll be creating a different controller as it will be a different client request. In that i'll be fetching the data through get method. But the data that i'll be fetching are in two different tables. previously i fetched the data from a single table as mentioned in the above code.
Comment: @DanNguyen: Second table is EmpPersonal
Comment: How are you going to use the second table and what result you expect?
Comment: You need to show Accord_BMHEntities class. EmpPersonal is an entity like ITPLUser, so you can query EmpPersonal same as you did with ITPLUser, I mean utilizing LINQ to Entity. Then in the action method, you have 2 data for EmpPersonal and ITPLUser, then you return an instance of a class that wrap two data above. If you want to more details, you must provide more about Accord_BMHEntities and which EmpPersonal objects you want to return
Comment: @JianpingLiu: That's exactly what i am looking for. How am i suppose to use my second table to retrieve my complete data? I am expecting all the information related to a particular employee.
Comment: @DanNguyen: Ok Dan. Thank you. Also Dan, what if i want to retrieve data from two different databases in a single get method?
Comment: If you have two, so in the action method you have not just Accord_BMHEntities but also someotherEntities class. Accord_BMHEntities is used to query data from the first database, someotherEntities is used to query the second database
Comment: @DanNguyen: Thank you so much Dan.
Comment: Please add the class definition code for the EmpMaster and EmpPersonal
Comment: @lonut : I have added the mentioned class.
Comment: Seeing and somewhat understanding the error that i am getting i think its getting into an infinite loop because both the entity is calling the another and its never ending. Please someone? i need to fix this.
Answer: If you have modeled the relation between the entities, you could use the Entity Framweork Include method (for eager loading) or Load method (for lazy loading).
Docs here: Entity Framework Loading Related Entities
Otherwise you could return an anonymous type:
var userLogin = entities.ITPLUsers.firstOrDefault(e => e.Login == Login
            & e.Password ==  EncryptedPassword;
var empPersonal = entities.EmpPersonal.Where(....your condition...);
if (UserLogin == null)
{
   return Request.CreateErrorResponse(HttpStatusCode.NotFound)
}
else
{
   return Request.CreateResponse(HttpStatusCode.OK,new {userlogin = UserLogin, empPersonal = empPersonal});
}

Comment: Sorry i forgot to mention that my tables EmpMaster and EmpPersonal has Primary key and foreign key relation due to which i am getting an error "System.InvalidOperationException" when i run the above code. please help.
Answer: I assume you want user address from Address entity along with user data. You have 2 options here. You can either use linq and join to get all related data with one query or you can get user and address datas one by one. In the end, you need to consolidate the data and return one result set since you want to return all of them in a single response.
You obviously need a resultModel for your endpoint.
Like;
public class UserResultModel
{
    //Properties from User entity
    public int Id { get; set; }
    public string Username { get; set; }
    //Properties from Address entity
    public string City { get; set; }
}

You need to fill this resultModel and return it.
Irrelevant suggestion: I suggest not to check user's authentication like that. MVC has a really nice feature called Filters(Authorization Filters for more detailed)
Answer: Try Linq with joins by matching keys. You will get an example from msdn site.Msdn site


Demora muito a consulta em mysql

Question: Ola amigos estou tendo uma dificuldade em encontrar o que esta errado no meu código de selecção (SELECT) em mysql, esta a demorar mais de 70sec não sei porque. Alguém ai pra me ajudar por favor?
Código:
SELECT id_aluno, nome_aluno, ano_lectivo, data data_pagamento_m, nome_classe, codigo_classe, nome_curso, valor_curso1, multa
FROM tb_matriculas
LEFT JOIN tb_classe ON tb_matriculas.classe = tb_classe.id_classe
LEFT JOIN tb_curso ON tb_curso.codigo_curso = tb_matriculas.curso
WHERE  data_pagamento_m < '$data_nova '
AND data_pagamento_m <> '2017-01-01'
AND YEAR(data_pagamento_m) = '$ano_select'
AND classe BETWEEN '$classe1'
AND '$classe2'
AND classe <> '10'
AND curso BETWEEN '$curso1' AND '$curso2'
AND turma BETWEEN $turma1 AND $turma2
AND periodo BETWEEN '$periodo1' AND '$periodo2'
GROUP BY id_aluno

Comment: crie índices para sua tabela, que resultará em mais velocidade na sua  pesquisa
Comment: Qual o motivo de `GROUP BY id_aluno`?
Comment: Outra dúvida, tem certeza que é `LEFT JOIN`, recomendo leitura: [Qual é a diferença entre INNER JOIN e OUTER JOIN?](https://pt.stackoverflow.com/questions/6441/qual-%C3%A9-a-diferen%C3%A7a-entre-inner-join-e-outer-join)
Comment: Ola obrigado, já criei um  indece na tabela tb_matriculas, o GROUP BY id_aluno para agrupar por aluno
Comment: Rode um EXPLAIN de sua consulta e analise o resultado.
Comment: A function YEAR quebra um índice se houver na coluna de data_pagamento_m , e parece ter um problema de modelo pois pagamento é atributo de que tabela ? Há um só pagamento ?
Comment: Você utiliza a cláusula GROUP BY mas não utiliza nenhuma função de agregação em sua lista de seleção. O que deseja agrupar?
Answer: Se a tabela tiver muitos registros e esta consulta for muito recorrente ou importante retornar com rapidez crie um índice contendo todos os campos usados na cláusula WHERE.
Reveja as cláusulas com BETWEEN que recebem STRING que podem comprometer a query, como os seguintes:
AND classe BETWEEN '$classe1' AND '$classe2'
AND curso BETWEEN '$curso1' AND '$curso2'
AND periodo BETWEEN '$periodo1' AND '$periodo2'

O tratamento das strings funciona mas caso tenham IDs será muito mais rápido de executar.
Altere os LEFT JOIN para INNER JOIN conforme indicado pelo @Marconi, pois como as cláusulas são sobre alunos que devem estar em classes, cursos e períodos indicados não faz sentido fazer um LEFT JOIN. Este ponto dependerá da sua regra de negócio.

Demora muito a consulta em mysql


Why are residual connections needed in transformer architectures?

Question: Residual connections are often motivated by the fact that very deep neural networks tend to "forget" some features of their input data-set samples during training.
This problem is circumvented by summing the input x to the result of a typical feed-forward computation in the following way:
$$ \mathcal F(x) + x = \left[ W_2 \sigma( W_1 \mathbf{x} + b_1 ) + b_2 \right]  + \mathbf{x}.$$
This was schematically represented in [1] as:

On the other hand, it is also well known that transformer architectures have some residual networks, as the following picture elaborates:

Question: Residual connections are motivated in the context of very deep network architectures, but attention blocks perform very little computations compared to the networks that were outperformed in [1]; so, what is the motivation for the presence of shortcut connections in the attention-blocks of transformer architectures ?
Comment: personally i throw resids on everything
Comment: not reflexively in that case but if I run into trouble it's one of the things I would probably try (though in shallow networks I would probably try increasing the hidden layer widths to try to get asymptotic Gaussian Process behavior first).
Comment: @JohnMadden Even in shallow neural networks?
Comment: That makes sense, thanks for your comment @JohnMadden
Comment: @RamiroHum-Sah: Can you please give me a link to the second of the illustrations above. I am especially interested in the annotations (which are not found in the original illustration from the Attention is all you need paper, right?) Thanks in advance.
Answer: The reason for having the residual connection in Transformer is more technical than motivated by the architecture design.
Residual connections mainly help mitigate the vanishing gradient problem. During the back-propagation, the signal gets multiplied by the derivative of the activation function. In the case of ReLU, it means that in approximately half of the cases, the gradient is zero. Without the residual connections, a large part of the training signal would get lost during back-propagation. Residual connections reduce effect because summation is linear with respect to derivative, so each residual block also gets a signal that is not affected by the vanishing gradient. The summation operations of residual connections form a path in the computation graphs where the gradient does not get lost.
Another effect of residual connections is that the information stays local in the Transformer layer stack. The self-attention mechanism allows an arbitrary information flow in the network and thus arbitrary permuting the input tokens. The residual connections, however, always "remind" the representation of what the original state was. To some extent, the residual connections give a guarantee that contextual representations of the input tokens really represent the tokens.
Comment: Awesome, @Jindřich! Thanks for your very illuminating answer. I can't resist to ask about one detail in your last paragraph: Could you be so kind to elaborate a little bit more about what you mean by "The self-attention mechanism allows an arbitrary information flow in the network and thus arbitrary permuting the input tokens", please? What I understand is that perhaps the construction of (say) queries $Q=W_{Q}x$, for a given random matrix of weights $W_{Q}$ could give a very bad answer at the beginning of the training and the shortcut connection help us to improve that initial guesses ?
Comment: I think he meant that with residuals, self attention blocks can perform arbitrary computations without being concerned about preserving the original data. If residuals weren't used, the self attention block would need to ensure that it somehow preserved (at least some of) the original data.


JSP useBean - Property not found on type mybeans.FrageAntwortListeBean

Question: I'm struggeling on this and I can't figure out why this error occurs.
I have a bean:
package mybeans;

import java.io.Serializable;

public class FrageAntwortListeBean implements Serializable {
    private static final long serialVersionUID = 1L;
    private String questions;

    public FrageAntwortListeBean() {
        this.questions = ""
    }

    public String toString() {
        return questions;
    }

    public String getQuestions() {
        return questions;
    }

    public void setQuestions(String questions) {
        this.questions = questions;
    }
}

So now I want to use this bean in a JSP:
<%@ page language="java" contentType="text/html; charset=UTF-8"  pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<jsp:useBean id="meineFragen" class="mybeans.FrageAntwortListeBean" scope="session"  />
<jsp:setProperty name="meineFragen" property="*" />
${meineFragen.questions}

And now it is firing this error: javax.el.PropertyNotFoundException: Property 'questions' not found on type mybeans.FrageAntwortListeBean
I have absolutely no clue, why this happens, because I never had this issue before... What am I doing wrong??
I simplified the example for just a string attribute, normally it looks more complex, but I get this error even with that simple structure! What am I doing wrong?
Even if I use a scriptlet, eclipse of course suggests me the function getQuestions() but when running the JSP it is showing a similar error.
<%= meineFragen.getQuestions() %>

If I import it via page directive and use the following it is working. BUT, scriptlets are ugly!
<%! FrageAntwortListeBean x = new FrageAntwortListeBean(); %>
<%= x.getQuestions() %>

I appreciate all help! :)
Working with apache tomcat 7, did redeployment, cleaning it up, compiling everything new. Used a new installation. No chance!
Answer: So I solved this now. :)
The issue was, that I used the built in eclipse function to generate new serialVersionUIDs...
Well, i missclicked a couple of times and had now twice  serialVersionUID = 1L
After changing it to for example serialVersionUID = -7497282229152922152L; it is not throwing that error anymore!
Comment: Oh my god, atleast you got it solved now :) So, SerialVersionUID should be related to it then...
Comment: Confuses me aswell, and I'm trying to understand. I think that the apache tomcat is searching for a bean with the serial uid provided, and since I have 2 Beans (QuestionBean and QuestionListbean) with the same serial uid (1L) it is like a collision for it... But, it solved the issue. Sitting here for 4h now on this to get this as a result... Do you have any other ideas? :-)


Angular show / hide with animation

Question: I'm trying to fade out a div and then show a new div but my code is broken.  How can I fix? The fade-out animation works but the showManagement div does not appear.
HTML

this is start content that should be faded

this is the new content to be displayed once the fade is complete.

JS
$scope.getManagement = function () {

    $scope.startFade = true;

    $timeout(function(){
        $scope.hidden = true;
    }, 2000);

    // this is the part that doesn't display
    $scope.showManagement = true;
 };

CSS
.fade{
    transition: opacity 3s;
    opacity: 0;
}

Comment: have you looked into ng-animate? it adds classes on-before for ng-hide, on ng-repeat, ng-switch
Comment: @Aaron is right, you should try to leverage on ngAnimate service. If you do want to solve the issue with the way you provide, you may refer to the example I provided below
Answer: Since you didn't provide your controller and didn't show where you call the function getManagement(), I'll assume that you want all the fade-out fade-in events show within 2 seconds after angular loaded.
Here's an example on CodePen for how you can achieve your goal with your approach.
And here's the code:
HTML

this is start content that should be faded

this is the new content to be displayed once the fade is complete.

CSS
.fade{
    transition: opacity 3s;
    opacity: 0;
}

.hideManagement {
  opacity: 0;
}

.showManagement {
    transition: opacity 3s 3s;
    opacity: 1;
}

JS
angular
  .module('myApp', [])
  .controller('MainCtrl', ['$scope', '$timeout', function($scope, $timeout) {
    $scope.startFade = false;
    $scope.showManagement = false;
    $scope.hideManagement = true;

    $timeout(function(){
      $scope.startFade = true;
      $scope.showManagement = true;
      $scope.hideManagement = false;
    }, 2000);
  }]);

A few things you have to keep in mind:

You cannot animate your display: none; and display: block; with CSS3 transition. This is the reason why ng-hide in your .showManagement  is not showing with transition effect. You should keep using opacity to achieve this goal, just like you did in ng-class="{fade: startFade}"
Initialize your state at the beginning of your Angular controller. In the example your provide, it's a little bit confusing how you set your $scope.showManagement, $scope.hidden, and $scope.startFade. Once you setup your initial state like the example I provide, it would be more clear that what kind of states change you should make in the function, whether it's in a $timeout callback or some other functions trigger by other events
To make .showManagement  fade-in right after the first
 finishing it's fade-out effect, you may set the delay in css transition.

If you are doing more complex animation, you should try leveraging on ngAnimate service. With ngAnimate, you can get rid of those ng-class in this example, and simply binding your animation rules with .ng-enter, .ng-enter-active, .ng-hide, .ng-hide-active, which are automatically bind to your elements by Angular. Here's the official documentation for ngAnimate.

Angular show / hide with animation


Proving the identity $\int_\alpha^\beta | f(t) | dt \leq \sqrt{\beta - \alpha} \cdot || f ||$

Question: For my Fourier analysis class, we have to prove this identity for piecewise continuous $f$ on an interval $(\alpha,\beta)$:
$$\int_\alpha^\beta | f(t) | dt \leq \sqrt{\beta - \alpha}  \cdot || f ||$$
We are advised to make use of the Cauchy-Schwarz inequality for inner products (stated as $| \left \langle f,g \right \rangle | \leq ||f|| \cdot ||g||$) and the fact $f = f \cdot 1$.
Initially, working with $g(t)=1$ suffices to yield the following (skipping over a few formalities of the definition and calculation of inner product and norm for brevity's sake):
$$| \left \langle f,1 \right \rangle | = \left |  \int_\alpha^\beta f(t) dt \right |$$
$$||1|| = \int_\alpha^\beta dt = \sqrt{\beta - \alpha}$$
Thus, so far by my calculations and the Cauchy-Schwarz inequality,
$$| \left \langle f,1 \right \rangle | = \left |  \int_\alpha^\beta f(t) dt \right | \leq \sqrt{\beta - \alpha} \cdot ||f|| = ||f|| \cdot ||1||$$
Of course, this isn't quite the identity we want; that is, to reiterate
$$\int_\alpha^\beta | f(t) | dt \leq \sqrt{\beta - \alpha} \cdot || f ||$$
(The difference being that the absolute value needs to be moved into the integral.)
I imagine I need to make use of the identity
$$\left |  \int_\alpha^\beta f(t) dt \right | \leq \int_\alpha^\beta | f(t) | dt$$
yet it's probably a little more nuanced than just applying it directly. (We'd essentially have a case of where we're saying $1 \leq 2$ and $1 \leq 4$ - doesn't mean $4 \leq 2$. In this case, $1$ being the absolute value of the integral, $2$ being the root and norm, and $4$ being the integral of the absolute value, as an oversimplification of why I don't think directly applying that identity would work.)
Does anyone have an idea of where to proceed from here? Thanks.
Comment: What ? By Cauchy-Schwartz, $$\left<|f|,1\right>\leq \sqrt{\beta -\alpha }\|f\|.$$ Done !
Comment: Ohhhhhhh, okay. I hadn't considered that, but it seems to work out; a few small nuances to work around, but I figured out how to handle them as I was originally about to comment on that (thus why you've might've gotten notified for some things that got deleted).

Thanks for the help; sorry for being dumb. I appreciate it.
Answer: Since the question is still open and I can't accept a comment as an answer:
The solution followed from $⟨|f|,1⟩≤\sqrt{β−α}∥f∥$


Why isn't $\int_{\gamma} \frac{\overline{z}}{2} \,dz = 0$?

Question: There's a Corollary saying the following:
$\mathbf{Corollary:} \text{ Let U be an open connected and simply connected space of } \mathbb{C}, f:\text{U} \rightarrow \mathbb{C} \text{ an analytic function and } \gamma:[a,b] \rightarrow \text{U a loop. Then, } \int_{\gamma} f = 0.$
$\text{I don't understand why I can't apply this Corollary to the following:}$
$\text{Loop is defined by } \gamma: [0,2\pi] \rightarrow \mathbb{C}, \gamma(t)=e^{it} \text{ and } f:D(0,2) \rightarrow \mathbb{C}, f(z)=\frac{\overline{z}}{2}$.
$\text{Here, I think that D(0,2) is an open connected and simply connected set (given 2 points, there's a}$

$\text{segment that unites them), f is analytic and } \gamma \text{ is a loop, but } \int_{\gamma} f = 2\pi i.$
$\text{Thank you for your help in advance!}$
Comment: $$\text{Why did you type like this?}$$
Answer: $f(z)=\overline z/2$ is not analytic. Apply the Cauchy-Riemann equations.
Comment: I think that Riemann deserves better…
Comment: Hmm soz. Fixed.
Answer: Like Empy2 already said, $f(z)=\bar z/2$ is not holomorphic. You can see this instandly if you know, any function that explicitly depends on $\bar z$ is not holomorphic.
Using Wirtinger Derivates it is possible to reformulate the Cauchy-Riemann equations into the condition $$\frac{\partial f}{\partial\bar z}=0$$
Even though the Wirtinger Derivates are NOT differentialquotients, you can still formally differentiate with respect to $\bar z$ and $z$.
Applying this to your example, you can acutally calculate
$$\frac{\partial }{\partial\bar z} \frac{\bar z}{2} = \frac{1}{2}\not=0$$
This idea instandly provides a reasoning why for example $\mathrm{Re}$ can not be holomorphic, since $\mathrm{Re(z)}=\frac{1}{2}(z+\bar z)$.
Answer: One can however use Schwarz function $\bar{z}=S(z)$ on $\gamma$ to evaluate the contour. Notice that on $\gamma$ the identity $z\bar{z}=2\Leftrightarrow \bar{z}=2/z$ holds, so instead one evaluates
$$\int_\gamma\frac{\bar{z}}{2}dz=\int_\gamma\frac1{z}dz=2\pi i.  $$


react router v6 - i am trying to add routes and keep getting a 404

Question: The homepage seems to work but the about page doesn't.
Here is my app.js file :-
import React from 'react'
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'
import Home from './Pages/Home'
import About from './Pages/About'

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
      </Routes>
    </Router>
  )
}

export default App

Here is my index.js file
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App.js'
import './style.css'

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
)

About page :-
import React from 'react'

function About() {
  return
 THIS IS THE ABOUT PAGE

}

export default About

It's being imported/exported correctly, and all the tutorials I'm following look like my code - so i'm not sure what to try next.
Comment: I got it thank you. I was missing  the "historyApiFallback: true" in my webpack config.
Comment: I can't reproduce your issue (I just copied you code into a sandbox and it is working). Could you please provide a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example)
Answer: Solved - it was my webpack configuration. I was missing -
  devServer: {
    port: 3000,
    hot: true,
    open: true,
    historyApiFallback: true,
  },


To use RInterface.GetArrayToVBA inside VBA function with arrays

Question: Let an Excel spreadsheet to be connected to R through RExcel and you want to write a VBA function which calls some R functions.
In your Excel spreadsheet you have a couple of simple arrays like the following ones:

The code could be something like this:
Function foo(x As Range, y As Range) As Variant

    RInterface.StartRServer

    If IsNumeric(x) = True Then
        RInterface.PutArrayFromVBA "x", x
    End If

    If IsNumeric(y) = True Then
        RInterface.PutArrayFromVBA "y", y
    End If

    foo = RInterface.GetArrayToVBA("cbind(x, y, y ^ x)")

End Function

and its evident purpose is to return a matrix containing cbind(x, y, y ^ x) in Excel.
I'm not able to get it, I get strange results as I slightly amend the code: sometimes output is equal to 1, sometimes it's equal to #VALUE!... it doesn't work, though, and I am not able to understand the syntax needed in such a case.
Comment: **GetArrayToVBA** (_RExpression As String_)
Comment: Not sure how `R` works but isn't `GetArrayToVBA("cbind(x, y, y ^ x)")` supposed to be `GetArrayToVBA(cbind(x, y, y ^ x))` considering the fact that anything within quotes is considered as a string?
Comment: `Compile error: Sub or Function not defined`

...and it highlights `y`
Comment: What is the syntax/parametrers for `Rinterface.GetArray()`? Just did a quick search on internet. It is something like `Rinterface.GetArray("something", Range)`?
Comment: Unfortunately this is where my knowledge about `R` shows :p
Answer: Function foo(x As Range, y As Range) As Variant

RInterface.StartRServer
RInterface.PutArrayFromVBA "x", x.Value 'you were missing this .Value'
RInterface.PutArrayFromVBA "y", y.Value
foo = RInterface.GetArrayToVBA("cbind(x, y, y ^ x)")

End Function

I'm omitting your error checks since they will only cause other errors. If you want to do error checking do a on error goto
Comment: why was this answer unaccepted after it was accepted? is there anything that you'd like me to explain/add?


Prove that $\sqrt 7 + 2 \sqrt 5 < 2 + \sqrt{35}$

Question: How can I prove that $\sqrt 7 + 2 \sqrt 5 < 2 + \sqrt{35}$?
I can't convert the right side to get the $\sqrt 5$.
Comment: Have you tried squaring both sides?
Answer: Why make things more complex than they are? As both sides are positive, just compare the squares:
$$ \sqrt 7+2\sqrt 5<2+\sqrt{35}\iff7+4\sqrt{35}+4\cdot5<4+4\sqrt35+35
\iff 27 <39. $$
Answer: Hint:
$$(\sqrt{7}+2\sqrt{5})^2-(2+\sqrt{35})^2=?$$
Answer: If $\sqrt7=a,\sqrt 5=b$
We need
$$a+2b<2+ab$$
$$\iff0>a-2-b(a-2)=(a-2)(a-b)$$
But $a=\sqrt7>\sqrt5(=b)>2$
Answer: Just to give a different approach, from $7\cdot16=112\lt121=11^2$ we have $\sqrt7\lt11/4$, from $5\cdot16=80\lt81=9^2$ we have $\sqrt5\lt9/4$, and from $11^2=121\lt140=4\cdot35$ we have $11/2\lt\sqrt{35}$.  It follows that
$$\sqrt7+2\sqrt5\lt{11\over4}+2\cdot{9\over4}={29\over4}\lt{30\over4}={15\over2}=2+{11\over2}\lt2+\sqrt{35}$$
Answer: Start from the following inequality (I obtained it from rearranging the intial inequality as you can see in the following steps)
$$(\sqrt{7}-2)(1-\sqrt{5})<0$$
$$\implies \sqrt{7}-2-\sqrt{7}\sqrt{5}+2\sqrt{5}<0$$
$$\implies \sqrt{7}+2\sqrt{5}<2+\sqrt{35}.$$
The first inequality is trivally true as $\sqrt{7}>\sqrt{4}=2$ and $-\sqrt{5}<-1$.
Answer: Since $\sqrt5\gt1$ and $\sqrt7\gt2$, we have
$$\sqrt7-2\lt\sqrt5(\sqrt7-2)=\sqrt{35}-2\sqrt5$$
and therefore $\sqrt7+2\sqrt5\lt2+\sqrt{35}$.
Comment: Ah, this is essentially equivalent to MachineLearner's answer, which was posted while I was composing mine.
Comment: It's also essentially equivalent to Peter Szilas's answer.
Answer: Since $2^2 <7$. we get
$2=\sqrt{2^2} <√7$ since $√$ is strictly increasing.
Also since $1 < 5$ we get $1 <√5.$
Finally :
$2(√5-1) < √7(√5-1)$; (Why?)
$√7 +2√5 < 2 +\sqrt{35}.$


How to assign permissions based on user points?

Question: I am building a site where users are given permissions similar to SO. I am working with two models.
The first model assigns roles to users based on points. I can probably use Rules or a build a module for that. The nice things with this is that I get to use Drupal's build permission system. The downside is that I probably have to setup +10 roles and add even more if I want to give new permissions.
The second model is based on a custom build module (not build) that checks if a user is permitted to do whatever he/she intends to do. In this way all the roles can be avoided, but it doesn't use Drupal's permission system, which makes me a bit uncomfortable. On the other hand, there is no need for many roles.
So, is there a performance hit on having many roles? Other problems?
Any thought on this? Other approaches to give users permissions based on user points?
Comment: Possibility: http://drupal.org/project/ranks related: http://drupal.stackexchange.com/questions/16795/content-by-credit-level-in-drupal http://drupal.stackexchange.com/questions/11566/module-for-creating-a-site-similar-to-stack-overflow
Answer: Use roles.
The only problem with 10+ roles is that your permission table is going to get huge but you can solve this by limiting it per role (see link on roles list) or use a module like faster permissions.
The loading of roles is most likely much faster than doing custom checks. Also, when doing something like this, you'll certainly run into issues, for example when trying to work around existing permission checks in modules and so on. The permission system is one of the core elements of Drupal. Use it and don't try to fight it. That's not going to work.
There is a Userpoints Role module in http://drupal.org/project/userpoints_contrib, which allows you to configure how many points users require for a given role and it should just work. There are even a few tests there now. Note that it currently gives you all permissions the user has enough points for. This might not be what you'd expect but it has the advantage that it would be enough to only specify the additional permissions each role has.


Multiple linear regression: p-value=0.25 pre-filter variable selection

Question: I have used many times in a multiple logistic regression the criteria of p-value=0.25 like pre-filter variable selection using bivariate logistic regression , then I use a MANUAL stepwise (backward) to finish the variable selection (p-value=0.05) (only main effects models).
I wonder if its possible use this method in multiple linear regression (pre-filter variable selection using bivariate linear regression), then... I have looking in literature this topic but only I got for multiple logistic regression (only main effects models).
I know that stepwise variable selection have a lot of critics in literature (I repeat: I use a manual method, not automated method...) but my focus is in bivariate linear regression like pre-filter using p-value=0.25 in variable selection...
Could use correlation analysis like a pre filter?
I would grateful some reference if exist...
Thanks in advance.
Regards, Rodrigo.
Comment: The problem exists in the estimation of the effect.  The significance doesn't really matter all that much.  You're free to try and demonstrate that the cut off threshold of p=0.25 leads to the type of behaviour you expect, but I'm rather confident it will not.
Comment: I would not do this.  Pre-filtering fails to account for confounding variables, and so your selection method could miss important effects. See this paper for more https://pubmed.ncbi.nlm.nih.gov/8699212.  Finally, stepwise is a method fraught with faults.  See Frank Harrell's problems with stepwise regression or these artilces https://journalofbigdata.springeropen.com/articles/10.1186/s40537-018-0143-6
Comment: You're still subject to the criticisms in those papers. Enough evidence exists that these methods do not accomplish what users think they do.  Use them at your own peril.
Comment: Only I use manual stepwise and main effects model. Thanks for papers...
Comment: They use: "bivariable analysis is greater than an arbitrary value (often p = 0.05)"... I use p-value= 0.25 in bivariable analysis... I know that stepwise have a lot of critics but main interest is in bivariate regression...
Answer: Automated variable selection methods don't respect the causal model used to inform model development. These approaches can omit important confounders, include colliders, and inappropriately (depending on your precise question) include mediating variables. Depending on how interactions are handled, important effect modifiers could also be missed. So this is their first problem: the interpretation of each independent variable in a model is contingent on the other variables included/not included in the model and this cannot be both fully automated and expected to be sensible at the same time.
The second problem here is that all of the problems of stepwise/forward selection/backward elimination apply whether a computer implements the algorithm or you do. While a manual approach might, in theory, give opportunities to consider individual decisions, if the process is objectively performed according to pre-specified criteria, the only difference between the manual and computer-performed version will be that the former will take more time to do. A pre-screening approach is just a single round of forward selection and so will still overestimate the magnitude of effects and underestimate their p-values.
Note that iterative decisions based on information criteria (e.g. AIC and BIC) have the same problems. I strongly recommend reading Frank Harrell's Regression Modeling Strategies: With Applications to Linear Models, Logistic Regression, and Survival Analysis as this contains a lot of practical wisdom and the results of many, many simulations that Frank's already done on our behalf.
The only reasons for using any of these approaches, in my opinion, are if you are not concerned about generalisability (you simply want to fit the simplest adequate model to a set of data) or to identify a set of variables for future investigation. If you want to make generalisable conclusions based on the data in front of you, don't use any form of automated variable selection.
Comment: When I say "automated", I'm not referring to who/what does the work, but rather to the data-driven nature of the process (rather than an expert-driven selection of the relevant variables before looking at the data). It doesn't matter whether you do the modelling and variable selection work by hand or the computer does it for you behind the scenes, the final model selected and so the end result is identical, including the biases for your point estimates and p-values.
Comment: Thanks but I dont use an automated method. I wrote that use a manual stepwise starting with a full model (backward method)...


Trouble finding a linear transformation.

Question: I'm having some trouble solving the following question:

Given $$\vec{u_1} = \begin{bmatrix}1 \\ 1 \\ 1\end{bmatrix}, \quad\vec{u_2} = \begin{bmatrix}1 \\ 0 \\ 1\end{bmatrix}, \quad\vec{u_3} = \begin{bmatrix}1 \\ 0 \\ -1\end{bmatrix}, \quad\vec{u_4} = \begin{bmatrix}1 \\ 1 \\ 2\end{bmatrix},$$ is there any linear transformation $L$ such that $L\left(u_1\right)=u_2$ and $L\left(u_3\right)=u_4$?

I don't really know where to begin with the problem and would appreciate some leads on where to begin.
Comment: $T[u_1 \,\,u_3] = [u_2 \,\,u_4]$, $T$ is a $3$x$3$ matrix.
Comment: Please include your efforts, or some form of context.  Please understand, this site is not a "do my work for me" service.
Comment: @amWhy sorry, I forgot to include that but I've now updated my post. Thank you for your feedback! :)
Comment: @Arthur thank you, we will try it right away! :)
Answer: Try:
$$T(x,y,z)=(x,x-y,x+y-z)$$


Difference between parameters and members of a class

Question: I am new to Coq and was wondering what is the difference between the following things:
Class test (f g: nat -> nat) := {
  init:   f 0 = 0 /\ g 0 = 0;
  output: ...another proposition about f and g...;
}.

and
Class test := {
  f: nat -> nat;
  g: nat -> nat;
  init:   f 0 = 0 /\ g 0 = 0;
  output: ...another proposition about f and g...;
}.

Could anyone provide an explanation ?
Comment: For those interested in Proof Assistants, there is a new proposed SE site [ProofAssistants](https://area51.stackexchange.com/proposals/126242/proof-assistants?referrer=NjQzMjU3YTVjNzdhOWMzMGI1ZDMxN2ExMmVjZjNlMDI0Y2U0OGQyY2YxOGUxNjE4YmUxMWE3MGVlNjEwZmZhYvQzSfPUP9ckbNrxkouh5gaYRPNF7ix3vwBaRKqqkc730)
Answer: The difference between them is referred to as bundling.
Class test (f g: nat -> nat) := {
  init:   f 0 = 0 /\ g 0 = 0;
  output: ...another proposition about f and g...;
}.

is unbundled, and
Class test := {
  f: nat -> nat;
  g: nat -> nat;
  init:   f 0 = 0 /\ g 0 = 0;
  output: ...another proposition about f and g...;
}.

is bundled.
The advantage of bundling is that you don't need to always provide f and g. The advantage of unbundling is that you can have different instances of the same class sharing the same f and g. If you bundle them, Coq will not be easily convinced that different instances share parameters.
You can read more about this in Type Classes for Mathematics in Type Theory.
Answer: To complement Ana's excellent answer, here is a practical difference:

the unbundled version (call it utest) allows you to write the logical statement utest f g about a specific pair of functions f and g,
whereas the bundled version (call it btest) allows you to state that there exists a pair of functions which satisfies the properties; you can later refer to these functions by the projection names f and g.

So, roughly speaking:

btest is "equivalent" to ∃ f g, utest f g;
utest f' g' is "equivalent" to btest  ∧  "the f (resp. g) in the aforementioned proof of btest is equal to f' (resp. g')".

More formally, here are the equivalences for a minimal example
(in this code, the notation { x : A | B } is a dependent pair type,
i.e. the type of (x, y) where x : A and y : B
and the type B depends on the value x):
(* unbundled: *)
Class utest (x : nat) : Prop := {
  uprop : x = 0;
}.

(* bundled: *)
Class btest : Type := {
  bx : nat;
  bprop : bx = 0;
}.

(* [btest] is equivalent to: *)

Goal { x : nat | utest x } -> btest.
Proof.
  intros [x u]. econstructor. exact (@uprop x u).
Qed.

Goal btest -> { x : nat | utest x }.
Proof.
  intros b. exists (@bx b). constructor. exact (@bprop b).
Qed.

(* [utest x] is equivalent to: *)

Goal forall x, { b : btest | @bx b = x } -> utest x.
Proof.
  intros x [b <-]. constructor. exact (@bprop b).
Qed.

Goal forall x, utest x -> { b : btest | @bx b = x }.
Proof.
  intros x u. exists {| bx := x ; bprop := @uprop x u |}. reflexivity.
Qed.

(* NOTE: Here I've explicited all implicit arguments; in fact, you
   can let Coq infer them, and write just [bx], [bprop], [uprop]
   instead of [@bx b], [@bprop b], [@uprop x u]. *)

In this example, we can also observe a difference with respect to computational relevance: utest can live in Prop, because its only member, uprop, is a proposition. On the other hand, I cannot really put btest in Prop, because that would mean that both bx and bprop would live in Prop but bf is computationally relevant. In other words, Coq gives you this warning:
Class btest : Prop := {
  bx : nat;
  bprop : bx = 0;
}.
(* WARNING:
     bx cannot be defined because it is informative and btest is not.
     bprop cannot be defined because the projection bx was not defined.
*)


How to set up the database for load-balanced Drupal 7

Question: We currently run two Drupal instances (www1 and www2) behind a load balancer, and both instances are reading/writing the same mysql database. This seems like the wrong setup to me. Shouldn't we have it set up so that www1 reads and writes to db1, www2 reads and writes to db2, and db2 is a slave of db1?
Answer: db2 should never be written to if it is a slave of db1, because any write to db2 will never be propagated to db1, and they will quickly get out of sync.  The database must be shared and consistent.
There are 3 ways of getting a shared and consistent database experience: (1) Only have one database for all reads and writes.  This is the easiest, but provides a single point of failure, and unless the db is on a separate machine, it can result in unequal response times for the different servers.  (2) Use a Master-Slave setup and split your read and write requests between the master and slave.  Ideally, a master and slave databases are on different machines than the application servers.  (3) Use a multi-master so that writes to one are propagated to the other databases automatically, and vice-versa.  Again, usually the database machines are separate from the application servers.
The question is on how big does your system need to be?  If you are big enough to need more than one database server, then you should be looking at a cluster solution (MariaDB with Multi-Master Galera cluster, for example), but for that you need an odd number (minimum of 3) machines, which should be separate from your application servers.  Furthermore, in order to minimize bandwidth and cache rebuilding, you should also use a shared memcached server for cache tables.
As a point of reference, I implemented our system with a MariaDB Galera Cluster setup as a Multi-Master, but I treat it as a Master-Slave (which minimizes the chance of write conflicts).  I use AutoSlave to separate read and write requests, and send the read and write requests to different ports using HAProxy.  HAProxy then sends them to either a read or write server.  The "read" and "write" servers are really just part of the same Multi-Master cluster, but if my write master goes down, I have configured HAProxy to failover to the "read" servers until the "write" server comes back up.  The same thing happens for the "read" requests: Read requests are load balanced between the available read servers, but should they ever go down, HAProxy is configured to redirect all reads to the write server.  The end result is that Drupal thinks it is splitting up reads and writes, the cluster thinks that it is a multi-master, and it performs like a Master-Slave, with the advantage that it does not fail if either the master or the slaves go down.


What is the difference between LIKE '[A-D]%' ; and BETWEEN 'A' AND 'D' ; in SQL Server

Question: What is the difference between
SELECT *
FROM table1
WHERE name LIKE ' [A-D] %' ;

and
BETWEEN 'A' AND 'D'

in SQL server?
Answer: Let me assume you are talking about SQL Server, not MySQL.
SQL Server has limited extensions of LIKE that support character ranges.  So, you are comparing:
where name like '[A-D]%'
where name between 'A' and 'D'

The difference is simple.  A name longer than "D" that starts with "D" matches the first condition but not the second.  For instance, 'Dionysis' and 'Dracula' match the like but not the between.
The equivalent comparison would be:
where name >= 'A' and name < 'E'

Comment: Thank you now i understand the difference between them.
Answer: LIKE '[A-D]%' checks if the first character of a string is an A,B,C or D.
BETWEEN 'A' AND 'D' checks if a string falls between 'A' and 'D' when sorting. For a string of a single character, they will act the same (depending on collation).
LIKE '[A-D]', without the wildcard, is equivalient BETWEEN 'A' AND 'D' when comparing a single character.
LEFT(textcolumn, 1) BETWEEN 'A' AND 'D' is equivalient to textcolumn LIKE '[A-D]%' - that is, only looking at the first character of the string.
Comment: without the wildcard , what does this means.
Comment: @SanjitPrasad . . . That part of the answer is wrong.
Comment: Without the wildcard means that I removed the `%` from the `LIKE` expression. And no, it's not wrong, @GordonLinoff. Those two tests will return true, false and null in the same situations, afaik. When will they behave differently?
Comment: @gnud . . . `like` without the wildcard would match four  character, 'A', 'B', 'C', 'D'.  Well, it might also match lower case and accented versions, but the length of any matching string would be one character.
Comment: You're completely right, I meant they're equivalient when comparing a single character. I realize now my answer is a bit unclear about that.


trouble with unwanted space between divs

Question: I have some space that I don't want between classes.
Here's a Fiddle: http://jsfiddle.net/4YSXv/
it should be a box without any spaces in between:

I can't figure out how to erase this space, i googled it of course and apparently it's a common problem, but all solutions I found didn't help me.
HTML

CSS
.headerimage {
    position:absolute;
    left:0px;
    right:0px;
    height:273px;
    background-color:#000000;
}
.box1 {
    position:relative;
    top:273px;
}
.produkt {
    width:224px;
    height:318px;
    position:relative;
    float:left;
}
.image {
    width:224px;
    height:230px;
    background-color:#afeeee;
    position:relative;
}
.line1 {
    width:224px;
    height:1px;
    background-color:#000000;
    position:relative;
}
.head {
    width:224px;
    height:25px;
    background-color:#eeeeee;
    position:relative;
}
.subBox {
    width:224px;
    height:50px;
    position:relative;
}
.sub {
    width:224px;
    height:25px;
    position:relative;
}
.price {
    width:160px;
    height:20px;
    background-color:#847077;
    position:relative;
    float:left;
}
.button {
    width:58px;
    height:20px;
    background-color:#6A5ACD;
    position:relative;
    float:left;
}
.line2 {
    width:224px;
    height:5px;
    background-color:#000000;
    position:relative;
    padding-bottom:20px;
}
.placeholder {
    height:800px;
    width:800px;
    position:relative;
    padding-top:1000px;
}

Comment: Did you add a `* {margin: 0; padding 0;}` at the beginning of your CSS?
Comment: To reset all margins and paddings that the browser adds by default. Add it before any other CSS code.
Comment: Yes, but it didn't change.
Comment: Make sure you have your backgrounds correct. You have a few lines like `background-color:` and no value behind it
Comment: Please post a fiddle with your code and your CSS and markup.
Comment: @Hidde as far as I know that's no longer recommended. Rather use YUI for a reset http://developer.yahoo.com/yui/reset/
Comment: do you want .sub,.price,.button side by side or vertically
Comment: @Gangadhar All divs are in the right position, only the space in between is the problem.
This is how it should look like: http://tinypic.com/r/24gvn9y/5
Comment: @hidde http://jsfiddle.net/m5t6e/
Answer: .subBox {
    position: relative;
    width: 224px;
}
.sub {
    position: relative;
    width: 224px;
}

Answer: .sub {
    width: 224px;
    position: relative;
}

you are getting the white space of 20px from the height of the .sub
Also height of the
.subBox {
width: 224px;
height: 20px;
position: relative;
}

Comment: Now I have a new problem…for my layout, I need to multiply this box 8 times like this: http://tinypic.com/r/sc826t/5

It worked before, but now (after I erased the height) I get this: http://tinypic.com/r/ra67g9/5
Comment: Can you give the html for this so that i can see where the problem is
Comment: your jsfiddle is incomplete


Unable to clone ArrayList elements

Question: I am using the following code to clone my array:
aproximatedContours = cloneList(contours);

The body of method:
public static ArrayList<MatOfPoint> cloneList(ArrayList<MatOfPoint> contours) {
    ArrayList<MatOfPoint> clone = new ArrayList<MatOfPoint>(contours.size());
    for(MatOfPoint item: contours)
        clone.add((MatOfPoint) item.clone()); // Line 479
    return clone;
}

However, even though both contours and clone are type of ArrayList, and obviously their elements are type of MatOfPoint, I get the following error:
08-16 16:34:16.015: W/System.err(21747): java.lang.ClassCastException: org.opencv.core.Mat cannot be cast to org.opencv.core.MatOfPoint
08-16 16:34:16.020: W/System.err(21747):    at com.example.objecttracker.ObjectTracker.cloneList(ObjectTracker.java:469)
08-16 16:34:16.020: W/System.err(21747):    at com.example.objecttracker.ObjectTracker.onCameraFrame(ObjectTracker.java:446)
08-16 16:34:16.020: W/System.err(21747):    at org.opencv.android.CameraBridgeViewBase.deliverAndDrawFrame(CameraBridgeViewBase.java:387)
08-16 16:34:16.020: W/System.err(21747):    at org.opencv.android.JavaCameraView$CameraWorker.run(JavaCameraView.java:321)
08-16 16:34:16.025: W/System.err(21747):    at java.lang.Thread.run(Thread.java:856)

Does anyone have an idea what is happeining here?
Comment: Updated for your request
Answer: This appears to be an API bug in MatOfPoint: It inherits its clone method from Mat, so when you call it, you're getting a plain Mat returned (and presumably only the superclass's fields copied). The overall semantics for MatOfPoint don't appear to be cleanly defined, and there's no mechanism for copying one.
Edit: If the native object handle contains all of the necessary data, you might be able to use new MatOfPoint(Mat m) as a copy constructor.
Comment: Possibly the [copy constructor](http://docs.opencv.org/java/org/opencv/core/MatOfPoint.html#MatOfPoint%28org.opencv.core.Mat%29) is the way to go, but you'd need to check the source to see if it works correctly with `MatOfPoint` instances.
Comment: @Marek I didn't say it wouldn't help. I just recommended you looked at the source to confirm - have you done that?
Comment: I am having a lot of troubles while using OpenCV for android. Is there any other good library for CV? You are sure that it is a bug? Could you also check my bounty question: http://stackoverflow.com/questions/18073239/opencv-java-convexity-defects-computer-vision
Comment: @Marek Please don't use comments to ask further questions.
Comment: This is a bug in the sense that a class really shouldn't implement `clone()` unless it's `final`, and `Mat` also doesn't implement the `Cloneable` interface.
Comment: chrylis, accoring to Duncan Jones, new MatOfPoint(Mat m) will not help. So what should be correct way to have two independent list? I want to process second list that contain elements same as first list and I don't want to change first list elements. Would my code work if ArrayList would contain different elements? For example Point?
Answer: Clone is a very tricky thing and maybe not implemented correctly in opencv
Answer: It looks like a library issue because MatOfPoint is oddly relying on Mat's clone method which will clone a Mat object that is not a MatOfPoint.
As a workaround you could try to not depend on the clone() method but explicitly build copies on your own (untested):
    // Use a copy ctor
    clone.add(new MatOfPoint(item));

Comment: Not working - MatOfPoint have same references so when I change clone elements list elements get also changed...
Comment: You could try to deep clone the values then. Maybe something like new clone.add(new MatOfPoint(item.toArray()));

Unable to clone ArrayList elements


View Field Display placing table label on top of the description

Question: So I have this table created with display suit and table group.

How am I going to make it look like this?

The label is already set to be above, but that doesn't seem to work.
I'm not really good in CSS nor Drupal. Consider me a newbie and willing to learn.
Answer: Use list formatting with custom CSS.
Comment: I know this may sound stupid, but can you give me a little sample?
Comment: When you edit a view. Find  Format: Table | Settings . Click on "Table", select "HTML list".
Comment: The table I want to format is a table created from fields in a view and inside a page created by a view.

It's a custom content type created by a view.

I can't format it by going to Structure>content types>manage display.
Comment: Edit a view not a content type.
Comment: When I change it the the view table settings. The table on this page becomes a html list.(http://responsemap.iom.int/haiyan) and I'm suppose to format this content type page.(http://responsemap.iom.int/map/b663). Not the view page.


Which one to choose between Lang and Dummit Foote

Question: I am looking for a complete book on Abstract Algebra.By a "complete book" I mean to say a book that will cover all the topics of abstract algebra  starting from group theory,ring theory ,field theory,Galois theory,Non-commutative rings ,jacobson radicals,Kummer ,cyclotomic extensions ,Krull topology and ending in Commutative algebra.
I searched on the web and found two only i.e
Dummit Foote and Lang's Algebra
I can't understand which book to start with.I have  basic knowledge in group and ring theory and i also know some field theory.
Which one to buy between these two? I am confused.Please help
Comment: We cannot suggest a different one except these two?
Answer: I only used Lang from those two, so I will tell you about that one.
Lang is not a book you learn from but a reference or a book to use for secondary literature. This information you can read anywhere(e.g. amazon) so I'll tell you my experience.
I bought Lang as a third year bachelor with the same knowledge as you approximately. The first year I browsed through it a few times and stared intimidating at me from my bookshelf. The exercises are too difficult and the text is too concise to help a starting mathematician grow.
After every algebra course I took, Commutative Algebra, Advanced Field Theory, Category theory, algebraic number theory etc. , I noticed my whole course was in that book and I could follow that chapter. Also you start liking the conciseness if you know more: you did not open that book for intuition building but to read how that one proof went.
I have never bought so much mathematics for 90 euro.
Comment: what books would you recommend for intuition building?
Comment: For what subject specifically? Books that build intuition tend to have narrow subjects.
Comment: With regards to Libear Algebra and Abstract Algebra
Comment: I learned linear Algebra from lecture notes in Dutch and read no other books.
Abstract Algebra is very broad: Group theory, commutative algebra, field theory, etc. I can recommend Atiyah&MacDonald for Com. Algebra- very good exercises! Try looking for reference requests on this site for these subjects.
Answer: I only used Dummit and Foote, so my answer should serve as a complement of Mr Hashi's.
First, I believe Dummit and Foote contains all the materials you need.
Second, the way I used this book is I took a year-long course on algebra, going through most of the important topics in D&F. My instructors assign important exercises in the book and I tried them all.
One caution about using this book is it contains too much material.Trying to read all of them at once would be a huge waste of time and well of frustration. You should choose on your own what you need and read the corresponding sections. After you go through most of the important sections, you can use this book as a reference. It is fantastic for this purpose.


What do I need to notate as I play?

Question: I hope this isn't a silly enquiry.  My daughter improvises on our piano, classical style, and I would like to know if there's a means to notate on computer as she plays.
We bought Sibelius software but haven't taken it out of the box yet!  I gather we would need an electric keyboard to connect with our laptop, but do we need anything else?
Is it as straightforward as that? We home educate so can't ask for advice from music teachers.
Comment: *Electric keyboard* can be divided into two categories: *sound producing* keyboard with a digital computer interface, and *silent* keyboard with a digital computer interface. In fact, most semi to professional "electric", "electronic" keyboards have a digital computer interface, most generally implemented as MIDI (over USB).
Comment: Apart from the answer I've given below, long story short -**yes, it's as straightforward as coupling an electric (digital) keyboard with a laptop on which you have Sibelius**. What is not as straightforward is that _silent_ keyboards are generally less realistic _to the touch_, and cheaper, than _sound producing_ keyboards. Another thing to consider, which my answer covers, is alternative software solutions, since Sibelius has a steep learning curve, it might be "overkill".
Comment: Also, if she wants to hear what she's playing as she plays it, and the keyboard is not sound-producing or the difference between the keyboard and the computer sounds is too annoying, you would need a way to eliminate latency. This can be done through ASIO-capable hardware or ASIO-simulating drivers. If this turns out to be relevant for you I can write an answer or point you to resources with more detail. P.S. One last consideration is whether she'll enjoy a digital keyboard as much and feel as comfortable improvising on it. That's always a hitch without spending a lot of money.
Answer: Sibelius offers 'Flexitime input'.  It is meant to detect the tempo of freely-played music from a MIDI keyboard and create notation.  In reality, this doesn't work outside laboratory conditions.  What you CAN do is turn off the 'flexi' feature and play VERY accurately to the click.  If you know what notation you want, this can help get it down on paper.  But it's not as useful as you might hope, and it certainly won't auto-magically produce idiomatic piano notation.
Try ScoreCloud.
https://scorecloud.com/
It's free, and makes, I think, the best attempt at capturing freely-played keyboard input to notation that is currently available.
But, unless her playing is very clear and simple, I fear you'll be disappointed.  Sorry.  Music transcription is still a job for a skilled musician.  The computers aren't quite there yet.
P.S. Sibelius now comes in three flavours.  'Sibelius First' is free and very basic.  'Sibelius' is the 'lite' version, previously called 'Sibelius First'.  I'm not sure if it has Flexitime.   'Sibelius Ultimate' is the full version, what used to be called just 'Sibelius'.  Yes, a ridiculous re-use of established names meaning something different, I agree.
Comment: @Dekkadeci I do; I'm referring to the pure MIDI data, not to any standard notation system. When I just want to get a sketch down, that's often what I do. Then I know I can come back and tweak and quantize and whatnot, but before trying to box it into good traditional notation a human could read, I just want to make sure the idea or the emotion isn't lost. :) While it does sound like the OP wants notation as an output, they shouldn't be intimidated by the difficulty of getting perfect notation if the core concern is to capture the girl's playing (at least as a starting point).
Comment: Of course, *capturing* the performance data so the improv isn't lost is easy. Notating it in a given time signature is hard.
Comment: @LukeSawczak - If by "capturing" you mean "leaving all the inadvertent tied 64th notes and ugly tuplets in", then yes, it's easy.
Answer: Ableton Live |-> (a serious DAW - digital audio workstation software used for composing, live performance, mixing and recording, post-production, etc., compare it with Cubase |-> and Logic |->) has in the recent years started implementing "audio to midi" feature.
So far it implements the following:

Melody to MIDI
Harmony to MIDI
Drums to MIDI

(MIDI |-> is the lowest common denominator when it comes to recording notes, it's a protocol, a language, a file format and a published standard originating in 1983; the essential thing to note is that by "lowest common denominator" I mean it is a very old format that facilitates interchange of notes between virtually all semi to professional music software, scoring or production)
The most useful of these is the "Melody to MIDI", which assumes "monophonic" (single-voice) recording.
I assume, if you give it a simple enough recording, it will be able to automatically transcribe the notes for you. There might be other "open-source (free or gratis)" solutions out there, but this is in general quite an uncharted territory yet.
As far as "notation" software (which essentially deals with visual aspects of publishing), MuseScore |-> is so far gratis (although somewhat less intuitive than old-time favorites such as Sibelius and Finale |->).
Ableton Live, as opposed to Cubase and Logic, does not provide scorewriting capabilites, and there is quite a good implementation of those in said programs (think of it as "lightweight" scoring functionality integrated into a music recording system).
Thus, the question you are probably going to ponder over is about whether you need more intricate scoring capabilites, whether you need publishing capabilities at all, and whether the creative process is more "theoretical" (i.e. paper and pencil, notation software) or more "practical" (i.e. automatic recording of notes, voices and instruments with recording software).
Post scriptum - Logic (also called Logic Pro, acquired by Apple in 2006) is Mac only, but recently, they reduced the price for the whole package to $200. You get a lot of stuff for that, trust me on that one. So if you own a Mac, and can spare $200, it's kind of an essential music making tool. Ableton Live, on the other hand (as well as Cubase) are both Mac and Windows, so that is also somthing to consider (apart from the price, by which Apple takes the cake, for reasons unknown to me)
Comment: Apple is losing the 'creative' market because of its capricious hardware design policies.  I guess it feels musicians must be bribed to stick around.
Comment: True - so is Avid though... But I believe the software that predates Avid and Apple's prosumer market segmentation justifies itself.

What do I need to notate as I play?


probability of two integers being equal to one another

Question: Came across this problem, and while i know the correct answer, I cannot seem to rationalize it.
Given 2 bit strings that are generated randomly , where each bit is either 0 or 1 (eg 001010101010).  What is the probability that the bit at a specific place will equal the bit in the same place in the other string?
Now, the correct answer is noticing that there are only four possible combinations for this; 00, 01, 10, 11 , where only two of them lead the numbers being the same.  Thus the answer is 1/2
However, the way that I think about this, is to say, the probability that the bit in string 1 will be a certain number is 1/2, the probability that the bit in the other string will be 1/2  , so 1/4.
Or using the formula , two random integers are equal in a range [m,n]
1/(n-m+1)*(n-m+1) = 1/(2)(2) = 1/4
Can someone help me rationalize this
Comment: The probability that they are both $0$ is $1/4$ and the probability that they are both $1$ is $1/4$. The probability that they are both the same is therefore the sum of these two probabilities
Comment: the probability of 1/4 you are working out is the probability that both bits are 1.  it is also the independent probability that both bits are 0.  Since 11 and 00 are the only two ways the bits can be the same P(both the same) = 1/4 + 1/4 = 1/2
Comment: It's kinda hard to rationalize something that is not true.
Answer: Whatever the value of the bit in the first number, the corresponding bit in the other number is either the same or different, with equal probability. In other words, the probability is $\frac12$. The probability of all bits being the same in two $n$-bit numbers is therefore $(\frac12)^n$. This should make sense because there are $2^n$ such numbers; fixing one, the second has a $\frac1{2^n}$ chance of being the same.

However, the way that I think about this, is to say, the probability that the bit in string 1 will be a certain number is 1/2, the probability that the bit in the other string will be 1/2 , so 1/4.

That's true, but you're accounting for only one of two possibilities. You've counted the probability of both bits being $0$, say. The probability of both being $1$ is also $\frac14$, so the overall probability that the bits are identical is $\frac14+\frac14=\frac12$, which agrees with my first paragraph.
Answer: There are lots of ways to try and rationalize your question, because your statement is correct and you seem to intuitively understand what is happening. I would point you in the direction of Conditional Probability to help you see what is happening.
What you are really asking is: What is the probability that the bit in the second string will be the same number as the bit in the first string?
It's commonly denoted as Bayes' Formula, but in our case it is simply reduced to $$P( E\, | \,F ) = {P(E\, \cap\,F)\over P(F)}.$$
where E is the event that depends strictly on F.
P(F) denotes the probability of choosing a one or a zero with equal probability, thus $$P(F) = 1$$
P(E) is going to denote the probability that we choose the same value that was chosen before, which makes $$P(E) = .5$$
Observe that$$P(E \cap F) = P(E)P(F)$$ due to the fact that the two events are independent. Substituting these values into the first equation shows that $$P(E\,|\,F) = {{1 \over 2}\cdot1 \over 1} = {1 \over 2}.$$
So the probability of the items being the same is 1/2, as you suspected.


How do I add oAuth (DevDefined oAuth) to a C# windows forms project?

Question: I'm trying to make a desktop Justin.TV notifier with C#. I'm new to C# but I programmed in C++ and Java.
I've been google-ing and searching stackoverflow but haven't found a guide on how to add something like DevDefined to my project.
For Java, it was pretty simple adding oAuth. Just imported a couple of .js files. I've been stuck and frustrated searching. I wish I didn't have to ask such a simple question but help would be very much appreciated.
Thanks a lot.
Answer: The sources are on their GitHub page. Download them, build the library and add the library in your C# project references.
There are code examples on the GitHub page or the Google Code one.
Comment: Ohhhhh. I was downloading the files and folders being displayed on their Github page. Not the download and releases on the bottom.

I'm new to Github. Could you explain what the files displayed are vs. the ones being downloaded? Thanks Otiel!
Comment: @RogerLam: The files displayed (you can download them by clicking the **`ZIP`** button on the top) are the sources for the `.dll` file, the sources for examples and tests. The *download and releases* allows you to directly download the compiled `.dll` file.


Apache: How to tell which LDAP server my user was authenticated with

Question: I am authenticating my users with the following configuration (simplified)
<AuthnProviderAlias ldap server1>
  AuthLDAPURL ldap://server1/whatever?uid?one?
</AuthnProviderAlias>

<AuthnProviderAlias ldap server2>
  AuthLDAPURL ldap://server2/whatever?uid?one?
</AuthnProviderAlias>

<Location />
  AuthName "Realm"
  AuthType Basic
  AuthBasicProvider server1 server2
  AuthzLDAPAuthoritative off
  require valid-user
</Location>

Is there any way I can know if which LDAP server my user was authenticated from? When the authentication is sucessful I'd like to set an HTTP header (something like "SourceLDAPServer: server2") to be able to tell which server the user was valid in. Is that possible with Apache 2.2.x?
Answer: Should be possible with Apache mod_headers. I don't know about the environment variables mod_ldap would use, though. If you have PHP installed, just create a PHP file containing line
<?php phpinfo(); ?>

And surf to that file. See the environment variables printed in that page and try to find out if there are any ldap variables around.
Answer: It seems the only way to do this is to select more attributes from the LDAP servers like so:
<AuthnProviderAlias ldap server1>
  AuthLDAPURL ldap://server1/whatever?uid,type1?one?
</AuthnProviderAlias>

<AuthnProviderAlias ldap server2>
  AuthLDAPURL ldap://server2/whatever?uid,type2?one?
</AuthnProviderAlias>

When the authentication succeeds you find either AUTHENTICATE_type1 or AUTHENTICATE_type2 as environment variables depending on which LDAP server did the authentication.
With mod_headers, it then becomes possible to setup the header value this way
Header set UserType type1 env=AUTHENTICATE_type1
Header set UserType type2 env=AUTHENTICATE_type2


Javascipt Canvas, Remove a circle after I click on it

Question: In this code I create a circle and put it where I want on canvas; I want to remove it after clicking on it and if I click again than display it. How I can do this?
var createCircle = new ShootyController();
createCircle.x;
createCircle.y;
createCircle.radius = 10;
createCircle.color = "red";

canvas.addEventListener(
  "click",
  function (e) {
    createCircle.x = e.clientX;
    createCircle.y = e.clientY;

    createCircle.x -= canvas.offsetLeft;
    createCircle.y -= canvas.offsetTop;
  },
  {once: true}
);

Answer: You have to clear the canvas part where your circle is drawing
let canvas = document.getElementById("myCanvasID");
let context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);


How many elements in $\hom_{\mathbb F_2}(\mathbb F_2^2,\mathbb F_2^2)?$

Question: My syllabus says that $\hom_{\mathbb F_2}(\mathbb F_2^2,\mathbb F_2^2)$ contains 16 elements. I'm guessing this is because $\mathbb F_2^{2\times 2}$ contains 16 elements, but I don't see why this should be the reason.
It happens to be that we also have three bases for $\mathbb F_2^2$, so shouldn't there be $< 16$ linear maps? Some linear map could be represented by several matrix representations, i.e. some of  the matrices in $\mathbb F_2^{2\times 2}$ are similar.
Answer: Let's consider $\mathrm{Hom}_F(V,W)$ where $F$ is a field, and
$V$ and $W$ are vector spaces over $K$ with dimensions $m$ and $n$.
Then $\mathrm{Hom}_F(V,W)$ is a vector space of dimension $mn$; it
corresponds to the $m\times n$ matrices over $K$.
In this example $K=\Bbb F_2$ and $m=n=2$. So we get a vector space
of dimension $4$ over $\Bbb F_2$. It has order $|\Bbb F_2|^4=2^4=16$.
Comment: How did you come up with $\vert \mathbb F_2\vert^2$? Also, shouldn't it then be $\vert \mathbb F_2\vert^4$?
Comment: For the case  $|Hom_{\mathbb F_9^3}(\mathbb F_9^3, \mathbb F_9^5)|$ would that mean $m=3,n=5 $ and thus $|\mathbb F_9|^{15}=9^{15}=205891132094649$? Or do I understand something wrong?
Answer: The set $\hom_{\mathbb{F}_2}(\mathbb{F}_2^2, \mathbb{F}_2^2)$ can be identified with $M_{2}(\mathbb{F}_2)$ (matrices of size $2\times 2$ with entries from $\mathbb{F}_2$). The association is not hard as every linear transformation corresponds to a matrix after you fix a basis.
If you believe this, then it can be seen that $|M_{2}(\mathbb{F}_2)|=2^4=16$.
Comment: How can we identify those two sets, when one linear map might correspond to two different matrices (different bases).
Comment: Indeed, one linear map can correspond to two different matrices (in different bases) BUT after you fix a basis, you can associate a unique matrix with a linear transformation.
Comment: Similarity as a relation between matrices(if you have already fixed a basis) or as a relation on $\hom_{\mathbb{F}_2}(\mathbb{F}_2^2,\mathbb{F}_2^2)$ is not capturing the number of different linear transformations from $\mathbb{F}_2^2$ to itself. It is counting all the matrices/linear transformations with the same determinant and same trace.  Since determinant and trace can only take the values $0$ or $1$ we have at most $4$ equivalence classes of matrices upto similarity. But clearly you can find more than 4 linear transformations from $\mathbb{F}_2^2$  to itself.
Comment: Sorry, I deleted my comment that you're answering, because I figured it out.  I think it must have happened simultaneously? Next time I might add a comment that I got it, instead of deleting the previous one. Anyhow, thanks for your help!


Visual Studio Copilot Chat Extension, Code Output too narrow to read

Question: I have no idea how I ended up like this but am unable to resolve this.

As you can see the output of the copilot chat extension is too narrow for me to read. But it is there, and the Copy, CreateNewFile and Preview buttons work.
I am using Visual Studio 17.9.0 Preview 2.0 and have a Copilot Individual subscription.
It worked before. I have already tried to delete the .vs folder inside my solution, but that does not seem to be related to the solution but to the global Visual Studio setting.
Do you have any idea how to solve this? Uninstalling and re-installing the extension did not help.
Answer: There's a related ticket about this on the VS community platform, which is resolved here, the comment saying that the problem went away by using "GitHub Copilot Chat 0.2.241.22873 &
Microsoft Visual Studio Community 2022 (64-bit) - Preview Version 17.9.0 Preview 2.1" (quoting Kevin Gallahan).


WPF Path Binding to PointCollection not updating UI

Question: I am trying to learn MVVM style updates. Not going so swimmingly.
I'm stuck on updating a simple rectangle that is drawn based upon a change to a Point Collection.
On initialization, the UI Updates, but upon a simple change to the Point Collection, the Path is not updated in the UI.
I added a few TextBlocks to make sure the Change event is getting fired, but I am a little lost at this point.
Any help appreciated:
XAML:
<Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:ExampleGreg" x:Class="ExampleGreg.MainWindow"
        Title="MainWindow" Height="161.614" Width="324.087">
    <Grid x:Name="gridUser" MouseDown="click_MouseDown" >
        <Canvas x:Name="MeterCanvas" Margin="14,7,30,0" Background="#FFAFAFAF" Height="35" VerticalAlignment="Top">
            <Path Stroke="Black" StrokeThickness="2">
                <Path.Data>
                    <PathGeometry x:Name="geometry"/>
                </Path.Data>
            </Path>
            <Path Stroke="Black" StrokeThickness="2">
                <Path.Data>
                    <PathGeometry x:Name="polylinePwr">
                        <PathGeometry.Transform>
                            <ScaleTransform ScaleX="{Binding ActualWidth, ElementName=MeterCanvas}" ScaleY="{Binding ActualHeight, ElementName=MeterCanvas}" />
                        </PathGeometry.Transform>
                        <PathGeometry.Figures>
                            <PathFigure IsClosed ="True" StartPoint="{Binding Path=thePoints[0]}">
                                <PathFigure.Segments>
                                    <PathSegmentCollection>
                                        <PolyLineSegment Points="{Binding thePoints, UpdateSourceTrigger=PropertyChanged}" />
                                    </PathSegmentCollection>
                                </PathFigure.Segments>
                            </PathFigure>
                        </PathGeometry.Figures>
                    </PathGeometry>
                </Path.Data>
            </Path>
        </Canvas>

    </Grid>
</Window>

MainWindow:
    public partial class MainWindow : Window
{
    private MainViewModel mvm;
    public MainWindow()
    {
        InitializeComponent();
        mvm = new MainViewModel();
        this.DataContext = mvm;

    }

    private void click_MouseDown(object sender, MouseButtonEventArgs e)
    {
        mvm.theText = mvm.theText + ".";
        mvm.ChangePoint(.4);
    }
}

ModelView:
    class MainViewModel : INotifyPropertyChanged
{
    private string _theText = "Initial";
    private PointCollection _points = new PointCollection();
    private PolyLineSegment segment;

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(String info)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(info));
        }
    }
    public MainViewModel()
    {
        ChangePoint(0.9);
    }

    public string theText
    {
        get { return _theText; }
        set
        {
            if (_theText != value)
            {
                _theText = value;
                OnPropertyChanged("theText");
            }
        }
    }
    public PointCollection thePoints
    {
        get
        { return _points; }
    }

    public void ChangePoint(double x)
    {
        _points.Clear();
        AddPoint(new Point(0.2, 0.2));
        AddPoint(new Point(0.2, 0.8));
        AddPoint(new Point(x, 0.8));
        AddPoint(new Point(x, 0.2));

        OnPropertyChanged("thePoints");
        _theText = _theText + "!";
        OnPropertyChanged("theText");

    }

    public void AddPoint(Point p)
    {
        _points.Add(p);
    }
}

Thanks for any suggestions (that work :) )
--EDIT PER THE ANSWER BELOW--
I added an IValueConverter Class:
    public class PointCollectionConverter : IValueConverter
{
    #region IValueConverter Members

    public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value.GetType() == typeof(ObservableCollection<Point>) && targetType == typeof(PointCollection))
        {
            var pointCollection = new PointCollection();
            foreach (var point in value as ObservableCollection<Point>)
                pointCollection.Add(point);
            return pointCollection;
        }
        return null;

    }

    public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return null; //not needed
    }

    #endregion
}

And Changed the ModelView to use an Observable Collection ...
Updated ModelView:
    class MainViewModel : INotifyPropertyChanged
{
    private string _theText = "Initial";
    private ObservableCollection<Point> _points;
    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(String info)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(info));
        }
    }

    public MainViewModel()
    {
        _points = new ObservableCollection<Point>();
        _points.Add(new Point(0.2, 0.2));
        _points.Add(new Point(0.2, 0.8));
    }

    public string theText
    {
        get { return _theText; }
        set
        {
            if (_theText != value)
            {
                _theText = value;
                OnPropertyChanged("theText");
            }
        }
    }
    public ObservableCollection<Point> thePoints
    {
        get
        { return _points; }
    }

    double xAdder = 0;
    double y = 0.0;
    public void ChangePoint(double x)
    {
        y = y + .1;
        if (y > .9) { y = .1; xAdder += .1; }
        _points.Add(new Point(x+xAdder, y));
        OnPropertyChanged("thePoints");

        _theText = _theText + "!";
        OnPropertyChanged("theText");

    }

}

And updated XAML:
<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:ExampleGreg"  x:Class="ExampleGreg.MainWindow"
    Title="MainWindow" Height="161.614" Width="324.087">
<Window.Resources>
    <local:PointCollectionConverter x:Key="pointCollectionConverter"/>
</Window.Resources>
<Grid x:Name="gridUser" MouseDown="click_MouseDown" >
    <Canvas x:Name="MeterCanvas" Margin="14,7,30,0" Background="#FFAFAFAF" Height="35" VerticalAlignment="Top">
        <Path Stroke="Black" StrokeThickness="2">
            <Path.Data>
                <PathGeometry x:Name="geometry"/>
            </Path.Data>
        </Path>
        <Path Stroke="Black" StrokeThickness="2">
            <Path.Data>
                <PathGeometry x:Name="polylinePwr">
                    <PathGeometry.Transform>
                        <ScaleTransform ScaleX="{Binding ActualWidth, ElementName=MeterCanvas}" ScaleY="{Binding ActualHeight, ElementName=MeterCanvas}" />
                    </PathGeometry.Transform>
                    <PathGeometry.Figures>
                        <PathFigure StartPoint="{Binding Path=thePoints[0], Converter={StaticResource pointCollectionConverter}}">
                            <PathFigure.Segments>
                                <PathSegmentCollection>
                                    <PolyLineSegment Points="{Binding thePoints, Converter={StaticResource pointCollectionConverter}}" />
                                </PathSegmentCollection>
                            </PathFigure.Segments>
                        </PathFigure>
                    </PathGeometry.Figures>
                </PathGeometry>
            </Path.Data>
        </Path>
    </Canvas>

</Grid>

I am not really sure if I will gain any performance improvement, given the IValueConverter creates a new PointCollection Each the ObservableCollection is changed.
THANK YOU everyone for helping me through this. I wanted to paste the complete code as working if any others run into the same thing.
EDIT #2 - After benchmarking the Observable w/ IValueConverter vs. Copying PointCollection to a new PointCollection, the Point Collection seems faster:
    // Option 2 - WAY Faster.
    // Just Use a Points Collection, copy it, and add a point.
    public void AddPoint2(Point pt)
    {
        PointCollection pc = new PointCollection(_points2);
        pc.Add(new Point(pt.X, pt.Y));
        _points2 = pc;
        OnPropertyChanged("thePoints2");
    }

called from
            // 5000 point sinwave for testing
            foreach (Point pt in sinWave) mvm.AddPoint2(pt);
            x++;

If there is a better way, comments appreciated.
Answer: Try replacing the property, rather than clearing+re-populating it.
public void ChangePoint(double x)
{
    var newPoints = new PointCollection();
    newPoints.Add(new Point(0.2, 0.2));
    newPoints.Add(new Point(0.2, 0.8));
    newPoints.Add(new Point(x, 0.8));
    newPoints.Add(new Point(x, 0.2));

    OnPropertyChanged("thePoints");
    _theText = _theText + "!";
    OnPropertyChanged("theText");
}

It seems like bindings sometimes ignore the "PropertyChanged" event if the object reference is the same.
Comment: Last update. I tried benchmarking ObservableCollection w/ IConverter vs. Copying PointCollection to new PointCollection and adding a Point.  Doing a copy of the PointCollection was **way** faster: `// Option 2 - WAY Faster.
        // Just Use a Points Collection, copy it, and add a point.
        public void AddPoint2(Point pt)
        {
            PointCollection pc = new PointCollection(_points2);
            pc.Add(new Point(pt.X, pt.Y));
            _points2 = pc;
            OnPropertyChanged("thePoints2");
        }
`
Comment: My question to follow up, is what is the performance implication of doing this way? I am trying to update an App for more efficiency, but if I were to apply this to a situation where my Point Collection is growing, would I actually gain advantage over my current, non-mvvm model? Here I am just continuously creating PathSegments, and adding them to a PathSegmentCollection.  I guess I'll have to do some testing.
Comment: @GregG if performance is important, then you should definitely try and use an `ObservableCollection` instead of replacing the entire collection on every change.
Comment: @GregG as far as overall performance, well ... it really depends.  I take it you're doing an animation of some sort?  In that case, wouldn't it be better to use a storyboard/animation?
Comment: The ObservableCollection was my first attempt. Upon doing this, the UI doesn't even draw the line upon initialization. Do you know if I just need to implement a Converter in this case? Sorry if this is a dumb question. I'm trying to wrap my head around this.
Comment: Thanks for this.  running the Clear method on point collection and then adding the points did not update the UI.  Even if I forced the property changed event after adding all the points.  Creating a brand new PointCollection each time did the trick!  Seems like a bug in WPF though :-)


META tags module description [node:summary] doesn't work

Question: I have a content type with title, image, body field (long text with summary). I use meta tag module and when I add in Description: [node:summary] or [node:field_body:summary] nothing appears in the meta description in view-source.
<meta name="title" content="..."
<meta name="image" content="..."

Title and image work, but not summary.
Does anyone have a solution?
Answer: I can confirm, that the token [node:summary] works in metatag. But only for the original "body" field with exactly that name. Did you change the field name? Because the original "body" field is not "field_body".
Comment: Yes, i use custom field for body !
Comment: Then the solution is to use a body field with the machine name "body".


Using Powershell to export NTFS permissions

Question: I am making use of this script to export NTFS permissions from a large folder structure on a file server. I get the information I want to see using out-gridview, but I need it in CSV format.
Here is what currently works:
Get-ChildItem -recurse -force C:\Test -Directory | get-acl | out-gridview
So I tried the following to get it into CSV format:
Get-ChildItem -recurse -force C:\Test -Directory | get-acl |export-csv C:\temp\permissions.csv
However, the output now includes the following in the CSV output:

Microsoft.PowerShell.Core\FileSystem::C:\Test\Subfolder1

How do I exclude the above from the output?
Answer: The path must be converted, there is an example of this using ACLs here
Get-ChildItem -recurse -force c:\test -Directory | get-acl | %{$_| Add-Member -NotePropertyName Folder -NotePropertyValue (Convert-Path $_.path) -PassThru }|select -ExpandProperty access -property Folder, owner|export-csv C:\temp\permissions.csv -NoTypeInformation

Comment: Fantastic, thanks so much that seems to be working great. Would it have any issue parsing through about 3000 folders?
Comment: Just wondering if you can assist with this, when I run the script some of the folders have long names and are nested within others, so it ends up being over the 256 character limit, and Powershell writes an error for that. Is there anyway to ignore that limit and still include it in the results?
Comment: That is a limit for most cmdlets such as Get-ChildItem. I would recommend checking out https://github.com/alphaleonis/AlphaFS, which uses extends this limit to 32.000 characters.


Wordpress custom header files for different pages?

Question: I'm wondering if it is possible to call different headers like for the get_sidebar('newsidebar')?
can I maybe call get_header('custom')? I want to make my header for the index different then all the other pages
Comment: Do you want to add different syntax.. or just style the headers different?
Answer: Multi headers
Different header for different pages.
<code><?php
if ( is_home() ) :
get_header('home');
elseif ( is_404() ) :
get_header('404');
else :
get_header();
endif;
?>
</code>
The file names for the home and 404 headers should be header-home.php and header-404.php respectively.
Answer: Sure you can, view the codex:
http://codex.wordpress.org/Function_Reference/get_header


Is there any rule of lbw which considers 2.5 meters?

Question: Is there any rule which states that leg before wicket is not a violation when the batsman is 2.5 meters from the stumps? I have read the rule about the lbw but there is nothing stating that.
But there is an instance in World Cup 2011 in a match of India where I saw that because the batsman's distance from stumps was more than 2.5 meters, he was given not out.
So if that's the rule why it is not written somewhere?
And is there any marking on the pitch so that the umpire can know that batman is out 2.5 m from the stumps?
Answer: The only situation in which 2.5 m comes into play is if the Decision Review System is used. At that point, if the point of impact is more than 2.5 m from the stumps, then (hand waving slightly) the on-field umpire's original decision is less likely to be overturned. Specifically, see section 3.3(i)(iii) of the Decision Review System - Playing Conditions (Appendix 2) from the standard Test Match Playing Conditions:

With regard to determining whether the ball was likely to have hit the stumps [...] where the evidence shows that the ball would have hit the
  stumps within the demarcated area as set out above but that:
  * The point of impact is 300cm or more from the stumps; or
  * The point of impact is more than 250cm but less than 300cm from the
  stumps and the distance between point of pitching and point of impact is
  less than 40cm,
  the original decision will stand (i.e. not out)

As such, there's no need for any markings on the pitch, as it is determined by the information from the DRS cameras, not by the on-field umpires.
Comment: but it is not written in DRS rules
Comment: Yes, it is. See my edit. What is your basis for saying it is not written in the DRS rules?


\Drupal::request() vs $request_stack->getCurrentRequest()

Question: These seem to return the same thing:
\Drupal::request()
$request_stack->getCurrentRequest()
Which is the preferred way to get the current request and why? Is one of these to be deprecated? Any other advantages/disadvantages?
Thanks!
Comment: What context are you calling it in? Generally speaking if your context supports dependency injection, you would inject the request stack service and use it the latter way (better for testability). If you're in procedural code, e.g. a hook, you would use the former
Comment: Thanks, @Clive ... it is in a service that I didn't originally write and I had seen the other way from more time in hooks, but that makes sense. Thanks for the clarification!
Answer: How to get the current request object:
Procedural
In procedural code get the request from the static wrapper \Drupal:
$request = \Drupal::request();

Service
In a service get the current request from the injected argument @request_stack:
The module_name/module_name.services.yml file :
services:
  custom.service:
    class: Drupal\module_name\Service\CustomService
    arguments:
      - '@request_stack'

The module_name/src/Service/CustomService.php file :
use Symfony\Component\HttpFoundation\RequestStack;

/** @var \Symfony\Component\HttpFoundation\RequestStack */
protected $requestStack;

class customService
{
  public function __construct(RequestStack $requestStack) {
    $this->requestStack = $requestStack;
  }

  public function doSomething() {
    // use $this->requestStack->getCurrentRequest()
  }
}

Controller
In a controller you can pull the request from the route argument stack by including a typed request parameter. An example from UserController:
use Symfony\Component\HttpFoundation\Request;

  public function resetPass(Request $request, $uid, $timestamp, $hash) {
    // use $request
  }

It's not necessary to define the route parameter in the route definition. The request is always available.
Form
In a form method get the request from getRequest():
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $request = $this->getRequest();
    ...
  }

Don't use the injected requestStack property directly, because it is not available for all Form API callbacks.
Comment: @joachim, the service needs `@request_stack` as argument. You find examples in core.services.yml.
Comment: Thanks! ... it is in a service that I didn't originally write and I had seen the other way from more time spent in hooks, but that makes sense. Thanks for the clarification!
Comment: How does a service get the injected request stack?
Comment: @4k4 Could you give us an example scenario of when the requestStack wouldn't be available if injected directly?
Comment: @HeitorAlthmann, if injected directly it would be available, but you can't be sure it is when using the form class in Form API. `$request = $this->getRequest()` gets the request from the injected service, but has a fallback in case it is not available.


Can't assign char "X" in part of String

Question: I can't assign a specific char like "X" in part of my input string.
For example I want to assign a default char with substring method in specific range of my input string. How can I assign a specific char in specific range of my
input string.
Can you help me?
import java.util.*;
public class Algoproject {

    public static void main(String[] args) {
        Scanner input=new Scanner(System.in);
         while(true){
        int num=input.nextInt();//number of colums
         if(num!=0)    {
         String s;
         s=input.next();//enter string without space
        int count=s.length();//string length
         displayMessage(s,num,count);
         }else
             break;
         }

    }
    public static void displayMessage(String str, int pi,int slength){
      int j=0,i=pi;
      while(pi<=slength){

                System.out.print(str.substring(j,pi )+"\n");
                j=pi;
                pi=pi+i;
    }
      System.out.print(str.substring(j,slength ));
      String in="$";
      //line29
    }}

in line 29 I want a method that give 3 value:

my arbitrary char
first index of my string
last index of my string

and I want to assign that char in this string range
Comment: Java *and* C? Which language are you using?
Comment: Unclear what you are asking for.
Comment: Welcome to StackOverflow. Please visit the [help] and read [ask].  Your question is unclear, and you need to show us the code you are working with.  Otherwise it is considered off-topic.
Comment: i use java and i want method to assign arbitrary char in a specific range of my input string
Comment: `str = str.substring() + stringOfSize(lengthToInsert, 'X') + str.substring()`.  See http://stackoverflow.com/a/16800351/646887 for an example on how stringOfSize could be constrructed.
Answer: Get the index at which you want to assign your character, suppose it's "x"
Then do this
newstring = originalstring.substring(0, x) + your_character + originalstring.substring(x, originalstring.length());

Can't assign char "X" in part of String


Find the relationship between $x$ and $y$ so that $y:=0\rightarrow\frac{\pi}{2}\Leftrightarrow x:=y\rightarrow\frac{\pi}{2}$

Question:
Find the relationship between $x$ and $y$ so that
$$y:=0\rightarrow\frac{\pi}{2}\Leftrightarrow x:=y\rightarrow\frac{\pi}{2}$$

I'm having trouble solving the multivariable calculus if I change the order between ${\rm d}x, {\rm d}y,$ so I try a new approach like finding function $y=\!f_{1}\left ( x \right )$ and $x=\!f_{2}\left ( y \right )$ but unsuccessfully . I need to the help
Comment: What are the limits for your integral? $y \leq x \leq \frac{\pi}{2}$ and $0 \leq y \leq \frac{\pi}{2}$? Now you want to change order $dx \ dy$ to $dy \ dx$? Is that the question?
Comment: ok I see it now
Comment: I think to get the answer you must have to provide more details. Such as what is the main problem ? You told about a double integral, what is it ? Because it seems incomplete question from my side.@hd_30102
Comment: Your previous edit does not provide any extra information ? We need detailed information about your question.
Comment: @haidangel I think you need to give more details. For the example by Martund's answer, do you mean you can evaluate the double integral by a new approach? In your new approach, you need to find two functions $f_1, f_2$ such that $y= f_{1}\left ( x \right ), x= f_{2}\left ( y \right )$?
Comment: @haidangel You should use @, otherwise I can not receive notification. Do you have example about your new approach?
Comment: @haidangel Why without graphing? We often need graphing of the region to calculate the iterated integral?
Comment: Yes, but I wanna try a different approach..
Comment: Thanks a rl lot
Comment: I fixed smthang
Comment: @nmasanta sorry
Comment: Yes, kind of it
Comment: No such an idea
Comment: @RiverLi, I'm having trouble solving double integral without graphing.
Comment: @RiverLi, it's just for my curiosity.
Answer: I can give an example of an integral such that changing order of the integration changes limits like you've said in the title of your question. Consider the following double integral:
\begin{equation}
\iint\limits_{0<x<y<\frac\pi2}\mathrm dx\mathrm dy
\end{equation}
That, which I've written below the integral sign is the region of integration, and this integration will find out area of the region given by
\begin{equation}
A = \left\{(x,y)\Bigg|0<x<y<\frac\pi2\right\}
\end{equation}
in the plane.
Separating the limits, and doing integration in this order, we get the required integral to be
\begin{align}
I&=\iint\limits_A\mathrm dx\mathrm dy\\
&=\int_0^\frac\pi2\int_0^y\mathrm dx\mathrm dy\\
&=\int_0^\frac\pi2y\mathrm dy\\
&=\dfrac{\pi^2}{8}
\end{align}
Changing the order of integration, we get,
\begin{align}
I&=\iint\limits_A\mathrm dy\mathrm dx\\
&=\int_0^\frac\pi2\int_x^\frac\pi2\mathrm dy\mathrm dx\\
&=\int_0^\frac\pi2\left(\dfrac\pi2-x\right)\mathrm dx\\
&=\dfrac{\pi^2}{8}
\end{align}
Since the problem is not entirely clear to me, please comment if it doesn't answer your question.