Dúvida com manipulação de TreeView e arquivos TXT delimitado

Question: estou com uma pequena dificuldade com Delphi, estou criando uma pequena aplicação bem básica pra eu gerenciar contas, de jogos, emails etc algo bem básico.. e eu resolvi usar o esquema do TreeView como base de listagem das contas, mas estou tendo uma grande dificuldade o que eu quero fazer basicamente é registrar arquivos num TXT, e fazer com que a aplicação leia o arquivo delimitado por ";" e ele crie itens e subitens dependendo do que eu quero visualizar, como se cada item fosse uma categoria, tipo Emails, Jogos, etc... Vou enviar uma Print de como eu queria tirar umas dúvidas se alguém puder me ajudar com isso e souber.. agradeço desde já
Comment: qual é a duvida ao certo?
Comment: Eu queria fazer a aplicação ler arquivos de texto delimitados por ;  e ler os dados como está na imagem, só que até  ai de ler ta OK funciona, o fato é botar isso numa Treeview, tipo cada  Nó principal ser usado  a primeira TAG de cada coluna por exemplo
"Email, Games, Steam" como Tags Pais ou seja os subitens seriam apenas  o resto das informações especificas de cada categoria
Answer: Como você apontou nos comentários, que a sua dificuldade é montar uma estrutura no TreeView, vou deixar uma solução com esse foco.
Para a solução usei:

Um TMemo como base para o arquivo.
Um TTreeView.
Um TValueListEditor para armazenar os campos que ficarão fora da árvore, invisível pois vai servir apenas para guardar os dados temporários.
Outro TMemo para mostrar os campos do nó selecionado na árvore.

Códigos
Declarar o tipo TVetorDeString
type
   TVetorDeString = array of string;

Clique do botão "Processar"
var
   i: Integer;
   Linha: TVetorDeString;
   NohNivel1: TTreeNode;
   NohNivel2: TTreeNode;
begin
   SetLength(Linha, 0);

   for i := 0 to Memo1.Lines.Count-1 do
   begin
      Linha := StringParaVetor(Memo1.Lines[i]);

      NohNivel1 := nil;
      NohNivel2 := nil;

      AddNoh(NohNivel1, nil, Linha[0]);
      AddNoh(NohNivel2, NohNivel1, Linha[1]);

      ValueListEditor1.Strings.Add(Format('%s;%s;1=%s', [Linha[0], Linha[1], Linha[2]]));
      ValueListEditor1.Strings.Add(Format('%s;%s;2=%s', [Linha[0], Linha[1], Linha[3]]));
      ValueListEditor1.Strings.Add(Format('%s;%s;3=%s', [Linha[0], Linha[1], Linha[4]]));
   end;
end;

Clique do TreeView1
procedure TForm1.TreeView1Click(Sender: TObject);
begin
   if TreeView1.Selected.Parent = nil then
   begin
      Exit;
   end;

   Memo2.Clear;
   Memo2.Lines.Add(ValueListEditor1.Values[Format('%s;%s;1', [TreeView1.Selected.Parent.Text, TreeView1.Selected.Text])]);
   Memo2.Lines.Add(ValueListEditor1.Values[Format('%s;%s;2', [TreeView1.Selected.Parent.Text, TreeView1.Selected.Text])]);
   Memo2.Lines.Add(ValueListEditor1.Values[Format('%s;%s;3', [TreeView1.Selected.Parent.Text, TreeView1.Selected.Text])]);
end;

Função StringParaVetor
function StringParaVetor(const pString: String; const pDelimitador: Char = ';'): TVetorDeString;
var
   i: Integer;
   aux: string;

  begin
     SetLength(Result, 0);
     aux := EmptyStr;

     for i := 1 to Length(pString) do
     begin
        if pString[i] = pDelimitador then
        begin
           SetLength(Result, Length(Result)+1);
           Result[High(Result)] := aux;
           aux := EmptyStr;
           Continue;
        end;

        aux := aux + pString[i]
     end;

     SetLength(Result, Length(Result)+1);
     Result[High(Result)] := aux;
end;

Procedure AddNoh
   procedure AddNoh(var pNoh: TTreeNode; const pNohPai: TTreeNode; const pTexto: String);
   var
      i: Integer;
   begin
      if pNohPai = nil then
      begin
        for i := 0 to TreeView1.Items.Count-1 do
        begin
           if TreeView1.Items[i].Text = pTexto then
           begin
              pNoh := TreeView1.Items[i];
              Break;
           end;
        end;

        if pNoh = nil then
        begin
           pNoh := TreeView1.Items.Add(pNohPai, pTexto);
        end;
      end
      else
      begin
         pNoh := TreeView1.Items.AddChild(pNohPai, pTexto);
      end;
   end;

Explicando
Button1Click
Percorrer linha-a-linha do StringList do Memo1
for i := 0 to Memo1.Lines.Count-1 do
Cada linha foi transformada em um vetor com a função StringParaVetor:
A posição 1 do vetor é um nó de primeiro nível, adiciono ele só se ainda não foi adicionado usando a procedure AddNoh:
AddNoh(NohNivel1, nil, Linha[0]);
A posição 2 do vetor é um nó de segundo nível (filho do primeiro nível):
AddNoh(NohNivel2, NohNivel1, Linha[1]);
Posições 3, 4 e 5 são os campos a serem salvos no ValueListEditor1, são salvos cada campo em uma linha com uma "chave" que identifica cada linha:
  ValueListEditor1.Strings.Add(Format('%s;%s;1=%s', [Linha[0], Linha[1], Linha[2]]));
  ValueListEditor1.Strings.Add(Format('%s;%s;2=%s', [Linha[0], Linha[1], Linha[3]]));
  ValueListEditor1.Strings.Add(Format('%s;%s;3=%s', [Linha[0], Linha[1], Linha[4]]));

Essa parte pode ser otimizada com um laço, para várias linhas.
TreeView1Click
Para mostrar no Memo2 ao clicar no nó correspondente, a ideia é buscar a "chave" guardada no ValueListEditor1, e adicionar o Value correspondente.
Comment: Realmente era isso que eu queria, eu agradeço pela ajuda, ajudou muito, eu sempre tive dúvidas de como utilizar o Treeview sofri perdi muito tempo, mas felizmente você sanou minhas dúvidas, acredito que muita gente também  tem dificuldade de utilizar este componente.
Comment: bacana, que bom que ajudei, sucesso!


Setting/Resetting the value of a variable that is declared and initialized in __init__ in __main__

Question: I would like to set/ reset the value of a variable that I initialized in init in the main.  I have the following code.
class myClass:

    def myfun(self):

       # code using the url

    def __init__(self):
        self.url = None

if __name__ == '__main__':

   # list of integers
   my_list = [1, 2, 3,4,5]
   count = 0

   for item in my_list:
       if count % 2 == 0:
           self.url = "http://myurl.com" # I want to set/reset my url here

I received this error:

