NLP Categorizing Details with Confidence Values

Question: Background
I'm writing a Swift application that requires the classification of user events by categories. These categories can be things like:

Athletics
Cinema
Food
Work

However, I have a set list of these categories, and do not wish to make any more than the minimal amount I believe is needed to be able to classify any type of event.
Question
Is there a machine learning (nlp) procedure that does the following?

Takes a block of text (in my case, a description of an event).
Creates a "percentage match" to each possible classification.

For instance, suppose the description of an event is as follows:

Fun, energetic bike ride for people of all ages.

The algorithm in which this description would be passed in would return an object that looks something like this:
{
    athletics: 0.8,
    cinema: 0.1,
    food: 0.06,
    work: 0.04
}

where the values of each key in the object is a confidence.
If anyone can guide me in the right direction (or even send some general resources or solutions specific to iOS dev), I'd be super appreciative!
Comment: Could someone explain why this is being downvoted...
Answer: You are talking about typical classification model. I believe iOS offers you APIs to do this inside your app. Here Look for natural language processing bit - NLP
Also you are probably being downvoted because this forum typically looks to solve specific programming queries and not generic ones (this is an assumption and there could be another reason for downvotes.)
Comment: Thanks for the solution. I suppose it's not a popular question because of it's specific nature.


Can I use a violin plot to visualize logistic regression results (predicted probabilities)?

Question: I have a simple study in which I predicted the likelihood of an outcome as a function of a two-level grouping variable. Now I'd like to display these results in a graph. Initially I was thinking of using a bar plot of the predicted probabilities with confidence intervals, but because bar plots don't show the distribution of the data points, I'm leaning towards other options, like a violin plot. However, I'm not sure if this is possible or even desirable.
Comment: If your grouping variable has only two levels, then fitted probabilities will only take one of two values, won't they? That will make for a very degenerate violin plot.
Comment: Yes, I wasn't thinking too clearly about this but I realized the same. The other alternative would be to use the violin plot to show the subject-level data instead, showing mean percentage correct on the DV (instead of the trial level data, which is dichotomous) but then the concern is that it's not a pictorial summary representation of my analysis. Also, the violin plot is more about displaying the distributions vs. a clean summary, so it's tricky.
Answer: Answered in comments by Stephan Kolassa:

If your grouping variable has only two levels, then fitted
probabilities will only take one of two values, won't they? That will
make for a very degenerate violin plot.


Experiences with Scala swing, how does it add to what's already available in Java swing? Are there any challenges?

Question: I've just started learning the Scala language with the intent of using Scala swing to develop GUI applications.
I'm just curious as to some of the experiences other people have had with Scala swing and in what ways is it better than Java?
For example, the main arguments I've heard for the advantages of Scala swing are:
1) That it wraps java swing, so many of the features available in Java swing can be used
2) It simplifies event handling.. no more of those pesky anonymous classes and remembering which methods to override as in Java
3) You can make use of the powerful Scala collections library
4) More powerful graphics drawing (edit: not really true, sorry I'm a beginner :P)
I say nothing beats experience though, so to those who have used Scala swing for a while.. what are your experiences? Are there any benefits I didn't list up there? Are there any challenges (or some things it doesn't do as well as Java swing?)?
Answer: I happened to look yesterday at an older project of mine which contained a lot of things migrated from a previous Java version of that project. At the time I was not fully convinced of Scala Swing, so it still used javax.swing (in Scala). Seeing that code, it struck me what a huge mistake it was not to use Scala Swing here.
Scala Swing has the huge advantage of making the code much less verbose and easier to read and write. Items 1, 2 and 3 on your list absolutely apply. I don't understand No. 4 "more powerful graphics drawing", though. Scala Swing's wrapper components have a hook that allows you to override their own paintComponent methods, and drawing code will be correctly injected. But other than getting a java.awt.Graphics2D instead of the java.awt.Graphics which you must typically cast in Java, I see no advantage here.
Scala Swing's design was mostly done well, but there are a few things I don't like. First of all, there are a couple of missing things, which means that for any non-trivial GUI, you will have to resort to calling into the peer javax.swing layer from time to time. No big deal, but aesthetically unsatisfying. There are a few projects to amend this, e.g. ScalaSwingContrib and SwingPlus.
Scala Swing typically makes the assumption that your GUI is simple. For example, there are often no proper wrappers for the underlying widget models. Take for example ListView—you create it with a static list of items. There is no concept of a dynamic list model which drives the view. If you want that, you have to deal with the peer again.
The second thing I don't like is that the type design of the reactor approach is very dynamic and not quite type safe. I would have preferred a different approach which uses sealed traits for the events published by a widget, so your reaction PartialFunctions can be type checked. A related problem is that with type parametrised widgets, e.g. ListView[A], there is no way to have events parametrised in A (hypothesised: ListView.ItemSelected[A](v: ListView[A], elem: A)). For Table, not even the effort was made to use type parameters.
Nevertheless, I would recommend to anyone who writes desktop applications in Scala to go and use Scala Swing and not javax.swing.


Modelling spatio-temporal data with repeated measurements

Question: I would like to perform regression on an environmental dataset. The covariates are in the following form

I realize that the 4 repeated measures for each region are dependent because they come from the same region. For this reason, a model with mixed effects should be used. I also suspect that the data is spatially and temporally correlated.
I am not sure what models I should try on my dataset first. I am open to anything from very advanced state-of-the-art  models (preferred) to the more simple models that are taught in textbooks. I would appreciate suggestions from those that are familiar with spatio-temporal data.
Answer: One possible approach here is to use a mixed effects model with random intercepts for Region to handle the within-region correlations.
In R, the glmmTMB package can handle several different correlation structures:

Heterogeneous unstructured
Heterogeneous Toeplitz
Heterogeneous compound symmetry
Heterogeneous diagonal
AR(1)
Ornstein-Uhlenbeck
Spatial exponential
Spatial Gaussian
Spatial Matern
Reduced rank

https://cran.r-project.org/web/packages/glmmTMB/vignettes/covstruct.html
Comment: Hello Robert, how would I determine the kind of correlation structure in my spatio-temporal dataset?
Comment: Probably the best thing to do is to read the documentation together with a reference on spatio-temporal analysis
Answer: This is a longitudinal/panel data set. Standard textbook methods are fixed, random, or mixed effects. R has a package called plm to handle these.
Alternatively, one can use least squares dummy variable (LSDV) estimation, where one includes dummies for region (LSDV1), year (LSDV2), or both (LSDV3). This method is equivalent to fixed effects, as Cameron and Trivedi (2005) explain.


check if 2 bitmaps are the same

Question: i'm trying to do a memory game in android studio and i have the following code but it isn't working. can someone tell me why/ how to fix it?
 public void onClick1(View view) {
            if(counter<2) {
                button1[0][0].setBackgroundResource(pics[0][0]);
                clicked[0][0]=true;
                if(counter==1) {
                    for(int i= clicked.length -1; i>0;i--) {
                        for (int j=clicked[i].length -1; j>0; j--){
                            if(clicked[i][j]==true){
                                Bitmap bitmap = ((BitmapDrawable)button1[0][0].getBackground()).getBitmap();
                                Bitmap bitmap2 = ((BitmapDrawable)button1[i][j].getBackground()).getBitmap();
                                if(bitmap == bitmap2)
                                {
                                    button1[i][j].setVisibility(View.INVISIBLE);
                                    button1[0][0].setVisibility(View.INVISIBLE);
                                }
                                else {
                                    button1[0][0].setBackgroundResource(R.drawable.pic1);
                                    clicked[0][0]=false;
                                    button1[i][j].setBackgroundResource(R.drawable.pic1);
                                    clicked[i][j]=false;
                                    counter=0;
                                }
                            }
                        }
                    }
                }
                else
                    counter++;
            }
        }

Comment: Can you elaborate more what is not working? Does it crash with an error? If yes post the errors. If it doesn't crash post the expected result and the real result. Just "not working" is not helpful at all.
Comment: Please provide exactly what you problem is. ``Not working`` is not helpful at all.
Answer: For Bitmap objects you can use the method Bitmap.sameAs() to compare if 2 bitmaps are the same.

boolean sameAs(Bitmap other)
Given another bitmap, return true if it has the same dimensions,
  config, and pixel data as this bitmap. If any of those differ, return
  false. If other is null, return false.

So instead of:
if(bitmap == bitmap2)

Use:
if(bitmap.sameAs(bitmap2))

Answer: I am comparing two Bitmap using Bitmap.sameAs() method and it says on docs :
/**
 *  Given another bitmap, return true if it has the same dimensions, config,
 *  and pixel data as this bitmap. If any of those differ, return false.
 *  If other is null, return false.
 */

For example :
Bitmap dogeBitmap;
Bitmap duckBitmap;

if(dogeBitmap.sameAs(duckBitmap)) {
  // they are same
}

If you are creating bitmaps manually make sure at least they have same config to compare them visually
Answer: You can do something like this  to compare Bitmap:
private fun compareBitMap(bitmap: Bitmap, otherBitmap: Bitmap): Boolean {
    val bitMapAreSame = bitmap.sameAs(otherBitmap) &&
            (bitmap.width == otherBitmap.width &&
                    bitmap.width == otherBitmap.width &&
                    bitmap.height == otherBitmap.height &&
                    bitmap.byteCount == otherBitmap.byteCount &&
                    bitmap.density == otherBitmap.density)
    bitmap.recycle()
    otherBitmap.recycle()
    return bitMapAreSame
}

Answer: I do a hard check like this:
private fun compareBitMap(bitmap: Bitmap, otherBitmap: Bitmap): Boolean {
    val bitMapAreSame = bitmap.sameAs(otherBitmap) &&
            (bitmap.width == otherBitmap.width &&
                    bitmap.width == otherBitmap.width &&
                    bitmap.height == otherBitmap.height &&
                    bitmap.byteCount == otherBitmap.byteCount &&
                    bitmap.density == otherBitmap.density)
    bitmap.recycle()
    otherBitmap.recycle()
    return bitMapAreSame
}

Answer: You can check if there's an arrayByte which is the same by this
public boolen isSameBitmap(Bitmap bitmap1, Bitmap bitmap2) {
   ByteArrayOutputStream stream1 = new ByteArrayOutputStream();
   bmp1.compress(Bitmap.CompressFormat.PNG, 100, stream1);
   byte[] byteArrayBitmap1 = stream.toByteArray();

   ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
   bmp2.compress(Bitmap.CompressFormat.PNG, 100, stream2);
   byte[] byteArrayBitmap2 = stream.toByteArray();

  return Arrays.equals(byteArrayBitmap1, byteArrayBitmap2);
}

check if 2 bitmaps are the same


Execute actions after specific commands in Apache Guacamole SSH

Question: I setup Apache Guacamole 0.9.14 on my CentOS 7 with nginx as reverse proxy to it.
I want to give limited access to some of my employees for some of my servers via ssh.
Some of them are SFTP enabled and to prevent sabotage on purpose or not I edit guacamole upload function to upload a copy of file uploaded on guacamole server itself alongside destination server.
I was wondering if I could create a copy of files getting on destination servers via wget, curl, etc.
If I can control specific commands on destination servers and do some actions before executing them, (For example backing files on guacamole server before executing any rm -rf command or creating a copy of file 'wget'ed on guacamole server), that would be great.
There are more than a thousand servers with different Linux OSs on them, so editing any server except guacamole server itself is impossible to do.
Any idea on how to control commands before executing on guacamole server specially on ssh?

I answered my own question, but as you read my answer you can know I didn't actually answer my question, so I'm not accepting mine and any better ideas are welcome.
Answer: I couldn't find any way to achieve my goal, but I did find a little tricky way to do that in my servers.
I changed some of my commands like wget to wget2 and wrote my own wget like this:
#!/bin/bash
wget2 $1 -P /tmp > /dev/null 2>&1 & wget2 $1

