How to create a directory during a module install?

Question: I need to create a directory in public:// when the module is installed via file_prepare_directory(). I used this code in function mymodule_install():
$mydir = 'public://mydir';
file_prepare_directory($mydir, FILE_CREATE_DIRECTORY);`

Upon uninstalling, clear the cache, and installing the module it does not create mydir.
Comment: Possible solution from a similar issue: http://stackoverflow.com/questions/21117941/file-prepare-directory-does-not-seem-to-be-creating-a-directory/33185696#33185696
Answer: Are you sure the directory where you are creating directory is writable?
file_prepare_directory checks that the directory exists and is writable.
You can try drupal_mkdir statement to create directory in hook_install


Probability of A Specific Type of Experiment Occuring

Question: The problem is:
An experimenter is studying the effects of temperature, pres-sure, and type of catalyst on yield from a certain chemical reaction. Three different temperatures, four different pressures, and five different catalysts are under consideration.
a.If any particular experimental run involves the use of a
single temperature, pressure, and catalyst, how many
experimental runs are possible?
b.How many experimental runs are there that involve use
of the lowest temperature and two lowest pressures?
c. Suppose that five different experimental runs are to be
made on the first day of experimentation. If the five are
randomly selected from among all the possibilities, so
that any group of five has the same probability of selection, what is the probability that
a different catalyst is
used on each run?

I am stuck on part c. I know that the total number of experiments is, $3 \cdot 4 \cdot 5=60$; and so, the total number of ways of choosing five of the sixty experiments would be ${{60}\choose{5}}$. What I am having trouble with is finding the total number of sequence of five experiments where a catalyst is not repeated in each sequence. I thought, for the first experiment, there would be $5 \cdot 4 \cdot 3$, and for the second experiment, $4 \cdot 4 \cdot 3$, and for the third, $3 \cdot 4 \cdot 3$, and so on. However, this isn't correct. What am I doing wrong?
Answer: The problem is that you disregarded the order of the runs in the first calculation but not in the second. Either is OK, but you need to do it the same way in both calculations. The order accounts for a factor of $5!=120$, so your result for the probability should be $120$ times the correct value.
Comment: Well, I did $\LARGE \frac{5! \cdot 12^5}{P_{60, 5}}$, and this produces the correct answer.
Comment: So are you saying that I should have done a permutation, instead of a combination? Implying that the order in which you choose the experiments matters?
Comment: @Eli: To the contrary, I explicitly said that it's OK to do either. The error was not in taking order into account or not; it was in doing one in the one calculation and the other in the other calculation. If you do them consistently, it doesn't matter, since the factors of $5!$ cancel.


Can't import LlamaParse

Question: I created a short python application in a Google Colab notebook, that works fine. I am trying to move the application from Google Colab into a local Docker-Python-Application.
But whenever I run the application with Docker and do in a .py file
from llama_parse import LlamaParse

My application fails with the following error:
pdf-compare-mvp1-web-1  |   File "/usr/local/lib/python3.8/site-packages/llama_parse/base.py", line 386, in LlamaParse
pdf-compare-mvp1-web-1  |     def get_images(self, json_result: list[dict], download_path: str) -> List[dict]:
pdf-compare-mvp1-web-1  | TypeError: 'type' object is not subscriptable

here is the functional notebook code
!pip install -q llama-index
!pip install -q openai
!pip install -q transformers
!pip install -q accelerate

import os
os.environ["OPENAI_API_KEY"] = "..."

from IPython.display import Markdown, display
from llama_index.llms.openai import OpenAI
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader
from llama_parse import LlamaParse

parser = LlamaParse(
    api_key="...",
    result_type="markdown"
)
document1 = await parser.aload_data("data/some.pdf")

# some more code

Following the not working local Docker application:
To build and run the application locally on my machine, I created Python flask app with the following relevant files:
Dockerfile
# Use an official Python runtime as a parent image
FROM python:3.8-slim

# Set the working directory in the container
WORKDIR /app

# Copy the current directory contents into the container at /app
COPY . /app

# Install any needed packages specified in requirements.txt
RUN pip install --no-cache-dir -r requirements.txt

# Make port 5000 available to the world outside this container
EXPOSE 5000

# Define environment variable
ENV FLASK_APP=app.py

# Run app.py when the container launches
CMD ["flask", "run", "--host=0.0.0.0"]

docker-compose.yml
version: '3.8'
services:
  web:
    build: .
    volumes:
      - .:/app
    ports:
      - "5002:5000"
    environment:
      - FLASK_ENV=development

requirements.txt
Flask==2.1.2
python-dotenv==0.20.0
boto3==1.24.12
Werkzeug==2.2.0
PyMuPDF
llama-index
openai
llama-parse
# transformers
# accelerate

processor.py
import fitz  # PyMuPDF
import os
from config import Config

# from llama_parse import LlamaParse
# import nest_asyncio
# nest_asyncio.apply()

from llama_index.llms.openai import OpenAI
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader
from llama_parse import LlamaParse

The last line from llama_parse import LlamaParse result in the error. Whenever this line is present/not present, the application is functional/ functional
Answer: As per this answer,
list[dict] is supported from python 3.9 and up. You need to upgrade your python version.
You can change FROM python:3.8-slim to FROM python:3.9-slim or any higher version in your Dockerfile

Can't import LlamaParse


Erro na hora de limpar e construir: "uses unchecked or unsafe operations."

Question: Seguinte, tenho uma classe "Tabuleiro" no meu projeto que na hora de Limpar e Construir está apresentando o seguinte erro: "Tabuleiro.java uses unchecked or unsafe operations."
Dei uma pesquisada e a princípio seria problema de usar ArrayList genérico, sem definição de tipo. Porém os ArrayList da classe estão todos com definição de tipo :|
Segue a classe:
private void setItemCelula(){
    ArrayList<Pedra>[] listPedra = new ArrayList[linhas*colunas];
    ArrayList<Animal>[] listAnimal = new ArrayList[linhas*colunas];
    ArrayList<Arma>[] listArma = new ArrayList[linhas*colunas];
    ArrayList<Pessoa>[] listPessoa = new ArrayList[linhas*colunas];

    for (int i = 0; i < linhas*colunas; i++) {
        listPedra[i] = new ArrayList<>();
        listAnimal[i] = new ArrayList<>();
        listArma[i] = new ArrayList<>();
        listPessoa[i] = new ArrayList<>();
    }

    for (Pedra pedra : this.itensTabuleiro.getPedras()) {
        Random rand = new Random();
        int pos = rand.nextInt(linhas*colunas);
        listPedra[pos].add(pedra);
    }
    for (Animal animal : this.itensTabuleiro.getAnimais()){
        Random rand = new Random();
        int pos = rand.nextInt(linhas*colunas);
        if(listAnimal[pos].isEmpty())
            listAnimal[pos].add(animal);
    }
    for (Arma arma : this.itensTabuleiro.getArmas()) {
        Random rand = new Random();
        int pos = rand.nextInt(linhas*colunas);
        listArma[pos].add(arma);
    }
    for (Pessoa pessoa : this.itensTabuleiro.getPessoas()) {
        Random rand = new Random();
        int pos = rand.nextInt(linhas*colunas);
        listPessoa[pos].add(pessoa);
    }
    int i = 0;
    for (Celula[] linha : campos) {
        for (Celula coluna : linha) {
            Itens it = coluna.getItens();
            it.setPedras(listPedra[i]);
            it.setAnimais(listAnimal[i]);
            it.setArmas(listArma[i]);
            it.setPessoas(listPessoa[i]);
            i++;
        }
    }
}

Answer: Para iniciarmos, isto não é um erro, é apenas um aviso. A causa raiz para este aviso é devido a types erasure, já que ArrayList é um raw type.
No seu código, na verdade, nenhuma destas declarações estão com definição de tipo:
ArrayList<Pedra>[] listPedra = new ArrayList[linhas * colunas];
ArrayList<Animal>[] listAnimal = new ArrayList[linhas * colunas];
ArrayList<Arma>[] listArma = new ArrayList[linhas * colunas];
ArrayList<Pessoa>[] listPessoa = new ArrayList[linhas * colunas];

Para evitar este aviso você tem algumas alternativas:

"suprimir" o aviso, por exemplo adicionando isto ao seu método:
@SuppressWarnings("unchecked")
private void setItemCelula() {}

alterar sua solução de um vetor de ArrayList para lista de listas, pois em Java não é possível criar array de tipos parametrizados, algo assim:
final List<List<Pedra>> listPedra = new ArrayList<>(linhas * colunas);
final List<List<Animal>> listAnimal = new ArrayList<>(linhas * colunas);
final List<List<Arma>> listArma = new ArrayList<>(linhas * colunas);
final List<List<Pessoa>> listPessoa = new ArrayList<>(linhas * colunas);

Nesta segunda solução você precisará alterar a forma com que seu código está construído, levando em consideração que agora você não tem mais vetores, e sim listas de listas. Por exemplo, seu primeiro for ficaria assim:
for (int i = 0; i < linhas * colunas; i++) {
    listPedra.add(i, new ArrayList<>());
    listAnimal.add(i, new ArrayList<>());
    listArma.add(i, new ArrayList<>());
    listPessoa.add(i, new ArrayList<>());
}

E ao contrário de fazer isso:
listPedra[pos].add(pedra);

Você deve agora usar assim:
listPedra.get(pos).add(pedra);

P.S.: dê preferência para ter como referência uma interface, como a List utilizada. Você consegue encontrar o porque desta boa prática facilmente na internet.


ARC and a window by thread

Question: I don't understand why a window created in a thread is still alive after thread's end (under ARC)?
This is called:
<code>-(void)prefsWindow:(id)sender {
    NSRect frame = NSMakeRect(200, 200, 640, 480);
    NSWindow *window  = [[NSWindow alloc] initWithContentRect:frame
                                                    styleMask:NSTitledWindowMask | NSClosableWindowMask
                                                      backing:NSBackingStoreBuffered
                                                        defer:NO];
    [window center];
    [window makeKeyAndOrderFront:NSApp];
    [NSThread exit];
}
</code>
by
<code>[NSThread detachNewThreadSelector:@selector(prefsWindow:) toTarget:self withObject:nil];
</code>
I would expect it to die cause its out of scope. Thank you!
Comment: Unrelated to xcode, I edited the question.
Answer: When the window is made key AppKit must have a reference to it, so that it can represent it to the window manager among other things. It's likely that AppKit has a retaining reference—or that you've just released a window that's still being used by a framework so that a crash will occur shortly.
The one thing you know about window object given the above code is that you no longer have ownership of the window, not that nothing has ownership of it.
Answer: The window is still alive because NSApp still holds a strong reference to it, since it's the application key window.
Call close when you don't want the window anymore:
<code>[window close];
</code>
Comment: You're welcome. I must be impartial: choose the one that you like more :-)

ARC and a window by thread


Is this fortissimo passage in the flute possible?

Question: I am writing this piece for a piano flute duet to represent Spring and it has 3 main sections. Those sections are:
A - Quiet, Molto adagio, A minor, very melodic, rocking fifths in the bass, melody rises out of the first octave - Warming up
B - Fortissimo, Presto, still in A minor, more motivic towards the beginning and more melodic towards the end, octaves in the bass - Rainstorm with the sun peaking through the clouds towards the end of the storm
C - Forte, Allegro, Picardy third to A major, joyful, melodic, Alberti bass in the bass, towards the end of the piece it becomes chords
There is a bridging A section between the B and C sections, this one being faster and hinting at the major tonality of the ending while still being in A minor. There is also a transition from the A section to the B section, where an accelerando and creschendo takes place.
You see, I am a bit worried that I might have written part of the Presto section too low for a flutist to play it fortissimo because the lowest note in the Presto is D in the second octave. If I have, I can just raise that part up an octave in the flute with no issues. Nope, not even the issue of going too high and having to switch to a piccolo. I can imagine that on a woodwind instrument, just how low or how high you can play at a certain dynamic has to do partly with the tempo(I know that on the piano, playing pianissimo at a Presto tempo is much more difficult than playing fortissimo at the same tempo).
But, is D in the second octave too low for a flutist to play fortissimo in a section that is at a Presto tempo? Or will everything be okay having D in the second octave being my lowest fortissimo note on the flute because it is a duet and not a whole orchestra? I'm just worried that the pianist might drown out the flute. The section I am most concerned about is Bars 46 and 47, where the flute plays a scalar motive to represent the wind of the storm and it is playing over an implied D minor harmony(I say implied, because the only notes in the left hand in that section are D's in octaves).
Here is the section in question where that D occurs:

For context of where this passage occurs, here is the start of the Presto section:

So, is the D in my passage too low for the flutist to be able to play it fortissimo? Are the octaves in the left hand of the piano going to drown out the flute? Or will everything be fine the way I have it written? The only reason you don't see slurs in the images is because I haven't finished writing the piece yet.
Answer: Flutes are not nearly as mousy as people like to think. That entire second octave can be played very loudly. The piano part is 2 octaves lower, so even if the piano were playing as loud as possible each instrument would have its own space in the spectrum and you'd be able to hear both.
Comment: Any decent flautist will be able to make that punch through with little problem. Fortissimo on the flute is never going to equal fortissimo on the tuba, but with the reasonably open harmony you've written there's no danger of the flute getting lost.


Finding $p'(0)$ for the polynomial of least degree which has a local maximum at $x=1$ and a local minimum at $x=3$

Question: The question goes as follows:

Let $p(x)$ be a real polynomial of least degree which has a local maximum at $x=1$ and a local minimum at $x=3$. If $p(1)=6$ and $p(3)=2$, then $p'(0)$ is...

What I did first, naturally, was consider that $p(x)$ is a cubic. But, all conditions cannot be satisfied simultaneously if $p(x)$ is a cubic.
Next, I considered $p(x)$ to be a $4$ degree polynomial, solved and got $p'(0)=15$. But the answer provided was $p'(0)=9$.
Comment: Why do you think a cubic doesn't work?
Comment: @DanielFischer I made a mistake.. I considered $f'(x)$ to be $(x-1)(x-3)$, whereas I should have considered it to be $a(x-1)(x-3)$...
Comment: *maxima* is the plural form of *maximum*. You want a singular form here (I edited).
Answer: Basically you need to setup system of equations and solve the coefficients of $p(x)$
Since $p(x)$ has two turning points, the minimum possible degree is $3$
Say $p(x) = ax^3+bx^2+cx+d$
$\implies p'(x) = 3ax^2+2bx+c$
from the problem we have :
$p(1) = 6$
$p(3) = 2$
$p'(1) = 0$
$p'(3)=0$
four equations and four unknowns - can be easily solved
Answer: $p'(1)=0, p'(3)=0, p(1)=6, p(3)=2$.
We must have $\partial p' \ge 2$, so try $p'(x) = c(x-1)(x-3)$. This gives
$p(x) = p(1)+c\int_1^x p'(t)dt = 6+{c \over 3} (x-4)(x-1)^2$. Setting $p(3) = 2$ gives $c=3$ and so we have
$p(x) =
6+(x-4)(x-1)^2$.
Computing $p'(0)$ gives 9.
Answer: As an alternative to finding the coefficients of $p$ explicitly, start with the "standard" zig-zagging cubic
$$ f(x) = 2x^3 - 3x^2 $$
which has a maximum at $(0,0)$ and a minimum at $(1,-1)$.
Now just scale and translate to get $p(x) = 6 + 4f(\frac{x-1}2)$. Then you don't even need to simplify to find $p'(0)$, just the chain rule.
Answer: Hint:
$p(x)$ is in fact a cubic.
The system of equations you have to solve is:
$$\begin{eqnarray}p'(1) = 0&\Rightarrow&3a& + &2b& + &c& & &=& 0\\p(1) = 6&\Rightarrow&a&+&b&+&c&+&d &=& 6\\p'(3) = 0&\Rightarrow&27a&+&6b&+&c& & &=&0\\ p'(3) = 2&\Rightarrow&27a&+&9b&+&3c&+&d&=&2 \end{eqnarray}$$
Note that $p'(0) = c$
(You should end up with $p(x) = x^3-6x^2+9x+2$)


Is there a way to display formatted rich text in WPF datagrid?

Question: I'm trying to display rich text inside of a column of a WPF DataGrid (from WPF Toolkit). Something like this:
Name: Bob
Title: Doctor
I am creating a data object programmatically in code with the string property. And I want this string to contain the rich text and than bind it to the column contents. Is that possible?
Would really appreciate any help!
Answer: Use the DataGridTemplateColumn:
<code><dg:DataGridTemplateColumn Header="Info">
    <dg:DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition />
                    <RowDefinition />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition />
                    <ColumnDefinition />
                </Grid.ColumnDefinitions>
                <TextBlock Text="Name:" FontWeight="Bold" Grid.Row="0" Grid.Column="0" />
                <TextBlock Text="{Binding Name}" Grid.Row="0" Grid.Column="1" />

                <TextBlock Text="Title:" FontWeight="Bold" Grid.Row="1" Grid.Column="0" />
                <TextBlock Text="{Binding Title}" Grid.Row="1" Grid.Column="1" />
            </Grid>
        </DataTemplate>
    </dg:DataGridTemplateColumn.CellTemplate>
</dg:DataGridTemplateColumn>
</code>
Comment: Thanks, but as I said above, I am creating a data object programmatically in code.

I want to build a string like this: "Name: Bob\nTitle: Doctor" and assign it to the column. Is that possible?
Comment: That can work if you're creating the data object programmatically. Just make sure the type in your collection has Name and Title properties. I updated the example to show how it can bind to them.
Comment: Thanks, I figured you can get it done this way, but I was hoping if Name and Title were not 2 set properties, but there might be any number of them, it would be great to build up the layout programmatically and not depend on preset template. Is that possible?
Comment: Perhaps. You could always set the DataTemplate programatically, adding elements and bindings in code. There might be a way to do it with a binding Converter that parses the string and makes it into a FlowDocument. But I would only go that route if I was sure that normal databinding wasn't going to work.
Comment: Since I can't find a better way of doing this, I am marking this as good enough answer :)


I want to reset the modalafter closing it, but it's not working

Question: I have a modal box which is as follows:

        <button type="button" class="btn btn-warning" data-toggle="modal" data-target="#couponcode<?php echo $result->id; ?>">Show Coupon Code</button>

         <div class="modal fade" id="couponcode<?php echo $result->id; ?>" role="dialog">

                  <button type="button" class="close" data-dismiss="modal"></button>

                  <?php echo $result->coupon_code; ?>
                  <span class="copy-btn" data-type="attribute" data-attr-name="data-clipboard-text" data-model="couponCode" data-clipboard-text="<?php echo $result->coupon_code; ?>">COPY CODE

                  <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

I am using it for showing code, when a user click on COPY CODE, it is copied to clipboard and the backroundcolor as well as text is changed to green and COPIED respectively. But when I close the modal, I want to reset it. What I have tried is as folows:
$(document).ready(function(){
    $('.copy-btn').on("click", function(){
        value = $(this).data('clipboard-text');
        //console.log(value);
        var $temp = $("<input>");
          $("body").append($temp);
          $temp.val(value).select();
          document.execCommand("copy");
          $temp.remove();
          $('.copy-btn').css("background-color", "green").text("Copied!");
          $(modal).on("close", function(){ //I am getting problem here
            $(this).css('background-color', '').text('');
          })
    })
})

There are three ways to close the modal. First oneis using close symbol, second one is using close link.Andthied one is by clicking outside the modal box, which also closes the box. How can I reset the modalbox text and color changed in these three cases.
Answer: To listen for when a modal closes, use this $( "#modal" ).on( "hide.bs.modal", function(e) { });
To reset the background color and remove the coupon code, use:
$( "#modal" ).on( "hide.bs.modal", function(e) {

    $( ".code-txt" ).html( "" );

    $( ".copy-btn" ).css( "background-color", "" );
    $( ".copy-btn" ).text( "" );

});

You have not defined the modal variable in your question, so I used "#modal"


Spectral clustering k, vs k-means k?

Question: In spectral clustering, as I've seen the algorithm presented, we often choose the first $k$ eigenvectors of the "graph Laplacian" to cluster on. It appears to me that this $k$ is the number of clusters expected, just like in $k$-means.
However, it seems like an arbitrary choice to cluster on the first $k$ eigenvectors based on the fact that we believe there are $k$ clusters. What is the mathematical intuition behind reducing the number of dimensions to the number of expected clusters?
A second thing I have have learned is that the multiplicity of the 0 eigenvalue tells you how many connected components there are in the graph represented by the Laplacian. This makes rough sense to me.
But, what seems to be constantly glossed over is how to interpret the eigenvalues of a fully connected similarity graph, which is often used in practice for spectral clustering. How can the eigenvalues be interpreted in this fully connected case?
Answer: For the first question I do recommend Luxburg (2007) paper: A Tutorial on Spectral Clustering, page 9-14. Basically you take those k eigenvectores because you are transforming your clustering problem into a linear algebra problem, solving it by a relaxation and using Rayleigh-Ritz.
For the second question, the number of zeros of Laplacian matrix is the same as connected component (you can think it as clusters) on the graph. The thing about fully connected graphs is that you would like to see if it is close to be with k connected componentes, so if the first k eigenvalues are close to zero, this could lead that the fully connected graph is close to be a k connected component graph.
Comment: Yes, I have since read that paper in full a few times and implemented software based on it. Very informative.

Spectral clustering k, vs k-means k?


Evaluate $\int\frac {\sin 4x }{\sin x}\ dx$

Question:
Evaluate $$\int \frac{\sin 4x}{\sin x} dx$$

Attempt:
I've tried to use the double angle formulas and get it all into one identity, which came out as:
$$
\int \left( 8\cos^3x - 4\cos x \right) dx
$$
But I'm not sure if this is the right way to go about it. Any help would be much appreciated!
Comment: It is a good way. Now note that $\cos^3 x=(\cos x)(1-\sin^2 x)$.
Answer: $$\frac{\sin(4x)}{\sin(x)}=U_3(\cos(x)) = 8\cos^3(x)-4\cos(x) = 2T_3(\cos x)+2T_1(\cos(x))$$
hence:
$$ \frac{\sin(4x)}{\sin(x)} = 2\cos(3x)+2\cos(x) $$
implies:
$$ \int\frac{\sin(4x)}{\sin(x)}\,dx = \frac{2}{3}\sin(3x)+2\sin(x)+C. $$
Comment: Nice, but it would be worth to mention $T_n$ and $U_n$ are [Chebyshev polynomials](https://en.wikipedia.org/wiki/Chebyshev_polynomials) of the first and second kind, respectively ;-)
Answer: Notice, $$\int\frac{\sin 4x}{\sin x}\ dx$$
$$=\int\frac{2\sin 2x\cos 2x}{\sin x}\ dx$$
$$=\int\frac{2(2\sin x\cos x) (1-2\sin^2x)}{\sin x}\ dx$$
$$=\int4(\cos x -2\sin^2x\cos x)\ dx$$
$$=4\int\cos x -8\int \sin^2x\cos x\ dx$$
$$=4\int\cos x -8\int \sin^2x\ d(\sin x)$$
$$=\color{blue}{4\sin x-\frac{8\sin^3 x}{3}+C}$$
Answer: We have
$$\frac{\sin(4x)}{\sin x}=\frac{2\sin(2x)\cos(2x)}{\sin x}=\frac{4\sin x\cos x\cos(2x)}{\sin x}$$
$$=4\cos x\cos(2x)=4\cos x(1-2\sin^2x)$$
Now set $\sin x=t$.
Answer: Here is another solution based on Dirichlet kernel
Lemma: $\sum _{k=-n} ^{n} e^{ikx} =  1 + 2 \sum _{k=1} ^{n} cos(kx) = \frac{sin((n+1)/2)}{sin(x/2)}$
Proof:
It's direct application for series sum $\sum _{k=-n} ^{n} x^k$, and Euler celebrated identity $e^{ix} = cos(x) + i sin(x)$, see wikipedia entry for full proof see wikipedia's entry
Now:
put $ x = \frac{u}{2} \Rightarrow dx = \frac{1}{2}du$
$\frac{1}{2} \int \frac{\sin 2u}{\sin \frac{u}{2}} dx = \int (1 +2 \sum _{k=1} ^{1} cos(ku)) dx = u - 2   sin(u) $

Note: This method works for any positive integer $n$ in $\int \frac{sin(2nx)}{sin(x)}$
Answer: We can put the complex identity
$$\sin \alpha := \frac{\exp(i \alpha) - \exp(-i \alpha)}{2i}$$ to efficient use here.
Taking $\alpha = 4 x$ gives
$$\sin 4x = \frac{\exp(4 i x) - \exp(-4 i x)}{2i},$$
We can use a difference-of-squares factorization to write the numerator as
\begin{align*}
\exp(4 i x) - \exp(-4 i x)
&= [\exp(2 i x) + \exp(-2 i x)][\exp(2 i x - \exp(2 i x)] \\
&= [\exp(2 i x) + \exp(-2 i x)][\exp (i x) + \exp(- i x)][\exp (i x) - \exp(- i x)]
\end{align*}
Now, substituting using the complex identity for $\alpha = x$ gives
\begin{align*}
\sin 4x = [\exp(2 i x) + \exp(-2 i x)][\exp (i x) + \exp(- i x)] \cdot \frac{\exp (i x) - \exp(- i x)}{2 i} = [\exp(2 i x) + \exp(-2 i x)][\exp (i x) + \exp(- i x)] \sin x.
\end{align*}
So, expanding and using the corresponding cosine identity
$$\cos \alpha = \frac{\exp(i \alpha) + \exp(-i \alpha)}{2}$$ gives
\begin{align*}
\frac{\sin 4x}{\sin x}
&= [\exp(2 i x) + \exp(-2 i x)][\exp (i x) + \exp(- i x)]\\
&= \exp(3 i x) + \exp(-3 i x) + \exp(i x) + \exp(-i x) \\
&= 2 (\cos 3x - \cos x) .
\end{align*}
In this form, we can compute the antiderivative quickly.
Answer: $$\int\;\frac {sin(4x)}{sin(x)}dx=\int\;\frac {2sin(2x)cos(2x)}{sin(x)}dx=\int4cos(x)cos(2x)dx\\~\\=4\int\;cos(x)(1-2sin^2(x))dx$$
let u = sin(x) and du = -cos(x) dx
and therfore :
$$=-4\int1-2u^2du=-4u+\frac {8}{3}u^3+C=-4sin(x)+\frac {8}{3}sin(x)^3+C$$
Answer: $$\int \left( 8\cos^3x - 4\cos x \right) dx=\int \left( 8\cos x (1-\sin^2 x) - 4\cos x \right) dx = \int \left( -8\cos x \sin^2 x  + 4\cos x \right) dx=-8\int \cos x \sin^2 x dx + 4\int cos x dx = \frac{-8\sin^3 x}{3} +4\sin x + C
$$


SQL parent/child hierarchy

Question: I have a table as shown below which has a parent/child relation.

My output should look like this:
Comment: You might want to provide some additional info plus your current attempt.
Comment: What have you tried so far? Let us see your work and maybe we can guide you better - did you try joining the tables?
Comment: Do a self left join.
Answer: Just use join:
select pc.*, pcp.id as parentid
from parentchild pc left join
     parentchild pcp
     on pc.childbook = pcp.parentbook;

I don't think I quite understand why the parent of "1" is "1.1" and why parentId is associated with childbook, but that appears to be what you are asking for.
Comment: That helps, pardon the names there. i was joining the wrong child and parent earlier.
Comment: one more query, how do i get the book which don't have a child in a separate flag?
Comment: @Abrah . . . That is what the `left join` does.

SQL parent/child hierarchy


Badoo repeat - How to determine and keep track of user's location in IOS?

Question: I want to do the following.

Keep updating a user's location using Core Location and send that information to a database.

I am creating an app like badoo so I need to know where a user is located at all times to know who is near them.
I did the following:
I put the following code in applicationDidFinishLaunchWithOptions
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
[locationManager startUpdatingLocation];

and then the following function in AppDelegate.m
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    self.currentLocation = newLocation;

    // send location to server

    if(newLocation.horizontalAccuracy <= 100.0f) { [locationManager stopUpdatingLocation]; }
}

Is that the most efficient way to do it?
How then can I use the longitude and latitude details and django to be able to tell who is near a user?
Thanks for your help!
Answer: As for efficiency - it depends on what you mean.  The method you describe doesn't allow the user to actually start the process of determining location - it starts when the app starts.  If that is your intent, then I see this as being efficient for the user to not take the time to start it.
However, you have the code in the appdelegate file.  For efficiency as to maintaining code, I would not agree to the pattern you have provided.  A more efficient (in terms of development) it would be best to have a separate model handle the updates from the location manager and have the appdelegate create an instance of said model.
Sorry - can't help with django.
Comment: What do you mean by separate model?
Comment: As in http://www.infragistics.com/community/blogs/todd_snyder/archive/2007/10/17/mvc-or-mvp-pattern-whats-the-difference.aspx


Subversion Edge SSL

Question: We've got Subversion Edge installed successfully and I need to secure it with a SSL certificate rather than the generated one.
I have a cert in the windows cert store, I need to export this to .crt and .key.
Does anyone know what tools I should use to do it, or If i can do it in windows?
is it openssl?
Answer: Yeah, use OpenSSL.
You'll export a PKCS12 file from windows (make sure you include the private key), and you'll convert it to X509:
<code>openssl pkcs12 -in cert.pfx -out cert.pem -nokeys
openssl pkcs12 -in cert.pfx -out cert.key -nocerts -nodes
</code>
Comment: perfect thanks, my first exposure to openssl :) nice little tool

Subversion Edge SSL


How to notate orchestral toms?

Question: I want to ask how are orchestral toms notated.
I Know how toms in a drumset are placed in the staff and there are only few of them but what if I want to use more toms with different pitches?
How to notate them?
Can I just arbitrarily place them on the staff based on their pitch or is there a standard way of placing the notes?
Comment: Are these toms with a drum kit, or are they just a set of toms? Are they tuned to definite pitches?
Answer: There's not even a 'standard' way in which to show each drum! There are some 'industry standards', but the best to do in this case is to include a legend (key) at the top of the chart, explaining which line/space represents each tom. As it's a rare occurrence, that would be the safest to do.
If they're tuned toms, it could be an idea to signify their placing on the appropriate line/space.

How to notate orchestral toms?


Let A and B be n by n matrices. Suppose A is invertible. Show that AB is similar to BA.

Question: Let $A$ and $B$ be $n\times n$ matrices. Suppose $A$ is invertible. Show that $AB$ is similar to BA.
I started with $BA = P^{-1}(AB)P$, but I'm drawing a blank now.
Comment: Have you tried plugging anything in for $P$ to see what happens?
Comment: Is this homework? What have you tried?
Comment: Do you remember what $A^{-1}A$ equals?
Comment: A^-1A = In. Also, yes this is homework. I'm stuck. Since this is a proof I don't know where to go, since everything has to be theoretical.
Answer: Since $AB=BA$, and A is invertible, then we have ${A^{-1}}ABA=BA$, there exist $P=A$, such that ${P^{-1}}ABP=BA$.
Comment: It isn't given that AB=BA.
Comment: Got it! Thanks.


Determining the branch of logarithm

Question: I want to determine a branch of logarithm such that $f(z)=L(z^3-2)$ is analytic at $0$. I am not really sure how to find a branch but I will explain few things I tried.
 Since $z^3-2$ maps $0$ onto $-2$, what needs to be done is to find a branch of logarithm which is analytic at $-2$.So if L is a branch of logarithm, by the chain rule we have that $L(z^3-2)$ is analytic at $0$ since $z^3-2$ is analytic at $0$. I just don't know how to proceed from here. Any help will be appreciated. Thanks
Comment: If you cut along the positive reals, you obviously avoid $-2$.
Comment: @HagenvonEitzen I don't think I understood what you said
Answer: You can define a logarithm on any simply connected subset of $\mathbb{C}\setminus \{0\}$, so this can for instance be $\mathbb{C} \setminus \mathbb{R}^+$.
This logarithm $L$ is a holomorphic function, so composing it with the holomorphic $z \mapsto z^3-2$ gives a holomorphic function $f$. Holomorphic functions are analytic on their domain, so $f$ will be analytic at $0$ as well as at any point on which it is defined.
Comment: So $L(z^3-2)$ is the answer?
Comment: What do you mean exactly ? If $L$ is *a* logarithm (you can construct many, there is no canonical one) then $L(z^3-2)$ is automatically analytic at $0$ *if it is defined*.
Comment: I meant the purpose was to determine a branch of logarithm. Hence I showed that $L(z^3-2)$ is analytic at 0 my answer is correct then?
Comment: I am sorry I have not still understood properly what a branch of logarithm exactly is so I thought I have to find some explicit function for $f(z)$
Comment: @Chocosup You said L is a holomorphic function. On what domain are you talking about?
Answer: Define $g(z)=z^3-2$. The chain rule asserts that $f$ will be differentiable at each point $z$ for which $g(z)$ lies in the domain consisting of all points of the complex plane except those lying on the nonpositive real axis (the branch cut of Log ($z$)). Thus, $f$ will not be analytic at the points where $z^3-2$ is negative or zero if $L$ is the principal value of the logarithm. At the point zero, $g(z)=-2$, which is a negative real number. This means we must use a branch of the logarithm that has its branch cut not along the negative reals.
We can specify the logarithm branch $L(z)=\mbox{Log }|z|+i\arg_0(z)$ where $\arg_0(z)$ is the branch of arg(z) in the interval ($0$, $2\pi$), which solves the problem.

Determining the branch of logarithm


Variable declaration difference in Objective-C

Question: I'm was reading a tutorial about coreImage in iOS 6.
In that tutorial I found something like:
@implementation ViewController {
    CIContext *context;
    CIFilter *filter;
    CIImage *beginImage;
    UIImageOrientation orientation;
}
//Some methods
@end

The variables are declared in the .m file in a parenthesis after the @implementation statement. I'm seeing these kind of variable declaration first time.
Is there any difference between the above variable declaration and the following code
@implementation ViewController

    CIContext *context;
    CIFilter *filter;
    CIImage *beginImage;
    UIImageOrientation orientation;

//Some methods

@end

Comment: retag it please .. this is LANGUAGE specific and not specific to ios ios5 xcode4.5 ... also this has always been how objC and also C++ work (ios1-6)
Comment: @Daij-Djan: ok done it :) I saw this feature in iOS 6 that's why I added that tag.
Comment: @Daij-Djan I'm quite sure the "ivar block inside `@implementation`" option (instead of `@interface`) was added only a few years ago.
Comment: The Op doesn't have ivars in the implementation though. No curly braces. And static vars were always supported
Comment: @Daij-Djan: No curly brace ??? Can you check the first code snippet ?
Comment: Read it wrong ;) but I didn't answer
Answer: There is a HUGE difference.
Variables inside brackets directly after the @interface or @implementation are instance variables. These are variables associated with each instance of your class, and thus accessible anywhere in your instance methods.
If you don't put the brackets, you declare global variables. Any variable declared outside of any bracket block will be a global variable, whether these variables are before or after the @implementation directive. And global variables are evil and need to be avoided at all costs (you can declare global constants, but avoid global variables), especially because they are not thread-safe (and may thus generate bugs that are a mess to debug).

In fact, historically (in first versions of Objective-C and the compilers), you were only able to declare instance variables in brackets after your @interface in your .h file.
// .h
@interface YourClass : ParentClass
{
    // Declare instance variables here
    int ivar1;
}
// declare instance and class methods here, as well as properties (which are nothing more than getter/setter instance methods)
-(void)printIVar;
@end

// .m
int someGlobalVariable; // Global variable (bad idea!!)

@implementation YourClass

int someOtherGlobalVariable; // Still a bad idea
-(void)printIVar
{
    NSLog(@"ivar = %d", ivar1); // you can access ivar1 because it is an instance variable
    // Each instance of YourClass (created using [[YourClass alloc] init] will have its own value for ivar1
}

Only modern compilers let you declare instance variables (still in brackets) also inside either your class extension (@interface YourClass () in your .m implementation file) or in your @implementation, in addition to the possibility to declare them after the @interface in your .h. The benefits being to hide those instance variables from external users of your classes, by declaring them in the .m file and not in the .h file anymore, because users of your class don't need to be aware of the internal coding details of your class, but only needs to know the public API.

One final advice: instead of using instance variables, Apple more and more recommends to use @property directly, and let the compiler (explicitely using the @synthesize directive, or implicity with modern LLVM compilers) generate the internal backing variable. So that at the end you generally won't need to declare instance variables at all, and thus omit the empty { } after the @interface directive:
// .h
@interface YourClass : ParentClass

// Declare methods and properties here
@property(nonatomic, assign) int prop1;
-(void)printProp;
@end

// .m
@implementation YourClass
// @synthesize prop1; // That's even not needed with modern LLVM compiler
-(void)printProp
{
    NSLog(@"ivar = %d", self.prop1);
}

Answer: Thats a way of declaring private variables, they are not visible outside the class nor shown in header file


Should I create a role for every user?

Question: On Drupal 7 I have tested many modules, because I simply want in the user view some fields which are public and others can only see friends (user relationship or flag friend, ...).
would be nice if I had a fieldgroup 'open' and 'friends' with the correct permission.
Because it is not running yet, I want by register a new user creating and assign a role named role_userID. These I want do with a rule but I can't do it... After this I can give every friend of this person his role, that they can see the fields.
Or is not a good idea?
How can I do that?
Thanks
Thomy
Answer: I seem to understand that for every user with "uid" = "userID", you want to create 1 role like "role_userId" ... That means if you have dozens of users (only), you have dozens of roles. Not to mention that you have hundreds (or thousands?) of users if you'd have hundreds (or thousands?) of roles ... IMO that is not a good idea. I'm not sure what exactly you're up to with that "user view some fields which are public and others can only see friends (user relationship or flag friend, ...)", as in your question, but it does seem to be related to access permission somehow.
Have a look at the Group module, which allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.
In your case you could have 1 Group "Type" (eg: "User Groups"?), and create 1 group for each user. Think of a Group Type as equivalent to a Content Type, and a Group (of a specific Group type) as equivalent to a node of a specific Content Type). You'd probably come close to having something with a 1-to-1 relationship between a specific user and Group permissions related to that user (whereas Group permissions is not the same as standard Drupal permissions ...).
Also, since Group is fully entity based, it integrates perfectly with Rules also. With that in mind, you could use Rules to capture Rules Events about user relationship or flag friend (as in your question), and then trigger Rules Actions to manage various access levels to the Group designated to that user. Important to realize: you wouldn't need like dozens (or hundreds/thousands?) of "roles".
For more details about the various roles and permissions, refer to my answer to "What are the various roles supported by the Group module?".
Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".

Should I create a role for every user?


How to check if php-fpm is installed and running correctly?

Question: As in title, how to check php-fpm status? Is it running? How many request serving? Thanks.
Answer: Is ps -ef | grep php-fpm too simple an answer for the first part?
You could also use the ping feature that you can enable with the ping.path configuration directive.
The second part can be achieved with the pm.status_path configuration directive that gives you access to a number of statistics, including the number of accepted connections.
Answer: You can get the SAPI with

php_sapi_name — Returns the type of interface between web server and PHP

Returns the interface type, as a lowercase string.
  Although not exhaustive, the possible return values include aolserver, apache, apache2filter, apache2handler, caudium, cgi (until PHP 5.3), cgi-fcgi, cli, continuity, embed, isapi, litespeed, milter, nsapi, phttpd, pi3web, roxen, thttpd, tux, and webjames.

For status and how many requests are served you might want to use exec or system.


PHP function to manipulate values isn't working unless string includes a dollar sign ('$')

Question: The PHP & JS functions shown below work together to 1) Populate select elements from arrays 2) Pre-select the options matching the db values, and 3) Manipulate the value of select element options on focus.
The PHP helper function works in concert with the JS focus function, and manipulates the string values if the db value included the suffix '_default'), but it's only being triggered if the option/string value includes a dollar sign ('$'). There isn't anything in the code that should require this, but I've tested every possibility and that's the only thing that seems to be causing it.
I've posted a functional example with the combined code at http://click2fit.com/sample_php_select.php. To see the problem in action, click on the 'Submit' button without focusing on either select element, and it will echo the posted values for two select elements with 'default' values  -  one with a dollar sign and one without. For purposes of demonstrating the problem, I have hardcoded the values instead of fetching them from the db. In addition, I've posted a fiddle with JS function here http://jsfiddle.net/chayacooper/JHAPp/6/
PHP & HTML
<?php
// Helper function that replaces a key while maintaining the entry's position in the array. It does not modify the given array, but returns a new array.
function replaceKey($array, $oldKey, $newKey) {
    $newArray = array();
    foreach ($array as $key => $value) {
        $newArray[($key === $oldKey) ? $newKey : $key] = $value;
    }
    return $newArray;
}
// Function to select the option matching the value in the db
function printSelectOptions($dataArray, $currentSelection) {
    foreach ($dataArray as $key => $value) {
        echo '<option ' . (($key == $currentSelection) ? 'selected="selected"' : '') . ' value="' . $key . '">' . $value . '</option>';
    }
}
  try {
    $stmt = $conn->prepare("SELECT * FROM price WHERE user_id = :user_id");
    $stmt->bindValue(':user_id', $user_id);
    $stmt->execute();
}  catch(PDOException $e) {echo $e->getMessage();}
$row = $stmt->fetch();
$search_default = array('_default');
$replace_default = array('');
$row_default = str_replace($search_default, $replace_default, $row);
?>

<select name="importance" id="importance">
<?php
    // Generates a <select> element with the options specified in this array
    $options = array("1"=>"1", "2"=>"2", "3"=>"3", "4"=>"4", "5"=>"5");
    // If these are different then the value from the database includes "_default"
    if ($row_default['importance'] !== $row['importance']) {
        // Change the key for the entry in $options so it includes "_default"
        $options = replaceKey($options, $row_default['importance'], $row['importance']);
    }
    $selected = $row['importance'];
    // Pre-selects the option matching the db information
    echo printSelectOptions($options, $selected);
?>
</select>

JS Function
 $(function () {
     $('select').focus(function () {
         var option = $(this).find("option[value*=default]");
         option.attr('value', option.attr('value').replace(/_default/g, ''));
     });
 });

Purpose of JS function
I am pre-selecting the most commonly chosen options for apx. 300 select elements, and am using this function to differentiate between when those values are still in their initial pre-selected/default state vs. when a user has actively chosen that value after focusing on the form element.
Answer: option doesn't get any value and replace doesn't work well with jQuery.
Change this:
$(function () {
  $('select').focus(function () {
     var option = $(this).find("option[value*=default]");
     option.attr('value', option.attr('value').replace(/_default/g, ''));
  });
});

To this:
$(function () {
  $('select').focus(function () {
    var default_option = $("option[value*=default]"); // Just added this part to a variable, for easy of use.
    var option = default_option.val(); // Got the option value that contains the word default.
    // This will replace the '_default' with '' and assign the new value to the option
    default_option.val(function(index, value) {
      return value.replace(/_default/g, '');
    });
  });
});

But javascript is not your only problem. You have a lot of problems in the php code and I am afraid you have made it more complicated than it actually is.
Comment: It's still showing Importance as '3' instead of '3_default' :-(
Comment: I just updated the question because I realized that the problem is that the PHP 'helper' function - which manipulates the string values - isn't getting triggered
Comment: `$options = replaceKey($options, $row_default['importance'], $row['importance']);` is wrong. What exactly do you think `php` does in this case?
Comment: Maybe you have to reconsider your whole code structure. You have a lot of coding problems too. Also, study how `php arrays` work. Or give this to an expert to build it for you.
Comment: As far as I understand, that should change the key for the entry in $options so it includes "_default" if the value from the database includes "_default". I actually created the PHP 'helper' function with the help of another SO member (in this posting http://stackoverflow.com/a/15469489/1056713) :-) It works correctly for prices (about 50% of the select elements), but I'd like to be able to use it for the remaining elements
Comment: Would you mind clarifying the changing you made to the js function (so that I can learn from my mistakes ;-))? And of course I would welcome a simpler way to handle the php :-D
Comment: I added some comments, but really is exactly what you were trying to do. Nothing extra. You can't just assign an array to an array or replace elements of an array the way you are trying to. You have to `unset` the elements first. I don't think this post will be helpful to anyone else... Wish you luck :)
Comment: Thank you for clarifying your improvements to the JS function a bit :-) I'm open to going about this another way in order to be able to use arrays, but I'm not following your suggestion to first unset the elements
Answer: On your example page option is not found because initially there is no option that has _default in its value. You need to set one from start or edit your JS to include an option what to do, when there is no option found:
var option = $(this).find("option[value*=default]") ||  $(this).find("option:first-child");

But to be honest, I have no idea what you are trying to achieve with this code.
Comment: Your post made me realize that the problem is that the PHP 'helper' function isn't getting triggered, and I've updated the question.  The PHP 'helper' function  manipulates the string values if the db value included the suffix '_default') in order to create an option with '_default'.


Estou com este erro em advpl

Question: Estou com o erro da imagem quando faço a impressão do pedido de vendas no Totvs. Mas só apresenta este erro na terceira vez que faço a impressão, imprimo uma vez ok da certo, na segunda vez também, agora na terceira vez apresenta o erro.
Segue o código da Impressão
<code>#INCLUDE "FWPrintSetup.ch"
#INCLUDE "topconn.ch"
#INCLUDE "Protheus.ch"
#INCLUDE "TBICONN.CH"
#INCLUDE "rwmake.ch
</code>
User Function TSTREL()
<code>Local cQuery   := ""
Local cNum     := ""
Local nTotal   := 0
Local nIpi     := 0
Local nIcmsSub := 0
Local nTotalF  := 0
Private oPrinter
Private oFont1
Private oFont2
Private oHGRAY := TBrush():New( , CLR_HGRAY)
Private lPreview
Private cLogo := FisxLogo("1")

RPCSetType(3)
If cEmpAnt == "01"
     Prepare Environment Empresa "01" Filial "01"
Else
     Prepare Environment Empresa "02" Filial "01"
EndIf

//RPCSetEnv("99","01")

    /*** FONTES ***/
Private oFont18T    := TFont():New("Courier New",,18,,.T.,,,,,.F.)
Private oFont16T    := TFont():New("Courier New",,16,,.T.,,,,,.F.)
Private oFont14TC   := TFont():New("Courier New",,14,,.T.,,,,,.F.)
Private oFont14T    := TFont():New("Arial"      ,,14,,.T.,,,,,.F.)
Private oFont18TA   := TFont():New("Arial"      ,,18,,.T.,,,,,.F.)
Private oFont14TI   := TFont():New("Arial"      ,,13,,.T.,,,,.T.,.F.)
Private oFont11F    := TFont():New("Arial"      ,,11,,.F.,,,,,.F.)
Private oFont13T    := TFont():New("Arial"      ,,12,,.T.,,,,,.F.)
Private oFont13F    := TFont():New("Arial"      ,,12,,.F.,,,,,.F.)
Private oFont10FA   := TFont():New("Arial"      ,,10,,.F.,,,,,.F.)
Private oFont10F    := TFont():New("Courier New",,10,,.F.,,,,,.F.)
Private oFont11FA   := TFont():New("Arial"      ,,11,,.F.,,,,,.F.)

Private oFont09T    := TFont():New("Courier New",,09,,.T.,,,,,.F.)
Private oFont07F    := TFont():New("Courier New",,07,,.F.,,,,,.F.)
Private oFont09F    := TFont():New("Courier New",,09,,.F.,,,,,.F.)
Private oFont09FA   := TFont():New("Arial",,09,,.F.,,,,,.F.)

Private oFont7TA    := TFont():New("Courier New",,07,,.T.,,,,,.F.)
Private oFont12F    := TFont():New("Courier New",,12,,.F.,,,,,.F.)
Private oFont10T    := TFont():New("Courier New",,10,,.T.,,,,,.F.)
Private oFont09F    := TFont():New("Courier New",,09,,.F.,,,,,.F.)
Private oFont09T    := TFont():New("Courier New",,09,,.T.,,,,,.F.)
Private oFont14N    := TFont():New("Courier New",14,14,,.T.,,,,.T.,.F.)

Private oFont10AT   := TFont():New("Arial"      ,,10,,.T.,,,,,.F.)
Private oFont10AF   := TFont():New("Arial"      ,,10,,.F.,,,,,.F.)

Private  nLin       := 350
Private  NSpace10   := 10
Private  NSpace20   := 20
Private  NSpace30   := 30
Private  NSpace40   := 40
Private  NSpace50   := 50

If oPrinter == Nil
    lPreview := .T.
    oPrinter      := FWMSPrinter():New(SC5->C5_NUM ,6,.F.,,.T.)
    oPrinter:SetResolution(72) //Tamanho estipulado para a Danfe
    oPrinter:SetPortrait()
    oPrinter:SetPaperSize(9)
    oPrinter:SetMargin(60,60,60,60)
    oPrinter:cPathPDF :="C:\TEMP\"
EndIf

oPrinter:StartPage()
//oPrinter:Box (60, 60, 830, 530)

If cEmpAnt == "01"
oPrinter:SayBitmap( 50, 30, cLogo , 100, 100)
oPrinter:Say(80,180,"PIC-QUÍMICA E FARMACÊUTICA LTDA",                                         oFont14TC)
oPrinter:Say(100,150,"Morada da Estrelas, 65 - Jd. Nova Itapevi - ITAPEVI - SP",              oFont09F)
oPrinter:Say(108,150, "Fone: 11 4151-9000 - CNPJ: 03.421.909/0001-01 - I.E: 373.083.103.117",  oFont09F)
oPrinter:Say(116,150, "www.pic-web.com.br.com.br - email@example.com",                     oFont09F)
oPrinter:Say(140,210, "PEDIDO DE VENDA Nº:" + SC5->C5_NUM ,                                    oFont14TC)
Else
oPrinter:SayBitmap( 80, 20, cLogo , 110, 60)
oPrinter:Say(80,80,"PHARMASPECIAL ESTEPCIALIDADES QUIMÍCAS E FARMACEUTICAS LTDA",              oFont14TC)
oPrinter:Say(100, 150,"Morada da Estrelas, 55 - Jd. Nova Itapevi - ITAPEVI - SP",              oFont09F)
oPrinter:Say(108,150, "Fone: 11 4151-9000 - CNPJ: 65.678.617/0001-06 - I.E: 373.083.103.117",  oFont09F)
oPrinter:Say(116,150, "www.pharmaspecial.com.br - email@example.com",                oFont09F)
oPrinter:Say(140,210, "PEDIDO DE VENDA Nº:" + SC5->C5_NUM ,                                    oFont14TC)
EndIf

oPrinter:Line(150,05,150,550)

cQuery += " SELECT  SC5.C5_FILIAL,SC5.C5_EMISSAO,SC5.C5_FECENT,SC5.C5_NUM,SC5.C5_CLIENTE,SC5.C5_TPFRETE,SC5.C5_MOEDA,SC5.C5_TXMOEDA,SC5.C5_PESOL,SC5.C5_PBRUTO," + CRLF
cQuery += " SA1.A1_NOME,SA1.A1_END,SA1.A1_BAIRRO,SA1.A1_CEP,SA1.A1_MUN,SA1.A1_EST,SA1.A1_DDD,SA1.A1_TEL,SA1.A1_CONTATO,SA1.A1_CGC,SA1.A1_INSCR,SA1.A1_EMAIL," + CRLF
cQuery += " SC5.C5_TRANSP,SA4.A4_NOME,SA4.A4_END,SA4.A4_BAIRRO,SA4.A4_CEP,SA4.A4_MUN,SA4.A4_EST,SA4.A4_DDD,SA4.A4_TEL,SA4.A4_CONTATO,SA3.A3_NOME,SC5.C5_CONDPAG," + CRLF
cQuery += " SE4.E4_COND,SE4.E4_DESCRI,SC6.C6_ITEM,SC6.C6_DESCRI,SC6.C6_QTDVEN,SC6.C6_UM,SC6.C6_PRCVEN,SC6.C6_XIPI,SC6.C6_XICMSRT,SC6.C6_VALOR,SC6.C6_XPROCLI," + CRLF
cQuery += " SC6.C6_PEDCLI,SC5.C5_MENNOTA,SC5.C5_XOBS" + CRLF"
cQuery += " FROM " +RetSqlName("SC5")+ " SC5(NOLOCK), " + CRLF
cQuery += "      " +RetSqlName("SA1")+ " SA1(NOLOCK), " + CRLF
cQuery += "      " +RetSqlName("SA4")+ " SA4(NOLOCK), " + CRLF
cQuery += "      " +RetSqlName("SA3")+ " SA3(NOLOCK), " + CRLF
cQuery += "      " +RetSqlName("SE4")+ " SE4(NOLOCK), " + CRLF
cQuery += "      " +RetSqlName("SC6")+ " SC6(NOLOCK)  " + CRLF
cQuery += " WHERE SC5.C5_NUM =" + SC5->C5_NUM + CRLF
cQuery += " AND SC5.C5_FILIAL = '" + xFilial ("SC5") + "'" + CRLF
cQuery += " AND SA1.A1_FILIAL = '" + xFilial ("SA1") + "'" + CRLF
cQuery += " AND SA1.A1_COD = SC5.C5_CLIENTE              " + CRLF
cQuery += " AND SA1.A1_LOJA = SC5.C5_LOJACLI             " + CRLF
cQuery += " AND SA4.A4_COD = SC5.C5_TRANSP               " + CRLF
cQuery += " AND SA3.A3_COD = SC5.C5_VEND1                " + CRLF
cQuery += " AND SE4.E4_CODIGO = SC5.C5_CONDPAG           " + CRLF
cQuery += " AND SC6.C6_NUM = SC5.C5_NUM                  " + CRLF
cQuery += " AND SA1.D_E_L_E_T_ = ' '                     " + CRLF
cQuery += " AND SC5.D_E_L_E_T_ = ' '                     " + CRLF
cQuery += " AND SA4.D_E_L_E_T_ = ' '                     " + CRLF
cQuery += " AND SA3.D_E_L_E_T_ = ' '                     " + CRLF
cQuery += " AND SE4.D_E_L_E_T_ = ' '                     " + CRLF
cQuery += " AND SC6.D_E_L_E_T_ = ' '                     " + CRLF

If Select("QRY") > 0
    Dbselectarea("QRY")
    QRY->(DbClosearea())
EndIf

TcQuery cQuery New Alias "QRY"

//Tratamento para campo data
TCSetField( 'QRY', "C5_EMISSAO", "D" )
TCSetField( 'QRY', "C5_FECENT", "D" )

//Tratamento para tarzer a descrição da moeda
_cMoeda := QRY->C5_MOEDA
DbSelectArea('SM2');SM2->(DbSetOrder(1));SM2->(DbSeek(DtoS(dDataBase)))
oPrinter:Say(310,iIF(_cMoeda==1,2200,2000),OemToAnsi('Moeda: '+GetMV("MV_SIMB"+cValToChar(_cMoeda),.F.,'') + iIF(_cMoeda==1,'',' - Taxa: '+TransForm(&("SM2->M2_MOEDA"+cValToChar(_cMoeda)),'@e 99.9999')) ),oFont09T)

oPrinter:Say(130, 435, "EMISSÃO: " +OemToAnsi(Dtoc(QRY->C5_EMISSAO)),                                                           oFont13T)
oPrinter:Say(140, 433, "ENTREGA: " +OemToAnsi(Dtoc(QRY->C5_FECENT)),                                                            oFont13T)
oPrinter:Say(160, 200, "DADOS DO CLIENTE ENTREGA",                                                                              oFont14TC)
oPrinter:Say(170, 10, "CLIENTE: ",                                                                                oFont10T)
oPrinter:Say(170, 50, +ALLTRIM(QRY->C5_CLIENTE)+ ' - ' +ALLTRIM(QRY->A1_NOME),                                                  oFont10F)
oPrinter:Say(180, 10, "ENDEREÇO: ",                                                                                oFont10T)
oPrinter:Say(180, 55, +ALLTRIM(QRY->A1_END),                                                                                oFont10F)
oPrinter:Say(190, 10, "BAIRRO: ",                                                                                oFont10T)
oPrinter:Say(190, 45, +ALLTRIM(QRY->A1_BAIRRO),                                                                                oFont10F)
oPrinter:Say(190, 300, "CEP: ",                                                                                oFont10T)
oPrinter:Say(190, 320, +ALLTRIM(QRY->A1_CEP),                                                                                oFont10F)
oPrinter:Say(200, 10, "CIDADE: ",                                                                                oFont10T)
oPrinter:Say(200, 45, +ALLTRIM(QRY->A1_MUN),                                                                                oFont10F)
oPrinter:Say(200, 300, "UF: ",                                                                                oFont10T)
oPrinter:Say(200, 320, +ALLTRIM(QRY->A1_EST),                                                                                oFont10F)
oPrinter:Say(190, 400, "INSC. EST.: ",                                                                                oFont10T)
oPrinter:Say(190, 455, +ALLTRIM(TransForm(QRY->A1_INSCR, '@r 999.999.999-99')),                                                 oFont10F)
oPrinter:Say(200, 425, "CNPJ: ",                                                                                oFont10T)
oPrinter:Say(200, 455, +ALLTRIM(TransForm(QRY->A1_CGC, '@r 99.999.999/9999-99')),                                               oFont10F)
oPrinter:Say(210, 10, "CONTATO: ",                                                                                oFont10T)
oPrinter:Say(210, 50, +ALLTRIM(QRY->A1_CONTATO),                                                                                oFont10F)
oPrinter:Say(210, 200, "TEL: ",                                                                                oFont10T)
oPrinter:Say(210, 220, '('+ALLTRIM(QRY->A1_DDD)+')'+ALLTRIM(TransForm(QRY->A1_TEL, '@r 9999-9999')),                            oFont10F)
oPrinter:Say(210, 300, "E-MAIL: ",                                                                                oFont10T)
oPrinter:Say(210, 335, +ALLTRIM(QRY->A1_EMAIL),                                                                                oFont10F)

oPrinter:Line(215,05,215,550)

oPrinter:Say(225,200, " DADOS DO TRANSPORTE",                                                                                oFont14TC)
oPrinter:Say(235, 10, "TRANSPORTADORA: ",                                                                                oFont10T)
oPrinter:Say(235, 80, +ALLTRIM(QRY->C5_TRANSP)+ ' - ' +ALLTRIM(QRY->A4_NOME),                                                   oFont10F)
oPrinter:Say(245, 10, "ENDEREÇO: ",                                                                                oFont10T)
oPrinter:Say(245, 55, +ALLTRIM(QRY->A4_END),                                                                                oFont10F)
oPrinter:Say(255, 10, "BAIRRO: ",                                                                                oFont10T)
oPrinter:Say(255, 45, +ALLTRIM(QRY->A4_BAIRRO),                                                                                oFont10F)
oPrinter:Say(255, 300, "CEP: ",                                                                                oFont10T)
oPrinter:Say(255, 320, +ALLTRIM(QRY->A4_CEP),                                                                                oFont10F)
oPrinter:Say(265, 10, "CIDADE: ",                                                                                oFont10T)
oPrinter:Say(265, 45, +ALLTRIM(QRY->A4_MUN),                                                                                oFont10F)
oPrinter:Say(265, 300, "UF: ",                                                                                oFont10T)
oPrinter:Say(265, 320, +ALLTRIM(QRY->A4_EST),                                                                                oFont10F)
oPrinter:Say(275, 10, "CONTATO: ",                                                                                oFont10T)
oPrinter:Say(275, 50, +ALLTRIM(QRY->A4_CONTATO),                                                                                oFont10F)
oPrinter:Say(275, 200, "TEL: ",                                                                                oFont10T)
oPrinter:Say(275, 220, '('+ALLTRIM(QRY->A4_DDD)+')'+ALLTRIM(TransForm(QRY->A4_TEL, '@r 9999-9999')),                            oFont10F)

oPrinter:Line(280,05,280,550)

 oPrinter:Say(290,200, " DADOS INTERNOS",                                                                                oFont14TC)
 oPrinter:Say(300, 10, "VENDEDOR(A): ",                                                                                oFont10T)
 oPrinter:Say(300, 70, +ALLTRIM(QRY->A3_NOME),                                                                                oFont10F)
 oPrinter:Say(300, 220, "COND. PGTO.: ",                                                                                oFont10T)
 oPrinter:Say(300, 280, +ALLTRIM(QRY->E4_COND)+ '/' +ALLTRIM(QRY->E4_DESCRI),                                                   oFont10F)
 oPrinter:Say(300, 430, "TIPO FRETE: ",                                                                                oFont10T)
 oPrinter:Say(300, 485, +ALLTRIM(QRY->C5_TPFRETE),                                                                              oFont10F)
 oPrinter:Say(310, 10,  "MOEDA: ",                                                                                oFont10T)
 oPrinter:Say(310, 40,  OemToAnsi(GetMV("MV_SIMB"+cValToChar(QRY->C5_MOEDA),.F.,'')),                                           oFont10F)
 oPrinter:Say(310, 55, ' - ' +cValTochar(QRY->C5_TXMOEDA),                                                                      oFont10F)
 oPrinter:Say(310, 190, "PED. CLIENTE: ",                                                                                oFont10T)
 oPrinter:Say(310, 255, +ALLTRIM(QRY->C6_PEDCLI),                                                                               oFont10F)
 oPrinter:Say(310, 400, "PROD. CLIENTE: ",                                                                                oFont10T)
 oPrinter:Say(310, 470, +ALLTRIM(QRY->C6_XPROCLI),                                                                              oFont10F)
 oPrinter:Say(320, 10, "OBSERVAÇÃO: ",                                                                                oFont10T)
 oPrinter:Say(320, 65, +ALLTRIM(QRY->C5_XOBS),                                                                                oFont10F)
 oPrinter:Say(330, 10, "MENSAG. NOTA: ",                                                                                oFont10T)
 oPrinter:Say(330, 75, +ALLTRIM(QRY->C5_MENNOTA),                                                                               oFont10F)

oPrinter:Line(335,05,335,550)

oPrinter:Say(345,200, " ITENS DO PEDIDO ",                                                                                oFont14TC)

//nLin += NSpace30

oPrinter:FillRect({350, 05, 350+010, 550}, oHGRAY)
oPrinter:Line( 335      ,05 , 60,     05)
oPrinter:Line( 60       ,05 , 60,     550)
oPrinter:Line( 335      ,550 , 60,     550)
oPrinter:Line( 350      ,05 , 350   , 550)
oPrinter:Line( 350+10   ,05 , 350+10, 550)
oPrinter:Line( 350      ,05 , 350+10,  05)
oPrinter:Line( 350      ,05 , 350+10,  05)
// Linhas horizontais
oPrinter:Line( 350      ,40  , 350+10,  40)
oPrinter:Line( 350      ,260 , 350+10,  260)
oPrinter:Line( 350      ,310 , 350+10,  310)
oPrinter:Line( 350      ,340 , 350+10,  340)
oPrinter:Line( 350      ,400 , 350+10,  400)
oPrinter:Line( 350      ,430 , 350+10,  430)
oPrinter:Line( 350      ,480 , 350+10,  480)
oPrinter:Line( 350      ,550 , 350+10,  550)

oPrinter:Say(357, 12, "ITENS",                                                                                oFont7TA)
oPrinter:Say(357, 45, "DESCRIÇÃO - PRODUTOS",                                                                                oFont7TA)
oPrinter:Say(357, 277, "QTDA.",                                                                                oFont7TA)
oPrinter:Say(357, 317, "UNID.",                                                                                oFont7TA)
oPrinter:Say(357, 353, "VLR. UNIT.",                                                                                oFont7TA)
oPrinter:Say(357, 409, "% IPI",                                                                                oFont7TA)
oPrinter:Say(357, 442, "ICMSRET",                                                                                oFont7TA)
oPrinter:Say(357, 505, "TOTAL",                                                                                oFont7TA)

nLinha1 := 360
nLinha2 := 367
nLinha  := 370

While !("QRY")->(EOF())

   oPrinter:Line( nLinha  ,05 , nLinha   , 550)

   oPrinter:Line( nLinha1 ,05  , nLinha1+10,  05)
   oPrinter:Line( nLinha1 ,40  , nLinha1+10,  40)
   oPrinter:Line( nLinha1 ,260 , nLinha1+10,  260)
   oPrinter:Line( nLinha1 ,310 , nLinha1+10,  310)
   oPrinter:Line( nLinha1 ,340 , nLinha1+10,  340)
   oPrinter:Line( nLinha1 ,400 , nLinha1+10,  400)
   oPrinter:Line( nLinha1 ,430 , nLinha1+10,  430)
   oPrinter:Line( nLinha1 ,480 , nLinha1+10,  480)
   oPrinter:Line( nLinha1 ,550 , nLinha1+10,  550)
   oPrinter:Say( nLinha2, 15, +ALLTRIM(("QRY")->C6_ITEM),                                                                            oFont09F )
   oPrinter:Say( nLinha2, 45, +ALLTRIM(("QRY")->C6_DESCRI),                                                                          oFont09F )
   oPrinter:Say( nLinha2, 275, +TRANSFORM(("QRY")->C6_QTDVEN,'@e 999.99'),                                                           oFont09F )
   oPrinter:Say( nLinha2, 320, +ALLTRIM(("QRY")->C6_UM),                                                                             oFont09F )
   oPrinter:Say( nLinha2, 350, +TRANSFORM(("QRY")->C6_PRCVEN,'@E 999,999.999'),                                                      oFont09F )
   oPrinter:Say( nLinha2, 400, +TRANSFORM(("QRY")->C6_XIPI,'@E 999.99'),                                                             oFont09F )
   oPrinter:Say( nLinha2, 420, +TRANSFORM(("QRY")->C6_XICMSRT,'@E 999,999.999'),                                                     oFont09F )
   oPrinter:Say( nLinha2, 490, +TRANSFORM(("QRY")->C6_VALOR,'@E 999,999.999'),                                                       oFont09F )
   nLinha1 += 10
   nLinha2 += 10
   nLinha  += 10

   nTotal    += QRY->C6_VALOR
   nIpi      += (QRY->C6_VALOR * QRY->C6_XIPI)/100
   nIcmsSub  += QRY->C6_XICMSRT

   QRY->(DbSkip())

EndDo

nTotalF   += (nTotal + nIpi + nIcmsSub)

oPrinter:Box(nLinha1,    05, nLinha1+80, 550)
oPrinter:Line( nLinha+55  ,05 , nLinha+55   , 550)
oPrinter:Say(nLinha1+15, 15, "SUBTOTAL: ",                                                                                oFont14TC)
oPrinter:Say(nLinha1+15, 90, +TRANSFORM(nTotal,'@E 999,999.999'),                                                                    oFont14TC)
oPrinter:Say(nLinha1+30, 15, "TOTAL IPI: ",                                                                                oFont14TC)
oPrinter:Say(nLinha1+30, 90, +TRANSFORM(nIpi,'@E 999,999.999'),                                                                      oFont14TC)
oPrinter:Say(nLinha1+45, 15, "ICMS SUB.: ",                                                                                oFont14TC)
oPrinter:Say(nLinha1+45, 90, +TRANSFORM(nIcmsSub,'@E 999,999.999'),                                                                  oFont14TC)
oPrinter:Say(nLinha1+60, 15, "TOTAL FAT.: ",                                                                                oFont14TC)
oPrinter:Say(nLinha1+60, 90, +TRANSFORM(nTotalF,'@E 999,999.999'),                                                                   oFont14TC)

oPrinter:Say(nLinha+65,  45, "PESO LIQUIDO: ",                                                                                oFont10T)
oPrinter:Say(nLinha+65,  90,  +TRANSFORM(SC5->C5_PESOL,'@E 999,999.999'),                                                            oFont10F)
oPrinter:Say(nLinha+65,  355, "PESO BRUTO: ",                                                                                oFont10T)
oPrinter:Say(nLinha+65,  390, +TRANSFORM(SC5->C5_PBRUTO,'@E 999,999.999'),                                                           oFont10F)

oPrinter:EndPage()

If lPreview
     oPrinter:Preview()
EndIf

FreeObj(oPrinter)
oPrinter := Nil

Return .T.
</code>
Answer: Acredito que a causa do erro esteja no fato de você estar re-executando um PREPARE ENVIRONMENT, dentro de uma função ( U_TSTREL ) que está sendo chamada a partir de uma opção de Menu ou Browse, onde você já tem o ambiente / contexto de execução do ERP já preparado. Recomendo remover as chamadas de RPCSetEnv() e Prepare Environment, desnecessárias neste caso, e verifique se isso resolve o problema.
Comment: Muito obrigado, retirei esta parte da minha função e deu certo não apareceu mais o erro....Muito obrigado

Estou com este erro em advpl


Python code in AWS Lambda to load Shapefile to PostGIS(RDS)

Question: I am new to GIS implementation. I am trying to develop AWS Lambda Code in Python to Load Shape File Dynamically.
I developed the code after doing some research and it is perfectly working on my local.
But the same code is troubling when I am trying to run in AWS Lambda.
I have added libraries(Lambda Layers) for 'OSGEO/GDAL' in AWS Lambda and tested it by calling import and it's working fine.
Following is the code :
<code>import os
import subprocess
import boto3
import urllib.parse
from osgeo import gdal
from osgeo import ogr

s3 = boto3.client('s3')

def lambda_handler(event, context):

    bucket = event['Records'][0]['s3']['bucket']['name']
    s3key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'], encoding='utf-8')

    # input shapefile
    input_shp = ('s3://' + bucket + '/' + s3key)

    # database options
    db_schema = "SCHEMA=public"
    overwrite_option = "OVERWRITE=YES"
    geom_type = "MULTILINESTRING"
    output_format = "PostgreSQL"

    # database connection string
    db_connection = """PG:host=<RDS host name> port=5432 user=<RDS User Name> dbname= postgres password=<RDS Password>"""

    # call ogr2ogr from python
    subprocess.call(["ogr2ogr", "-lco", db_schema, "-lco", overwrite_option, "-nlt", geom_type, "-f", output_format, db_connection, input_shp])
</code>
Error Message is :
<code>[ERROR] FileNotFoundError: [Errno 2] No such file or directory: 'ogr2ogr': 'ogr2ogr'

</code>
The same code is working fine on my local with only difference that instead of S3 I am providing hard-coded path where shape file is stored on my local machine.
Any suggestions!
Comment: How did you deply the lambda? In my understanding, here the dependency is missing
Comment: @tsamaya - Dependencies I have implemented via AWS Layers.
Answer: GDAL/Osgeo is a bit problematic when it comes to Python.
But this works on me. You can use this :https://github.com/developmentseed/geolambda
You just need to add these layers to your lambda function.


Which one is better for handling spatio-temporal data: 3D CNN vs 2D Recurrent CNN?

Question: Please forgive my ignorance and lack of experience: I am asking this question seeking answer from the experts/experienced persons in the field.
I have a training dataset where each sample is a 3D cube (x,y,t) with grid points of (Nx = 256, Ny = 256, Nt = 200). The input consists of spatio-temporal evolution of a specific wave propagation. However, the input is also corrupted by other unwanted wave modes and noise components. I need to build a neural network (possibly convolutional auto-encoder or something similar) that can provide 3D output cube where the target wave propagation is mapped in space and time, effectively denoised of the unwanted wave modes and noises.
My question is: should I consider a 3D convolutional neural network for this task? Or, since each (x,y) frames are stored in a collection of a time series from t(1) to t(n) in the 3D cube, should I try a Recurrent 2D convolutional neural network for this job? Is there any advantage of trying one over the other?
Eventually I have to do this for 4D cube (x,y,z,t) with grid points of (Nx = 256, Ny = 256, Nz = 100, Nt = 200). In that case, would a Recurrent 3D convolutional neural network be better than 4D convolutional neural network?
If you have any literature in mind regarding this, please share. Thanks in advance.
Answer: The question to ask knowing how filters work is will looking at them all at once help? A filter is a nnd size and is placed at each nnd grid. It computes a dot product across the depth of the image. So in rgb case, to classify a region we want to look at all rgb channels in a single view as they provide complementary information about the object at that point. However in your case, you have to ask if the noise at the 100'th image influences noise at the first few images. The filters will necessarily try to form such links as they look through the depth.
3D filters go furthur, being of size nnd*p, they not only look through depth but also across the temporal blocks. In order to segment the square on the top right of the first image, you will be looking at the top right of all images across time. Try to visualize it and see what the dot product is considering. Ask if looking at all this information is needed to segment one region. If not, then your network will have a very hard time figuring the same out.
I think recurrent networks will work better.
Btw: As segmentation is poorly explained as compared to classification I made a video to provide some intuition. You may find it useful :https://youtu.be/NzY5IJodjek
Let me know if you have any more questions.


Visual Studio 2010 Setup/Deployment Project targeting Windows 2000

Question: I'm currently working on a C#/.NET project in Visual Studio 2010. The target framework for this application is .NET 2. As for the deployment of this project on my target system, I'm using a Deployment Project in my Visual Studio solution.
As for installing my binaries on a XP (or higher) system, there's no problem. But when I try to deploy on a Windows 2000 system, my Setup.exe will not work. It will immediately throw an exception The procedure entry point GetNativeSystemInfo could not be located in the dynamic link library KERNEL32.DLL.
I do have Windows Installer 3.1 on my Windows 2000 system. My guess is that this problem is because Windows 2000 doesn't support installers created by Visual Studio 2010, but I wonder if someone can confirm that. An if so - is there a workaround in VS 2010 or do I need to build my solution on, let's say, VS 2008?
Cheers!
Comment: According the [Microsoft's system requirements page](http://msdn.microsoft.com/en-us/library/ms229070(VS.80).aspx), you must have at least Windows 2000 ***SP4***. Can you check this?
Answer: Since I couldn't really solve this problem, the best workaround for me in this case was to simply rebuild my project in VS 2008. Solution files built in VS 2010 are not backwards compatible with VS 2010, so I had to create a new solution in VS 2008 and add all my projects from VS 2010 to that solution.


Geometry (Finding angle $x$)

Question: So everybody was given this question:
in the recent new zealand mathematics exam yesterday (for students aged 14-15), and most if not everybody was stumped by it.
How would you solve this?
Comment: First thing to figure out is, is it possible that a kite can fit in a square at an oblique angle.  If not then $FG = GH = \frac 12 DG$ and $\angle FGD = 60$ and $\angle DGB = 30$ and $\angle GDB=(180 -30)/2 = 75$ so $\angle DBE = 75 + 75 = 150$.  But is it possible that $FG \ne GH$?  That needs to be figured out first.
Answer: I think you mean that $B$ and $G$ they are mid-points of $FH$ and $AC$ respectively.
Since $FG=\frac{1}{2}BG= \frac{1}{2}DG,$ we obtain:
$$\measuredangle DGB=\measuredangle FDG=30^{\circ}.$$
Thus, $$\measuredangle DBE=2\measuredangle DBG=2\cdot75^{\circ}=150^{\circ}.$$
Comment: How do you conclude DGB is 30 degrees?
Comment: @dydxx I added something. See now.
Comment: Shouldn't that mean 2*60 = 120?
Comment: No! Because $\measuredangle GDB=75^{\circ}\neq90^{\circ}.$.
Comment: How do you know $FG = \frac 12 BG$.  I.e. how do you know a kite must fit in symmetrically?
Comment: @fleablood I agree with you. The given is not full.
Comment: A slightly more interesting problem is to start with $x=150^\circ$, $DG=EG$, and $FG=HG$, and prove that $\measuredangle DGE=60^{\circ}$. With trigonometry, this is easy since $\tan 60^\circ +\tan 15^\circ=2$. But a purely geometric proof, with ruler and straightedge only, might take a bit longer.
Comment: I think the problem needs more information to be given to be rigorously solved. Being given that G is the midpoint of FH is sufficient. Right now, it's not possible to conclude that BG is a line of symmetry for the whole figure, and that's crucial.
Comment: Yes, I agree with you.
Comment: Surely someone can trig-chase this.  Suppose $\angle FGB=\theta \ne 90$ then, we can using trig express the lengths of $DF, FG, GH, HE$ etc. in terms of angles and knowing that $AF = FH = HC = AC$ while $BG = DG = GE$ can we not conclude those are only consistant if $\theta = 90$.  I mean, *I*'m not going to do it, but... can't it be done.
Comment: Oh, wait.  The "top" of a kite, can be anything independent of a the bottom. So just as we can fit a symmetric kite into squares or rectangles of any dimension, we can stick asymmetic kits into squares or rectiangles of nearly any dimensions (some restrictions of course).  So we can fit an assymetrical kite into a square.  Just stick it into a rectangle and "pop" the top of the kite out until the sides of the rectangle are equal.... So no, we do not have enough information.
Answer: There isn't enough information.  If we assume $G$ is the midpoint of $FH$ or if we assume the kite is symmetrically aligned with the square so that line $DE$ is parallel with $FH$ then by Michael Rozenberg's and Deepak's deleted answer we can conclude that the angle is $150$.
But if the kite is inserted into the square at an angle so that $G$ is not the midpoint and $DE$ is not parallel, we can not conclude anything.  Suppose we place point $B$ on line $AC$ slightly to the left of $G$ on line $FH$.  There will be one pair of points $D,E$ so that $BG= DG= EF$, but those might not forma a kite if $BD \ne BE$.  However but sliding $B,G$ to the left or right we will force point $D$ lower or higher and point $E$ higher or lower, and line $DB$ longer or shorter and line $BE$ shorter or longer.  The will be one precise point where $DB = BE$ and an assymetric kite was placed in the square.
There are several such kites depending on how "askance" points $B$ and $G$ are from each other.  But they will all form angles $DBE$ that are $\ge 150$, if I am not mistaken[$*$], with $BDE = 150$ precisely at the one symmetrical embedded kite.
Somehow, I suspect the original problem either indicated the kite was inserted symmetrically, or it was assumed.
[$*$] A big "if".  But I'm pretty sure the wider "askew" the kite is aligned, the larger angle $DBE$ will be.

Geometry (Finding angle $x$)


Normality plot and shapiro test for repeated-measures ANOVA: near significant but not quite

Question: I have a repeated-measures anova (Two-way), and I want to check for normality; my plots show this:
lmerabsolute <- aov(Proportionofundershoots~ Target*Experiment + (ID/(Target*Experiment)), data=overallundershootproportion)

However, my shapiro test shows this:
shapiro.test(resid(lmerabsolute))

    Shapiro-Wilk normality test

data:  resid(lmerabsolute)
W = 0.98896, p-value = 0.001789

What do I do? I would be so grateful for some advice!
When I arcsine transform the data, my new shapiro test result looks like this:
Shapiro-Wilk normality test

data:  resid(lmerabsolute)
W = 0.98975, p-value = 0.003128

Here is the arcsine transformed normality plot:

So definitely an improvement! I have not managed to get a more significant P-value than this!
Comment: Please say more about the details of your data and experimental design. If your outcome is a proportion, as the name `Proportionofundershoots` suggests, then a mixed-effects ANOVA such as you have done might not be the best analysis to pursue. Also, please say more about why you are doing normality testing; see [this page](https://stats.stackexchange.com/q/2492/28500) for an introduction to why such testing often can be unnecessary or even misleading.
Comment: Why would you use a *test* when the conditional response is obviously not continuous? The null is immediately false. What could the test tell you that you don't already know for sure? The QQ plot addresses a somewhat more useful question ("how far from normal" in some sense), though there are still issues with choosing analyses by looking at your data.
Answer: Based on your first graph, your problem is granularity; there is a limited number of values that happen often. It is impossible to (meaningfully) fix that using a transformation. So, the second graph suggests to me that you made an error when applying the arcsine transformation. Appart from the granularity, the original distribution does not look bad, so I would stick with that. Based on eyeballing your graph, the number of observations is large enough, such that a statistically "significant" result could easily be the result of a substantively insignificant deviation from the null hypothesis. So the tests are not that meaningful in your case.


Preventing double booked appointments in Outlook

Question: At our organization we use a series of shared Outlook calendars to schedule out our conference rooms.  All domain users are setup as authors of these calenders.  We are now running into a problem where the end user is either not checking/caring if a room already has an appointment assigned to the room for the period of time that they want to use it.  So my question is this:  Is there any way to prevent a user from scheduling an appointment or meeting on one of these calendars when there is already a preexisting one on it?
We've already tried going into Options -> Resource Scheduling and checking "Automatically decline conflicting meeting requests," but this did not resolve the issue.
Comment: What version of exchange are you running?
Comment: Server is Exchange 2007--Clients are mostly Outlook 2003 with a couple running 2007.
Answer: I'd recommend that you set up your conference rooms as resources.  You can then use resource booking to prevent this from happening.  Have a look at this article from MSExchange.org for Exchange 2003.
Here are articles for Exchange 2007 for making Resource Mailboxes.

Part 1
Part 2
Part 3
Answer: I believe you would have to set these up as shared resources (Resource Mailboxes in 2007) and use the "Invite" feature rather than giving users the ability to directly schedule appointments in the calendar.  Then your Resource Scheduling options would apply.
Answer: If they are already not looking at the meeting responses coming back from the resources (I think that's what you are describing) what do you want to have happen when the response comes back declined?  I think this is more of a user education issue than a technical one.  That being said, exchange has a whole event sink architecture you can hook into.  It involves writing code but you can do pretty much anything you want.


Exchange rule regex on sender name not address

Question: In Exchange 2013, is ist possible to create a Transport regex rule based on the sender name, not the sender emailaddress?
The goal is to identify fake senders, using the name field for a fake emailaddress.
Normal: "John Doe "
Bad: "email@example.com "
The very goal would be to identify two @ in the Sender, an exception would be, when both are the same like
"firstname.lastname@example.com "
Answer: I'm afraid not, there's no special rule action to compare the sender name and its email address, also it's not a valuable way to prevent "fake" sender.
Instead, the SPF record will be used to declare and verify who can send e-mails from a given domain. Thus, we can use it to detect and prevent spoofing message.


Can I enforce a cipher suite with powershell

Question: Can I enforce a cipher suite to be used when connecting to a TLS web site via a script.
For monitoring and trouble shooting purposes, my goal is to create a powershell script that checks if a remote server is able to use a specific cypher. I'm using the command Invoke-WebRequest now to connect to the websiste, but as far as I can see, there is no option to enforce a cipher.
Google was not friendly to me either.
Thanks for helping out.
PS: Powershell is prefered, but command line or vbscript is also fine.
Answer: As far as I know you have no control over what cipher suite is used from PowerShell or dot.net, the underlying Windows APIs will negotiate the 'best' suite with the server.
I am using https://github.com/nabla-c0d3/sslyze/ which also has a binary exe version to test for cipher suites. When calling it from PowerShell, you have to do some parsing of the output. Or use the native Python implementation.
Of look at the Python code to see what they are doing.
Answer: You kind of can.
When looking at this page, you can set your own Cipher with the highest priority to use:
<code>PS C:\>Enable-TlsCipherSuite -Name "TLS_DHE_DSS_WITH_AES_256_CBC_SHA" -Position 0
</code>


FFTW3 2D, passing fftw_complex array

Question: I am trying to implement the directions in here to calculate 2D Fourier transform:
#include <stdio.h>
#include <stdlib.h>
#include </usr/local/include/fftw3.h>
#include <math.h>

#define NUM_POINTS 600

#define REAL 0
#define IMAG 1

void acquire_from_somewhere(fftw_complex *signal) {

    int i, j, m_gamma=2, Lambda=1;
    double theta=0.095,kappa=5.;
    for (i = 0; i < NUM_POINTS; ++i) {
    for (j = 0; j < NUM_POINTS; ++j) {
    double x = (double)i / (double)NUM_POINTS * M_PI, y = (double)j / (double)NUM_POINTS * M_PI;

    signal[i][j][REAL] = Lambda*cos(theta/2)*cos(theta/2)*cos(m_gamma * atan(y/x));

    signal[i][j][IMAG] =0.;
    }}
}

void do_something_with(fftw_complex *result, double *mag) {
    int i,j;
    for (i = 0; i < NUM_POINTS; ++i) {
    for (j = 0; j < NUM_POINTS; ++j) {
        *mag = sqrt(result[i][j][REAL] * result[i][j][REAL] + result[i][j][IMAG] * result[i][j][IMAG]);

        printf("%g\n", *mag);
    }}
}

/* Resume reading here */

int main() {

    double mag;
    fftw_complex signal[NUM_POINTS][NUM_POINTS];
    fftw_complex result[NUM_POINTS][NUM_POINTS];

    fftw_plan plan = fftw_plan_dft_2d(NUM_POINTS,NUM_POINTS,
                                  &signal[0][0],
                                  &result[0][0],
                                  FFTW_FORWARD,
                                  FFTW_ESTIMATE);

    acquire_from_somewhere(&signal[0][0]);
    fftw_execute(plan);
    do_something_with(&result[0][0], &mag);

//    printf("%g\n", mag);

        fftw_destroy_plan(plan);

        return 0;
}

I get the following kind of errors:
FFT.c:26:21: error: subscripted value is not an array, pointer, or vector
    signal[i][j][REAL] = Lambda*cos(theta/2)*cos(theta/2)*cos(m_gamma * atan(y/x));//Lambda*(cos(theta/2)*cos(theta/2)*cos(m_gamm...
    ~~~~~~~~~~~~^~~~~

I am not sure where to look... I suppose, conventional way of passing the 2D array doesn't work for fftw_complex. How to fix my mistake?
Answer: fftw_complex *signal

Indicates a pointer to an fftw_complex is being passed, possibly a decayed 1D array.
A 3D array decays into a pointer to a 2D array. So you should have written that argument as
fftw_complex (*signal)[][]

Also in your question, you talk about 2D arrays yet treat signal as a 3D array, inconsistent.
Comment: Thank you! According to the manual fftw_complex [size][size] is 2D, with the third implicit dimension [1]-imaginary and [0]-real. If I said 3D, one might have thought about fftw_complex [size][size][size] case... I follow the manual definitions.
Comment: This way I get: error: array has incomplete element type 'fftw_complex []'
void acquire_from_somewhere(fftw_complex (*signal)[][])

FFTW3 2D, passing fftw_complex array


Can someone help me understand this Jorja Smith song?

Question:

I'm a beginner as far as music theory goes however would like to know more about this song. I notice that the piano is changing keys constantly but it still sounds good. Does this have something to do with modes and if so what mode is she playing in? Would also appreciate some beginner readings/piano pieces.
Answer:
I'm a beginner as far as music theory goes however would like to know
  more about this song.

When you study first information about chords you would know and understand a lot more about this song. It is always motivating to everybody if first there are questions about chords and then you read about chord building.

I notice that the piano is changing keys constantly but it still
  sounds good.

In almost all piano pieces the chords change (not the key):

Does this have something to do with modes and if so what mode is she playing in?

some chords are just borrowed from other keys as substitution for the mode chords he is playing in. I could write you down the chords but this is not the purpose of this site.
There are keyboards that show the chords on a display on the desk.
you might also look up for a midi file and load down a midi player that analyzes the chords.

Would also appreciate some beginner readings/piano pieces.

While I'm writing this answer youtube is playing some more examples  of  Jorja Smith Piano Tutorial:
they would all fit or benefit for a beginner! as you like this style you should try to write down the sheet music, so you will achieve the ability of reading:
!READING BY WRITING!
and you will understand better the chords and the explications about the theory of the chords.


Geolocate a PostGIS database

Question: I have a PostGIS database with addresses (street with number, city, state) and fields for lat and long as well as geometry. I geolocated some of the addresses before bringing into PostGIS but since have added other addresses. How do I geolocate these addresses.
FWIW they are all in the same city, but I have city and state fields.
A major problem will be many of the addresses won't exist or will have different coordinates because the addresses are from 100 or more years ago. I know I'll have to do some of the addresses manually using overlay maps from the period.
I see plenty of suggestions on how to geolocate CSV files, but not using directly from QGIS or pgAdmin!
The database is managed in Ruby on Rails if that's a better way to tackle this.
Comment: if you have lat long, just create the geometry object as a point, not sure what is the problem
Comment: I don't have lat long for some of the addresses.
Comment: Then you ask the wrong  question.  If you have a layer for state city you can geolocate aprox, but you probably will need do something by hand
Comment: I have address, city and state fields; and I want to geolocate and fill the lat and long fields. This is in a PostGIS database.
Comment: beside your address, what layers you have in Postgis?
Comment: I have layers on QGIS, but not in PostGIS AFAIK. I have other tables.
Answer: Take a look at the Tiger Geocoder, which only works for U.S. addresses. Install it with:
<code>CREATE EXTENSION IF NOT EXISTS postgis;
CREATE EXTENSION fuzzystrmatch;
CREATE EXTENSION postgis_tiger_geocoder;
</code>
Then load the data for your State(s), and the use Geocode to approximate the geometry. For historic addresses, perhaps you can request historic TIGER data from these guys (although I have no idea if they actually have digitized census data from 100 years ago).

Otherwise, if you know Python, there are a range of services you can use with geopy to geocode locations from addresses.
Comment: Thank you. I'll try to get my head around this. I ran your installation.

From your link I gather I need to write SQL to do what I want. I'll give it a go.
Comment: I followed Mike T's suggestion and found  National Historical Geographic Information System (NHGIS),  http://nhgis.org.
Answer: Thanks you Mike T, your answer got me looking with clearer understanding of what I needed. I followed http://railscasts.com/episodes/273-geocoder describing using the Ruby geocoder gem which I was able to integrate into my Rails project.
I understand that I answered a different question than I asked. I haven't completely done this, but I think it will be easier than what I was thinking of. I may have to force it for each address, but I don't have that many.

Geolocate a PostGIS database


Authenticating DNS Queries

Question: Is there any way to use a TSIG (or other) key in combination with a DNS query to authenticate into a DNS view for use with recursion?  Something like:
key trusted-key {
    algorithm HMAC-SHA256;
    secret "blonggggg";
};

acl trusted { key trusted-key; };

view trusted {
    match-clients { trusted; };
    allow-recursion { any; };
};

If so, how would the querying client go about specifying the key for authentication?  What if it can be guaranteed that the queries are always coming from a downstream DNS server providing local caching DNS for a branch office?  Can the downstream DNS server be configured to use a particular key with all of the queries it's forwarding to the upstream server?
Thanks.
Comment: I do not believe you can configure DNS clients with TSIG (or other) keys. How do you plan on distributing the key and preventing others from using your key also?
Answer: For testing purposes, you could just use dig -k ... or dig -y ....
For client machines to do this directly, I do not think it's viable. I'm not aware of any OS having a stub resolver that actually does TSIG signing.
However, it is possible to have a forwarding nameserver which uses TSIG to sign the forwarded queries.
You could do something like this (possibly on both ends, depending on the scenario):
key trusted-key {
    algorithm HMAC-SHA256;
    secret "x";
};

server 192.0.2.1 {
    keys { trusted-key.; };
};

This will cause BIND to always use the specified key to sign queries to the other server (identified by IP).
From the server section in the manual:

The keys clause identifies a key_id defined by the key statement, to be used for transaction security (TSIG, the section called "TSIG") when talking to the remote server. When a request is sent to the remote server, a request signature will be generated using the key specified here and appended to the message. A request originating from the remote server is not required to be signed by this key.
Only a single key per server is currently supported.
Comment: I guess for mobile clients, I can run a local caching-only DNS that forwards all queries to the central server and authenticates with TSIG.  Thanks.

Authenticating DNS Queries


SourceTree lost all branches and commits

Question: A random thing happened on SourceTree, working fine yesterday but loaded it up this morning to do some more work and everything has disappeared. SourceTree now wants me to commit everything again as if it was the first commit.
Strangely, running git log --all in the terminal does show all the commits. I am getting this when trying to git log normally.
fatal: bad default revision 'HEAD'

Is there any way to repair this so I can see all my branches and commits again.
Answer: To anyone who has experienced this problem here is how I have fixed it from piecing together various other posts.
First you need to get your last commit, adding the --all worked for me otherwise I'd get "fatal: bad HEAD" error.
git reflog --all

Then you need to check to make sure you have a HEAD file. If not I recreated one by doing the following:
echo ref: refs/heads/master >.git/HEAD

Once this has been done you should be able to hard reset to the most recent commit using:
git reset --hard 73b9363

Replace the commit id after --hard for the commit which is the newest from your git reflog --all.


URL alias in page.tpl.php

Question: I try to make link 'Mobile version' on site page site.com/page. This link leads to this page but on subdomain m.site.com/page.
I use page.tpl.php. I try to write this.
<a href="http://m.site.com/<?php print drupal_get_path_alias();?>">Mobile version

<?php print drupal_get_path_alias();?> prints nothing. What's wrong? Maybe there is some more elegant and right way to solve this?
Comment: [drupal_get_path_alias](https://api.drupal.org/api/drupal/includes%21path.inc/function/drupal_get_path_alias/6.x) requires at least one argument for Drupal 6.
Answer: Your code only work for Drupal 7. As you are using Drupal 6, please pass the current url as argument.
print drupal_get_path_alias($_GET['q']);

URL alias in page.tpl.php