NameError: name 'self' is not defined`

What can I do to set/reset my variable that can be used globally later on in all the methods of my class?
Answer: The import guard if __name__ == '__main__': and everything in it is in the global namespace. It's not part of your class, much less a method in the class. To have an instance of your class, you need to instantiate it:
my_obj = myClass()

Now, in the same namespace, you can do
my_obj.url = ...

followed by
my_obj.myfun()

Answer: You need to instantiate your class, and use this name to refer to your class, not self. Like this:
class myClass:

    def myfun(self):
        pass
       # code using the url

    def __init__(self):
        self.url = None

if __name__ == '__main__':

   # list of integers
   my_list = [1, 2, 3,4,5]
   count = 0
   obj = myClass() # HERE!
   for item in my_list:
       if count % 2 == 0:
           obj.url = "http://myurl.com"

You need to refer to your class as obj after instantiating it (or any other name you gave it). If you don't instantiate a class, it's just some kind of skeleton with pre-defined properties and behaviors, but that doesn't exist yet. You can't manipulate it before instantiation.
After it's instantiated, you can refer to it with the instance name, obj in my example. self in a class refers to itself, no matter what it's called when instantiated. So outside of the class, you can't use self.
Comment: `cls` is conventionally used for class objects. `obj` or `inst` would be less misleading, since the instance is not a class.
Answer: I think you want a class variable.

that can be used globally later on in all the methods of my class

When you use self.url, if there is no url attribute in instance, it will refer class variable. It is shared by all instances. If you define self.url on some instances, their self.url will be shadowed.
class MyClass:
    url = None

    def my_fun(self):
        print(self.url)
        # code using the url

if __name__ == '__main__':

    # list of integers
    my_list = [1, 2, 3, 4, 5]
    count = 0
    my_object = MyClass()

    for item in my_list:
        if count % 2 == 0:
            MyClass.url = "http://myurl.com"  # I want to set/reset my url here
            my_object.my_fun()

Answer: The problem is self represents the object created from the class, and is not accessible in the if main statement.
self should only be used inside the class methods.
You would need to instantiate myClass then call myClass.url
for example:
class MyClass:

def myfun(self):

   # code using the url

def __init__(self):
    self.url = None

if __name__ == '__main__':

   # list of integers
   my_list = [1, 2, 3,4,5]
   count = 0
   my_class = MyClass()

   for item in my_list:
       if count % 2 == 0:
           my_class.url = "http://myurl.com" # I want to set/reset my url here

I also took the liberty of renaming your class to MyClass as this is more pythonic


How can I restrict access to Amazon EC2 instance, so that even Amazon cannot access it?

Question: Is there are way I can restrict access to an Amazon EC2 instance, so that no one except me will be able to login to my EC2 instance? I want to restrict access such that not even Amazon data center admins can login to my EC2 instance.  If it is possible, what is the easiest way of doing so?
EDIT
To clarify, I understand anyone with physical access to the hardware my EC2 instance is running on, they can get into my EC2 instance if they hack it open.  But, I'm not concerned with that level of security.
Assuming I remove any SSH keys from the EC2 instance, are there any "authorized" ways an Amazon employee could get into my EC2 instance?  And if so, what can be done to prevent them from doing do?
I hope I'm stating my question the right way.  Now that I'm thinking about it in more depth, I realize it might be a tough question to answer.  So, I hope you get the "spirit" of my question, if that makes sense.
Answer: Not possible that I am aware of. They have physical access, so they can do whatever they want to get in. And who knows what backdoors they have just in case they need to get in.
Comment: @MikeyE This isn't going to happen unless a nation-state requests Amazon to do it. If nation states are in your threat model, you probably should not be on Amazon or any public cloud at all.
Comment: @MikeyE For example, the USA, Russia, China, France, Spain, Mexico, ...
Comment: Good point about the physical access.  I probably should have clarified that I'm not trying to prevent from intrusion due to not having physical control.  I'm just wondering about getting in via an SSH key or the like.  I will update my question to reflect.
Comment: I could install monitoring software, which would notify me if the EC2 instance was taken down.  WIth that installed, at least I would know if any tampering happened.  That would be good enough for my purposes.
Comment: @MichaelHampton good point, thanks for that.  Just to clarify, can you give an example of who you would consider to be a nation state?
Comment: P.S. My EC2 instances are in the US serving only US customers.  And I live in the US.  Hopefully that adds clarity.
Answer: Based on your edit, it might be worthwhile shooting Amazon the question. You will get an answer that we would all get most likely. If there is some inside baseball type access, most of us would not know about it.
I would also assume, depending on their virtualization platform, they have some console-like access anyway. It always bothered me that they did not have something like that, but maybe it is a security function to not have that type of access. I've never dove that deep into AWS.
Comment: I actually run a company that does web hosting, VPS, and Dedicated server hosting. Namecheap probably does not want to spend the time to do it for you, they're a large company. If you have out of band management via their portal, you can do it yourself though. It's very simple. Depending on your OS, I can get your root password reset no problemo. It would require a reboot though. I could do it in person, or via ilo/idrac/ipmi; lights out management-different server manufacturers call it a different name.
Comment: I have a dedicated server hosted by Namecheap.  When I asked them if I locked myself out of the server how could they help me get back in they told me they have no way to gain root access because it is an "unmanaged server".  I presume Amazon has something similar.  I'm not asking how to protect against "hackers" and the like.  I'm just asking given Amazon's published policies, do they have a way to gain access to my box?  I understand they could back-door or hack their way in, but that's outside the scope of my question.
Comment: Thanks for the info Anthony.  You confirmed my suspicions and answered my question.  I was thinking I could put some kind of monitoring or send an email when the server shuts down to detect an reboot from an unauthorized person.  But, it would be better to have my servers under lock and key.  I actually found an ISP who offers a server cabinet, which can only be physically accessed by a key, which only me and the data center director will have.  So, I'm going to use them and if business goes well, stand up a data center in a year of my own in a year or two.  Thanks again.
Comment: Yes, if you want to be more physical control, you need to colocate your own equipment. Some places have badge access, not just lock and key to cages which can be nice.
Comment: Good point.  The ISP I am colocating my servers in has both, along with a few other security procedures and the like.


Next JS Dynamic Metadata

Question: I was trying to update metadata dynamically in NextJS 13. For this I have a rest api as backend that sends metadata like title, description, keywords, images etc . My goal was, by this approach I can update the sites metadata anytime I want. But the problem is, after applying this, It works fine in my local server but once I hosted it to vercel server it is not working as I wanted. It fetched data once, but when I change the data in the API it is not updating in the website.
Here is a code sample of what I did,

using this function in about-us/page.tsx

export async function generateMetadata(): Promise<Metadata> {
    const meta = await getMetaApi("about");
    return {
        title: `${meta?.data?.page_name} | Legato Designs `,
        generator: "Legato Designs",
        applicationName: "Legato Designs",
        keywords: meta?.data?.meta_keywords?.split(","),
        authors: [{name: 'Golden Infotech Ltd'}, {name: 'Golden Infotech Ltd', url: 'https://goldeninfotech.com.bd/'}],
        creator: 'Golden Infotech Ltd',
        publisher: 'Legato Designs',
        metadataBase: new URL("https://legatodesigns.com/"),
        alternates: {
            canonical: '/',
            languages: {
                'en-US': '/en-US',
                'de-DE': '/de-DE',
            },
        },
        openGraph: {
            title: meta?.data?.og_title,
            description: meta?.data?.og_description,
            url: 'https://legatodesigns.com/',
            siteName: 'Legato Designs',
            images: [
                {
                    url: `${process.env.NEXT_PUBLIC_BASE_URL_IMG_ALT}${meta?.data?.og_image}`,
                    width: 800,
                    height: 600,
                },
                {
                    url: `${process.env.NEXT_PUBLIC_BASE_URL_IMG_ALT}${meta?.data?.meta_image}`,
                    width: 1800,
                    height: 1600,
                    alt: 'Legato Designs',
                },
            ],
            locale: 'en-US',
            type: 'website',
        },
        twitter: {
            card: 'summary_large_image',
            title: meta?.data?.og_title,
            description: meta?.data?.og_description,
            creator: '@goldeninfotech',
            images: [`${process.env.NEXT_PUBLIC_BASE_URL_IMG_ALT}${meta?.data?.og_image}`],
        },
        robots: {
            index: true,
            follow: true,
            nocache: true,
            googleBot: {
                index: true,
                follow: false,
                noimageindex: true,
                'max-video-preview': -1,
                'max-image-preview': 'large',
                'max-snippet': -1,
            },
        },
        icons: {
            icon: '/legato_fav.png',
            shortcut: '/legato_fav.png',
            apple: '/legato_fav.png',
            other: {
                rel: '/legato_fav',
                url: '/legato_fav.png',
            },
        },
        manifest: 'https://nextjs.org/manifest.json',

    };
}

Code for getMetaApi function

export const getMetaApi = async (page) => {
    try {
        const response = await Axios.get(`get-meta/${page}`);
        return response.data;
    } catch (err) {
        console.log(err)
    }
}

and here is what the api responses with

{
"status": true,
"data": {
"id": 1,
"page_name": "Home",
"slug": "home",
"meta_title": "Legato Designs | Home",
"meta_keywords": "legato design, best furniture mart",
"meta_description": "Shop high-quality furniture at Legato Designs. Our wide selection of modern and contemporary furniture will elevate your home decor.",
"meta_image": null,
"og_title": "Legato Designs Home",
"og_description": "Shop high-quality furniture at Legato Designs. Our wide selection of modern and contemporary furniture will elevate your home decor.",
"og_image": "uploads/collection/meta/6463bb1520020.20230516.jpg",
"created_at": "2023-04-16 12:47:31",
"updated_at": "2023-05-16 23:19:17"
}
}

Comment: Does this answer your question? [How to avoid caching in the app directory of Next.js?](https://stackoverflow.com/questions/76204353/how-to-avoid-caching-in-the-app-directory-of-next-js)
Answer: You can instruct Next to re-generate your page (and re-fetch the metadata) at fixed intervals by exporting the following constant in your page:
// re-validate every 10 minutes
export const revalidate = 600;

You can read about other revalidation strategies in Next.js documentation here - https://nextjs.org/docs/app/building-your-application/data-fetching/revalidating
Comment: Thank you very much for the help, now the metadata is updating properly.
Answer:
#typescript / #javascript

//navigate to /app/layout.tsx

//paste the following code*

import { Metadata } from "next";

export const metadata: Metadata = {
 title: {
  template: "... | %s",
  default: "...",
 },
 description: "...",
 icons: {
  icon: "/...",
 apple: [
   {
     url: "/...",
   },
 ],
 other: [
    {
     rel: "custom logo description for your project ...",
     url: "/...",
    }
   ],
  },
 };

 //navigate to /app/page.tsx

 //paste the following code

 export const metadata = {
   title: {
    absolute: "custom page title for Home page...",
   }
 };

 //use the metadata object in your page.tsx, page.jsx files.

Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).

Next JS Dynamic Metadata


Abstract Equality Comparison - Prefix Operator

Question: I read the specs of javascript and found this snippet:

7.2.14 Abstract Equality Comparison

If Type(x) is Boolean, return the result of the comparison ! ToNumber(x) == y.

What does !ToNumber(x) mean?
Example:
true == 1 equals to true
but !true == 1 equals to false, so it is not the negate operator.
Comment: `!ToNumber(x)` is the same as `Boolean(ToNumber(x)) !== true`. `!true == 1` is basically `false == 1`, which evaluates as `false`.
Comment: but !1 == 1 will be false because true will be converted to 1. The expression true == 1 will evaluate to true.
Comment: "but !1 == 1 will be false because true will be converted to 1." No, `!1` will become `false` then compared with `1`
Answer: I found the answer in the spec while searching "!".

Similarly, prefix ! is used to indicate that the following invocation of an abstract or syntax-directed operation will never return an abrupt completion and that the resulting Completion Record's [[Value]] field should be used in place of the return value of the operation.
  Source


Privileged operations in netbeans mobility

Question: I'm writing a Java ME app that will use privileged operations such as messaging.  By default the user is prompted to confirm each of these operations, but I would like to run it as a background service.
Documentation says to request permission in the jad file, I have done so and presume it will work on a device.  However I would like to test this on the Netbeans mobility emulator first.
I tried signing the app as "trusted" but my emulated execution still prompts the user for permission.
Answer: The MIDP security model needs to be explained in 2 parts:
The phone (or the emulator) contains a security policy.
The security policy is made of several domains.
each domain defines function groups and root certificates.
a function group decides which protection options (auto agree always, user agree always, user agree once...) are available in the domain for which protected API (i.e. messaging).
The domain that applies to your MIDlet depends on which of the root certificates trusts the certificate you signed your MIDlet with.
Your problem is that there is a mismatch between what you think the protection options should be for the API you want in the domain you think your MIDlet belongs too and what is actually defined in the emulator security policy.
EDIT:
how-to for WTK-based emulators:
There are 3 _policy.txt* files in the ${netbeans_installation_folder}\mobility8\WTK2.5.2\j2mewtk_template\appdb\ folder.
They each contain a list of "alias" definitions and a list of "domain" definitions.
Make every domain have the same content as the "maximum" domain.
After this, Your emulator will never again ask for any user permission.
If you have already used the emulator contained in Netbeans, you probably want to make the same changes to the ${netbeans_installation_folder}\mobility8\WTK2.5.2\appdb\ folder.
Comment: So no idea how to edit the emulator's security policy?  The runtime options are rather limited.
Comment: @michael aubert please do you think you could help me with this question https://stackoverflow.com/questions/23730176/j2me-how-to-parse-a-byte-array-into-xml-and-then-read-and-display-specific-data


Absolue continuity of the integral

Question: Let $f \in L^1(X,\mu)$ Show that for every $\epsilon \gt 0$ it exists $\sigma \gt 0$ such that $\int_{A}f \lt \epsilon$ if $\mu(A) \lt \sigma$
Comment: You want $|f|$ in the integral
Answer: Hint: We could assume that $f$ is positive. And there is a increasing sequence of simple functions that converge a.e. to $f$, i.e.,
$$0{\le\varphi}_1\le\varphi_2\le\cdots\le f,$$ $$\varphi_n\rightarrow f,a.e.,as\ n\rightarrow+\infty$$
and it's easy to prove the proposition for simple functions. And by using the convergence, we could finish the proof.
Answer: If the thesis were not true, it would exist an $\varepsilon > 0$ such that for all $\sigma$ then: if $\mu(A) < \sigma$, then $|\int_{A} f| \geq \varepsilon$. If this happens, you can make the integral arbitrarily large.
Comment: That is my thought too but I was hoping someone could formulate it in a formal way
Answer: Hint: Given $\epsilon>0,$ you can find a bounded $b$ such that $\int_X|f-b|<\epsilon.$ The result is clearly true for $b.$

Absolue continuity of the integral


Diferença entre function factory e closure

Question: No livro Advanced R, aos capítulos 10 e 11, o autor define function factory como:

"a factory for making new functions"

Tradução Google Translate: uma fábrica para fazer novas funções.
E closure como:

"functions returned by another function"

Tradução Google Translate: funções retornadas por outra função.
Então, uma function factory é uma função que cria closures? Por exemplo:
myfun <- function(x) {
  funs <- c(mean, median, sd, mad, IQR)
  lapply(funs, function(f) f(x, na.rm = TRUE))
}

pode ser considerada uma function factory. Enquanto que: myfun pode ser considerada uma closure, pois:
abc <- 1:10

myfun(abc)

Fiquei com dúvida em relação a estes conceitos, que parecem estar relacionados.
Informação complementar
Answer: Isso mesmo. Considere o exemplo:
power <- function(exponent) {
  function(x) {
    x ^ exponent
  }
}
square <- power(2)

Neste caso a função power é uma function factory e square é uma closure.
O nome closure vem porque elas incluem (enclose em inglês) o ambiente em que foram criadas. Neste caso, a closure square vai incluir o nome exponent no seu ambiente e quando for chamada usará o valor de exponent.
Fábricas de funções são abstrações legais, mas não tem muito mais utilidade do que uma função com múltiplos argumentos. Muito dos códigos com funções fábricas podem ser transformados usando a função partial do purrr, por exemplo:
power <- function(x, exponent) {
  x^exponent
}

square <- purrr::partial(power, exponent = 2)


Por que o resultado deste mini programa é 2?

Question: Por que o resultado deste mini programa é 2?
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int *P = (int *)malloc(10*sizeof(int));
    for(int i = 0; i < 10; i++)
    {
        P[i] = i*10;
    }
    int *Q = P + 8;
    int *L = Q - 2;
    int result = Q - L;
    printf("O resultado e ... : %d\n", result);
    return 0;
}

Comment: faltam os includes #include
#include
Comment: A resposta resolveu sua dúvida? Acha que pode aceitá-la? Veja o [tour] se não souber como faz. Isso ajudaria muito indicar que a solução foi útil para você. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo (quando tiver 15 pontos).
Answer: A variável Q passa apontar para a posição de memória igual ao endereço de P, portanto o começo do array, mais um deslocamento de 8 posições segundo a aritmética de ponteiros, então é a posição 8 que tem o valor 80. Destaquei o número que importa aqui.
L aponta para essa posição voltando duas posições antes, portanto a 6 que tem o valor 60. Novamente destaquei o número que importa.
Aí em result pega a o valor de Q que é o valor de P mais 8, e o valor de L é o valor de P mais 6 (Q - 2), por isso podemos ignorar o valor de P, no fundo a conta é só 8 menos 6, que dá 2. Só olhando o Q - 2 já dá para perceber que p i resultado é 2.
No fundo, tirando o fato de entender que é aritmética de ponteiro é matemática pura e simples.
A aritmética de ponteiro é usada para encontrar a posição relativa de algum item em um conjunto de informações, mais notadamente em arrays. Então quando soma 1 no ponteiro está deslocando uma posição para o próximo item. O deslocamento sempre vai de acordo com o tamanho do elemento do array. A fórmula é sempre endereco_inicial + posicao_relativa * tamanho_elemento.
É possível fazer aritmética de ponteiro em dados que não estão em arrays, mas não esse deslocamento linear.
Todo esse código não faz muito sentido, começando por alocar memória sem necessidade e depois por fazer uma conta tão sem sentido assim. Pode ser útil para demonstrar aritmética de ponteiro, mas não é um bom exemplo.


Monthly and Annual Compound Interest in SAS using DO Loop

Question: I am studying SAS on my own. I have no one to refer to so I just wanted to check if my code is correct.
In a fixed term deposit of 25 years calculate the total amount at the end of
term with initial amount of $5,00,000 and annual interest rate of 7 %  */
 1) Compounded Annually
 2) Compounded Monthly.Show the amount at monthly level
My Code:
data deposit;
amount = 500000;
rate = 0.07;
do year = 1 to 25;
amount + earned;
earned + (amount*0.07);
principal = amount + earned;
output;
end;
run;

For the second question compounded monthly
data deposit1;
rate = 0.006;
amount1 = 500000;
do year = 1 to 25;
do month = 1 to 12;
earned1 + (earned1 + amount1)*0.006;
amount1 + earned1;
output;
end;
end;
run;

Pasting the Screenshots of Solution 1 and Solution 2

I am confused because when I compound annually and monthly both have different results at the end of a particular year.
Please suggest if anything is wrong in my code. Thank you for your time and attention.
Comment: Why did you change the interest rate from 7% in the annual calculations to 6% in the monthly calculations?
Answer: It looks like you are double-counting your earned1 variable in the monthly compounding code.
earned1 + (earned1 + amount1)*0.006;
amount1 + earned1;

Should be:
earned1 = amount1*0.07**(1/12);
amount1 + earned1;

Note also you will not want to round the interest rate.
Comment: Thank you Craig but one question will the compound interest monthly and CI annual will always differ as they have different values. Because Compound Interest is always applied on the total which has the amount and the interest unlike in case of Simple interest where the value is applied on only the amount. So if we see here neither of the scenario fulfill the criteria for the monthly compound interest calculation. Please guide.
Comment: Sorry, I just made an edit to fix an error in the first line of the monthly code - should be `earned1 = amount1*0.07**(1/12);`and not `earned1 + amount1*0.07**(1/12);`
Comment: Monthly compounding is going to give you a different result than annual compounding.
Comment: Many thanks Craig for helping out ! Really grateful !


How can I open a file as a Http link

Question: I want to open a file in the folder (/root/Desktop/HTMLFiles/sample.html) as http://localhost/HTMLFiles/sample.html. I'm using a Linux machine.
Can anyone help me?
Thanks in advance,
Gnik
Answer: place HTMLFiles under your webroot. If you dont wnat to do that check https://serverfault.com/questions/295975/add-a-directory-to-the-apache-web-root
Answer: You most certainly have python installed. I would use the simple HTTP server bundled with Python:
<code>python -m SimpleHTTPServer
</code>
Just navigate to the directory you want to serve files from and run that command.
You will be able to see the content at http://127.0.0.1:8000 or http://localhost:8000

How can I open a file as a Http link


line graph renders wrongly and problem with the X axis (time), cannot brush the graph - time series dc.js

Question: I'm creating a dashboard for a scanning tool. I have created a bunch of graphs but got stuck with plotting a line chart to show kind of like a time series ( like how many records are populated at that particular scan time). I'm using dc.js and have tried a couple of ways, but the line does not render correctly and the axis has weird thing going with it.
I cannot brush the graph too, it is throwing "coordinate-grid-mixin.js:1083 Uncaught TypeError: undefined is not a function".
I have a UNIX timestamp, which I'm converting to datetime and then I'm using these to plot the line chart.

//Converting the timestamp
var dateFormatSpecifier = "%m/%d/%Y";
var day_FormatSpecifier = "%d %b %y";
var dateFormat = d3.timeFormat(dateFormatSpecifier);
var dayFormat = d3.timeFormat(day_FormatSpecifier)
var dateFormatParser = d3.timeParse(dateFormatSpecifier);
var numberFormat = d3.format(".2f");

facts.forEach(function(d) {
    console.log('Before Change : ' + d.timestamp);
    d.date = new Date(d.timestamp * 1000);

    d.month = d3.timeMonth(d.date);
    d.day = d3.timeDay(d.date);

    d.date = dateFormat(d.date);
    d.day = dayFormat(d.day)

    console.log('After Change : ' + d.date + ' ' + d.month + ' '+ d.day);
    // console.log('After Change Month: ' + d.month);
  });

//Plotting

var dateDim = data.dimension(function(d) { return (d.day);});
var groupForSNR = dateDim.group().reduceCount(item => 1);

var time_chart = dc.lineChart("#time-chart");

var minDate = dateDim.bottom(1)[0].date;
console.log('min : ' + minDate);
var maxDate = dateDim.top(1)[0].date;
console.log('max : ' + maxDate);

var xmin = dayFormat(new Date(1559890800*1000))
console.log('xmin : ' + xmin);
var xmax = dayFormat(new Date(1561878000*1000))
console.log('xmin : ' + xmax);

time_chart
    .height(150)
    .transitionDuration(500)
    .margins({top: 10, right: 10, bottom: 20, left: 40})
    .dimension(dateDim)
    .group(groupForSNR)
    .brushOn(true)
    .elasticY(true)
    .y(d3.scaleLinear().domain([0,100]))
    .x(d3.scaleOrdinal().domain(xmin, xmax))
    .xUnits(d3.timeDay);

    time_chart.xAxis().ticks(15);
    time_chart.yAxis().ticks(10);

-
".x(d3.scaleTime().domain(xmin, xmax))" is not even displaying anything.
Comment: Hi, could you please look at [this example](http://dc-js.github.io/dc.js/examples/right-axis.html) and its source? Basically you will want to use Javascript date objects as your keys, then quantize to days (I presume) using `d3.timeDay`, specify `d3.timeDays` for `xUnits`. Seems like we need a proper tutorial for using time scales, since this keeps coming up...
Comment: Please give it a try and edit your question if you get stuck. Thanks!
Comment: I tried and stuck with a similar one again
Answer: Thanks for your effort.
Your syntax is slightly off, and you always want to work with JavaScript Date objects when using D3 time scales. Only the ticks and labels (output) will be formatted as strings, all input will be Dates.
.domain() always takes an array.
You want
var minDate = dateDim.bottom(1)[0].day; // Date object
var maxDate = dateDim.top(1)[0].day;

.x(d3.scaleTime().domain([minDate, maxDate]))

Not sure if these are the only problems - everything else looks okay but it's hard to tell without trying.
Just keep studying, look very closely at what the examples are doing, you'll pick it up quickly!
EDIT: you will find examples where the dates are formatted as strings with an ordinal scale on input. There are only particular cases where is this a good idea, and I don't think this is one of them.
Comment: Thanks @Gordon. The main Issue is my d.date field got converted to String and that is why when I use d3.scaleTime() it was not rendering. I fixed it and my chart is rendering. :-D
Comment: Yep, that's exactly it. Make sure that all the inputs are Dates. There usually isn't any reason to deal with strings on the input side, or to keep formatted dates around for any reason. If you feel that the answer set you on the right path, please click the green checkmark to accept the answer. Thanks!
Comment: Hey, @Gordon just one more follow up when I try to visualize with more than 1000 rows the webpage pauses and crashes. I found out this is just due to this line chart if I remove this everything seems normal and other graphs render fine. Do you know any workaround for this situation?
Comment: That's not normal at all. Crossfilter and dc.js can handle thousands of rows, up to maybe half a million as long as the data is properly aggregated. Most likely there is something else going wrong. Please open another question or a GitHub issue with a reproducible example.


Automatically add node to menu

Question: How can I automatically create a menu link for a new node in Drupal 8?
Answer: You can use a deriver class for this.
In your foo.links.menu.yml file
entity.node.canonical:
  deriver: '\Drupal\foo\Plugin\Deriver\FooMenuLinkDeriver'
  route_name: entity.node.canonical

In Drupal\foo\Plugin\Deriver\FooMenuLinkDeriver
class FooMenuLinkDeriver extends DeriverBase implements ContainerDeriverInterface {
  public function getDerivativeDefinitions($base) {
    $plugin_definitions = [];
    foreach (Node::loadMultiple() as $nid => $node) {
      $plugin_definitions[$nid] = $base;
      $plugin_definitions[$nid]['route_parameters']['node'] = $nid;
      $plugin_definitions[$nid]['title'] = $node->label();
    }
    return $plugin_definitions;
  }

Answer: As far as I know you will need a custom module implementing hook_entity_presave or hook_entity_insert
hook_entity_insert would be called only when a NEW node is created
hook_entity_presave would be called any time a node is saved/updated
<?php
use \Drupal\Core\Entity\EntityInterface;
use \Drupal\menu_link_content\Entity\MenuLinkContent;

function MODULE_NAME_entity_insert(EntityInterface $entity){

    if ($entity->getEntityType()->id() == 'node') {
        $title = $entity->getTitle();
        //OR
        //$title = $entity->title->value;
        $nid = $entity->id();

        $menu_link = MenuLinkContent::create([
          'title' => $title,
          'link' => ['uri' => 'internal:/node/' . $nid],
          'menu_name' => 'main',
          'expanded' => TRUE,
        ]);
        $menu_link->save();
    }
}
?>

If you use hook_entity_presave you might need to check whether the MENU item exists otherwise you will end up with a new menu item each time the node is updated.
<?php
use \Drupal\Core\Entity\EntityInterface;
use \Drupal\menu_link_content\Entity\MenuLinkContent;

function MODULE_NAME_entity_presave(EntityInterface $entity){

    if ($entity->getEntityType()->id() == 'node') {
        $title = $entity->getTitle();
        //OR
        //$title = $entity->title->value;
        $nid = $entity->id();

        $menu_link_manager = \Drupal::service('plugin.manager.menu.link');

        $menu_links = $menu_link_manager->loadLinksByRoute('entity.node.canonical', array('node' => $nid));
        if(sizeof($menu_links)){
            foreach ($menu_links as $menu_link) {
                $definition = $menu_link->getPluginDefinition();
                $definition['title'] = $title;
                $menu_link_manager->updateDefinition($menu_link->getPluginId(), $definition);
                //PHP warning pending fix https://www.drupal.org/node/2775665
            }
        }else{
            $menu_link = MenuLinkContent::create([
                'title' => $title,
                'link' => ['uri' => 'internal:/node/' . $nid],
                'menu_name' => 'main',
                'expanded' => TRUE,
            ]);
            $menu_link->save();
        }
    }
}

To get the basic of custom modules please look here https://www.drupal.org/docs/8/creating-custom-modules
for similar question and answers for drupal 7 look here https://stackoverflow.com/questions/3163537/drupal-automatically-add-menu-items-when-new-nodes-are-added

Automatically add node to menu


Fórmula dentro de um Campo

Question: Em um campo possuo o valor de uma fórmula ((B/2)+ C), sendo que o valor B e C vem de outros campos, como posso trocar os valores das letras pelos seus valores reais e calcular a fórmula?
Preciso só de um norte de como fazer isso, pois não estou conseguindo achar um padrão.
OBS: Existem n tipos de fórmulas, não é fixo o valor.
EDIT

Só faço uma busca nessa tabela simples e preciso substituis o valor de B e C pelos seus valores. Depois calcular a fórmula.
Ex: (10/2) + 5

Comment: Você poderia exemplificar mais sua pergunta com exemplos de retorno da sua consulta e como é sua tabela também?
Comment: Editei, meu select é só buscar os valores, mas meu problema é como substituir esses valores e depois calcular a formula inteira.
Comment: Vide `SQL Server Eval | Dynamically evaluate arithmetic operation and expression in SQL`: https://github.com/zzzprojects/Eval-SQL.NET/wiki/SQL-Server-Eval-%7C-Dynamically-evaluate-arithmetic-operation-and-expression-in-SQL
Answer: Montei um exemplo utilizando o exec
SET NOCOUNT ON;
--crio uma tabela temporária para simular a sua tabela
CREATE TABLE #formulas_table(
formula varchar(100),
A int,
B int,
C int)
--insiro uns dados de amostra
insert into #formulas_table
select '(B/2)+ C' formula, 10 B,5 C,0 A
union all select '(B/1)+ C' formula, 10 B,5 C,0 A
union all select '(B/3)+ C' formula, 10 B,5 C,0 A

begin --esse é o trecho que você precisa
    --declaro um cursor com os dados da tabela de amostra
    --aqui você irá substituir pelo seu select na sua tabela
    declare formulas cursor fast_forward for
    select formula
    from #formulas_table
    declare @formula varchar(100)

    --abre o cursor e atribiu o valor na variável @formula
    OPEN formulas
    FETCH NEXT FROM formulas
    INTO @formula

    --percorro o cursor até que não tenha mais dados
    while @@FETCH_STATUS = 0
    BEGIN
        --o exec pode ser usado para montar consultas concatenadas em uma string
        exec('select top 1 ' + @formula + ' from #formulas_table')

        --vai para o próximo item do cursor
        FETCH NEXT FROM formulas
        INTO @formula
    END

    --fecha e libera o cursor de memória
    CLOSE formulas;
    DEALLOCATE formulas;
end --fim do trecho que você precisa

--dropa a tabela temporária, pois só precisei dela para montar o exemplo
drop table #formulas_table

Comment: Obrigado pelo script, mas poderia comentar? pois não entendi direito essa lógica.
Comment: Adicionei os comentários ao script
Comment: A entendi agora, obrigado. Mas agora com os valores concatenados como eu conseguiria executar a formula para obter o resultado dela ? tipo (10/2) + 5 => Resultado: 10
Comment: mas isso é o que o `exec('select top 1 ' + @formula + ' from #formulas_table')` faz, ele vai concatenar o resultado do @formula e ficaria algo do tipo `select top 1 (B/2)+ C from #formulas_table`
Comment: @Aprendiz A sugestão do Pablo é uma das soluções para calcular fórmulas. Se achar adequado, você pode armazenar o resultado de cada linha em uma tabela temporária e ao final listar como um único dataset.