A little more explanation:
I moved /usr/bin/wget to /usr/bin/wget2 therefore I have the original wget and then I wrote my own wget which while it downloads link to this directory, also downloads a copy into /tmp folder which doesn't show any output to command line.
I know that user can realize wget2 is running when he/she executes ps (lists process), but I don't care about that because he knows I'm supervising:)
It's just the case of audit.


Are inverse unique in unital algebra?

Question: Let $A$ be a unital algebra over a field $F$ with unity $1$. If $a,b,c\in A$ such that $ab=ba=1=ac=ca$, does this imply that $b=c$?
We have $c(ab)=c$. However, algebras are not necessarily associative so we can't conclude $c=c(ab)=(ca)b=b$.
Are there examples of algebras over a field with elements having multiple inverses?
Answer:
Are there examples of algebras over a field with elements having multiple inverses?

Yes. Consider $S=\{e,a,b\}$ with the following multiplication table
$$
\begin{array}{c|c|c|c}
& e
& a
& b \\\hline
e
& e
& a
& b \\\hline
a
& a
& e
& e \\\hline
b
& b
& e
& e \\
\end{array}$$
which is nonassociative with unity and with multiple inverses.
Now let $F$ be any field and consider $F[S]$ which is a vector space over $F$ with $S$ as a basis. The multiplication on $F[S]$ is induced linearly from the multipication on $S$, i.e.
$$\bigg(\sum_{i=1}^n \lambda_i s_i\bigg)\cdot \bigg(\sum_{i=1}^n\tau_i s_i\bigg):=\sum_{i,j=1}^n\lambda_i\tau_j s_is_j$$
This makes it a unital, nonassociative algebra over $F$, but $a$ has at least two inverses: itself and $b$.

Are inverse unique in unital algebra?


how to check whether an vector of boolean contains false or not?

Question: Why the following returns false? I expect it should return true since one element of the vector is really false
user=> (contains? [1 false] false)
false

Answer: contains? checks for the presence of a key in an associative collection. false is a value, not a key, in [1 false]. Only 0 and 1 are keys. You should use:
(some false? [1 false])


Erro em função de UPDATE no PHP com PDO

Question: Esse código não consegue encontrar os registros, e traz que a variável $lista é indefinida.
Meu HTML:

    <meta charset="UTF-8">
    <title></title>

    <?php
        include_once '../classes/Sistema2/Administrador.class.php';

    ?>
    <form action="Crud.php" method="post" id="none">
        <input type="hidden" name="acao" id="acao" value="<?php echo isset($_GET["id"])?'atualizar':'';?>">
        Nome:<input type="text" id="none" name="nome" value="<?php echo $lista['nome']?>">
        email:<input type="text" id="none" name="email" value="<?php echo $lista['email']?>">
        cpf:<input type="text" id="none" name="cpf" value="<?php echo $lista['cpf']?>">
        salario:<input type="text" id="none" name="salario" value="<?php echo $lista['salario']?>">
        <input type="submit" value="atualizar" name="atualizar">

    </form>

Esse código fica no meu Crud.php e um arquivo que recebe do post e faz a chamada com a class Administrador
if(isset($_GET["id"])){
                if($_POST["acao"] == "atualizar"):
                    $administrador = new Administrador();
                    $administrador->atualizar((strip_tags(trim($_POST['nome']))),(trim($_POST['email'])),(trim($_POST['cpf'])),(trim($_POST['salario'])));
                endif;
            }

Esse código fica na class:
public function atualizar($nome,$email,$cpf,$salario){
        $sql_atualizar = "UPDATE administrador SET nome=:nome, email=:email, cpf=:cpf salario=:salario WHERE id = :id";
        print_r($sql_atualizar);
        try{
            $query_atualizar = $this->conn()->prepare($sql_atualizar);
            $query_atualizar->bindValue(':nome',$nome,PDO::PARAM_STR);
            $query_atualizar->bindValue(':email',$email,PDO::PARAM_STR);
            $query_atualizar->bindValue(':cpf',$cpf,PDO::PARAM_STR);
            $query_atualizar->bindValue(':salario',$salario,PDO::PARAM_STR);
            //echo "";
            header('location: Index.php');

        }catch(PDOException $err){
            echo " Erro: ".$err->getMessage();
        }
    }

Comment: Huuum, code review :D. Já comenta aquele `header()` p começar.
Answer: Primeiro defina um campo hidden com id do registro em seu form.
<form action="Crud.php" method="post" id="none">
   <input type="hidden" name="id" value="<?php echo $lista['id'; ?> " />