Fórmula dentro de um Campo


What notes to sing with chords

Question: Ok, lets say you are playing a guitar and you have a song with 4 chords ( C D Am and F ).
Should I sing the C note for C chord and D note for D chord and A note for Am and F note for F chord ?
Or how does it work?
Thank you for your answers
Comment: I'd take a good look at [Do-Re-Mi from the Sound of Music](https://www.youtube.com/watch?v=xIjobdArtiA). I can't think of anything better to quickly explain how melodies are structured from simple beginnings.
Comment: here is a link to a great answer on a similar question that was recently posted. [http://music.stackexchange.com/a/30664/16897](link)
Answer: To put it simply, in a song, there's melody and there's chords. They do have some relation (certain notes do not sound good with certain chords, to various degrees) but they are two separate things.
In order to play the guitar you should know the chords (you already have that), in order to sing the melody you should find the notes sequence that consist it. That can be done my ear, or by reading a music score, like this example below. See that C in a square? That's the chord. The notes are the melody.
Answer: Not being completely sure what you are asking - I will answer the question as if you are writing a melody for a song based on a pre-determined chord progression.
If you were to approach writing a melody by first defining a chord progression, you would probably want to start with chords that fit within the key you decide your song should be in.
So let's pretend we are going to write a chord progression in the key of C.  So we choose chords from the key of C and let's say we decide our progression will be C / F / Dm / G and it repeats.  Since chords and chord changes define our rhythm, we need to decide how many beats each chord gets and where the chord changes fall.
Let's keep it simple and say each chord in our progression will be played for one bar or 4 beats (4/4) time and the chord changes will occur on beat one of each new measure.
So now we need some melody notes to go with the chords.  Within each measure (or bar) we will have a certain number of notes depending on how fast we want our melody to go.  So we could have 4 quarter notes in a measure or 8 eighth notes or 16 sixteenth notes or any combination depending on how we want the melody to flow.
So if we choose six notes per measure then we must decide which six notes we might use.  Let's start with the C chord in the first measure.  The easiest notes that we can be sure will work - will be the notes in the C major triad or C,E and G.  As a general rule, the first note of the measure that begins with a C chord should be one of the 3 notes in the C major chord meaning either C or E or G. It can be an octave or more higher or lower than the notes played on your guitar.
If you have six notes total, at least three of the six notes should be one of the three notes found in the C chord (can be octave or more higher or lower as long as it's a C or E or G).  In any given measure, try to choose most of the notes (at least every other note) from the notes found in whatever chord you are playing for the duration of that run of notes.  It won't sound good if you play a measure strumming the C chord and only one of the melody notes are within the chord. The more the better but at least half as a guideline.
Our options for notes other than the C, E or G are any note in the C major scale (key of C major).  This applies only to the tonic chord or the chord that is the same as the key we are playing in.
For our next measure using the F chord, our notes are more limited.  The same principle will apply for using one of the 3 notes in the F major triad (chord) as our first note in this measure.  That gives us a choice of **F, A and C.**  The same guideline applies to make most of the notes in that measure either an F, A or C (any octave).
The other notes available will be derived from a combination of the F major scale and the C major scale.  We want to choose from notes that are common to both scales. We want to keep our notes within the C major scale because our song is in the key of C and if we are singing or playing melody notes over an F chord, they will sound better if they are in the key of F.
The notes in C major are C,D,E,F,G,A,B.  The notes in F major are F,G,A,Bb,C,D,E.  So the notes we should not use while playing the F major chord is Bb because it is not in the key of C and B because it is not in the key of F major.  This leaves the notes common to both the C major scale (key of our song) and the F major scale (the chord we are now playing) which would be F,G,A,C,D and E.
The same logic will apply to the other chord sequences.  Again, first note played after the chord change should be one of the notes that form the chord.  If it's a four note chord (7th, augmented, etc.) you can use any of the four notes and often the note that makes it something other than a triad will be suggested strongly as a melody note or two while playing that chord.  If you must use a formula, a safe bet is to choose the notes that are common to the chord being played AND the key of the song.  In other words choose from the list of notes that are common to both of these two scales.  There are exceptions that will work in some circumstances, but this will keep you in safe territory.
You don't really need to chart out all the notes of all the scales of all the chords if you are composing a melody to go with a chord progression though.  If you try to choose most of the notes that are to be played or sung over a certain chord - from the notes that form that chord, your ear will lead you to the other notes that will fit with that chord.  If you pick a wrong note while sounding that chord - it will sound sour or wrong.
So the simplest way to compose a melody over chords is to use the notes in the chord itself (octave or more in either direction is okay) as a basic framework for the notes that fit with that chord, and the rest of the notes will fit naturally within that framework and you will hear what works without having to compare scales and match notes.  Let your ear be the guide for any notes that are not a part of the chord.
As you can see, you have more than one note that will work with any chord. Feel free to experiment and just see what sounds good.  Hope this helps.
Comment: Listen to Mancini's Moon River. 3rd bar, B works beautifully over an F chord. But as a rule for a beginner, your tenet is a good one.
Comment: Wow, thank you so much for your answers

So am I getting it right, so if I use the chords C F Dm and G
And on the melody line we have 6 notes per measure

1st measure: C E G ( from the C chord triad ) + D F B ( from the C scale )

2nd measure: F A C ( from F chord triad ) + F G A ( common notes from C and F scales )

3rd measure: D F A ( from Dm chord triad ) + D E F ( common notes from C and Dm scale )

4th measure: G B D ( from G triad ) + G A B ( common notes from C and G scale )
Comment: 1 ) So I can't use the B flat note from F or Dm scale and I also can't use the F sharp note from G scale ?

2) Can I use the B note on 4th measure or do I have to use the notes that all 4 scales have in common ?

3) On the second measure, with F chord the notes after triad would sound better in the key of F so the notes F G A will sound better than E G A ?

Thanks again
- Rocky
Comment: Not notes in all 4 scales.  Just in two.  The first note after the chord is played will usually sound better if it is one of the notes in the chord.  After the first note on new chord - just use any note common to the two keys.  In some cases depending on the overall movement of the melody (where it's been and where it is going) notes outside the two scales will also work.  You have to use your ear to tell you if a note works or not.  I just gave you some safe bet general guidelines that will almost always work.
Answer: If you already have the song, the notes are already there to be sung. If you only sang a C note with a C chord etc, it would be a poor song. A C chord will work with several notes from the C scale. The best are C, E and G, as they actually make up that chord. Depending where in the bar you sing other notes over it, others may or may not fit. Your ear will tell you better than a written explanation.
The chords you show are not diatonic- they don't all come from the C key. The D is foreign.
To get an idea as to which chord fits in a bar, look at the main notes - often the 1st and 3rd beats. If they belong to one particular chord, then that will fit well. Maybe it's not the only one, though, it could depend on what chords are before and after that.
This is a simplified answer at the moment. If you actually meant 'when I sing a C note do I play a C chord,' etc., then the basic answer is NO. The C note will fit with several other chords that may make the song sound much better.
Answer: You can, and there's nothing wrong with that.  It's the simplest way to harmonize your melody (notes sung) to the underlying chords.
The next simplest way, and one that is pretty much guaranteed to not produce any dissonance, is to sing a note from the chord you're playing over.  For the C chord, then, that would be C, E, or G.
Beyond that, it's up to you.
Answer: If you Can Sing it shouldn't be a problem your voice doesn't have to be the same notes that's almost impossible. I say just stay in your vocal range.  I practice the song without playing with headsets on and record so I know were I need to work before I play it and practice like he'll before we go on stage.

What notes to sing with chords


Hosting Multiple Domains seamlessly with same site code, theme, modules, data etc. not a multisites situation!

Question: I would like to use D7 to support two domains with same code, themes, modules and even database and content, completely transparent to the end-user.
So, user of oxustech.com would see only oxustech.com and user of oxustechnolgies.com would see only oxustechecholgies.com (not be redirected to oxustech.com).
We don't want to use forwarding/frame forwarding. because frame forwarding will hide the full url and will show every url as oxustechnologies.com only.
The site is under shared hosting and we don't have enough permission to change the Apache setting.
Pointing oxustechnologies.com to same htdocs didn't work.
Answer: This has worked for me in the past. Given the following assumptions:

I assume the server is already configured to direct requests for the domain oxustech.com to the correct site (meaning that this is already working for you)
I assume Drupal is finding for your site's settings.php file in the directory /sites/oxustech.com/settings.php
I assume you want to make requests for the domain oxustechnologies.com to show the SAME site (same database) as oxustech.com, but displaying the domain oxustechnologies.com as the base URL for all pages accessed through this requests.

IF this is the case, this has worked for me. Try this:

In the /sites directory, rename the file example.sites.php to sites.php
Add the following line at the end: $sites['oxustechnologies.com'] = 'oxustech.com';

This will effectively tell Drupal that oxustechnologies.com is an "alias" of oxustech.com, will use all settings (including the database) for oxustech.com. It will also always display oxsutechnologies.com as the base URL when you navigate inside the site. But people who access the site through the name oxustech.com will continue to see that as the base URL.
Comment: at the moment we have single site installation where setting.php for oxustech.com is under default folder.

Do we need to change the current setting into multi-site setting ? and have oxustech.com folder ? thanks
Comment: I haven't tried that situation. You can try and see if `$sites['oxustechnologies.com'] = 'default'` works for you. If not, then I'd try moving the `settings.php` file and all other files used by the site to its own folder called `oxustech.com`
Comment: I'm curious if you could make this work?


Linux: user defined daemons/services

Question: I'm looking for a framework/library/environment so an ordinary user can set up it's own server processes. These processes should run under his uid as any other user process.
However the definition of which processes should be started, with arguments they get etc should be specified by an ordinary user without extra privileges. It's important to me that this happens without the necessity for the user to actually log in. Ideally it should work with SYSV init but a systemd-based thing is ok as well.
Examples/use cases:

nginx uwsgi/fast cgi processes
mongodb instances
different builders for continuous integration server

All of these have in common, that I might want to start multiple instances of the same binary (with different parameters) and that these parameters might need regular changes. However users should be able to tweak all of that without requiring root privileges.
Any suggestions/pointers how this can be implemented in Linux?
EDIT: The minimal requirement is just to start the user processes but obviously there will be the need for more advanced control mechanisms. For example there should be an easy way to query if the service is running, stopping the instance, restarting it, reloading it, ...
Comment: This is the type of thing `sudo` is for.
Comment: No, `sudo` only handles the actual switch to a different user account but it doesn't enable users to manage their own services.
Comment: In /etc/sudoers, you define which which users can run which programs. This does let them manage their own services.
Comment: This doesn't solve "start service at startup without manual interaction". You'd still have to put each service in /etc/init.d and that's what I tried to avoid. Of course sudo may be a part of the final solution but by itself it doesn't solve the problem.
Answer: cron provides for this with the @reboot prefix (Vixie, and perhaps other flavors, check man 5 crontab).  The user would use crontab to create/edit their own crontab file, and specify
@reboot /some/path/command -flags --moreflags

Which will run that command on startup, as that user.
Comment: @FelixSchwarz Make your users write their own initscripts that handle the vagaries of managing their process, then you can tell them to put all the scripts in a folder in $HOME and use symcbean's script to run them all at once (or tell them to put `@reboot /home/user/init/foo start` in their crontab).  symcbean's script has the advantage that if everyone implements `status` you can call them all at once with `/etc/init.d/symcbean status`
Comment: That's a very nice start and actually fulfills all my basic needs! However (I'm not easy to satisfy you know ;-) I hoped for something more sophisticated with job control (is the service running?, restarting it, reloading it, ...).
Answer: This would be about 10 lines of shell script, why do you need a framework/library/environment?
As a quick example, using sysV init....
#!/bin/bash