Em Crud.php verifique se o id existe, caso sim é um update do contrario é um insert.
if(isset($_GET["id"] && ctype_digit($_GET["id"])){
   $administrador = new Administrador();
   $administrador->atualizar('valores ...');

Agora crie o bind respectivo para o id em atualizar() e não esqueça de chamar execute() do contrario sua consulta não chegará no banco de dados quanto e nem será executada.
$query_atualizar->bindValue(':salario',$salario,PDO::PARAM_STR);
$query_atualizar->bindValue(':id', $_GET["id"]);
if(!$query_atualizar->execute()){
   print_r($$query_atualizar->errorInfo()):
}else{
   echo 'sucesso';
}

Sugestões
Essa linha está bem longa, é uma boa oportunidade para criar uma função ou método que faça um sanitização nas entradas do usuário.
 $administrador->atualizar((strip_tags(trim($_POST['nome']))),(trim($_POST['email'])),(trim($_POST['cpf'])),(trim($_POST['salario'])))

Nova função
function sanitizar($input){
     return trim(strip_tags($input));
}

$administrador->atualizar(sanitizar($_POST['nome']),sanitizar($_POST['email']),sanitizar($_POST['cpf']),sanitizar($_POST['salario']));

Erro em função de UPDATE no PHP com PDO


Como eu pego o sql que a linq gera pelo debug do VS2013

Question: Como eu pego o sql que a linq gera pelo debug do VS2013? Como eu faço isso?
Fiz assim e não deu certo
public static List<MontaArvoreAcao> CriarListaArvoreUn(string _uf, string _cidade, string _un)
        {
            RupturaEntities db = new RupturaEntities();

            var _listaUnidade = (
                                   from r in db.Ruptura
                                   join a in db.Apresentacao on r.Codigo_Apresentacao equals (a.Codigo_Apresentacao)
                                   join m in db.Motivo on r.IDMotivo equals (m.IDMotivo)
                                   where r.IDMotivo != 6
                                   group r by new { a.Unidade_Negocio, r.IDMotivo } into gr
                                   select new MontaArvoreAcao
                                   {
                                       IDMotivo = gr.Key.IDMotivo,
                                       Unidade_Negocio = gr.Key.Unidade_Negocio,
                                       Somatorio = gr.Count()
                                   }
                                 ).Distinct().ToList().OrderBy(r => r.IDMotivo);

            if (_un != "" && _un != null)
            {
                _listaUnidade = _listaUnidade.Where(u => u.Unidade_Negocio == _un).ToList().Distinct().OrderBy(o => o.Unidade_Negocio);
            }

            var query = _listaUnidade.ToString();**==> Aqui não deu certo**

            return _listaUnidade.ToList();
        }

Comment: Estou como a mesma dúvida e realmente, a resposta dada abaixo não funciona! Infelizmente...
Answer: Quando você fizer o select usando linq, o resultado será do tipo DbQuery<T>. O metodo .ToString() dessa classe é sobrescrito para exibir o comando SQL, então basta chama-lo:
var query = from foo in db.foo
            select foo;
var sqlGerado = query.ToString();

Comment: @pnet Está explicado o motivo. Sua query é executada quando você chama o `.ToList()` (Não sei se o `.Distinct()` causa esse efeito, me corrijam se eu estiver errado). Nesse momento seu objeto deixa de ser um `DbQuery`. Se quiser ver o comando SQL gerado pela query, armazene o que está entre parenteses em uma variável, sem de chamar os métodos `.Distinct().ToList().OrderBy(r => r.IDMotivo)`.
Comment: não deu certo. Não veio o sql gerado. Foi isso que veio: System.Linq.OrderedEnumerable`2[Ruptura.Models.MontaArvoreAcao,System.Int32]
Comment: Você poderia postar partes relevantes do código para que possamos ajuda-lo? Esse método que eu descrevi sempre funcionou para mim, então creio que seu problema seja um pouco mais específico.
Comment: Fiz uma edição do meu método e a tentativa de pegar o sql gerado.
Comment: Isso mesmo, obrigado.


prepend one div in body in .inc file

Question: I want prepend one div using jQuery, But the div has to be generated dynamically, so I can not add it in html.tpl file.
I have tried below code
drupal_add_js('jQuery(document).ready(function () { jQuery("body").prepend("'+download_list()+'"); });', 'inline');

function download_list(){
    $output = "I am testing my div prepend";

    return $output;
}

But it is not working , whats the correct way to do this, please help
I am using Drupal 7
Thanks
Answer: It looks like you were using JS string concatenation syntax in PHP. Try
drupal_add_js('jQuery(document).ready(function () { jQuery("body").prepend("' . download_list() . '"); });', 'inline');

function download_list(){
    $output = "I am testing my div prepend";

    return $output;
}

prepend one div in body in .inc file


What is the length of AR in the given triangle ABC?

Question: I need your help with a question on triangles. It is from the entrance exam of an institute in India for students in 10th grade.
In the given triangle ABC, if
DP, MQ AR and ES are perpendiculars to BC such that DP = 6 cm, MQ = 4 cm and ES = 8 cm
Then find AR.

The image of the figure
The image of the original question with options

MY ATTEMPT:
I tried to use Pythagoras theorem and tried substituting Pythagorean triplets to find the base.
Then I also tried similarity of triangles △DPC & △MQC and △ESB &△MQB to find the base BC.
I even tried to join AM and then extend it to intersect BC at F so as to use the Menelaus theorem and Ceva theorem. However, that didn't work for me too.
Any help would mean a lot to me.
Comment: Previous question: [Find the length of AR in the given triangle](https://math.stackexchange.com/q/4844706/89922)
Comment: Please provide me with some hints or the method to solve this tricky question. Your help would mean a lot to me.
Comment: It's a multiple choice question; consider a particular case where $B=P=R$ and $BQ = PQ = QS = SC$.
Comment: However @peterwhy it is not mentioned in the question that BQ=PQ=QS=SC. Even if it can be used ,it has to be proved so. If you know how to prove it, please share.
Comment: From the closers' reception of the previous question, I can only suggest (not answer) briefly. A way is to let the ratio $BQ:QC$, then express $BC$ in another way as $BR=RC$. Other users had different methods in the previous question.
Comment: I provided a hint of "Hint: Let $AM$ intersect $BC$ at $F$.  What is $FM / FA$? $\quad$ What have you tried in that regard? You mentioned Menelaus and Ceva's theorem, how have you applied them?
Comment: Yes @Calvin Lin I constructed the line FA and tried to find the ratios but I couldn't find anything useful to find the length AR. If you could provide me with a way to contact you I could send you the pic of my attempt because I can't share pics on comments.
Comment: You should be able to edit your question to show your working (and include pictures). $\quad$ None of us can add pics in comments.
Answer: Like you thought, this is a question about similar triangles, so you should write down whatever ratios you know. You've implied a few of them already, and those are the important ones. You could be really close to a solution, but are just missing one important observation.
Unforuntately, this isn't a question about nice Pythagorean triples like you thought. Pythagorean theorem might be helpful, but it won't be my first choice.
The hint I gave was

Let $AM$ intersect $BC$ at $F$. What is $\frac{ FM}{FA} $?

If we knew the answer to the hint, then using similar triangles, we can obtain $ \frac{FM}{FA} = \frac{ MQ}{AR} = \frac{4}{AR}$. So it remains to find $ \frac{ FM}{FA}$.

Recall the well-known fact

 $$\frac{FM}{FA} + \frac{ EM}{EB} + \frac{DM}{DC} = 1.$$

Hence, conclude that $ \frac{ FM}{FA} = \frac{1}{6} $ and so $AR = 24$.
Note

The well-known fact can be proved using areas.
Given that OP quoted Menelaus and Ceva's Theorem, I believe that they have seen this fact before.
Answer: I am going to solve using a combination of Euclidean Geometry and Analytic Geometry.  Let $Q = (0,0)$ and let $B = (x_1, 0), P=(x_2,0), S = (x_3, 0), C = (x_4, 0)$ then by similar triangles
$ \dfrac{x_4}{ x_4 - x_2 } = \dfrac{2}{3} \tag{1}$
$ \dfrac{ -x_1}{x_3 - x_1} = \dfrac{1}{2} \tag{2}$
Now, let vertex $A = (x, y)$ , then again by similar triangles,
$ \dfrac{x_4 - x_3 }{x_4 - x} = \dfrac{8}{y} \tag{3}$
$ \dfrac{x_2 - x_1}{x  - x_1} = \dfrac{6}{y} \tag{4}$
Taking the reciprocal of the last two equations, and re-arranging,
$ y = \dfrac{8 (x_4 - x)}{x_4 - x_3} = \dfrac{6(x - x_1)}{x_2 - x_1} \tag{5} $
Now looking back at the first two equations, we have
$ 3 x_4 = 2 x_4 - 2 x_2 \tag{6}$
So $x_4 = -2 x_2 \tag{7}$
And we also have
$ - 2 x_1 = x_3 - x_1\tag{8} $
So $ x_1 = - x_3 \tag{9}$
Substituting $(7)$ and $(9)$ into $(5)$, and writing $x_3 $ and $x_4$ in terms of $x_1 $ and $x_2$, gives us
$ y = \dfrac{ 8 (- 2 x_2 - x )}{- 2 x_2 + x_1} = \dfrac{ 6 (x - x_1)}{ x_2 - x_1} \tag{10}$
Solving for $x$ from the right most equation,
$$ 4 (-2 x_2 - x) (x_2 - x_1) = 3 (x - x_1) ( -2 x_2 + x_1) $$
Hence,
$$ x \left( 4 (x_1 - x_2) - 3 (-2 x_2 + x_1) \right) = 8 x_2 (x_2 - x_1) - 3 x_1 (-2 x_2 + x_1) $$
That is,
$$ x \left( x_1 + 2 x_2 \right) = 8 x_2^2 - 8 x_1 x_2 + 6 x_1 x_2 - 3 x_1^2 $$
$$ x \left( x_1 + 2 x_2 \right) = - 3 x_1^2 - 2 x_1 x_2 + 8 x_2^2 = (4x_2 - 3x_1) (2 x_2 + x_1)$$
Therefore,
$$ x = 4 x_2 - 3 x_1 $$
Substitute this in $(10)$
$$ y = 6\dfrac{ x - x_1}{x_2 - x_1} = 6 \left(\dfrac{ 4 (x_2 - x_1) }{x_2 - x_1} \right)= 24 $$
Therefore, $AR = 24$
Comment: Ouch (but I agree that anything works when we're desperate) $\quad$ There's a one-paragraph solution to this.
Comment: This is actually one paragraph.  But it is stretched.
Answer: Menelaus's theorem with line $\stackrel{\longleftrightarrow}{CMD}$ and triangle $\stackrel{\triangle}{ABE}$:
$$\frac{AC}{CE}\frac{EM}{MB}
\frac{BD}{DA}=1$$
$$\frac{AR}{ES}\frac{ES-MQ}{MQ}
\frac{DP}{AR-DP}=1$$
$$\frac x8\frac{8-4}4\frac6{x-6}=1$$
$$\frac{3x}{4x-24}=1$$
$$x=24$$


Active Directory OpenDNS forwarding

Question: I currently have set up my Windows DNS to forward to OpenDNS. However, all traffic in OpenDNS shows up from the IP of my local Windows DNS server. Is there any way I can make the individual devices look to the local DNS and if they don't find what they are looking for look at OpenDNS. This way - OpenDNS would see the devices themselves and not just the Windows DNS Server. Or is there a way to have a public DNS and a private DNS?
All of my devices do not share a single IP - but open DNS is seeing the dns requests coming from our local DNS server which is required for active directory.
Thanks in advance for your help!
Comment: OK, then all of your domain clients should only use your AD DNS server(s) for DNS. Do not configure any alternate DNS servers on any of the domain clients, including the DC. Leave the OpenDNS forwarders in the configuration of the DNS server and leave it at that. Configuring any domain clients to use DNS servers other than your AD DNS server(s) goes against best practice and is asking for problems.
Comment: Is this an AD domain?
Comment: Yes - but it is on a public ip address scheme but is behind a firewall. However - it is not NAT.
Comment: Yeah - the problem I am having though is OpenDNS sees all traffic coming from the AD DNS server. So it is applying the same filter to everyone. I need OpenDNS to realize that the machines are all on separate IP addresses if possible in some way.
Comment: You can't do this.  Also, forwarding to OpenDNS public servers is a bad idea, as they return their own data for non-existent domains by default.  ('NX domain redirection')
Answer: We occasionally get questions about how one can selectively look up DNS domains at the client level, but it's simply not the job of the client to do that. Resolver libraries are dumb by design and expect the upstream recursor to do the heavy lifting for them.

The only way to solve this problem at the client level is for the client itself to operate a DNS server (not necessarily a full one, dnsmasq and the like are common solutions in Unix space), and have the client use 127.0.0.1 for its DNS. This is rarely ever done on Windows servers.
The recursor (Windows DNS) is responsible for preventing leakage to the upstream forwarder (OpenDNS). If the request is for a FQDN managed by AD, that query should not hit OpenDNS. Short names (foo as opposed to foo.example.com) will leak if you have a search suffix defined on the client that is not a domain your AD infrastructure considers itself authoritative for.

If this answer does not satisfy you, please update your question to include the search domains used by the client and an example of a query that is leaking to OpenDNS.
Comment: Do you know if there is a way to have AD DNS forward the request on to OpenDNS so that OpenDNS could see which device the request was coming from?
Comment: @dingerkingh OpenDNS would see the source IP of the server performing the recursion (or more likely the source IP of your outbound NAT address), not the workstation. If I'm not understanding this correctly, I strongly recommend updating your question to include an example of the behavior in question. We may not be using the same terms.

Active Directory OpenDNS forwarding


JdbcTemplate Reading a table with a list of filter values (with AND and LIKE )and returning a list of string

Question: How should I go about creating a Java method that can perform this operation?

        SELECT * FROM test.new_table
        WHERE IDS LIKE "%101G%"
        AND IDS LIKE "%14F%"
        AND IDS LIKE "%701G%"

I realized that my current code is OR operation rather than AND
public List<String> readFileNamesBy(String tableName, String categoryName, List<String> filterValues) {
        String sql = "select * from " + tableName + " where "+ categoryName + " like ?";
        JdbcTemplate jt = new JdbcTemplate(dataSource);

        final List<String> fileNames = new ArrayList<String>();
        for (String filterValue : filterValues){
            jt.query(sql,
                    new Object[] { filterValue },
                    new RowCallbackHandler() {
                        public void processRow(ResultSet rs) throws SQLException {
                            fileNames.add(rs.getString("FILE_NAME"));
                        }});
        }
        return fileNames;
    }

Note that List <String> filterValues could vary in length... so that's why I decided to go with a for loop here.
Btw Idk if it matters but I'm using Java 8 (since that's what this whole program is written) and I can't really do anything about it..
And here is my implementation of the method (fyi)
        List <String> filterValues = Arrays.asList("%101G%", "%14F%");
        List <String> hi = dbUtil.readFileNamesBy("test.new_table","IDS", filterValues);

Answer: It seems you need to build a filter method to take the values input and then construct them as SQL select statement in a dynamic way
suppose that the values that comes from user input is a Map object like this:
    Map<String, String> searchTerms = new HashMap<>();
    searchTerms.put("IDS", "101G");
    searchTerms.put("IDS", "14F");
    searchTerms.put("IDS", "701G");

Then you can generate the SQL query using buildSelectQuery method bellow:
public String buildSelectQuery(Map<String, String> searchTerms, String tableName) {
    StringBuilder sb = new StringBuilder();
    sb.append("SELECT * FROM ").append(tableName).append(" WHERE ");

    for (Map.Entry<String, String> entry : searchTerms.entrySet()) {
        String column = entry.getKey();
        String value = entry.getValue();
        sb.append(column).append(" LIKE '%").append(value).append("%' AND ");
    }

    sb.delete(sb.length() - 5, sb.length()); // Remove the trailing " AND "

    return sb.toString();
}

Finally, you can generate the SQL select query by calling the mentioned method:
    MyQueryBuilder qb = new MyQueryBuilder();
    String query = qb.buildSelectQuery(searchTerms, "test.new_table");

    System.out.println(query);


Is it possible to get result of an operation Speech to Text Recognition by its ID (Python)?

Question: I'm trying to get response of successfully executed long_running_recognize request (speech_v1p1beta1) by its ID.
I know how to get this job done from console by using SDK
gcloud ml speech operations wait <operation ID>

But I can not find any proper way to do this by using Python. All my attempts to solve the problem were with no success so far.
What I'm trying to find out is the way to get a text which is already recognized from a speech by Google Speech to Text API.
Let's imagine that I've already got the ID of that operation. The recognition was done, API returned its ID. A few days later I am going to run a Python script to process that text. What I want is to get the text from API directly within my Python code, without sending request via console.
Something like that
operation_ID = 123456788923 #ID of successfully done recognition
text_raw = operations.get(operation_ID)# just an example, it does not work this way

Any help will be very appreciated.
Answer: You can use two different ways:
The first one is using the Python Client for Cloud Speech API [1], in [2] and if you scroll down you'll find a first example of an implementation of long_running_recognize using this Python Library, in [3] you have another example. Another example is [4] but here they use a simple recognize. I just share it so you have more examples, use the one that works better for you.
I don't know if this is exactly what you need but I hope you'll find the solution here. Also notice that this Client Library is in beta feature currently [5], I haven't tried but it should work.
The second one is using the python subprocess module to call specific bash commands, in [4] you have the official documentation. I use this trick sometimes when something works on a terminal and I don't find a proper implementation in python.
[1] https://googleapis.dev/python/speech/latest/index.html
[2] https://googleapis.dev/python/speech/latest/gapic/v1p1beta1/api.html
[3] https://googleapis.dev/python/speech/latest/index.html#asynchronous-recognition
[4] https://cloud.google.com/speech-to-text/docs/quickstart-client-libraries#make_an_audio_transcription_request
[5] https://cloud.google.com/speech-to-text/docs/release-notes#June_18_2019
[6] https://docs.python.org/2/library/subprocess.html
Comment: Thank you for your willing to help and links you provide with. But none of them contains description of a function to get a result of speech recognition later on by sending a request to API within Python code.
Comment: Sorry, I don't know why I completely misunderstood you. I focused on understand the python library for myself and at the end I lost the root issue...

Does it [1] points what you mean?, I think you can access everything via http request.

[1] https://cloud.google.com/speech-to-text/docs/reference/rest/v1/operations


Good practices when doing time series forecasting

Question: I've been working for months on short-term load forecasting and the use of climate/weather data to improve the accuracy. I have a computer science background and for this reason I'm trying to not make big mistakes and unfair comparisons working with statistics tools like ARIMA models. I'd like to know your opinion about a couple of things:

I'm using both (S)ARIMA and (S)ARIMAX models to investigate the effect of weather data on forecasting, do you think it would be necessary to use also Exponential Smoothing methods?
Having a time series of 300 daily samples I'm starting from the first two weeks and I perform a 5 days-ahead forecast using models built with auto.arima R function (forecast package). Then, I add another sample to my data set and I calibrate again the models and I perform another 5 days forecast and so on until the end of the available data. Do you think this way to operate is correct?

Thank you for your suggestions, although the target of our work is an engineering journal article, I would like to do a work as rigorous as possible from a statistical point of view.
Comment: This question appears to be closely related: http://stats.stackexchange.com/questions/16915/proper-ways-to-perform-time-series-and-arima
Comment: Here's an old answer   http://stats.stackexchange.com/questions/6513/predicting-daily-electricity-load-fitting-time-series/6539#6539
Answer:
I think it would be worth exploring exponential smoothing models as well.  Exponential smoothing models are a fundamentally different class of models from ARIMA models, and may yield different results on your data.
This sounds like a valid approach, and is very similar to the time series cross-validation method proposed by Rob Hyndman.

I would aggregate the cross-validation error from each forecast (exponential smoothing, ARIMA, ARMAX) and then use the overall error to compare the 3 methods.
You may also want to consider a "grid search" for ARIMA parameters, rather than using auto.arima.  In a grid search, you would explore each possible parameter for an arima model, and then select the "best" ones using forecast accuracy.
Comment: @Matteo De Felice: If you're having trouble implementing time-series cross-validation, this blog post might help: http://robjhyndman.com/researchtips/tscvexample/
Comment: @Wart "the non-linear exponential smoothing models have no equivalent ARIMA counterparts. There are also many ARIMA models that have no exponential smoothing counterparts."
Comment: Thank you for the reply, I'm using auto.arima with STEPWISE search disabled and I think that in this way it will explore all the parameters between the min-max range (I haven't read the Hyndman & Kandahar 2008 paper yet)
Comment: @Matteo De Felice: the thing is, it is optimizing those parameters based on AIC.  I was suggesting it might be worth optimizing those parameters by their out-of-sample performance, which you could assess by cross-validation.  Furthermore, if you want to compare other models (such as ETS), you will need an out-of-sample performance metric, as you can't compare AIC between different types of models (such as auto.arima and ets).
Comment: at this moment I performed a grid search (using auto.arima with stepwise = FALSE) and then I tried the most frequent models in order to evaluate their performances.
Comment: It should be noted that ARIMA and ETS models are not fundamentally different.  In fact, linear exponential smoothing models are special cases of ARIMA models.   See here: https://www.otexts.org/fpp/8/10.


print("...") está sendo executado várias vezes

Question: Fiz um programa para verificar se o CPF informado é válido, mas está acontecendo um bug:
Quando digito um CPF válido imediatamente, a mensagem "O Cpf...." é impressa uma vez.
Quando digito um CPF errado e depois digito o válido, a mensagem "O Cpf...." é impressa duas vezes, e assim por diante: o número de vezes que é passado um CPF inválido é o número de vezes extras que é impresso o "O CPF: ....".
Não estou consiguindo entender o porquê disso.
Outra coisa: quando coloco um print() dentro de um while, o print é executado mais vezes do que o while: o while roda 3 vezes e o print é exibido 6 vezes.
Alguém sabe como resolver esse bug?
O código:
import os # Importando o Modulo Os -> Operating Systems

class ValidaCPF:

    CPF = "Vazio"

    def GetCPF(self):

        os.system("cls")

        print("--------Regras-------  ")
        print("| Apenas 11 Digitos |  ")
        print("| Apenas -- Numeros |  ")
        print("|___________________|  ")

        print("\n")

        self.CPF = input("Digite O CPF: ")

        self.Test1()

    def Test1(self):

        os.system("cls")

        if self.CPF.isdigit() != 1 or len(self.CPF) != 11: # ! O CPF INFORMATO CONTEM 11 DIGITOS?

            print("CPF Invalido.")
            os.system("pause")
            self.GetCPF()

        self.Test2()

    def Test2(self):

        Verifica1 = 0
        Contador1 = 0
        Contador2 = 1

        while Contador1 < 9:

            if self.CPF[Contador1] == self.CPF[Contador2]:
                Verifica1 += 1

            Contador1 += 1
            Contador2 += 1

        if Verifica1 >= 8: # CPF COM Padrao -> 220.127.116.11 e etc.. sao Invalidos

            print("CPF Invalido.")
            os.system("pause")
            self.GetCPF()

        self.VerificaDigito1()

    def VerificaDigito1(self):

        Test = 0
        Contador1 = 0
        Contador2 = 10

        while 1:

            Test = Test + (int(self.CPF[Contador1]) * Contador2)

            Contador1 += 1
            Contador2 -= 1

            if Contador2 == 1:
                break

        Test = Test * 10
        Test = Test % 11

        if Test == 10:
            Test = 0

        if Test != int(self.CPF[9]):

            print("CPF Invalido.")
            os.system("pause")
            self.GetCPF()

        self.VerificaDigito2()

    def VerificaDigito2(self):

        Test = 0
        Contador1 = 0
        Contador2 = 11

        while 1:

            Test = Test + (int(self.CPF[Contador1]) * Contador2)

            Contador1 += 1
            Contador2 -= 1

            if Contador2 == 1:
                break

        Test = Test * 10
        Test = Test % 11

        if Test != int(self.CPF[10]):

            print("CPF Invalido.")
            os.system("pause")
            self.GetCPF()

        print("O CPF: ", self.CPF, "E Valido.")

       Sistema = ValidaCPF() # <--- Error de indentação A partir daqui

       Sistema.GetCPF()      # <--- Retirar a Tabulação

       os.system("pause")    # <--- ....

Answer: Vamos ver se consigo lhe ajudar. Começando dividindo a dúvida em duas:
1 - Quando digito um CPF errado e depois digito o válido, a mensagem "O Cpf...." é impressa duas vezes [...] .
  if Verifica1 >= 8: # CPF COM Padrao -> 184.108.40.206 e etc.. sao Invalidos

        print("CPF Invalido.")
        os.system("pause")
        self.GetCPF()
        sys.exit(0) <== Pelo que pesquisei, isso deve resolver

Quando você informa que o CPF é inválido e chama a funçaõ "getCPF" novamente, você não PARA a execução do primeira "validação do CPF". Após esse getCPF, procure dar um "parar" na execuçaõ. Por que analisando o código, ele está após processar o "self.getCPF()" continuando a execuçaõ, ou seja, indo para o "self.verificaDigito1()".
2 - A dúvida 2 tem relação com o "bug" da primeira. Quando ocorre a digitação de um CPF inválido, ele não PARA a execução.
Vou tentar deixar mais claro mostrando a execução abaixo:
Considere que eu digitei um CPF inválido inicialmente:
    if Verifica1 >= 8: # CPF COM Padrao -> 22.214.171.124 e etc.. sao Invalidos

        print("CPF Invalido.") <== Da o alerta
        os.system("pause")
        self.GetCPF() <=== Pede o novo CPF !!

    self.VerificaDigito1() <== Mesmo eu digitando o CPF inválido, ele irá executar essa função depois de processar todo o "self.getCpf"

Comment: Vlw =) Coloquei um else depois de cada If resolveu
Comment: Que bom Vitor!! Fico feliz em ajudar.


How do I call .lower on a class object?

Question: I have a class I've called Earthquake, and it has a location as a string, and a few other parts that aren't important to this question (I don't think).
I've written a function (filter_by_place) that iterates through a list of Earthquakes that I've passed it, and looks for a given word in each Earthquake location string. If the word is found in the Earthquake's location, then it adds that Earthquake to a list. My problem is that it cannot be case sensitive, and I'm trying to make it that way by looking for an all lowercase word in an all lowercase version of the location string.
def filter_by_place(quakes, word):
   lst = []
   for quake in quakes:
      if word.lower in (quake.place).lower:
      lst.append(quake)
   return lst

I get an error saying "TypeError: argument of type 'builtin_function_or_method' is not itterable"
So, my question is: How do I get that string within the class to become lowercase just for this function so I can search for the word without worrying about case sensitivity?
I've already tried adding
if word.lower or word.upper in quake.place:

inside the for loop, but that didn't work, and I can understand why. Help?
Answer: You're getting the error because you're not actually calling the lower string function. I am guessing you're coming from ruby where this wouldn't be required.
Try:
def filter_by_place(quakes, word):
   lst = []
   for quake in quakes:
      if word.lower() in quake.place.lower():
         lst.append(quake)
   return lst

Comment: Thank you! That fixed it
Answer: You need to do word.lower(). You're missing the brackets. Happens all the time :)
Try this
def filter_by_place(quakes, word):
    lst = []
    for quake in quakes:
        if word.lower() in quake.place.lower():
            lst.append(quake)
    return lst

Because you're using python, you might want to take a look at list comprehensions. You're code would then look something like this
def filter_by_place(quakes, place):
    return [quake for quake in quakes if quakes.place.lower() is place]

Comment: Thank you! That is a much more graceful way of doing it. I appreciate the help :)

How do I call .lower on a class object?


Gulp webserver, What is the filter?

Question: I'm following a tutorial series, And I'm familiar with the principles of Gulp but

I can't seem to find what the Filter function does in the following example

The example is also shown here, but no further explanation is provided
https://github.com/hiddentao/gulp-server-livereload#how-can-i-pass-a-custom-filter-to-livereload
This is the code.
gulp.task('serve', function(done) {
  gulp.src('')
    .pipe(server({
      livereload: {
        enable: true,
        filter: function(filePath, cb) {
          if(/main.js/.test(filePath)) {
            cb(true)
          } else if(/style.css/.test(filePath)){
            cb(true)
          }
        }
      },
      open: true
    }));
});

Answer: Short answer:
The filter gives you the ability to exclude files in your project directory that my change (e.g. git files), but your server does not autmatically reloads. You may define arbitrary logic in this function.
Longer answer:
The filter defines a function that gets the filePath of the file that changed and the predefined callback function cb that triggers a reload:
function (shouldReload) {
  if (shouldReload) {
    gutil.log('Livereload: file changed: ' + filename);

    config.livereload.io.sockets.emit('reload');
    // Treat changes to sourcemaps as changes to the original files.
    filename = filename.replace(/\.map$/, '');

    config.livereload.io.sockets.emit('file_changed', {
      path: filename,
      name: path.basename(filename),
      ext: path.extname(filename),
    });
  }
}

That means if you call cb(true) a live reload of your server is done.
As I read your example you want to reload your server only if the files main.js and style.css are changed. Therefore escape the . by \. which might match any character (see regex):
if(/main\.js/.test(filePath)) {
  cb(true)
} else if(/style\.css/.test(filePath)){
  cb(true)
}

That means execute this task. Saving and changing either main.js or style.css will trigger a live reload of the server.
My server gets stuck sometimes and does not reload. Pressing one time CTRL+C helps getting him back to work ;-)

Gulp webserver, What is the filter?


How to let an OG administrator contact (via email) all group members?

Question: I've a request to set up an email form where by a OG administrator can send a message (via email) to all persons subscribed to that group.
I've seen a few modules OG Contact, OG Notify, and Organic Groups Email, but these seem out of date.
Answer: This question have been answer at -  How to loop over a list of Organic Group users using Rules
and at - How to send an email to Drupal 7 Organic Groups Role Members? in here is going to show you how to do it with a custom module.
There other alternatives:
1- You can use views_bulk_operations

I would think you should be able to do it by adding views_bulk_operations to the mix-- that should give you the ability to email users in a view which you can setup with the criteria you need via filtering.

Source
2- You can do it with Rules

Looping over a list can only be done in Rules (i.e. for Drupal 7).

Source
Answer: I would have thought that Rules would be your best option
Answer: Using the Forena module, you could start from one of the Sample reports and solutions that come with it. I.e. the Active Users Email, which is a demo of the ability to send email to all active users of a Drupal site.
The idea is that those users who have access to it, actually get a FORM to have Drupal send an eMail to all users selected via the query. To do so, you just have to "submit the report".
The easiest way to see the out-of-the-box example at work, is to (temporary) install the module in some dev environment you have available (for obvious reasons this sample report is NOT available to anonymous users in a Forena demo site ...).
Here is what would be needed to transform (clone) this sample to fit your needs:

Adapt its data block (an SQL query) to list "all persons subscribed to an organic group" (instead of all "active users of a Drupal site").
Adapt the actual content of the delivered eMail template to fit the actual eMail content (message).
Optionally you may want to make the "Organic group" to be selected a report parameter.
Secure "access" so that only the OG administrator can send such eMails. Depending on how your OG group(s) security is setup, you may want to adapt the Forena permissions accordingly.

Note: the above approach can be used for all sorts of eMails towards any set of users of a Drupal site. Whereas that "set of users" is just a matter of writing some (basic) SQL statement to select the users you want to target. E.g: (a) users with a selected role or (b) users who didn't login for X days anymore or ... And the actual eMail content (message to be delivered) is actually anything you can format as an XHTML document.
Disclosure: I'm a co-maintainer of the Forena module.
Answer: I think that module og_mailinglist will help you with the most functionality you need But still you have to do some customization.
First: It lets any member to send mail to all group users, And in your case you need only the group admin so I see you need to create a custom menu item with access checking for group admins only which navigates the admin to where he will send the module.
Second: reply to the email will create content which is not needed and considered a security risk you have to take care and prevent that functionality
Finally: Read the module documentation carefully and check its API well to achieve you goal with the optimal way.
Also message_notify deserves to give it a try But I think it may need extra configuration and customization.
Answer: If you aren't willing to use those OG specific modules, I'd suggest using an entity form with entity reference prepopulate to make it cleaner.

Create an entity form with the required fields such as email title and body.
Add an entity reference field with prepopulate (and hide) enabled.
Construct a url that fills the entity reference field with the group nid using tokens.

Using rules on entity form save, you can then loop through the subscribed members to the group referenced in the entity form and construct your email using the entity form fields.
Some benefits to using the above as a base method..

You can load the entity form inside a colorbox to give a very nice
UI.
You can add extra fields as needed.
You can get a bit fancier and make the email get sent to users from certain roles etc.


Stongswan and Libreswan in Centos

Question: I have a server running stongswan with one VPN connection.
Can I add another VPN connection Via Libreswan on the same server?
So the server will run both Strongswan and Libreswan.
Regards,
Michael
Comment: What's the reason you want to mix IKE implementations?
Comment: No, but you can have Strongswan handle both connections.
Answer: Generally not. First, IKE uses fixed UDP ports (500/4500) that both IKE daemons will want to bind their sockets to. Second, both IKE daemons will assume full control over the kernel's IPsec stack so there is a high chance for conflicts (e.g. duplicate reqids or policies).
You might be able to work around those issues (e.g. assign different ports, use static reqids, use network namespaces, or even use strongSwan's userland IPsec implementation), but you can probably avoid some headaches by sticking to one IKE implementation.

Stongswan and Libreswan in Centos


LDAP module and AD global catalog

Question: Does anybody successfully authenticate against AD global catalog? I've got the following configuration:

LDAP server:
ldaps://service.mydomain.com
LDAP port:
3269
Binding Method:
Service Account Bind
Base DNs for LDAP users:
DC=service,DC=mydomain,DC=com
DC=otherdomain,DC=mydomain,DC=com
AuthName attribute:
userPrincipalName

The module successfully authenticates users, which are members of parent domain called "service", but LDAP search can't find any user from "otherdomain", which is connected to parent domain inside AD domain forest. I´m able to test LDAP search using ldp.exe and using this tool I can find any user from any domain.
Also, there is the following error message in the Drupal watchdog:

ldap_search() function error. LDAP Error: Referral, ldap_search() parameters: ldap_search() call: base_dn: DC=otherdomain,DC=mydomain,DC=com, filter = (email@example.com), attributes: , attrsonly = 0, sizelimit = 0, timelimit = 0, deref = , scope = 3

Any help will be greatly appreciated.
Answer: I know it's been over half a year so you may have already found the answer to this, but I thought I would weigh in as it is a process that I am working on myself.
For the Base DN, consider simply using DC=mydomain,DC=com.  I have not had to do this yet, so it was just a thought from their suggestion of using a higher Base DN.
I had problems authenticating until I made sure of these items:

AuthName attribute and AccountName attribute set to: sAMAccountName,
PUID set to: objectGuid
then check the box with the question "Does PUID hold a binary value?

After that, authentication went perfectly.  Good luck!

LDAP module and AD global catalog


Closed form of $\int_{0}^{1} \frac{\log(1+x)\log(2+x) \log(3+x)}{1+x}\,dx$

Question: In https://math.stackexchange.com/a/3414337/198592 I have mentioned some integrals which I could not solve.
One of them is
$$i_{1}=\int_{0}^{1} \frac{\log(1+x)\log(2+x)\log(3+x)}{1+x}\,dx \simeq 0.295123\tag{1}$$
I have tried several approaches like partial integration and series expansion but with no avail.
The substiution
$$\log(x) = \int_0^{\infty } \frac{e^{-t}-e^{-t\; x}}{t} \, dt\tag{2}$$
did allow doing the $x$-integral but already the first integration of the triple integral failed.
Interestingly, with "one $\log$ less" or without the denominator $1+x$ the integration leads to a closed expression.
Problem: find a closed expression for $i_1$ or, equivalently, for
$$i_{1s}=\int_{0}^{1} \frac{\log(1+x)\log(1+\frac{x}{2})\log(1+\frac{x}{3})}{1+x}\,dx \simeq 0.0130713\tag{3}$$
Answer: The process flows elegantly if we simply make use of the variable change $x\mapsto (1-x)/(1+x)$. I'll develop it.
So, we have that
$$\int_0^1\frac{\log(1+x)\log(2+x)\log(3+x)}{1+x}\textrm{d}x$$
$$=\frac{1}{2}\log^2(2)\int_0^1 \frac{\log(3+x)}{1+x}\textrm{d}x-\frac{1}{2}\log^2(2)\int_0^1 \frac{\log(1+x)}{1+x}\textrm{d}x+\log(2)\int_0^1 \frac{\log^2(1+x)}{1+x}\textrm{d}x$$
$$-\frac{1}{2}\int_0^1\frac{\log^3(1+x)}{1+x}\textrm{d}x-\frac{\log(2)}{2}\int_0^1 \frac{\log(1+x)\log(2+x)}{1+x}\textrm{d}x$$
$$+\frac{\log(2)}{2}\int_0^1 \frac{\log(2+x)\log(3+x)}{1+x}\textrm{d}x-\log(2)\int_0^1 \frac{\log(1+x)\log(3+x)}{1+x}\textrm{d}x$$
$$+\frac{1}{2}\int_0^1 \frac{\log^2(1+x)\log(2+x)}{1+x}\textrm{d}x+\frac{1}{2}\int_0^1 \frac{\log^2(1+x)\log(3+x)}{1+x}\textrm{d}x.$$
What's next? We look at these integral with a trained eye and see all are reducible immediately to known, trivial integrals (mainly with integration by parts and usual knowledge of polylogarithms).
End of story.
Answer: Approach 1: Series expansion
Having studied approach 2 in more detail I found that it corresponds just to a direct series expansion of the integrand of the integral.
Using
$$\frac{\log(1+x)}{1+x} = \sum _{i=1}^{\infty } (-1)^{i+1} H_i x^i$$
where
$$H_i = \sum _{n=1}^i \frac{1}{n}$$
is the harmonic number, and
$$\log \left(1+\frac{x}{2}\right)=\sum _{j=1}^{\infty } \frac{(-1)^{j+1} 2^{-j} x^j}{j}$$
and
$$\log \left(1+\frac{x}{3}\right)= \sum _{k=1}^{\infty } \frac{(-1)^{k+1} 3^{-k} x^k}{k}$$
we can write the integrand of $i_{1s}$ as
$$\frac{\log(1+x)\log(1+\frac{x}{2})\log(1+\frac{x}{3})}{1+x}=\sum_{m=1}^{\infty} (-1)^{m+1} c(m) x^m$$
where the coefficients are defined as
$$c(m)=\sum _{i=1}^{\infty} \sum _{j=1}^{\infty} \sum _{k=1}^{\infty} \frac{ H_i}{ 2^{j}\;j\;3^{k}\; k} \delta _{m,i+j+k}$$
Here $\delta _{n,m}$ is Kronecker's delta ($=1$ if $n=m$, $= 0$ else).
Notice that the triple sum consists effectively only of $\left\lceil \frac{1}{2} (m-3) \left(m+\frac{1}{2}-3\right)\right\rceil$ summands.
Writing $c(m) = p(m)/q(m)$ as an irreducible fraction we have for the first few terms
$$\{p\}_{m=1}^{m=10}=\{0,0,0,1,23,283,2725,46261,1821713,4554217\}$$
$$\{q\}_{m=1}^{m=10} = \{1,1,1,6,72,648,5184,77760,2799360,6531840\}$$
none of which is contained in https://oeis.org/.
The integral itself is then given by
$$i_{1s} = \sum_{m=1}^{\infty} \frac{c(m)}{m+1}$$
The coefficients look suffciently complicated so that a closed expression seems to be out of reach.
However, still complicated looking cases do have closed expressions, as for instance
$$\int_0^1 \frac{\log (x+1) \log \left(\frac{x}{2}+1\right)}{x+1} \, dx=\operatorname{Li}_3(-2)-\operatorname{Li}_2(-2) \log (2)+\frac{3 \zeta (3)}{4}-\frac{1}{2} \log ^3(2)$$
Hence we don't give up but consider this sequence of integrals
$$i(k) = (-1)^{k+1} \int_0^1 \frac{x^k \log (x+1) \log \left(\frac{x}{2}+1\right)}{x+1} \, dx$$
from which we find the integral by forming the series of $\log(1+x/3)$ thus
$$i_{1s} = \sum_{k=1}^{\infty} \frac{ i(k)}{k \;3^k}$$
We have
$$i(1) = -\operatorname{Li}_2\left(-\frac{1}{2}\right)-\operatorname{Li}_3\left(-\frac{1}{2}\right)-\operatorname{Li}_2\left(-\frac{1}{2}\right) \log (2)-\frac{3 \zeta (3)}{4}-\frac{\pi ^2}{12}+2+\frac{1}{6}\log ^3(2)\\-\frac{5 \log ^2(2)}{2}+3 \log (3) \log (2)-\log \left(\frac{27}{2}\right)$$
$$i(2) = -\frac{5 \operatorname{Li}_2\left(-\frac{1}{2}\right)}{2}-\operatorname{Li}_3\left(-\frac{1}{2}\right)-\operatorname{Li}_2\left(-\frac{1}{2}\right) \log (2)-\frac{3 \zeta (3)}{4}-\frac{5 \pi ^2}{24}+4+\frac{1}{6} \log ^3(2)\\-\frac{5 \log ^2(2)}{4}+\frac{9}{2} \log (3) \log (2)+\frac{5 \log (2)}{4}-\frac{21 \log (3)}{4}-\frac{1}{12} \log (8) \log (256)$$
$$i(3) = -\frac{29 \operatorname{Li}_2\left(-\frac{1}{2}\right)}{6}-\operatorname{Li}_3\left(-\frac{1}{2}\right)-\operatorname{Li}_2\left(-\frac{1}{2}\right) \log (2)-\frac{3 \zeta (3)}{4}-\frac{29 \pi ^2}{72}+\frac{707}{108}+\frac{1}{6}\log ^3(2)\\-\frac{61 \log ^2(2)}{12}+\frac{15}{2} \log (3) \log (2)+\frac{31 \log (2)}{36}-\frac{31 \log (3)}{4}$$
$$i(4) =-\frac{103 \operatorname{Li}_2\left(-\frac{1}{2}\right)}{12}-\operatorname{Li}_3\left(-\frac{1}{2}\right)-\operatorname{Li}_2\left(-\frac{1}{2}\right) \log (2)-\frac{3 \zeta (3)}{4}-\frac{103 \pi ^2}{144}+\frac{2179}{216}-\frac{1}{6} \log ^3(2)\\-\frac{167 \log ^2(2)}{24}+\frac{45}{4} \log (3) \log (2)-\frac{95 \log (2)}{144}-\frac{169 \log (3)}{16}$$
It seems that the expressions have the form
$$i(k) = a_{1,k} + a_{2,k}\;\pi^2 + a_{3,k}\; \log (2)+ a_{4,k}\;\log ^2(2)+\\+ a_{5,k}\;\log (3)+ a_{6,k}\;\log (2)\log (3)+a_{7,k} \operatorname{Li}_2\left(-\frac{1}{2}\right)\\ + \left(\frac{1}{6} \log ^3(2)- \operatorname{Li}_3\left(-\frac{1}{2}\right)-\operatorname{Li}_2\left(-\frac{1}{2}\right) \log (2)-\frac{3 \zeta (3)}{4}\right)$$
where the $a_{i,k}$ are rational numbers.
Approach 2: Generating function (original post)
A few minutes after having posted the problem I took up a thread I had considered earlier, and it gives a formal solution in terms of derivatives of known (but not particularly common) functions.
The trick is to generate the $\log$ and the power by
$$\frac{\partial x^a}{\partial a}=x^a \log (x)$$
Consider the function
$$g(x,a,b,c) = (x+1)^a (x+2)^b (x+3)^c\tag{1}$$
from which we can generate the integrand
$$\frac{\log (x+1) \log (x+2) \log (x+3)}{x+1}\tag{2}$$
by a triple derivative and appropriate replacement of the parameters $a,b,c$ as follows
$$\frac{\partial ^3\left((x+1)^a (x+2)^b (x+3)^c\right)}{\partial a\, \partial b\, \partial c}\text{/.}\, \{a\to -1,b\to 0,c\to 0\}\tag{3}$$
Interchanging the order of operations and doing the $x$-integral first we get
$$G(a,b,c) = \int_{0}^{1} g(x,a,b,c)\,dx \\= \frac{2^c}{a+1} \left(2^{a+1} F_1(a+1;-b,-c;a+2;-2,-1)\\-F_1\left(a+1;-b,-c;a+2;-1,-\frac{1}{2}\right)\right)\tag{4}$$
Here
$$F_1(r;s,t;u;x,y)=\sum_{m,n=0}^{\infty} \frac{(r)_{m+n} (s)_{m} (t)_{n}}{(u)_{m+n}}\frac{x^m}{m!} \frac{y^n}{n!}\tag{5}$$
with the notation $(r)_n=\frac{\Gamma (n+r)}{\Gamma (r)}$ is the AppellF1 function which belongs to the class of the hypergeometric functions (http://mathworld.wolfram.com/AppellHypergeometricFunction.html).
The reference also provides an representation as a single integral
$$F_1(r;s,t;u;x,y)=\frac{\Gamma (u)}{\Gamma (r) \Gamma (u-r)} \int_0^1 z^{r-1} (1-z)^{-r+u-1} (1-x z)^{-s} (1-y z)^{-t} \, dz\tag{5a}$$
Hence we have the formal solution
$$i_{1}=\frac{\partial ^3 G(a,b,c)}{\partial a\, \partial b\, \partial c}\text{/.}\, \{a\to -1,b\to 0,c\to 0\}\tag{6}$$
The first steps in trying to evaluate $(6)$ do not support hope for a simple final expression. It seems that we will have replaced a nice integral by a more or less ugly double sum. But let's see ...
Answer: We have seen a great elegantly flowing answer of user97357329 (https://math.stackexchange.com/a/3522251/198592), the main step of which consisted in the substitution $x\to\frac{1-t}{1+t}$.
The next steps have been sketched very briefly in the answer, so that I take the freedom to elaborate a bit more and, in the end, provide the explit closed form  of our integral.
The transformation has the nice property (which can't be seen in the exposition of that user) that after expanding the resulting logs in the integrand we get one term that is the exact negative of the original term, and all other terms are simpler.
The transformation gives (with $dx\to- 2dt/(t+1)^2$)
$$i_{1}=\int_0^1 \frac{\log (x+1) \log (x+2) \log (x+3))}{x+1}\,dx\to\int_0^1 \frac{\log \left(\frac{2}{t+1}\right) \log \left(\frac{2 (t+2)}{t+1}\right) \log \left(\frac{t+3}{t+1}\right)}{t+1}\,dt$$
Expanding the logs in the integrand yields this list of terms
$$\left\{-\frac{\log ^2(2) \log (t+1)}{t+1},\frac{2 \log (2) \log ^2(t+1)}{t+1},-\frac{\log ^3(t+1)}{t+1},-\frac{\log (2) \log (t+1) \log (t+2)}{t+1},\frac{\log ^2(t+1) \log (t+2)}{t+1},\frac{\log ^2(2) \log (t+3)}{t+1},-\frac{2 \log (2) \log (t+1) \log (t+3)}{t+1},\frac{\log ^2(t+1) \log (t+3)}{t+1},\frac{\log (2) \log (t+2) \log (t+3)}{t+1},-\frac{\log (t+1) \log (t+2) \log (t+3)}{t+1}\right\}$$
We see that the last term is exactly the opposite of the original integrand, so that the complicated part drops out (move it to the l.h.s. and get twice the original expression).
The remaining integrals are in fact easy to solve. Using Mathematica we get some terms in the complex domain which, however compensate when we use the relations
$$\operatorname{Li}_2\left(\frac{3}{2}\right)= -\operatorname{Li}_2\left(-\frac{1}{2}\right)+\frac{\pi ^2}{6}+\log (2) \log \left(\frac{3}{2}\right)-i \pi  \log \left(\frac{3}{2}\right)$$
$$\operatorname{Li}_2(2)= \frac{\pi ^2}{6}+\frac{\pi ^2}{12}-i \pi  \log (2)$$
The final result then becomes (I'm busy simplifying this)
$$i_{1} = -\operatorname{Li}_4(-2)+\operatorname{Li}_4\left(-\frac{1}{2}\right)-\frac{1}{2} \operatorname{Li}_2\left(\frac{1}{3}\right) \log ^2(2)-2 \operatorname{Li}_2\left(\frac{2}{3}\right) \log ^2(2)+\frac{1}{4} \operatorname{Li}_2\left(\frac{1}{4}\right) \log ^2(2)-\frac{1}{2} \operatorname{Li}_2\left(\frac{1}{3}\right) \log (3) \log (2)+\frac{1}{2} \operatorname{Li}_2\left(\frac{2}{3}\right) \log (27) \log (2)-\frac{1}{2} \operatorname{Li}_2\left(\frac{3}{4}\right) \log (8) \log (2)+\frac{1}{2} \operatorname{Li}_2\left(\frac{3}{4}\right) \log (9) \log (2)-\frac{1}{2} \operatorname{Li}_3(-2) \log (2)-\frac{1}{2} \text{Li}_3\left(\frac{1}{3}\right) \log (2)+\frac{3}{2} \operatorname{Li}_3\left(\frac{2}{3}\right) \log (2)+\frac{1}{4} \operatorname{Li}_3\left(\frac{1}{4}\right) \log (2)-\operatorname{Li}_3\left(\frac{3}{4}\right) \log (2)+\frac{1}{2} \operatorname{Li}_3(-2) \log (4)-\frac{1}{2} \zeta (3) \log (2)-\frac{3}{8} \zeta (3) \log (4)-\frac{1}{24} 35 \log ^4(2)+\frac{5}{2} \log (3) \log ^3(2)+\frac{1}{3} \log ^3(3) \log (2)+\frac{1}{2} \zeta(2) \log ^2(2)-2 \log ^2(3) \log ^2(2)+\frac{1}{6} \log (3) \log (64) \log ^2(2)$$
This is a linear combination of the components $\log(2)$, $\log(3)$, $\zeta(2)$, $\zeta(3)$, $\operatorname{Li}_{2,3,4}$. Notice that there is no $\pi$ or (Euler)-$\gamma$ appearing.
Comment: the value can be non-trivially simplified, which in a sense best possible: $$-2 \text{Li}_4\left(\frac{1}{2}\right)+\frac{\text{Li}_4\left(\frac{1}{4}\right)}{4}+\text{Li}_2\left(\frac{1}{4}\right) \log ^2(2)+\text{Li}_3\left(\frac{1}{4}\right) \log (2)-\frac{49}{24} \zeta (3) \log (2)+\frac{7 \pi ^4}{360}+\frac{3 \log ^4(2)}{4}+\frac{1}{8} \pi ^2 \log ^2(2)$$
Answer: Not an answer but too long for a comment.
For the fun of it, I used Taylor expansion to $O(x^{n+1})$. Below are some numbers wich show a very slow convergence
$$\left(
\begin{array}{cc}
 n & \text{result} \\
 100 & \color{red} {0.295}088992683718 \\
 200 & \color{red} {0.2951}14319823039 \\
 300 & \color{red} {0.2951}19066043094 \\
 400 & \color{red} {0.29512}0734361895 \\
 500 & \color{red} {0.29512}1508301534 \\
 600 & \color{red} {0.29512}1929303681 \\
 700 & \color{red} {0.295122}183398346 \\
 800 & \color{red} {0.295122}348430736 \\
 900 & \color{red} {0.295122}461636524
\end{array}
\right)$$


How to access one usercontrol to another control using c#?

Question: I have two user controller test1.ascx & test2.ascx. How to access test1.ascx within test2.ascx.
Example:
test1.ascx.cs
I have follwing method:
Public string test()
{
   return "Welcome to user control 1";
}

In test2.axcs.cs
public void Page_Load(object obj, sender e)
    {
       test1();
    }

public string test1()
   {
        return "Welcome to user control 2";
   }

I would like to access second user control(test2.ascx.cs) within test1.ascx.cs.
Please help me to solve.
Comment: How I can call call test2.ascx page_load event from my test1.ascx. In my parent page is abc.aspx. So, I registered test1.ascx in my abc.aspx parent page.
Answer: You can register test2.ascx in test1.ascx
test1.ascx
<%@ Register Src="test2.ascx" TagName="Temp2" TagPrefix="uc2" %>
<uc2:Temp2 ID="Temp21" runat="server" />

test1.ascx.cs
Public string test()
{
   return Temp21.test1; // The output will be "Welcome to user control 2"
}

Comment: if it's possible to call test2.ascx.cs page_load event within test1.ascx.cs.
Comment: I don't think it's a good idea. How about you encapsulate it within one public method and call it through test1.ascx.cs . I think Microsoft set that rules (Page_Load to be protected) with something in mind.
Comment: else if it's possbile to refresh test2.ascx user control within test1.ascx.
Comment: Because I have one telerik:listbbox in test2.ascx. In test1.ascx while click save button i have to refresh test2.ascx listbox and reload the listbox items only without reload entire page.
Comment: I said before, if it is public method, you can call it from any ascx (if those ascxs or it's derived class in one page) Just call method to refresh your telerik list(in test2) and call in on save button click in (test1) like I post before.


How do I clean my harmonica without taking it apart?

Question: I have seen many videos on "how to clean harmonicas", but in all of them, you have to take the harmonica apart, clean it and reassemble it.
The thing is there's no marine band harmonica in my country. I bought it from the US on Amazon and I can't afford to take it apart. If something bad happens while taking it apart and putting it back together, I can't order another one easily. Besides, when you take the harmonica apart, you might have to retune it, and I don't know how to do that. Again, I can't afford to take the risk.
So is there any way to clean the harmonica without taking it apart, and without damaging the holes or changing the tune? I used to clean my Chinese haps with alcohol or water, but I don't know if it's the right way to do it for this one.
EDIT
Would putting some water or alcohol in every hole and then drying it with a hairdryer work? The hairdryer would remove the moisture from the water or alcohol.
Answer: I think it depends if you want to have it as an "active instrument" and play with it, or just keep it as a nice harmonica for memory/collection.
I play in one of my projects with Filip Jers. He was sponsored by Hering harmonicas and now Suzuki harmonicas, and he tunes his harmonicas every other show. To clean his harmonicas he opens it, cleans the reeds, scratches them to fix tuning, oils it and then puts it back together. He is a world class player and is very careful with tuning/performance of the instrument. I've seen him open/close harmonicas a lot and they don't get broken.
If you want to have the marine band harmonica as an active instrument, I would not be afraid of it, it's more complex with a chromatic harmonica. Just open it, blow on its reeds and clean what you see as dirty.
(This does not answer your question in the way that you ask "how to clean without taking them apart", still it's the experience/knowledge I would like to share with you)
Comment: +1 Fully agree. Harmonicas are really simple. Taking it apart to clean is easy and necessary.
Comment: the marine band is my active instrument and the thing is, i don't want to mess with the tuning, i don't know how to retunne, it's not like the guitar, you can't use a metronome right? you have to use your ear and i'm not trained enough to know the right tune for each hole, i don't know flip jers, but he seems very professional, he could retune his harp blindfolded, i can't.
Comment: @Fischer taking it apart, cleaning, reassembling will not affect the tuning.
Comment: @Fischer, (like slim also wrote) opening does not affect tuning. But not cleaning does actually, the reeds gets dirty with time and using and get lower in pitch, so opening and cleaning is recommendable. If you want to train tuning them then it's better to buy more common harmonicas and try on them. You can find videos on youtube with tips on that.
Comment: @slim [see this](https://www.youtube.com/watch?v=E3RwSiMEQvg) see the end of the video
Comment: @Sergio please watch the video in my previous comment to understand why i'm worried so much
Comment: @sergio watched the whole video. I don't see why you're worried. There is no risk to the tuning in anything he does.
Comment: @sergio Oh, he does mention a tuning issue at the end. That's not related to the cleaning he's just done.
Comment: @slim, I supose you ment Fischer in your comment :)
Comment: @Fischer, harmonica gets dirty by playing. Cleaning is a part of the routine of a professional player. I would say you should get familiar with tunning so you feel you have control over the instrument´s health. Cleaning a harmonica can untune it? yes. Not cleaning can untune it? yes. Cleaning without opening is cleaning? no. (this is my opinion as I said from touring with 2005´s harmonica world champion).
Comment: one last question. how often should it be cleaned? i play usually like 2h a day, maybe less because i'm busy these days but lets say 2h per day, how often should it be cleaned?
Answer: Don't take apart a marine band. They're put together with nails, not screws. After playing take a dry soft cloth and carefully dry it then let it air dry. Don't close it up in the box. Mine only gets closed in the box if I'm transporting it to a gig. I use the box at home to store it in always opened as sort of a cradle plus it's easier to find. Personally I wouldn't use any type of liquid on it. If you play enough for it to become that dirty it's likely that it's out of tune and time to replace it.
Answer: Take your favorite mug fill with about two thirds tepid water from the kettle and about one third vinegar - place your harp in the solution for twenty to thirty minutes - rinse thoroughly with clean tepid water - tap out both sides onto the palm of your hand - your harp will look and sound bright!
Don't use oil; it attracts dirt, dust and fluff.
Answer: Us peroxide for 3 min in a cup full of peroxide,  rinse with water,  tape it in your hand,  to take as much water out,  put it in a front of  fan to dry.


Rate content by the author's role

Question: I want a five-star content rating system, for example:
if a premium user creates a content this will be rated with five starts, if a simple user creates a content this will be rated with three starts etc. I dont wont users to rate the conten.
Is something like this possible ???
Comment: Erm, maybe not my place to say, but misleading your users into thinking one piece of content is better than another simply because it's been _paid_ for is not a good thing to do.
Comment: Maybe you are right, but this is the project's scenario.
Answer: I'll assume your using Drupal 7, you want to look into hook_node_update() this will allow you to run code whenever a node is saved/created.
From there you'll have full access to the node object in which you can use user_load() to grab the user object and check it's roles. Then you need to add logic based on the role to modify the nodes fivestar rating.
Comment: Yes your hooks and logic will have to go in a custom module. A good place to start is - https://drupal.org/developing/modules
Comment: I should create a custom module ??

Rate content by the author's role


Example of the five-lemma -- hatcher exercise 2.1.31

Question: So the five lemma asserts if we have the following commutative diagram
$$
\begin{array}{ccccccccc}
A & ^{i}\longrightarrow & B & ^{j}\longrightarrow & C & ^{k}\longrightarrow & D & ^{\ell}\longrightarrow & E \\
\downarrow_{\alpha} & \phantom{{i}\longrightarrow} & \downarrow_{\beta} & \phantom{^{j}\longrightarrow} & \downarrow_{\gamma} & \phantom{^{k}\longrightarrow}& \downarrow_{\delta} & \phantom{^{\ell}\longrightarrow E} & \downarrow_{\epsilon}\\
A' & ^{i'}\longrightarrow & B' & ^{j'}\longrightarrow & C' & ^{k'}\longrightarrow & D' & ^{\ell'}\longrightarrow & E' \\
\end{array}
$$
and the two rows are exact and $\alpha$, $\beta$, $\delta$, and $\epsilon$ are isomorphisms, then $\gamma$ is an isomorphism also.
I am trying to complete exercise 2.1.31 in Hatcher's Algebraic Topology which asks to give an example where $\alpha$, $\beta$, $\delta$, and $\epsilon$ are zero but $\gamma$ is nonzero. The text also offers a hint that this can be done by finding short exact sequences where all groups are 0 or $\mathbb{Z}$. I am having a hard time seeing how this could be true, so I want to clarify a few things.
If I want to make the top (or bottom) row a short exact sequence, then do I need to impose that A and E (or A' and E') equal to 0?
Also when they say $\alpha$, $\beta$, $\delta$, and $\epsilon$ are zero, does they mean that the are equal to the identity map? Because I interpret the zero map as the homomorphism that sends everything to the identity. If we want $\alpha$, $\beta$, $\delta$, and $\epsilon$ to be isomorphisms, then that does not exactly give me a lot of room for selecting $A,A', B, B', D, D', E,E'$....
Comment: (1) Yes, need to make $A,A',E,E'$ all $0$ for the sequences to be short exact. (2) The "identity map" $f(x)=x$ certainly does not send all $x$ to the identity element $0$.
Comment: @arctictern But my issue is if I make $B,B'$ (and others as well) nontrivial, then then zero map is not an isomorphism.
Comment: How is that an issue?
Comment: @arctictern Maybe I am misreading the question, but am I not supposed to essentially give a specific $A,A', \dots$ etc. and maps $i, i', \dots$, etc where satisfying all of the conditions of the five lemma? My understanding is that $\alpha$, $\beta$, etc. all need to be isomorphisms.
Comment: While the problem says "using the notation of the five lemma," it says nothing about satisfying the hypotheses of the lemma. Obviously zero maps will not be isomorphisms (except $0\to 0$).
Comment: @arctictern so basically just make a commutative diagram where the 4 outer, vertical maps are simply homomorphisms?
Comment: Where the four outer, vertical maps are *zero* (meaning the zero map).
Answer: Hatcher says we can use short exact sequences and only $0$s and $\mathbb{Z}$s. Let's try.
To be short exact, we need $A,A',E,E'$ to be $0$. We want $\gamma$ to be a nonzero isomorphism, which means we need $C$ to be $\mathbb{Z}$. So we have
$$ \begin{array}{ccccccccc} 0 & \longrightarrow & B & \longrightarrow & \mathbb{Z} & \longrightarrow & D & \longrightarrow & 0 \\ \downarrow & & \downarrow & & \downarrow & & \downarrow & & \downarrow \\ 0 & \longrightarrow & B' & \longrightarrow & \mathbb{Z} & \longrightarrow & D' & \longrightarrow & 0 \end{array} $$
We already know what all of the down arrows are: the outer four are zero maps, and the middle one is an isomorphism, so the identity map. In order for the sequences to be exact, we need both sets $\{B,D\}$ and $\{B',D'\}$ to be $\{0,\mathbb{Z}\}$. But which to make which? I'll let you try that.
Comment: So setting $B = D' = 0$, $B' = D = \mathbb{Z}$ works.
Comment: Yes. ${}{}{}{}$
Comment: Thanks for the help. Appreciate it.


Create a form for editing a single field of an entity

Question: I need to find a way for users just to edit a specific node field. We have a quite large content type and in a review process we would like some fields of a node to be editable for the revisioning user and some not. To avoid that the revisioning user needs to scroll through a large node form it would be very handy if he/ she would find a link on node detail page close to the text of the field where he/ she is pointed to a form just showing the field.
I found "Editable Fields" and "Quickedit" module which work not so well in our project due to some JavaScript conflicts. Additionally they do not really meet our needs as our main aim is not to make nodes editable on detail page. We just want to show a reduced form to the user for one specific field.
Does anyone has a solution how to create such a form? I think of something like calling the path "custom-form/[NID]/[REVISION_ID]/[FIELD_NAME]" which is connected to a page callback which renders a form for field [FIELD_NAME] in node [NID] of the corresponding revision version and validating and saving the input respecting the field's widget settings.
Answer: You can install the Field Permissions module.
Comment: I know this module but it does not meet my needs. I need a form just for a specified field of a specified node because some users may edit single fields just under more specific circumstances - they do not get permission to edit just by role.


Making certain products of three nonsingular matrices positive definite

Question: Let $A,C$ be two nonsingular (real or complex) square matrices. I do not assume that $A$ and $C$ commute.

Question - Part 1: is there a third square matrix $B$ such that:

$B$ is also nonsingular;
$B$ commutes with both $A$ and $C$;
$ABC$ is positive definite?

More generally, consider nonsingular (real or complex), not necessarily commuting square matrices $A,C_1,\ldots,C_k$.

Question - Part 2: are there square matrices $B_1,\ldots,B_k$ such that:

$B_j$ is nonsingular for all $j=1,\ldots,k$;
$B_j$ commutes with $A$ and $C_i$ for all $i,j=1,\ldots,k$;
$AB_jC_j$ is positive definite for all $j=1,\ldots,k$?

Therefore, Part 1 is the case $k=1$ of Part 2. I am particularly interested in the situation when $A$ and $AC_j$ are Hermitian for all $j=1,\ldots,k$.

Question - Part 3: Let $A,B_1,\ldots,B_k,C_1,\ldots,C_k$ be as in Part 2 with $A,C_1,\ldots,C_k$ as in the previous paragraph. Can one choose the $B_j$'s in such a way that $AB_j$ are also Hermitian for all $j=1,\ldots,k$?
Answer: The answers to your first two questions are "no" in general. E.g. consider
$$
A=\pmatrix{1\\ &-1},\ C=\pmatrix{1&1\\ -1&1}.
$$
Any matrix $B$ that commutes with $A$ must be diagonal. However, if $B$ has two different diagonal entries, then $B$ and $C$ do not commute; if $B$ is a nonzero multiple of $I$ instead, then $ABC$ is not positive definite because the product has zero trace.
Comment: Thanks. However, in your example $AC$ is not Hermitian since $A$ and $C$ do not commute. What if we are in the situation described in Part 3 - i.e. $A$ and $AC$ are required to be Hermitian? In such a case, if $A$ and $C$ do not commute, then $C$ cannot be Hermitian.
Comment: @PedroLauridsenRibeiro See my new edit.
Comment: That is a good example, thanks! It also easily extends to the higher-rank case by taking block-diagonal matrices.


Como detectar um texto específico em uma string

Question: Eu quero fazer um programa que detecte se tem um "texto" em específico, no input digitado pelo usuário.
Nesse exemplo, o "texto": 100
Quero que ele detecte esse 100(independente da posição) no input. Exemplo: teste100 ou 100teste
Estou querendo desenvolver esse programa, para excluir arquivos. Vamos supor que eu tenho os arquivos: "t100.txt", "a100.txt", "b100.txt". Eu quero que ele exclua cada arquivo que conter "100" no título.
import os

#Arquivos
a1 = open('t100.txt', 'r+')
a2 = open('a100.txt', 'r+')
a3 = open('b100.txt', 'r+')

string = input('Você deseja excluir todos os arquivos que contém qual string: ')

if string[] == '100':
    print("Removendo os arquivos que contém '100' no título")
    os.remove()
else:
    print("Não há arquivos que contém '100' no título")

Comment: No titulo ou no nome do arquivo ?
Comment: Nome do arquivo, acabei confundindo :x
Answer: Seu código não fez muito sentido, mesmo achando ele nem era para fazer mesmo, seria só para tentar ilustrar. Uma solução possível, visto que está tabalhando com arquivos é utilizar a função glob.glob para pegar os arquivos que obedecem uma determinada expressão regular. Com a expressão regular é possível verificar se determinado valor existe no nome do arquivo.
Por exemplo, se você precisa buscar todos os varquivos que possuem o número 100 no nome, dentro do diretório arquivos, você pode fazer:
from os import remove
from glob import glob

for arquivo in glob('arquivos/.*100.*'):
    remove(arquivo)

Outra solução, se utilizar Python 3.4+, é utilizar o pacote pathlib.
from pathlib import Path

for arquivo in Path('arquivos').glob('.*100.*'):
    arquivo.unlink()

Comment: Isso mesmo, o meu objetivo era tentar ilustrar.
Comment: Criei uma pasta com o nome "arquivos" na área de trabalho, e coloquei alguns arquivos com "100" no nome do arquivo. Rodei o programa, ele não excluiu os arquivos.
Comment: Mas seu script está rodando na área de trabalho?
Comment: Sim, eu cloquei pra rodar na área de trabalho, porque é onde a pasta está. Mas, depois, coloquei na pasta o script, e mesmo assim, não funcionou. Usei a segunda solução(python 3.4).
Comment: Tente colocar `./arquivos`
Comment: Não funcionou. Caso acrescente algo, estou usando windows 7.


Property of spectrum

Question: Let $T$ be an operator on $X$ with non-empty resolvent set, and let $\lambda _0 \in \rho (T)$. Show that
 $\lambda \in  \sigma (T)$ if and only if $(\lambda _0 − λ)^{−1} \in  \sigma(R(\lambda _0; T))$
I tried to prove it using definiton of resolvent set but it didn't work.
Comment: Please show us the work you did and how far you got using the definition of resolvent set.
Answer: Hint: $$(\lambda_0-\lambda)^{-1}-R(\lambda_0;T)=(\lambda_0-\lambda)^{-1}(\lambda-T)R(\lambda_0;T).$$
Comment: Thanks a lot. Your hint was very helpful.
Comment: @KrzysztofB Yes, you're right. From the expression. A shorter way: LHS is invertible iff RHS is invertible iff $(\lambda -T)$ is invertible. And this is what you want to show.
Comment: Ok, I think it helped me.

$ \Rightarrow $

So we know that $\lambda \in \sigma (T)$. It follows that $\nexists \ (T-\lambda I)^{-1}$. We have to show that $\nexists \ (R(\lambda _0;T)-(\lambda _0 -\lambda)^{-1})^{-1}$

From your hint the right hand side is not invertible because of $\lambda I-T$

$\Leftarrow$

$R(\lambda _0, T)$ is invertible and also $(\lambda _0 - \lambda )^{-1}$ but $(\lambda _0 - \lambda )^{-1}(\lambda - T)R(\lambda _0;T)$ is not invertible. It follows that $(\lambda - T)$ is not invertible so $\lambda \in \sigma (T)$

It's correct?

Property of spectrum


How can I make videos of myself playing my keyboard?

Question: I have a Privia PX 150 keyboard.
I want to start recording myself playing so I can show my friends and family videos of my progress.
So what I had in mind was film my hands, but record the audio separately and add the audio over the video because I don't want the background sounds like me pressing the keys or my computer fan humming behind me. I thought I could do this with the MIDI-USB port on the back of the piano. But I didn't know MIDI sounds were so bad. I want to record the sound that comes directly from my piano to my computer. But not just the notes with some cheesy sound that a MIDI program uses. I want it to sound authentic.
The PX 150 only has that one midi port though.
Comment: Just to be 'that guy' : MIDI *itself* actually has no 'sounds' - it's a control protocol. It's possible to control sounds  *via* MIDI that are as good as, or better than, your Casio.
Comment: To elaborate on @topomorto : MIDI is just *'This key was pressed this hard'*. You can then use any MIDI-capable software to generate piano sounds - sometimes better than your keyboard can do itself (based on my experience with the PX110). Examples I have used are *Cubase Halion* and *Native Instruments Akoustik Piano*, but these generally come with a hefty price tag.
Comment: I do not see how this question is about musical performance or theory.
Answer: I will explain below how to record the audio output from your Privia to your computer.
But from the question, it appears that your goal is to produce a video, with a separate, clean audio track to go with the video.
To do this, you will want to record both the video and audio - (with all the ambient noise and extraneous sounds you want to eliminate), with your video recorder - at the same time you are recording your clean audio from the direct signal being output from the Privia.  In order for your video recorder to pick up the audio, you will need to be able to send the sound from keyboard to an external monitor and feed the clean direct audio output to your interface - at the same time.
The reason you do this, is to make it easier to synchronize the clean audio to the video.  On any decent video editing program you will be able to import the audio only file saved on your computer and line it up under your video's audio file. By having both audio wave forms on the screen, you can zoom in to any section and match them visually and just drag one to line up precisely with the other.  Find a part that has some obvious dynamic peaks.   Then you mute the sound from the camera while playing the clean audio file, to be sure it syncs up perfectly with the video. Then you render (mix/finalize) your video with the sound file from the video recorder muted.  You end up with a video of your hands playing, and a perfectly synchronized audio that is nice and clean.   Having the the audio from the video to visually align with the clean audio wave form will save a ton of wasted trial and error time.
Now for recording the clean audio signal output from your Privia.  As tarun mentioned, you should use some type of interface to plug the Privia into and the interface will plug into your computer.  The headphone/line out jack on the Privia is where you will plug your cable that will run into your interface.  You will be recording the exact audio signal you would hear through the headphones.
The Scarlett 2i2    Scarlett 2i2 Focusrite that tarun uses appears to have exactly what you need to produce a video with clean audio.  It allows you to run a signal to a audio monitor (so you and the camera can hear the output of the keyboard) while you record video of your hands while recording one audio track to the video recorder and the second clean audio track to your computer.  You will need a DAW (Digital Audio Workstation) program as mentioned by tarun to convert the output into a file your computer will recognize (WAV, Mp3).  Many of the audio interface devices come bundled with this type software.
Another way to do what you want to do, and much more, is to use a multi track recording device that does not require DAW software and will save your music to an SD card.  I use a Boss BR 800 and I do something very similar with audio and video. Using the BR 800 I can send the signal from my instrument to both a monitor and record it directly through the output jack and a cable, so my video recorder will pick up the sound I am playing on my instrument that will be the same sound that is going directly through a cable from my instrument to the recorder.  As mentioned above this will make the synchronization easier.
To learn more about the Boss BR 800 and other interfaces that will allow you to accomplish your goal - read this Record Instrument To Computer
You plug your Privia into an interface or recorder the same way you would plug a guitar into one.  Run the appropriate cable (such as a 1/4 inch TRS to 1/4 inch TRS cable) from headphone/line out on Privia, to line in on interface - same as a guitar.
Good luck and have fun!
Comment: Is it possible to use the digital piano speakers itself as the audio monitor? I don't have separate external speakers; ideally I could record the audio into my computer while listening/recording the audio from the speaker output to do this merge.
Comment: If there is a separate audio output on your digital piano other than a headphone jack, then certainly you could use the built in speakers on the piano as your audio monitor.  But I would expect that if you are using the headphone jack as a line out to run the audio to an interface or recording device, the built in speakers would be automatically muted unless you could figure out how to bypass the switch that turns off the speakers when you plug in headphones.  I personally would not attempt that because I don't know enough about circuitry and electronics to mess with it.
Answer: I want to shares on how my way to records some stuff of music recording with videos :
so you will need these prerequisites :
 1. keyboard
 2. soundcard (e.g behringer UCA222)
 3. jack cable
 4. DAW (e.g nuendo)
 5. Video Editor (e.g adobe premiere)
tips :

connect your keyboard to soundcard via jack cable, and plug that soundcard to your PC-DAW installed.
prepare your camera to record your videos, and get recorded
while your camera is role-on, just plays your keyboard and records it you your DAW
so you have a video(recorded on camera) and audio(recorded on your pc), merge them in your video editor(e.g. adobe premiere)

that's all
Comment: You simply merge an audio-less video recording with the audio stored on your PC? Is that hard to do? The comment above says the easiest way to do that is to also have the video record audio as well so you can line up the soundwaves and mute the video-recorded audio; is this overkill in your opinion?
Answer: At the most basic level, to record the direct output from a digital piano, it'll need a line out jack. You'll need to connect to some kind of audio interface on your computer, and then use a DAW (like Audacity, Garage Band, Reaper or others) to record the sound.
For home recording, audio interfaces typically take in XLR or 1/8" plugs and connect to a computer via USB.
I have a fairly basic setup and I use a Scarlett 2i2 as mine.
The USB connection you have is for a midi connection and will not serve to record the actual audio that the keyboard outputs.
Edit: Based on the description of this keyboard on amazon, it looks like it has a combined headphones/line out jack. You may be able to use that to output sound.
Edit 2: As a side note, if you are unfamiliar with recording techniques, this course is a great introduction to music production.


Relation Between Drupal Commerce Line items and Products

Question: I am making a website in Drupal 7 and Drupal Commerce with some custom modules. Now, I have a set of Products.
The Products are,
 - Product 1
 - Product 2
 - Product 3
I have two line items. Lets say Product Sizes. And product weight.
Each have select or another module implemented. I have followed the concept of Randy Fay's Screencasts.
http://www.commerceguys.com/resources/articles/237

http://www.commerceguys.com/resources/articles/238
Now with each line items the cost of the product changes.
As per the screenscasts, the process will be,

Create Line Items
Create Products
Create Product Display and add a Product Field Reference to it.
Then it will display the line item in the product display page.

But, I am not creating the Product display. This is going to be via the custom module. So can you tell me from the coding point of view, what is the relation between a line item and a product. So that I can list all the created line items for a displayed product.
Answer: It sounds like you are confused.
Short answer:
Line items has a reference to a product.
Explaination
Line items are only used when you add something to your order (cart), they have a relationship between the order and the product and hold data like price quantity, but can hold additional data, like the address (in case of subscriptions), which a unique each time you buy something.
If you have product attributes like size or weight, you probably want to store this on the product, since a products with different sizes and weight should be different products (A S size t-shirt is not the same as a L sized t-shirt).
So it really sounds like you are doing this the wrong way.
Comment: I am using line item because I need to change the price of the product based on the types the user choose. Using attributes is fine but I need to change the price. So using select or another module to set different ratio buttons as well. As you told, they have a relationship between the order and the product.
So, what is the relation in terms of table.? Please let me know.
Comment: @AneekMukhopadhyay If you create 3 products, one for S, M and L sizes they can have different prices just fine. With regards of SQL, the relation between line item and product is stored in a field, I believe it's called commerce_product, you can see the name on the line item configuration page.
Comment: Suppose I have 3 products. Those are displayed via commerce APIs. Once a product is chosen I want to add it to the order and then add a line item to it programmatically. The line item will have some extra features like custom Prices etc. It needs to be done before it goes to the cart. Steps,
1. Select a product
2. Add Line Items to the order loaded from the product id. Add additional prices to it.
3. Add that product and show it in cart.
Note, the cart has to show the updated price.
Any ideas? Please help..
Comment: I'm not remember previous version of commerce, but now we can handle different price based on attributes using variation types