. /etc/rc.d/init.d/functions

. /etc/sysconfig/network

DAEMON_USERS=`cat /etc/daemon_users`

CMD="$1"

for DUSER in $DAEMON_USERS ; do
   DSCRIPTS=`ls /home/${DUSER}/init/`
   for DFILE in DSCRIPTS ; do
      if [ -x "/home/${DUSER}/init/${DFILE}" -a ! -d "/home/${DUSER}/init/${DFILE}" ]
      then
         su -c $DUSER /home/${DUSER}/init/${DFILE} $CMD
      fi
   done
done

If you really want to allow them to run stuff as root, then remove the 'su -c $DUSER' and add them to the sudoers so they can restart / add stuff without a reboot.
Comment: As I commented above I hoped for something more sophisticated with daemon control/status querying etc (without building this all by myself for each and every service again). I mean my needs are not that uncommon, are they?
Comment: @Felix: Unix provides all that out of the box.
Answer: So... just start the application as the user you want to run it as and don't try to access anything that would require root (like privileged ports, files that can only be read by root, etc.)?
If you want to automatically start these daemons and control them via the SysV init process you're going to need to create an init script for each one that specifies the parameters (or reads them from a file that the unprivileged user has write access to) and launches the daemon using su -c or similar, but BEWARE: Doing this has SERIOUS security implications (a carefully-crafted "parameters" file can let the user execute arbitrary code as the user running your init sequence, which is usually root).
DerfK mentioned the cron @reboot option, which may be a better choice (less of a security risk), but your admins need to be aware that these programs are going to be started by cron...
Comment: Well, as I said it's not about running as root so of course the daemon instances can't access privileged ports but that's fine. However the problem with creating an init script is that this requires root privileges.
Comment: Actually creating an init script doesn't require root privileges - you can make the rc.d directory group or world writable. This too has all sorts of horrible security implications (for the love of $_DEITY don't do it! :)
Comment: voretaq7: I take that as a joke. Of course I won't fiddle around with permissions on important directories like /etc/rc.d! So yes, in practice adding an init script *does* require root privileges.

Linux: user defined daemons/services


Show that the graph $G$ is $2$ colorable

Question:
Show that the graph $G$ is $2$ colorable which is define with vertex set $\mathbb Z^2$ where $(m,n)$ is adjacent to $(j,k)$ if $(m,n)\pm(1,0)=(j,k)$ or $(m,n)\pm(0,1)=(j,k)$.

I just draw a portion of the graph and it seems easily two colorable, like if I color a vertex with red and a different color (like blue) with all of it's adjacent vertices. But couldn't write it in a formal way.

I was doubt to write it in plain english because there are infintely many vertices to color, it would be nice if anyone show me the right way.
Answer: HINT: Consider whether $m+n$ is even or odd.
Comment: I see, if I just pick one color for even and another color for odd then the adjacent points in $\mathbb Z^2$ are distinguishable. Thanks @Brian M. Scott
Comment: @WhyGraph_: That's right. You're welcome.
Answer:
Using the theorem "A graph $G$ is bipartite if and only if it does not contain an odd cycle", since the grid graph does not contain an odd length cycle (prove with induction on the length of a cycle) it's a bipartite graph. For example, the following figure shows the original graph and an isomorphic bipartite representation:

Another theorem: "Any bipartite graph $G$ is 2-colorable" (consider $V(G) = V_1 \cup V_2$, with $E(G)=\{(u,v):u \in V_1, v \in V_2\}$. Color vertices in $V_1$ with one color and those in $V_2$ with a different color).

Combining the above two, the grid graph is 2-colorable.

For example, consider the off-diagonals in the grid-graph and color with alternate colors as shown in the next figure.

In this bipartite graph the unions of the alternate diagonals create the vertex sets $V_1$ and $V_2$.

Another way

Prove that the vertices on the same diagonal and also on every alternate off diagonals will be at least $\pm(1,1)$ distance away from one another, hence can't be adjacent and can be colored with the same color.
Comment: nice(+1) and detail answer. Thanks @Sandipan Dey


find the multiplicative factor for get a specific amount of sum on sin

Question: i am not a math guru so please sorry if this is a silly question. i'm not sure on how to latexize this question so i've done a spreadsheets with openoffice (and i'm interest also in the best way to write it in latex).
i want to find a multiplicative factor \beta to get a certain sin sum in n step. like this: find beta for
$$\sum_{\substack{0\le \theta\le \Pi}} \beta sin(x)$$
if theta goes from 0 to Pi in n step. say, for example if beta = 11, n = 10 so

the sum is 62.3841
now, if i have n step and i want the sum is alpha .. how to calculate beta?
Answer: I suggest $$\beta=\frac{\alpha}{\sum \sin x}.$$


Woocomerce notices keep remaining on page instead of updating and removing old notices

Question: My issue is that I'm using Divi which doesn't have an add to cart button feature but you can add one by putting this bit of code into functions.php :
add_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 20 );

Now, I have a mini cart set up in the cart page which allows users to shop for more things to get free shipping. When they click the Add to Cart button implemented with the code above, the cart refreshes to add it. However, the previous woocomerce notifications don't dissapear - new ones just get posted below it.
Example:
User is in their cart -they see a notification at the top saying:
" You'll receive 500 points when you checkout."
User then adds something from minicart into their main cart.
Instead of the woocomerce notice updating, they now have two notifications:
" You'll receive 500 points when you checkout."
" You'll receive 550 points when you checkout."
Now before someone tells me to do something with wc_clear_notices();
I already have this bit of code which works when someone clicks on the update cart button:
add_filter( 'woocommerce_update_cart_action_cart_updated', 'clear_notices_on_cart_update', 10, 1 );

function clear_notices_on_cart_update() {
        wc_clear_notices();
    };

But it only works when the update cart button is clicked. How do I default this so when the user clicks on "Add to Cart" from the minicart displayed on the cart page - It will update the notifications instead of displaying the duplicate each time? Or each time the cart updates in any manner - it removes the old woocomerce notices?
Edit:
Added an example of how the notices are set up on my site. This one for example is an anchor notice on mobile that when u click the button, takes you to the minicart at the bottom.
The other notices are set up the same way but with different functionality. Regardless of what's in the function - they all repeat when Add to Cart is clicked.
add_action( 'woocommerce_before_cart', 'mobile_notice' );

function mobile_notice() {
    if ( WC()->cart->get_cart_contents_count() != 0 && wp_is_mobile()) {
        $notice = sprintf('Add *3 of these exclusive products to the cart for $19.99 and get FREE SHIPPING!
Get Free Shipping');
        wc_print_notice( $notice, 'notice' );
    }

}

Here's an image of the notices if it helps any.
Notice Duplicates
Comment: Could you publish the entire code in which you place the notices?
Comment: Hey @VincenzoDiGaetano edited the original post. Can't really post all the code as it would be a violation in terms of privacy for my company however all the notices on our site follows the same syntax as the above.
Answer: Try adding wc_clear_notices(); before adding the new notice:
add_action( 'woocommerce_before_cart', 'mobile_notice' );
function mobile_notice() {
    if ( WC()->cart->get_cart_contents_count() != 0 && wp_is_mobile()) {
        wc_clear_notices();
        $notice = sprintf('Add *3 of these exclusive products to the cart for $19.99 and get FREE SHIPPING!
Get Free Shipping');
        wc_print_notice( $notice, 'notice' );
    }
}

Comment: This didn't work unfortunately. I've attached a picture of the error that might be helpful - it's what it looks like on mobile if a customer added something to cart - the woo notices keep duplicating each time.
Comment: I'm sorry but then I don't know how to help you. Did you clear the cache? Have you tried changing the priority of the `clear_notices_on_cart_update function`? If nothing works try to contact the theme support, they will surely know how to fix the problem.
Comment: Appreciate you trying to help!


Program never completes when loop is set to 4000000

Question: fib1 = 1
fib2 = 2

i = 0
sum = 0

while i < 3999998:

    fibn = fib1 + fib2

    fib1 = fib2
    fib2 = fibn

    i += 1

    if fibn % 2 == 0:
        sum = sum + fibn

print(sum + 2)

The challenge is to add even Fibonacci numbers under 4000000. It works for small limits say 10 numbers. But goes on forever when set for 4000000.
Code is in Python
Comment: the numbers are huge, addition of such a huge numbers is slow, using `%` modulo is slow as well
Comment: You are finding `4,000,000` fibonacci numbers, not fibonacci numbers upto `4,000,000`. Change your loop condition to `while fib2 < 3999998`?
Comment: In Python, you can write `a, b = b, a + b`.
Comment: Also, if you are doing this for Project Euler (I don't want to tell exactly what is wrong), but your loop condition is checking the wrong thing.
Answer: Yes, there are inefficiencies in your code, but the biggest one is that you're mistaken about what you're computing.
At each iteration i increases by one, and you are checking at each step whether i < 3999998. You are effectively finding the first 4 million fibonacci numbers.
You should change your loop condition to while fib2 < 3999998.
A couple of other minor optimisations. Leverage python's swapping syntax x, y = y, x and its sum function. Computing the sum once over a list is slightly faster then summing them up successively over a loop.
a, b = 1, 2
fib = []
while b < 3999998:
   a, b = b, a + b
   if b % 2 == 0:
      fib.append(b)

sum(fib) + 2

This runs in 100000 loops, best of 3: 7.51 µs per loop, a whopping 3 microseconds faster than your current code (once you fix it, that is).
Answer: You are computing the first 4 million fibonacci numbers. It's going to take a while. It took me almost 5 minutes to compute the result, which was about 817 KB of digits, after I replaced fibn % 2 == 0 with fibn & 1 == 0 - an optimization that makes a big difference on such large numbers.
In other words, your code will eventually finish - it will just take a long time.
Update: your version finished after 42 minutes.
Comment: I've been thinking about a possibility to eliminate the division by taking advantage of the fact that only every third Fibonacci number is even: 1, 1, 2, 3, 5, 8, ... -> O, O, E, O, O, E, ...; Of course, testing the last bit is faster
Comment: @cᴏʟᴅsᴘᴇᴇᴅ I think that they simply stopped at Fib(2222). Not so much because calculating Fib(2223) is much work (to add 2 numbers with a few thousand digits can be done in much less than a second), but more because the next number is also just large and not very interesting.
Comment: @COLDSPEED I don't know where you got that Fib(2222) is the largest fibonacci number. It's not true.
Comment: @Ronald Good observation. You could even just move three positions at once with `a, b = a+2*b, 2*a+3*b`. Then `b` will go through all the even Fibonacci numbers.
Comment: Hmm, what Python version did you use and what CPU? I just tried `a, b = 1, 2` followed by `for _ in range(4000000): a, b = b, a+b` and that already took 32 minutes on my fairly fast PC. So I'm surprised you took less than 5 minutes for doing more work. I used CPython 3.6.4 on an otherwise idle i7-6700 CPU.
Comment: That code took 3 minutes in python 3.6.4 on my laptop with a i7-3520M. I'm guessing the speed difference could be in the arbitrary precision integer implementation. I've seen similar speedups by switching implementation. Not sure what python uses, but I have gmp version 6.1.2 installed.


Firebase Index with Key as Parent

Question: I'm getting an error from Firebase:

Error: No index defined for read. FIREBASE WARNING: Using an unspecified index. Your data will be downloaded and filtered on the client. Consider adding ".indexOn": "read" at /checkins to your security rules for better performance.

My data structure is:
checkins: {
  -KwlbakCMOcjs1UhlqLv: {
    read: true,
    user: "someuserid"
  },
  -KwlysmdbSCfTI_Nz0Wo: {
    read: false,
    user: "someotherid"
  }
}

As you can see, the direct child of checkins is a key. Based on the error message, I've tried multiple ways of writing my rules, but the error persists:
{
  "rules": {
    ".read": true,
    ".write": true,
    "checkins": {
      "$checkinid": {
        ".indexOn": "read"
      }
    }
  }
}

{
  ..
  "checkins": {
    "$checkinid": {
      ".indexOn": ["read"]
    }
  }
}

{
  ..
  "checkins": {
    ".indexOn": "read"
  }
}

{
  ..
  "checkins": {
    ".indexOn": ["read"]
  }
}

Funny thing is: I tried to switch it up to indexOn user, but then I get an error there too (same idea - no index defined). checkins is not a child of anything, and there are no other rules but the ones you see for read/write at this point.
If it helps, my query is:
db.ref( 'checkins' ).orderByChild('read').equalTo(false).on(...

and I tried with user as the index on:
db.ref( 'checkins' ).orderByChild('user').on(...

So am I missing some key thing here? Any ideas? Thanks!
Comment: Those last two `.indexOn` definitions should work, as long as your data structure is indeed `/checkins`.
Answer: Remove this:
     "$checkinid": {
        ".indexOn": "read"
      }

And add this line inside "checkins" node as firebase suggestion, then you'll see the magic:
".indexOn": "read"

So your rule should become:
{
  "rules": {
    ".read": true,
    ".write": true,
    ".indexOn": "read"
  }
}

Firebase Index with Key as Parent


Get screen resolution independent of zoom in Firefox

Question: The existing answer is incorrect: Detect real screen resolution (ignoring browser zoom etc.)
It will not show the screen resolution, but rather the document size.
Is there a way to get screen resolution in Firefox, even when zoom is applied?
Comment: Whole debate and answer (more or less) here :
https://stackoverflow.com/questions/1713771/how-to-detect-page-zoom-level-in-all-modern-browsers
Answer: OK, thanks to https://github.com/mp31415
I have a working solution:
<code>var isIE = function () {
  if(navigator.appName === "Microsoft Internet Explorer") {
    return true;
  } else if(navigator.appName === "Netscape" && /Trident/.test(navigator.userAgent)) { // IE 11
    return true;
  }
  return false;
};
var isFF = function () {
  return !!navigator.userAgent.match(/firefox/i);
};
var sw = screen.width;
var sh = screen.height;
var zoom = 1;
if (this.isIE()) {
    zoom = screen.deviceXDPI / screen.systemXDPI;
    zoom = this.round5(zoom*100)/100;
}
else if (this.isFF()) {
    zoom = window.devicePixelRatio;
}
if (zoom != 1) {
  sh = this.round10(sh * zoom);
  sw = this.round10(sw * zoom);
}
</code>
This code returns resolution scaled for Retina displays but otherwise works fine.
Comment: Browser sniffing in 2015, seriously?
Comment: These comments disparaging browser detection are silly. Properties like screen.width exist in all browsers, but are scaled differently by browser vendor. This is a case where you HAVE to do browser detection because browsers have independent behavior that falls outside of a defined spec. (There is no defined spec for zooming.)
Comment: I don't understand why  you mean by your comment :)
Comment: [*Feature Detection vs Browser Detection*](https://www.joezimjs.com/javascript/feature-detection-vs-browser-detection/). ;-)
Comment: ok, got it :). Some implementation differences still exist today and require browser detection.
Comment: @Valentin Not this one, necessarily. You could test for the existence of the pertinent properties with `typeof`, and use them only if available.


Interpreting ordinal GEE coefficients

Question: I have a dataset with an ordinal dependent variable (iws_w) with a range of -3 to +1. I placed it, with two independent variables in an Ordinal Generalized Estimating Equation and got the following output:
                               OrdinalGEE Regression Results
===================================================================================
Dep. Variable:                       iws_w   No. Observations:                  352
Model:                          OrdinalGEE   No. clusters:                        2
Method:                        Generalized   Min. cluster size:                 156
                      Estimating Equations   Max. cluster size:                 196
Family:                           Binomial   Mean cluster size:               176.0
Dependence structure:         Independence   Num. iterations:                     2
Date:                     Mon, 21 Nov 2016   Scale:                           1.000
Covariance type:                    robust   Time:                         07:07:29
==============================================================================
                 coef    std err          z      P>|z|      [95.0% Conf. Int.]
------------------------------------------------------------------------------
I(y>-3.0)      0.5991      1.081      0.554      0.580        -1.520     2.718
I(y>-2.0)     -0.6484      0.542     -1.195      0.232        -1.711     0.415
I(y>-1.0)     -1.9218      0.231     -8.334      0.000        -2.374    -1.470
I(y>0.0)      -2.8109      0.090    -31.148      0.000        -2.988    -2.634
HF            -0.2999      0.061     -4.923      0.000        -0.419    -0.181
LF            -0.5081      0.200     -2.541      0.011        -0.900    -0.116
==============================================================================
Skew:                          0.4802   Kurtosis:                      -0.1278
Centered skew:                 0.6044   Centered kurtosis:              0.0444
==============================================================================

It is clear to me that IV's HF and LF decrease with increasing iws_w. However, what I cannot figure out yet are the intercepts I(y>XXX). It seems that with increasing iws_w, the intercept becomes lower, which I don't really understand. I guess that the intercepts are differences compared to iws_w = 1, but then it doesn't make sense that I(y>0.0) has a larger deviation than I(y>-3.0).
How should I interpret the I values?
A similar analysis was performed here, but no explanation was given
Answer: I'm not familiar with OrdinalGEE in Python, but I'll assume that the link function is logit, as is perhaps most common in ordinal regression.
If that is the case, the intercepts represent log odds. I(y>-3.0) represent the logged base odds of belonging to categories higher than -3.
We can calculate the probability of belonging to higher categories than -3:
exp(0.5991) / (1+exp(0.5991))
[1] 0.6454504

The probability of belonging to categories higher than -3 is thus 0.645, and the probability of belonging to category -3 is 1 - 0.645.
We can calculate the rest of the probabilities:
# probability of belonging to any category that is  > -2
exp(-0.6484) / (1+exp(-0.6484))
[1] 0.3433502

# probability of belonging to any category that is  > -1
exp(-1.9218) / (1+exp(-1.9218))
[1] 0.127661

# probability of belonging to any category that is  > 0, i.e. 1
exp(-2.8109) / (1+exp(-2.8109))
[1] 0.05673799

To calculate the probability of belonging to category 2, we need to subtract the probability of belonging to categories > -2 (0.3433502) from the probability of belonging to categories > -3 (0.6454504) = 0.3021002.
We can calculate the probabilities for belonging to each category in a similar manner:
-3.0    0.3545496
-2.0    0.3021002
-1.0    0.2156892
 0.0    0.07092301
 1.0    0.05673799

The sum of the probabilities is 1.
So in summary, the intercepts are the logged odds of belonging to the specified categories.
Comment: Amazing, thank you. This is a very clear answer :) So this also means that the coefficients of HF and LF are changes in the log-odds right?
Comment: No problem! Yes, HF and LF are changes in log odds!

Interpreting ordinal GEE coefficients


Databinding is not working in WPF

Question: I am unable to get databinding to UI.
Questions
Do I have to implement DependencyProperty OR INotifyPropertyChanged ? Its simple databinding
 and I am thinking I dont have to use above properties.
XMAL CODE
<Window x:Class="Pr.child"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
     xmlns:src="clr-namespace:Pr"
     xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase"
     Title="" Height="327" Width="683" WindowStartupLocation="CenterOwner">
     <Window.Resources>
        <ObjectDataProvider x:Key="Obj" ObjectType="{x:Type  src:test}" MethodName="getinfo" />
      </Window.Resources>
      <Label  x:Name="lblTest" Content="{Binding Source={StaticResource Obj},diag:PresentationTraceSources.TraceLevel=High}"
      <Button  Name="btnOK" Click="btnOK_Click">OK</Button>

code Behind
Main Windows class
public partial class Window1 : Window
{
   child w = new child();
}

Child Window Class
public partial class child : Window
{
     public child ()
     {
         InitializeComponent();
     }
     private void btnOK_Click(object sender, RoutedEventArgs e)
     {
         RunTest runTest = new RunTest();
     }
 }

RunTest runTest
 class RunTest
 {
     public RunTest()
     {
         test t = new test();
         t.info = "test info";
         t.getinfo();
     }
 }

Test Class
class test
{
     public string info { get; set; }
     public string getinfo()
     {
        return info;
     }
}

Debug Info
System.Windows.Data Warning: 52 : Created BindingExpression (hash=44780731) for Binding (hash=63630067)
System.Windows.Data Warning: 54 :   Path: ''
System.Windows.Data Warning: 56 : BindingExpression (hash=44780731): Default mode resolved to OneWay
System.Windows.Data Warning: 57 : BindingExpression (hash=44780731): Default update trigger resolved to PropertyChanged
System.Windows.Data Warning: 58 : BindingExpression (hash=44780731): Attach to System.Windows.Controls.Label.Content (hash=1867017)
System.Windows.Data Warning: 63 : BindingExpression (hash=44780731): Resolving source
System.Windows.Data Warning: 66 : BindingExpression (hash=44780731): Found data context element: <null> (OK)
System.Windows.Data Warning: 73 : BindingExpression (hash=44780731): Use Data from ObjectDataProvider (hash=16906910)
System.Windows.Data Warning: 74 : BindingExpression (hash=44780731): Activate with root item <null>
System.Windows.Data Warning: 100 : BindingExpression (hash=44780731): Replace item at level 0 with <null>, using accessor {DependencyProperty.UnsetValue}
System.Windows.Data Warning: 97 : BindingExpression (hash=44780731): GetValue at level 0 from <null> using <null>: <null>
System.Windows.Data Warning: 76 : BindingExpression (hash=44780731): TransferValue - got raw value <null>
System.Windows.Data Warning: 85 : BindingExpression (hash=44780731): TransferValue - using final value <null>

Comment: Your code makes no sense at all... the `RunTest` class just creates an instance of `test` that is never used anywhere, why would you expect the `ObjectDataProvider` to use this specific instance of `test` ? It will just create a new instance... What are you trying to achieve ?
Answer: This seems to make sense. Your ObjectDataProvider is creating a new test, and calling the getinfo method on it. This is null, because nothing has had a chance to set the info on that new instance, in fact your code doesn't even have a reference to it.
So the label is correctly displaying the value of null, which your trace agrees with.
You only need to implement INPC or use DependencyObjects if you want your UI to react to changes that something else makes to your bound objects. But it helps to have some properties to bind to!
Answer: I just 15 minutes ago ran into this exact situation.  You need to implement a DependencyProperty

Databinding is not working in WPF


Entity Reference, references dont display

Question: I have an article content type, and this article can be assigned to a topic content type. I have created a bunch of articles and topics, and this worked before. But for some reason, all of the sudden no more topics show up when editing an article content-type.
I was in the progress of adding a 'featured' story field with entity reference to the topic. This might have confused the database? Anyway, can I roll back without redo-ing everything and get this two sided relationship working?
** edit **
It seems that the old references still exist in the database as well, but dont show up as options in the article content-type add/edit forms.
Answer: Okay, found it. I had changed the language for my user session on the frontend.  Content wasn't yet populated in that langauge, therefore it didn't display.


$A \subset X$ closed, $B \subset X$ closed. Prove that $A \times B$ is a closed subset of $X \times Y$.

Question: Edit: I have been proven wrong.  Hence the claim below is true.  I will post an answer on this feed.  Thank you everyone who helped.
Claim: Let $X$ and $Y$ be topological spaces, let $A \subset X$, be a closed set in $X$, and let $B \subset Y$ be a closed set in $Y$.  Prove that $A \times B$ is a closed subset of $X \times Y$ (in the product topology).
(This is a question from my homework.  My work is showing that the claim is false but I am not very confident in my topological abilities and cannot see that I am doing anything wrong.  Will someone who is experienced with this will let me know what I am doing wrong or tell me that I am right?)
Proof: $A$ is closed in $X$, thus $A^{c}$ is open in $X$.  Similary, $B^{c}$ is open in $Y$.  Thus, by definition, $A^{c} \times B^{c}$ is open in the product topology on $X \times Y$.  However,
$(X \times Y) - (A \times B) = (A \times B)^{c} = (A^{c} \times B^{c}) \cup (A^{c} \times B) \cup (A \times B^{c})$
is not open in $X \times Y$ (specifically the sets $A^{c} \times B$ and $A \times B^{c}$ are not open in the product topology).  Thus, $A \times B$ is not a closed subset of $X \times Y$. !QED
Edit: I have been proven wrong.  Hence the claim above is true.  I will post an answer on this feed.  Thank you everyone who helped.
Comment: ***Hint:*** $(X\times Y)-(A\times B)=(A^c\times Y)\cup(X\times B^c).$
Comment: ***Hint:*** $(0,3)=(0,2]\cup[1,3)$, but $(0,2]$ is not open and $[1,3)$ is not open. Does that prove that $(0,3)$ is not open?
Comment: @Tim if $(x,y)$ is not in $A \times B$, $x \notin A$ or $y \notin B$ which covers the two options in the union.
Comment: The last term is redundant, because $A^c\times B^c\subseteq A^c\times Y$ and $A^c\times B^c\subseteq X\times B^c.$
Comment: One good way to test your proof is to put it to the test. Take $X=Y=\Bbb R$ and $A=B=[0,1]$. Or even simpler, $A=B=\{0\}$. Is $A\times B$ closed in $\Bbb R^2$? If the answer is positive, then your proof is wrong.
Comment: Doesn't your proof prove too much, namely, that the product of closed sets is ***never*** closed? I think you can find easy counterexamples to that in $\mathbb R\times\mathbb R.$ If you run your "proof" on that example, maybe you will see where your mistake is. (Are you concluding that $U\cup V\cup W$ is not open from the fact that $V$ and $W$ are not open? How does that work?)
Comment: OK.  So unions of "not open" sets does not necessarily mean that the union is "not open".  Thanks for your input.
Comment: @bof does the union on the right hand side cover $A^{c} \times B^{c}$?  It seems like $(X \times Y) - (A \times B) = (A^{c} \times Y) \cup (X \times B^{c}) \cup (A^{c} \times B^{c})$ unless the last term is redundant.
Answer: $A$ is closed in $X$, thus $A^{c}$ is open in $X$.  Similary, $B^{c}$ is open in $Y$.  Then $(X \times Y) - (A \times B) = (A^{c} \times Y) \cup (X \times B^{c})$ which is a union of open sets in the product topology on $X \times Y$.  Thus, $(A \times B)^{c}$ is open in $X \times Y$.  Hence, by definition, $A \times B$ is closed in $X \times Y$. $\hspace{1mm} \blacksquare$


Reseting the changes of paragrapgh

Question: I am working to display the changed paragraph that occurs in the span. Initially, this is the code for HTML.

This text will change.

I change the original text to :
Text Before ++ Text at the front --New Text for the Span == Text at the back@@Text After by using append, prepend, before and after.
I have this button.

   <button id="btnResetChanges">Reset Paragraph Text</button>

When I click this button I want to change all of the changes that occurs so that it returns to the original state .
I tried to do
$("#btnResetChanges").click(function () {
  ($("#spnOne").reset());

});

Comment: `reset()` is not a jQuery method.  It's a native method, which is intended to reset form fields.  Paragraphs are not form fields.  If you want to "reset" a paragraph, you are going to have to keep track of the original value yourself, and do the reset yourself.
Comment: @Taplar can you help me by giving an example. That would really be awesome
Comment: @Taplar is correct.   You should use a method to store the original paragraph using something like `local storage` -- Here is a great read on using `local storage` https://stackoverflow.com/questions/40791207/setting-and-getting-localstorage-with-jquery
Comment: You should store the value in a local param and then reset it it in javascript or jquery, I dont think so there is any API which reset it.
Comment: Easiest approach would be to store the original value on the paragraph as a data field.  No reason to put it in localStorage and make it more global than it has to be.
Comment: @Taplar .. Good call -- unless this is an "undo" function which is what I was assuming .. so there could be multiple versions of the paragraph needing reset ..  At this point local storage would be more efficient.
Comment: Also @rebbecca --  Asking multiple questions with the same content is frowned upon on Stack Overflow:  -->
 **original question** https://stackoverflow.com/questions/53552955/displaying-the-changed-paragraph-and-reseting-the-paragraph-in-original-form
Answer: You could use cookies and local storage in this case, but I would suggest to you to store the original paragraph using data-* attributes then call it when you want to reset, something like :

$('#spnOne').append('++++').prepend('----');

$('#btnResetChanges').click(function() {
  $('#spnOne').text($('#spnOne').data('original'));
})

This text will change.

  <button id="btnResetChanges">Reset Paragraph Text</button>

Answer:

//if you don't want to preload the data fields in the html
//you can set them with the javscript
var $changable = $('.changable').each(function(){
  $(this).data('originalHtml', this.innerHTML);
});

//when the button is clicked, change all the fields back to what is
//in their original data field
$('#btnResetChanges').on('click', function(){
  $changable.html(function(index, element){
    return $(this).data('originalHtml');
  });
});

This text will change.

This text will change.

This text will change.

  <button id="btnResetChanges">Reset Paragraph Text</button>

Reseting the changes of paragrapgh


What can I do with a closed file object?

Question: When you open a file, it's stored in an open file object which gives you access to various methods on it such as reading or writing.
>>> f = open("file0")
>>> f
<open file 'file0', mode 'r' at 0x0000000002E51660>

Of course when you're done you should close your file to prevent it taking up memory space.
>>> f.close()
>>> f
<closed file 'file0', mode 'r' at 0x0000000002E51660>

This leaves a closed file, so that the object still exists though it's no longer using space for the sake of being readable. But is there any practical application of this? It can't be read, or written. It can't be used to reopen the file again.
>>> f.open()

Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    f.open()
AttributeError: 'file' object has no attribute 'open'

>>> open(f)

Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    open(f)
TypeError: coercing to Unicode: need string or buffer, file found

Is there a practical use for this closed file object aside from identifying that a file object is being referenced but is closed?
Comment: Also, what is the alternative? An object can't delete itself, or modify the references to itself, so a closed file is essentially the only option.
Comment: You can check if the file has been "really" closed by f.closed
Comment: Note: you shouldn't generally have much to do with closed files because you want to handle them only inside `with` blocks and never reference them again, so you shouldn't even need to call `close()` explicitly.
Comment: @Lattyware I did not realise an object couldn't delete itself, though it makes sense as a practice.
Comment: @Bakuriu That's what I generally do, this thought just occurred to me when I saw a question about storing a list of file objects and I was curious about how closing the files would affect the data structure.
Comment: In theory, you could close and open a file represented by a `file` object multiple times (including the special case of creating the `file` object without actually opening it right away). However, those details are not exposed at the Python level, so creating an object automatically opens the file, and closing it is irreversible.
Answer: One use is  using the name to reopen the file:
open(f.name).read()

I use the name attribute when changing a file content using a NamedTemporaryFile to write the updated content to then replace the original file with shutil.move:
with open("foo.txt") as f, NamedTemporaryFile("w", dir=".", delete=False) as temp:
    for line in f:
        if stuff:
            temp.write("stuff")

shutil.move(temp.name, "foo.txt")

Also as commented you can use the f.closed to see if the file is really closed.


Query records with date greater than 60 days

Question: I am trying to query all records that have a date that is greater than 60 days of its created date and also has a null value in another field "Invoice#" The "Date_Created" field is saved as a date in YYYY-MM-DD. This is currently hat I am using but doesn't seem to be working. I get an error saying "Invoice_Number" is an unknown column and when I remove that part of the code I get nothing returned.

select * from PO_Information where Date_Created >= (Date_Created +
  Interval 60 day) and Invoice_Number IS NULL
Comment: try with Date_Created >= DATE_ADD(DateCreated, INTERVAL 60 day)
Answer: WHERE Date_Created >= DATE_ADD(Date_Created,INTERVAL 60 DAY)

For the interval, but This will always return false, this is why you are getting no results when you remove the IS NULL
as for the unknown column, you have not told us about the table structure so I can't help you there


How do I append one element to a list as efficiently as possible

Question: At the end of CLOJURE for the BRAVE and TRUE's Chapter 4 there's an exercise: make an append function that appends a new entry to a list.
What's the most efficient way to do so?
From what I understand of datatypes in general, if conj prepends elements to a list, that simply means that consistently appending to a list is either silly or the choice of using a list type was silly.
Anyway, the solution I've written is this
(defn append
  [lst item]
  (into '() (conj (into '() lst) item)))

Well, that's actually the same as
(defn append
  [lst item]
  (reverse (conj (reverse lst) item)))

I believe, so probably is costly because I reverse the list twice?
Another solution I could think of is
(defn append
  [lst item]
  (apply list (conj (apply vector lst) item)))

But they all seem to traverse the sequence of values twice, so I don't see why any one should be better than another.
Is there the proper way to accomplish the task?
Comment: `(apply list (concat lst [item]))` will traverse only once. But I can't say whether it's more efficient or not - you'd have to profile it with different input sizes. It might easily be the case that one solution is better where the number of items is small but a different one is better for large inputs.
Answer: There is a reason, why conj adds a new item at the start of the list and not at its end. Because you have to traverse the list to add something at its end. This is not very efficient. And it is because of the nature of a linked list. That's why in lisp you cons new items onto a list and at the very end reverse it. This way, you traverse the list just once while building it.
In Clojure, if you want to add to a list at the end, it is more idiomatic not to use a list but instead the vector type. On a vector, conj adds right to the end.
But let's say, you want to traverse a list once and add to the end.
That is actually:
(defn my-append [lst item] (concat lst (list item)))

(my-append '(1 2 3) 4)
;; (1 2 3 4)

but as I said, if you want to add repeatedly at the end, don't use a list, but a vector and conj to the end.
;; more idiomatic clojure in thisst to add something at its end. This is not very efficient. And it is because of the nature of a linked list. Tha case

(def v [1 2 3])

(conj v 4) ;; [1 2 3 4] ;; unbeatable in efficience, because no traversal!

;; and convert to a list
;; e.g.
(def l (conj v 4))
(seq l)    ;; (1 2 3 4)

Answer: to avoid the double traversal, you could use the classic recursive approach. Something like this:
(defn append [lst item]
  (loop [res [] lst lst]
    (if (seq lst)
      (recur (conj res (first lst))
             (rest lst))
      (seq (conj res item)))))

so, it just rebuilds the list from scratch.
To make it's performance better in clojure, you can optimize it with transient collection:
(defn append' [lst item]
  (loop [res (transient []) lst lst]
    (if (seq lst)
      (recur (conj! res (first lst))
             (rest lst))
      (seq (persistent! (conj! res item))))))

but yes, as another answer proposes, you should carefully pick the proper data structure for every specific task, so in practice you would want to use vector.
As of concat variant, it comes for free (since it is lazy), but it has this known pitfall, which is stack overflow on applying a lot of stacked lazy functions:
user> (defn append-concat [lst item]
        (concat lst [item]))

user> (reduce append-concat () (range 1000000))
;; Error printing return value (StackOverflowError) at clojure.lang.LazySeq/sval (LazySeq.java:42).