What is the difference between 'macro' and 'command'?

Question: Some people use the word 'macro' and 'command' interchangeably to refer to the instructions given to LaTeX. Is there a real difference between the two terms? If there is, can we see some examples on what the differences are?
Comment: We write `macro` or `command` or `control sequence` because we don't want to use the same name all the time. We're not lazy ;-)
Comment: I personally do use these three words slightly differently, and I'm now wondering if this is correct. For me a "macro" is a command defined in terms of other commands (it can be expanded, so I exclude primitives and lengths), a "command" is an instruction that does something (which is admittedly vague, but this would include macros, but not lengths) and a "control" sequence" is a single token that consists of a backslash followed by a sequence of characters (irrespective of whether it is defined at all, but I'm not including active characters). Most commands are all three of these things.
Comment: Perhaps Lamport introduced the term `command` for pedagogical reasons in an attempt to hide the supposedly arcane macro-expansion-based TeX user interface. Official LaTeX books propagate this. Recently, LaTeX3 does something a bit alike by introducing `function`-terminology (see the Abstract at very start of `texdoc expl3`). There is some analogy here that in both cases it is felt TeX terminology needs some additional layer.
Comment: "Commad" is used better when you want to be understood, "macro" could be used when you want to remark  that is a custom (not primitive) command to initiated people and "control sequence" is useful when you want that the uninitiated do not understand you.
Comment: @Circumscribe There are expandable primitives that are sometimes expanding to a value, e.g. `\eTeXrevision`. Is this a macro as per your definition?
Comment: @TeXnician: Good point, I realised that only just before you posted your comment [for those reading along: the first version of my comment said that a macro is something that expands to something else]. I would say it is not (nor are e.g. `\the`, `\ifx` and `\csname`), but I don't know how (or if) these terms are officially defined and I'm actually curious about what users think.
Comment: Clarification: for my definition a "macro" would be anything for which the `\show` output starts with "macro:"  (and which is thus ultimately defined using a version of `\def`?) and a command would be anything that is either a macro or a primitive (something for which `\show` outputs ``), but is not a register (or a character). That last part is probably terrible as a definition though. I also tend to say "command" rather than "macro" when the instruction performs an assignment rather than producing output, but that's probably just me.
Comment: Since you have some responses below that seem to answer your question, please consider marking one of them as 'Accepted' by clicking on the tickmark below their vote count (see [How do you accept an answer?](http://meta.tex.stackexchange.com/q/1852)). This shows which answer helped you most, and it assigns reputation points to the author of the answer (and to you!). It's part of [this site's idea to identify good questions and answers through upvotes and acceptance of answers](http://tex.stackexchange.com/about).
Comment: What is the difference between `\tracingcommands` and `\tracingmacros`? See https://tex.stackexchange.com/questions/60491/latex-tracing-commands-list
Answer: macro programming is a programming style (as distinct from compiled programs) where the operation works by each token being replaced inline by its replacement text. Popular macro programming languages other than TeX include the C language pre-processor and the m4 system.
What macro means in LaTeX?
TeX's main mode of user customisation is via its macro processing language, but of course it requires some built in commands (primitives) that you may use to build up macros.
So commands such as \def, \halign, \count are not macros.
Tex also has some primitives that are classed as expandable and so act pretty much the same as pre-defined macros although technically they are not classed as macros in TeX, a list of these expandable primitives is here:
Is there a list of expandable TeX primitives? LaTeX? e-TeX? others?
A control sequence is a string of characters such as \foobar that references a command (or token, or is  undefined) as opposed to a character such as x that just references itself, it may reference tex primitives or macros, depending on the context.  Note that being a macro is a property of the meaning of the token, but being a control sequence is a property of its syntax. So by default ~ is a macro but it is an active character token not a control sequence.
In TeX macros are always defined by \def and its variants such as \edef.  LaTeX definition commands such as \newcommand are themselves macros that ultimately result in an application of \def to define a macro.
Answer: I seldom use the term "command" when it is about (La)TeX.
In the TeXbook the term "command" does also appear in contexts where not single tokens but the coming into being of sequences of control word tokens plays a rôle.
E.g., chapter 15 of the TeXbook includes a double dangerous bend paragraph where you can read:

[...] Therefore plain TeX provides an allocation function for registers; Appendix B includes the command
\newinsert\footins
which defines \footins as the number for footnote insertions. [...]

So, e.g., \newinsert\footins is a "command".
(By the way: The mentioned appendix B does actually not exhibit tokens. It exhibits TeX code, i.e., TeX-input which the programmer of the plain TeX format did produce. That TeX-input itself is not tokens. TeX will create tokens when processing that code.)
In the TeXbook you also find the phrase "primitive command". It is used in contexts where very short and easily to grasp sequences of TeX-input play a rôle. (Sequences that, when being read and tokenized, yield primitives...)
I suppose, a "command" according to the diction of the TeXbook is a sequence of characters which forms some portion of TeX-input. A portion of TeX-input which, when TeX reads and tokenizes that sequence of characters, yields a set of whatsoever tokens and/or (e.g., in case the command in question contains "invalid characters"/characters of category code 15) some error-messages. In case of yielding a set of tokens, that set of tokens is intended to form a syntactical entity which TeX's token-processing-apparatus can attempt to carry out/to process in whatsoever way. Such an attempt in turn may also yield error-messages and/or erroneous behavior.
Thus the term "command" in the diction of the TeXbook itself seems to actually not focus on things as results of TeX's "digestive processes". One of the earlier results of TeX's digestive processes are tokens. Tokens are produced in TeX's mouth. Thus the term "command" itself seems to actually not refer to tokens. It seems to refer to subsets of the things which TeX "looks at" with its "eyes"—it refers to portions of the TeX-input, i.e., to the things which in interactive mode the user/programmer can type, or which TeX can read from .tex-input-files or \read-handles for tokenization and further processing.
In the LaTeX 2e-kernel you have things like \newcommand and \renewcommand.
These things during LaTeX's digestive processes cause LaTeX to perform assignments. But the point of view seems not to be the view of the LaTeX-program which "looks at" LaTeX-input and while "digesting" produces "tokens" etc. The point of view seems to be the view of the programmer. The programmer does not produce tokens. She/he produces LaTeX-input. That LaTeX-input is not tokens yet. It is a sequence of input-characters.
After writing \newcommand..., the programmer in her/his code can take the thing introduced via \newcommand for a small portion of LaTeX-input which when tokenized by LaTeX yields a token which itself is considered a syntactical entity which, when used as intended, can be carried out via LaTeX's token-processing-apparatus without yielding erroneous behavior.
I could not find the phrase "command token" in texbook.tex.
This can also be taken for an indication that "command" and "token" in the diction of the TeXbook do in the upshot not refer to the same stage of work.
It seems, in the TeXbook the term "command" is used when the focus is on that stage where the programmer produces/delivers/types whatsoever .tex-input.
It seems, in the TeXbook the terms "token" and "macro" are used when the focus is on that stage where the TeX-program does process the .tex-input.

The term "macro" seems to refer to the concept of TeX's tokens while tokens and thus macro-tokens do not come into being while writing/producing/delivering TeX-input but while having the TeX-program read and tokenize TeX-input and from the resulting tokens expand the expandable ones.
As far as I know, macro-tokens are ⟨control sequences⟩ that both are expandable and do not have the meaning of one of those about 300 low-level atomic operations that are called "primitives".

Besides "macro" and "command" there is another term in the TeX world which deserves the attempt of shedding light: The term "function".
The tern "function" is used a lot in the documentation of expl3—expl3 is an en-vogue and state-of-the-art programming layer for LaTeX.
A macro-token is processed in TeX's gullet, where expansion of expandable tokens takes place in some sort of "regurgitative process". A macro-token gets processed in TeX's gullet during a single expansion-step. After the expansion-step the macro-token and the tokens forming its arguments and argument-delimiters are removed from the token-stream and tokens forming replacement-text according to the macro-definition are inserted into the token-stream instead. After the expansion-step carrying out the macro is done.
Carrying out a macro does not necessarily mean entirely carrying out an algorithm. Carrying out a macro implies carrying out a single expansion-driven step of a routine/of an algorithm.
The term "function" focuses on the result of entirely carrying out a routine/an algorithm for obtaining a desired result whereby cascades of expansion-steps and other kinds of operation-steps—i.e., the invoking of (several) macros and/or the invoking of primitives (be they expandable or not), and/or the invoking of unexpandable non-primitives—may play a rôle.
Implementing a "function" may require defining several macros and non-expandable non-primitives that underlie the "mechanism".
In expl3-jargon also that token/control sequence is called a "function" which initiates the cascade of expansion-steps and/or whatsoever other operation-steps which yields carrying out the algorithm/routine in question.

Above I said:
"As far as I know, macro-tokens are ⟨control sequences⟩ that both are expandable and do not have the meaning of one of those about 300 low-level atomic operations that are called 'primitives'."
What kinds of tokens can form such ⟨control sequences⟩?
⟨control sequences⟩ come in two flavors:

⟨control sequence tokens⟩
These divide into ⟨control symbol tokens⟩ and ⟨control word tokens⟩
⟨active character tokens⟩

With this remark we reach the question of how to divide up ⟨control sequences⟩.

As just seen, one way of dividing up ⟨control sequences⟩ is by looking at the question what kinds of tokens can form ⟨control sequences⟩:
⟨control sequence tokens⟩ are those lovely "thingies" that in TeX input need to be preceded by a character whose category code is 0 (escape).
Usually the backslash-character is the only character whose category code is 0.
⟨control sequence tokens⟩ come in two flavors:
⟨control symbol tokens⟩ have names which consist of a single character which does not have category code 11 (letter).
E.g., usually \. and \\ are ⟨control symbol tokens⟩ as usually the characters . and \ do not have category code 11 (letter).  \a usually is not a ⟨control symbol token⟩ as usually the character a does have the category code 11 (letter).
⟨control word tokens⟩ have names which consist either of several characters which do not need to have the same category code, or of a single character which does have the category code 11 (letter).
There are two ways how a ⟨control sequence⟩ (, i.e., a ⟨control sequence token⟩ or an  ⟨active character token⟩, see below) can come into being:

When (La)TeX reads and tokenizes input.
When (La)TeX inserts it during expansion; e.g., as part of the ⟨replacement text⟩ of a macro; e.g., as part of the \the-expansion of a token-register.

A ⟨control sequence token⟩ can come into being also

as the result of expanding some \csname..\endcsname-expression.

Any character whose current category code is not 11 (letter), even a character of category code 15 (invalid), can form the name of a ⟨control symbol token⟩ that came into being as a result of reading and tokenizing TeX-input.
(I say "current" because as soon as the character that forms the name of the ⟨control sequence token⟩ in question is switched to 11 (letter), the ⟨control sequence token⟩ in question will not be treated as a ⟨control symbol token⟩ (any more) but as a ⟨control word token⟩.)
Otherwise you could, e.g., not use ⟨control symbol tokens⟩ for changing the category codes of characters that currently have category code 15 (invalid).
But you can do, e.g.,:
\catcode`\A=15 % Now uppercase-a is invalid.
% Typing an "A" both outside a comment and not behind a character
% of category code 5 (end of line) which is not
% intended to form the name of a control-symbol-token would yield
% an error-message now.
% But you can do:
\catcode`\A=11 % Now uppercase-a is a letter again.

After elaborating on the names of ⟨control symbol tokens⟩, let's elaborate on the names of ⟨control word tokens⟩:
On the one hand, TeX's reading- and tokenizing-apparatus will only take sequences of characters of category code 11 (letter) as names of ⟨control word tokens⟩.
Thus names of ⟨control word tokens⟩ created via having TeX read and tokenize them directly from TeX-input consist only of characters that had category code 11 (letter) at the time of reading and tokenizeng them.
On the other hand names of ⟨control word tokens⟩ created via evaluating \csname..\endcsname-expressions can consist either of more than one character of whatsoever category code differing from 5, 9, 14 and 15 at the time of reading and tokenizing the \csname..\endcsname-expression , or of a single character of category code 11 (letter).
Now some remarks about the subtle differences between TeX's treatment of ⟨control symbol tokens⟩ and TeX's treatment of ⟨control word tokens⟩:
Usually the space character (code-point 32 both in ASCII and in unicode) and the horizontal tab character (code-point 9 both in ASCII and in unicode) are the only characters which have category code 10 (space).
A character of category code 10 (space) that in the TeX-input occurs behind a character-sequence that got tokenized as a ⟨control symbol token⟩ whose name is formed by a character which does not have category code 10 (space) will be tokenized as an explicit space token.
A character of category code 10 (space) that in the TeX-input occurs behind a character-sequence that got tokenized as a ⟨control symbol token⟩ whose name is formed by a character which does have category code 10 (space) will be ignored/will not yield any token.
E.g., category code 10 (space)-characters that follow the control-space, \␣, i.e., that ⟨control symbol token⟩ whose name is formed by the space character, will be ignored/will not yield any token.
A character of category code 10 (space) that in the TeX-input occurs behind a character-sequence that got tokenized as ⟨control word token⟩ will be ignored/will not yield any token.
When (La)TeX does unexpanded-write a ⟨control word token⟩ (be it writing to file, be it writing to the screen), it automatically inserts a space character at the end of the character sequence that represents the ⟨control word token⟩ in question.
When (La)TeX does unexpanded-write a ⟨control symbol token⟩ it will not automatically insert such a trailing space character.
When applying \string for transforming the following token into a sequence of ⟨character tokens⟩ (La)TeX will not attach an additional trailing space token.
(\string produces character tokens of category 12 (other). Exception: Spaces produced by \string will be so called explicit space tokens, i.e., character tokens with character code 32 and of category 10 (space).)
You can change the way in which TeX does unexpanded-write a ⟨control sequence token⟩ whose name consists of a single character by before writing changing the category code of that character either to 11 (letter)—in this case it will be written as a ⟨control word token⟩ with trailing space— or to a value differing from 11—in this case it will be written as a ⟨control symbol token⟩ without trailing space.
Thus you can have fun with TeX's automatic insertion of spaces when doing delayed writes with unexpanded ⟨control sequence tokens⟩ whose names consist of a single character—the code
\documentclass{article}
\begin{document}
\newwrite\mywrite
\immediate\openout\mywrite test.txt\relax

\catcode`\A=12

\write\mywrite{b\noexpand\Ab}
\immediate\write\mywrite{b\noexpand\Ab}

\catcode`\A=11

Hello

\end{document}

besides the .dvi- or .pdf-file yields a file test.txt with the following content:
b\Ab
b\A b

As both \write-commands were issued while A was of category code 12 (other), you might have expected each \A to be unexpanded-written as ⟨control symbol token⟩ without a trailing space, and thus you might have expected the output
b\Ab
b\Ab

. But the first \write was not \immediate and thus it got carried out not immediately but at the time of shipping out the page. At that time, the second \write, which was \immediate, was already done and \A had category code 11 (letter) again and thus the \A in the first \write was written within the second line as a ⟨control word token⟩, with LaTeX attaching a trailing space character.
The nameless ⟨control sequence token⟩—methods for forming it are: 1) expanding \csname\endcsname; 2) placing a backslash (a character of category code 0 (escape)) at the end of a line while the parameter \endlinechar has a non-positive value or a value outside the range of code-points of the TeX-engine's input-encoding—deserves special attention:
Applying \string to it usually yields the catcode 12(other) character token sequence \12c12s12n12a12m12e12\12e12n12d12c12s12n12a12m12e12.
There is no space token between \12c12s12n12a12m12e12 and \12e12n12d12c12s12n12a12m12e12. There also is no trailing space token.
Unexpanded-writing it yields the character sequence \csname\endcsname␣—there is a trailing space character.
TeX will not necessarily produce backslash-character-tokens with \string/backslash-characters when unexpanded-writing to external text file or screen but will produce those character-tokens/characters whose character-code/code-point-number in the TeX-engine's internal character representation scheme (which with traditional TeX is ASCII and with LuaTeX/XeTeX is unicode whereof ASCII is a strict subset) equals the value of the integer parameter \escapechar.
If the value of \escapechar is outside the range of possible code-point-numbers for encoding characters, TeX will not deliver escape-character-tokens/characters.
Usually the value of \escapechar is 92 which denotes the backslash. But after \escapechar=65 the command \expandafter\string\csname\endcsname yields A12c12s12n12a12m12e12A12e12n12d12c12s12n12a12m12e12because 65 is the number of the code-point of the character A.
But after \escapechar=-8 the command \expandafter\string\csname\endcsname yields c12s12n12a12m12e12e12n12d12c12s12n12a12m12e12 because -8 is outside the range of possible code-point-numbers for encoding characters and thus tokens representing escape-characters (backslashes) are not delivered.
Character tokens produced via \string are of category 12(other). The only exception is: If the character code of the character token produced due to \string is 32 (32 denotes the space character), then the category is 10(space).
Besides the ⟨control sequence tokens⟩ there is another kind of ⟨control sequences⟩: ⟨active character tokens⟩.
An ⟨active character token⟩ is a ⟨character token⟩ whose category code is 13 (active).
An ⟨active character token⟩ can be used like a ⟨control sequence token⟩.
E.g., after \catcode`\b=13  you can do \def b{The active character \string b is a macro now.}

Another way of dividing up ⟨control sequences⟩ is by looking at their "decomposability":
The TeXBook says:

About 300 of TeX's control sequences are called primitive; these are
the low-level atomic operations that are not decomposable into simpler
functions. All other control sequences are defined, ultimately, in
terms of the primitive ones. For example, \input is a primitive
operation, but \' and \" are not; the latter are defined in terms of
an \accent primitive.

(It should not be overlooked that when defining ⟨control sequences⟩ that are macros, ⟨non-active character tokens⟩ can play a rôle also.)

Yet an another way of dividing up ⟨control sequences⟩ is by looking at the actions triggered by them and at the point in time when these actions are triggered:
There is the analogy between TeX's input-processing and digestive processes:

TeX input is divided up into so-called tokens (⟨control sequence tokens⟩ and ⟨character tokens⟩) in TeX's mouth.
Expansion of expandable ⟨control sequences⟩ takes place in the gullet.
Unexpandable ⟨control sequences⟩ will be handled in the stomach.

So you distinguish expandable ⟨control sequences⟩ and unexpandable ⟨control sequences⟩.
Expandable ⟨control sequences⟩ (and their arguments) will in the gullet be replaced by other constellations of tokens. Replacement of expandable ⟨control sequences⟩ takes place in the gullet until there are no more expandable ⟨control sequences⟩ left.
Unexpandable ⟨control sequences⟩ (which came into being either during tokenization in TeX's mouth or via replacement of expandable tokens during expansion) pass the gullet and reach the stomach where boxes will be built, assignment-primitives will be carried out, etc.
There are primitive ⟨control sequences⟩ that are expandable:
E.g., the \string-primitive is an expandable primitive. Together with the following token it vanishes in TeX's gullet and as replacement you get a set of ⟨character tokens⟩ of category 12 (other) or 10 (space) that represents the name of the ⟨control sequence token⟩ in question/is the catcode-12-pendant of the ⟨character token⟩ in question. (When in TeX's token stream an explicit space token trails the control-word-token \string, expanding \string yields an explicit space token.)
E.g., the \csname-primitive is an expandable primitive. It triggers the processing of a \csname..\endcsname-expression in TeX's gullet and it vanishes in TeX's gullet and as replacement you get the corresponding ⟨control symbol token⟩ or ⟨control word token⟩. In case that token is undefined, it will get the meaning of the \relax-primitive within the current scope.
E.g., the \romannumeral-primitive is an expandable primitive. It and a following ⟨number⟩ vanish in TeX's gullet and in case the ⟨number⟩ is positive as replacement you get a sequence of ⟨character tokens⟩ of category code 12 (other) that represent the corresponding ⟨number⟩ in lowercase-roman notation.
There are primitive ⟨control sequences⟩ that are not expandable:
E.g., the \relax-primitive is not expandable. It does pass the gullet and reach the stomach.
E.g., the assignment-primitives \def, \edef, \gdef, \xdef, \countdef etc are not expandable. They do not trigger their replacement in TeX's gullet but will reach the stomach.
There are non-primitive ⟨control sequences⟩ that are expandable:
Macros are non-primitive ⟨control sequences⟩ that are expandable. They and their arguments get replaced with their ⟨replacement text⟩ in TeX's gullet. Macros are defined in TeX's stomach in terms of the primitives \def, \edef, \gdef and \xdef. Be aware that LaTeX's \newcommand also is just a macro which "decomposes" in LaTeX's gullet to some set of tokens containing the \def-primitive.
There are non-primitive ⟨control sequences⟩ that are not expandable:
You can, e.g., do things like \let\bgroup={.
\bgroup is a ⟨control sequence⟩. More specific: It is a ⟨control sequence token⟩. It is a ⟨control word token⟩. It is not expandable but it also does not have the meaning of one of the about 300 non-decomposable functions of TeX that are called primitives. \bgroup is an implicit character  token. ;-)
Other kinds of non-primitive ⟨control sequences⟩ that are not expandable are, e.g., \chardef-tokens, \countdef-tokens, \toksdef-tokens, ...

In order to get used to the terminology, let's unravel some cases:
After carrying out the assignments
\catcode`\W=13 %
\catcode`\X=13 %
\catcode`\Y=13 %
\catcode`\Z=13 %
\newcommand W{The active character \stringW is a macro.}
\newcommand\something{This is a macro.}
\newcommand\+{This is a macro, too.}
\let X=a
\let Y=\relax
\let Z=\romannumeral

,

W is a ⟨control sequence⟩: It is an ⟨active character token⟩. It is a macro and thus both expandable and not a primitive.
X is a ⟨control sequence⟩: It is an
⟨active character token⟩. It is not expandable. Thus it cannot be a macro. It also is not an unexpandable primitive. It has the same meaning as the catcode 11(letter) ⟨character token⟩ a. It is an implicit character token.
Y is a ⟨control sequence⟩: It is an ⟨active character token⟩.  Its meaning equals the meaning of the unexpandable \relax-primitive. Thus it is an unexpandable primitive.
Z is a ⟨control sequence⟩: It is an ⟨active character token⟩.  Its meaning equals the meaning of the expandable \romannumeral-primitive. Thus it is an expandable primitive.
\something is a ⟨control sequence⟩: It is a ⟨control sequence token⟩. It is a ⟨control word token⟩. It is expandable. Its meaning does not equal one of the about 300 non-decomposable functions of TeX that are called primitives. It is a macro.
\+ is a ⟨control sequence⟩: It is a ⟨control sequence token⟩. It is a ⟨control symbol token⟩. It is expandable. Its meaning does not equal one of the about 300 non-decomposable functions of TeX that are called primitives. It is a macro.

The term "macro" does always denote a non-primitive expandable ⟨control sequence⟩.
Thus when you know that a token is a macro, you can conclude that it cannot be a
⟨non-active character token⟩ because ⟨non-active character tokens⟩ cannot be ⟨control sequences⟩.
You can conclude that it is a ⟨control sequence⟩.
But you cannot conclude whether the ⟨control sequence⟩ is a ⟨control word token⟩ or a ⟨control symbol token⟩ or an
⟨active character token⟩.
Not all expandable ⟨control sequences⟩ are macros.
There are expandable ⟨primitives⟩ as well.
Not all non-expandable ⟨control sequences⟩ are ⟨primitives⟩.
There are non-expandable non-primitives as well:
E.g., implicit character tokens, \chardef-tokens, \countdef-tokens, \toksdef-tokens, ...
Comment: Sorry for asking, but just curiosity: are you writing everything from your mind?
Comment: Ulrich, Since TeX doesn't end in an orthographic 's', it's possessive form should be "TeX's" not just "TeX'".
Comment: @AlanMunn These comments might prevent others from making the same mistakes... ;-)
Comment: @Sigur I just thought about it, looked up the quotes and spontaneously  typed into the input-field of the TeX-LaTeX-StackExchange-Website shown in my internet-browser. If I had really planned this answer systematically, I would have typed within my favorite editor-software, saved the text as a file and revised it a few times before pasting it from the editor-software to the input-field of the TeX-LaTeX-StackExchange-Website. But I didn't take it all too serious. I just wanted to have fun...;-)
Comment: As I started reading this answer, I just knew you were the author, so distinctive is your extreme thoroughness.
Comment: I mean: you just think about it and type or are you copying/pasting from some where?
Comment: @AlanMunn Thanks. I just looked into the mirror for once more in my life doing a face-palm at myself. The most embarrassing aspect of the matter is that I myself did in my answer quote a sentence from the TeXbook where the possessive form is spelled correctly. So I had an example of how to do it correctly right in front of my eyes and I did not realize it anyway. I even copied it for quoting... I don't know what I was thinking...
Comment: We've all done that at some point or other. :)  We can delete these comments.
Comment: Encyclopedic answer!
Answer: They're used interchangeably because they mean the same thing.

A macro is defined as

a single computer instruction that stands for a sequence of operations

The use of command probably stems from the way it's defined in LaTeX via \newcommand and \renewcommand and LaTeX3's xparse via \NewDocumentCommand and \RenewDocumentCommand.

There's also control sequence used by DEK in his TeX Book. They all point to the same thing.
Comment: I would not say they mean the same thing, tex primitives are not macros.
Comment: Certainly some do but that I think leads to confusion (as witnessed by this question)
Comment: I'm confident the majority of people using (La)TeX use the terminology interchangeably.
Comment: @DavidCarlisle I wish I didn't use them interchangeably, but I find myself doing it.  Even in my `tokcycle` package, where the documentation tries to draw limited attention to the distinction, the directive that absorbs anything cat-0 is called the `\Macrodirective`.  So I fail at this basic level, though `\CatZEROdirective` would have been too much of a pain to write.  Perhaps `\Commanddirective` would have worked, but folks would be stumbling over the double `d`.
Answer: A lot depends on how you're approaching LaTeX. If you're an author, you don't really care about macros, control sequences, tokens etc. From that perspective, anything that begins with \ and does something is a command. To a lesser degree, you'll worry about lengths and glues (dimens and skips in primitive TeX speak), although given an appropriate document class, an author would be unlikely to use any of these with the possible exception of \linewidth or \baselineskip for scaling purposes of imported graphics.
On the other hand, if you're approaching LaTeX as a developer and creating classes or packages, you'll care a bit more, although expl3 does abstract away a lot of that (albeit occasionally abusing terminology).² Everything is still macros built out of primitives at the bottom, but there's at least a consist terminology there, as long as you're able to get past the three-level archaeology of LaTeX's sources³ in understanding how things work.

It's possible to write an expl3 function that can be assigned to an expl3 value, but this is not the default behavior and expl3 has no inherent concept of return type since it's still, at its heart, macro expansion.

In other languages, if you apply a map to something, you get something of the same class (so, e.g., in Rust, iter.map(|x| x.to_string()) would take the iterator iter on some type and turn it onto an iterator on the string values of that type, and some_optional.map(|x| x*x) would transform the optional value some_optional into a new optional value holding the square of its contents (if present)) while the various _map functions of expl3 instead just iterate on their value but don't actually return a new tl, prop, str, but rather produce their output in situ. Perhaps more concerning is that Expl3 functions in most cases¹ are not what any other language calls a function, but are more properly procedures.
All this is not to complain (too much). Expl3 is a monumental accomplishment and together with xparse provides a means to make things that were previously difficult much easier to do. TeX is a truly unique programming idiom, the managing of which is akin to playing chess in a lot of ways in that the most direct route often does not yield the desired results.

viz, newer code written with Expl3, legacy⁴ code using private LaTeX commands with @ syntax and finally the lowest level code which employs primitive TeX syntax.

It seems a bit strange to refer to something as legacy when it comprises the bulk of the code.


How to configure vlan mapping with VPLS on Cisco 6500 routers?

Question: I'm using VPLS to extend vlan x from site1 (Cisco C6500) to two remotes sites (Cisco C6500) site2 and site3 over MPLS.
The issue I'm facing is that a vlan with the same number already exists in the remote site3, so I'm using a different vlan number (say y) in the remote site3. How do I configure vlan mapping between site1 and site3 to map vlan y to x and vice versa?
Thanks!
Comment: Has any answer solved your question? Then please accept it or your question will keep popping up here forever. Please also consider voting for useful answers.
Answer: To achieve VLAN mapping between site1 and site3 in VPLS, you can use the VLAN Translation feature on the Cisco Catalyst 6500 routers. This feature allows you to map VLANs between different sites in a VPLS network. Here's a general outline of the steps to configure VLAN mapping:
Identify the VLANs to be mapped: Determine which VLANs need to be mapped between site1 and site3. For example, if you have VLAN x in site1 and VLAN y in site3, you want to map VLAN y to VLAN x and vice versa.
Configure VPLS on both routers: Set up VPLS on both the site1 and site3 Cisco Catalyst 6500 routers. This involves configuring the VPLS instance, specifying the MPLS pseudowire, and defining the VFI (Virtual Forwarding Instance).
Configure VLAN translation on both routers: Use the "bridge-domain vlan-translation" command to configure VLAN translation on the VFI for both VLANs x and y. For example:
<code>Router (config)# bridge-domain vlan-translation vlan x map y
Router (config)# bridge-domain vlan-translation vlan y map x
</code>
Verify the configuration: Use the "show bridge-domain" command to verify that the VLAN translation is correctly configured on both routers.


How can I handle open ports?

Question: After  port scanning  my company's network, I found a lot of open ports. What are the risks that will result out of these ports, if I left them open? And is there any way to handle them without closing them?
Comment: Could you be slightly more specific about the ports you are talking here? The risk depends highly on this. For example is all `esp` or `IP` open? Is it just `53/udp/IP` or `80/tcp/IP` or `139/tcp/IP` which are opened?
Answer:
What are the risks that will result out of these ports, if I left
  them open?

As a security good practice, ports should be open only on a need-to-be basis.  You are exposing the services that are listening on those ports you left open to exploits. Why? Because a service means something is processing data and thus you are also exposing the vulnerabilities of the applications using those ports.
For example if you let your FTP port open to every one without any restriction rules (firewall) then a hacker could load lot of porn videos to consume lot of space of your server which thing will lead for example to very slow connection to your FTP service. Also lot of ports open expose you more to Trojan Ports.
This schema summarizes better the answer to your question:

And is there any way to handle them without closing them?

Yes, you can leave those ports open but under the condition you have to limit what is allowed to listen on them: that is the job for firewalls. For example, on port 21, allow only the IP address of your home office or home to connect to it and no one else.
You can leave them open and setting all the closed ones to stealth.
If you can change a port's number then do it. For example if you can modify the port 21 (FTP) to a higher one (3737 ?), that can lead the hacker to go away because he would start to scan common ports (20, 21 ...) and since port scan takes time, he could be impatient to wait until the scan performs over the 3737 port.
Use free services that could help you such as this free firewall and from time to time CanYouSeeMe.
Comment: Regarding canyouseeme: this only provides an "outside view". It is useful when you're interested in what your network looks like from the outside, but based on OP, I'd say he did the scan from the internal network. In that case, regular scans (with OK from the security/IT department, of course!) are a good equivalent.
Comment: What does the position, size and colour of the circles in the diagram symbolize? Or are they just arbitrary?
Answer: The biggest risk for you is that your company network security detected your portscan. It is a security attack and their countermeasures probably don't consider your wish to remain in your job seriously.
The biggest risk for the company is that a list of numerous open ports means elevated attack surface. Attacking something is a hard thing, but if there are a lot of them, earlier or later an attacker will find his way to get in.
Comment: Did you consider that OP might the the network security guy of his company? :-)
Comment: @Bergi He didn't says it explicitly, although maybe it is so. His question is imho not on the level of a professional security expert (or he wants to open a bikesched question to collect views and repu).
Comment: Good to remind the 1st risk for the author of the penetration test (legitimate to proceed or not, legitimate to break or not: some servers are so "soft" they can't withstand a `ping` or `nmap`).
Comment: May be he had authorization to do it @Bergi
Comment: @danielAzuelos Thanks. I think, a ping doesn't mean a really usable security risk, but it is highly useful in network testing. In case of nmap, it depends on the circumstances - for example, checking the ports in randomized order, through _tor_, and with a long (also randomized) delay, I don't think that a realistic firewall rule would exist to fiter this out.
Answer: Open ports are like unlocked doors. The risk depends on what you have in those rooms. If you have some money on a table, then the risk is high. If you have money in a safe, then the risk is medium. And if the safe is bolted to the wall, then the risk is low.
You can close the services behind those ports or you can use a firewall to control or block access to them. It is difficult to manage each host and service, so it is a general practice in companies to put hosts behind a firewall or NAT device. This way, they are not open to access on the internet so risk is reduced because, theoretically, only persons with internal access to the network have access to those hosts and services.
Establishing a security perimeter like this is gradually becoming an ineffective security policy. That is because the security perimeter is becoming porous. New technologies and vulnerabilities allow attackers easy and unexpected access to the internal network. A compromised mobile phone might join the network or an employee might get infected by browsing a malicious website and therefore compromise the perimeter.
As for your question of handling them, there are several ways of reducing the risk, some proactive and some reactive. Segment your network further so certain hosts are not accessible from all the other hosts. A computer in the accounting department should not be accessible without restrictions from any other computer in the company. The reactive method is to log and analyse access inside the company network. This would hopefully deter employees from accessing things that they should not and detect attacks from the outside of the company. This is not bullet proof and would not be effective in a large company.
Comment: Your metaphor lacks an important aspect: The open door is not necessarily in your home. It may also be the front door of the grocery store you're running to earn your livelihood, or its delivery entrance, or the entrance door to your neighbourhood's public library ... I guess you see what I'm aiming at.
Comment: I'll change it a bit. I also realised "open" is not a good word.
Answer: An open port as such is not a security risk. The security risk, if any, is with the service behind the port. The worst case is a port left open unintentionally, because it exposes a service that wasn't meant to be exposed and consequently might not be secured properly.
So the way to deal with the list of open ports you found is:

Check it against your list of ports that should be open, ie. the services you want to offer.
Close the ports that should not be open.
Verify that the services behind the open ports are properly secured as mandated by your security policy.

How can I handle open ports?


How could a planet with a long day-night cycle naturally regulate its temperatures to allow life?

Question: So, my planet has (around) an Earth year long day-night cycle. How could its temperatures not reach extremes that would disallow life? Assume that everything is Earth like except for multiple moons (everything can be modified, if needed).
Answer: Have a thick atmosphere with a high heat capacity.
Venus has an extremely long day length--about a third of an Earth year long--but a nearly-uniform temperature across its entire surface due to the thick atmosphere.
Give your planet a thicker atmosphere with plenty of CO2, and reduced insolation (either from a smaller star or a wider orbit) to make up for it, and you can keep temperatures across the globe uniformly in a range comfortable to Earthlike life (rather than uniformly in a range that will melt lead) over an indefinitely long nighttime period.
Water is also good for moving and retaining heat; note that coastal areas tend to have more stable temperatures than inland ones, getting both less hot and less cold than inland deserts, and northern Europe--particularly Britain--is temperate entirely because of the heat carried north on ocean currents. Equivalent latitudes in the interior of Russia and North America are frigid. So, give your world lots of ocean and little land, or at least landmasses that are broken up into small bits with plenty of ocean intrusion while leaving clear lanes for global circulation, and you will reduce the thermal load that must be born by the atmosphere.
Answer: There are only two possible solutions:

An immensely thick atmosphere. Something on the order of Venus' atmosphere, so the sheer thermal mass of the air conveys heat to the shade side, and cools the hot side.
Pro: more uniform temperatures on planetary surface.
Con:

Massive atmospheric pressure.
winds are much more powerful.
possible problems with greenhouse effect. This could make your planet as balmy as Venus(450C-ish)
If you are adapted to 100bar atmosphere, then space travel becomes a bit problematic. Your spaceship now needs to be an incredibly strong pressure vessel, thus heavy.
Just how do you plan to grow anything under all those clouds? Very little light will reach the surface! So it's artificial light all the way, including for crops.
How exactly is being on this planet better than making a Space Habitat?

Build your entire colony underground.
Pro: its a nice constant temperature down there
Con:

Air would be handy. But up on the surface, air temperature and composition fluctuates cyclically, and quite wildly. CO2 snow, anyone? So you need to have very fancy filters, or huge storage ability, or huge air reprocessing ability.
Lots of digging. Actually, this is not so bad, just takes a bit of time. You want to dig anyways, to mine minerals and metals.
Just how do you plan to grow anything under all that rock? NO light will reach the tunnels! So it's artificial light all the way, including for crops.
How exactly is being on this planet better than making a Space Habitat?


Verizon 4G broadband

Question: We have a 4G Wireless Broadband by Verizon.  It was originally set up for our office computers but we just purchased a new HP with Windows 7 and it will not recognize it.  What do I do?
Comment: What have you even tried?
Answer: You need to install the VZAccess Manager software, which includes the driver for your particular mobile broadband device.  If you do not have the CD that came with your device, you can download the software from http://www.vzam.net/download/

Verizon 4G broadband


My ISP using a transparent proxy

Question: I found that my internet service provider uses a transparent proxy on some sites and apps like Google, Whatsapp, etc. I know they use it to save bandwidth but my question here is if they are able to spy easily or not?
Comment: I would even dare to ask: do you understand what a proxy is ?
Comment: have you done any reading on the topic?
Comment: @Stephane short answer proxy methodology take your requests and give it to destination and vice versa "thank you"
Comment: Your ISP doesn't need transparent proxies for spying on you.
Answer: If HTTP is used, yes they can spy on you. If HTTPS is used, no they will not be able to spy on you. The transparent proxy is normally run on port 80 (HTTP) only, since it does not work with HTTPS.
The transparent proxy only caches content which is common to most users. e.g. logo.png, favicon.ico. Since every user is going to load the same site logo, it is a waste of bandwidth to download it from Google/Whatsapp repeatedly. Websites usually use headers to indicate that the content is "cache-able". Cache-Control: max-age=3600 indicates that the content is valid for 1 hour, hence your ISP only needs to retrieve the latest copy once every hour.
However, your personal mailbox or conversation list will never be cached. This is because it is unique to you, so there is no benefit from caching it. Hence, websites normally do not add cache headers to the response. If the website uses POST to retrieve this data, according to HTTP 1.1 RFC 2616 S. 13.10, the cache should be invalidated. If the website uses GET request, the URL is likely to be unique, e.g. http://example.com/getmessage.php?uid=123456, since every user has a different UID, it is pointless to cache such responses.
Comment: technically they could use SSL bump ... I have used it when creating squid proxy systems. If you wanted to you could spy on SSL traffic though it would be very difficult to do so without the users knowing, but not impossible.

My ISP using a transparent proxy


How do people know who sent them bitcoin, ex. in case of a ransomware targetting multiple locations?

Question: I have a rough understanding about how bitcoin works and have read about how anonymous it is, or rather how not anonymous it can be in certain situations. But I still do not get how is it possible to use bitcoin for transactions where it is important for the recipient to know who sent which amount while staying "anonymous" and not communicating with the sender. In case of a pirate expecting to receive money from more than one victim, how do they know who paid? Same question for people selling illegal stuff.

Disclaimer: I am not a pirate, nor a drug dealer. These are the first examples that came to mind.
Answer: The answer is simply that in almost all cases, the receiver does not care who paid. They care about what item/service/bill was paid, not by whom. And to do that, receivers create a new receive address for every payment they expect.
In the case of an online shop, when an order is placed, they create an address, store the address in their database together with the order information, and when that address receives the expected payment, the order is processed. It doesn't matter who paid it, or even whether that was the same person as the one who placed the order; it only matters which order was paid.
Comment: Turns out I had already missed the fact that a wallet and an address are not the same thing... thanks!


Density of Laplace image

Question: Let $D$ define the differential operator $-\frac{\partial^2}{\partial x^2}$ on $\mathbb R$.
Let $\xi\notin\mathbb R$ be a complex number.
Is it true that
$$
(D-\xi)C_c^\infty({\mathbb R})
$$
is dense in $C_c({\mathbb R})$, where the latter space has the usual locally convex inductive limit topology?
Answer: No. Consider $\mathbb RP^1= S^1$ as the 1-point compactification of $\mathbb R$. Then we have the short exact sequence (It would be nice to be able to write a diagram)
$$
C^\infty_c(\mathbb R) \to C^\infty(S^1) \to C^\infty_\infty(\mathbb RP^1)
$$
where the last space is the space of all germs at the point $\infty$.
$D-\xi$ acts on each of these spaces:
On the middle space it is elliptic of index -1, since we may move $\xi$ around without changing the index, and for $\xi=0$ the operator $D$ is elliptic, has exactly the constants in its kernel, and the image has codimension 2 (integral over $S^1$ has to vanish, so that the antiderivative is again periodic, and once more the antiderivative has to have vanishing integral). By elliptic regularity all this holds in $C^\infty(S^1) = \bigcap_k H^k(S^1)$.
On the space of germs $D-\xi$ is surjective, since we just have to find local solutions.
If $D-\xi$ would be surjective on the left space, then a diagram chase would show that also on the middle space it should be surjective which is not true.
EDIT:
The image is also not dense, because on the middle space there is a nonzero continuous linear functional vanishing on the image of $D-\xi$, because Fredholm operators have closed range. Restricted to $C^\infty_c$, it is still nonzero (since it cannot factor to the space of germs) and still vanishes on the image of $D-\xi$.
In fact, I believe that $D-\xi$ has closed range on the left hand side.
Comment: I didn't ask for surjectivity. I asked if the image be dense in $C_c({\mathbb R})$.
Comment: Ok its not dense in $C_c^\infty({\mathbb R})$ but could the image still be dense in $C_c({\mathbb R})$?
Comment: I cannot see how the operator is elliptic in the middle as the principal symbol vanishes at $\infty$?
Answer: I introduce the following notation: let $D_\xi = D-\xi$; let $\chi\colon \mathbb{R} \to \mathbb{R}$ be any smooth function such that $\chi(x) \equiv 0$, for $x<-1$, and $\chi(x) \equiv 1$, for $x>1$; also let $G_\xi$ and $G^\pm_\xi$ be the following integral operators
\begin{align}
  G_\xi[f](x) &= \int_{\mathbb{R}} \frac{\sin\sqrt{\xi}(y-x)}{\sqrt{\xi}} f(y) \, dy , \\
  G^+_\xi[f](x) &= \int_{\mathbb{R}} \Theta(x-y) \frac{\sin\sqrt{\xi}(y-x)}{\sqrt{\xi}} f(y) \, dy , \\
  G^-_\xi[f](x) &= \int_{\mathbb{R}} \Theta(y-x) \frac{\sin\sqrt{\xi}(y-x)}{\sqrt{\xi}} f(y) \, dy ,
\end{align}
where $\Theta(x)$ is the Heaviside step function equal to $1$ for $x>0$ and to $0$ for $x<0$.
Then the following is an exact sequence of vector spaces (not necessarily taking any topology into account), as evidenced by the contracting homotopy indicated with the dashed arrows:
$$\require{AMScd}
\begin{CD}
  0 \to
  C^\infty_c(\mathbb{R}) @>{D_\xi}>{\stackrel{\dashleftarrow}{{}^\chi G_\xi}}>
  C^\infty_c(\mathbb{R}) @>{G_\xi}>{\stackrel{\dashleftarrow}{D_\xi^\chi}}>
  C^\infty(\mathbb{R}) @>{D_\xi}>{\stackrel{\dashleftarrow}{G_\xi^\chi}}>
  C^\infty(\mathbb{R}) \to
  0 ,
\end{CD}
$$
where
$$
\begin{aligned}
  {}^\chi G_\xi[f] &= \chi G^-_\xi[f] + (1-\chi)G^+_\xi,
    \\
  D_\xi^\chi[g] &= D_\xi[\chi g] - \chi D_\xi[g], \\
  G_\xi^\chi[f] &= G^+_\xi[\chi f] + G^-_\xi[(1-\chi)f],
\end{aligned}
\quad \text{and} \quad
\begin{aligned}
  {}^\chi G_\xi \circ D_\xi &= \mathrm{id} , \\
  D_\xi \circ {}^\chi G_\xi + D_\xi^\chi \circ G_\xi &= \mathrm{id} , \\
  G_\xi \circ D_\xi^\chi + G_\xi^\chi \circ D_\xi &= \mathrm{id} , \\
  D_\xi \circ G_\xi^\chi &= \mathrm{id} .
\end{aligned}
$$
Once one chooses topologies, it remains to check that $G_\xi$ is a continuous map, which is not so hard with the standard topologies, so that its kernel is a closed subspace. By the exactness of the above sequence, this kernel coincides with the image of $D_\xi$. Again, following from the exactness of the above sequence, $G_\xi$ descends to an isomorphism between $\operatorname{coker} D_\xi|_{C^\infty_c}$ and $\ker D_\xi|_{C^\infty}$. Of course, everybody knows that the latter space is 2-dimensional, which shows that the image of $D_\xi$ is not dense in $C^\infty_c(\mathbb{R})$.
The above identities may appear mysterious at first, but they are easily checked if one starts with the observation that $G^\pm_\xi$ are Green functions for $D_\xi$, with particular support properties.

Density of Laplace image


Complete manifold in the Lee's book.

Question: In the completeness charpter of book "Riemannian manifold: an introduction to curvature", he constructed two examples (at page 108) of non geodesically complete manifold. 1) any proper open subset of $\mathbb{R}^n$ with standard metric is not geodesically complete, because the geodesics reach the boundary in finite time, so what happens to closed subset? I guess it is complete otherwise it violates the Hopf-Rinow theorem, but what the difference between open and closed set.  2) $\mathbb{R}^n$ with the pullback metric from $\mathbb{S}^n$ by stereographic projection, there are geodesics that escape to infinity in finite time, honestly speaking, I have no idea what it means. Could someone explain a little bit about this. Much appreciated.
Comment: I figure out first one, I forgot the Hopf Rinow theorem is for manifold without boundary.
Comment: Exactly, for the first one, just use Hopf-Rinow, a space is geodesically complete iff it's complete with the distance induced by its metric, No open subset of $\mathbb{R}^n$ is complete with the usual distance, because it's not closed, for example. If a closed subset is also bounded, then it's compact and hence complete again.
Comment: I think a bounded closed subset is not complete in geodesic sense, even though complete in distance metric sense. It doesn't violate the Hopf-Rinow theorem.
Comment: Take a look in do Carmo's "Riemannian Geometry", page 146 Theorem 2.8.
One of the equivalences to the property of being geodesically complete is item b), "every closed bounded set is compact". You have that in $\mathbb{R}^n$, exaclty those are the compact subsets in Euclidean space.
Comment: The problem is that a closed subset of $\mathbb R^n$ needs not be a Riemannian manifold. If it is the closure of a smooth open set then it will be a manifold with boundary. (Which is, I think, exactly the content of the [first comment](https://math.stackexchange.com/questions/2924657/complete-manifold-in-the-lees-book#comment6042107_2924657]))
Comment: Of course, non-manifolds and manifolds with boundary are out of the question (e.g in the $n$-ball any geodesic parametrized by arclenght starting at the origin is not extendable beyond the parameter $\pi$). Now, in this setting, any closed bounded manifold without boundary is complete by Hopf-Rinow, that's what I tried to say.
Answer: Remember that if you put a metric on $\mathbb{R}^n$ making a pullback of the metric in $\mathbb{S}^n \subset \mathbb{R}^{n+1}$ by the stereographic projection $\sigma$, then because $\sigma$ is a diffeomorphism (from $\mathbb{S}^n$ minus the North Pole to $\mathbb{R}^n$), it becomes an isometry. Now, isometries take geodesics to geodesics.
Just take a geodesic through the North Pole $N=(0,0, \dots, 0,1)$ (a great circle which is the intersection of $\mathbb{S}^n$ with a plane $P$ through the origin in $\mathbb{R}^{n+1}$ and $N$). Take the piece of it that goes from the South Pole $S=(0,0, \dots, 0,-1)$ to $N$ and parametrize it by acrlength, if you want. This geodesic goes to a straight line through the origin in $\mathbb{R}^n$, and since the one in $\mathbb{S}^n$  is parametrized by arclenght, this straight line $\gamma=\gamma(t)$ is also parametrized by arclenght and it satisfies $\lim_{t\to \pi} \gamma(t)=\infty$. Its lenght between the parameters $0$ and $\pi$ is $\infty$ in the topological sense that in time close $\pi$ it's out of every compact.
I think that's what Lee meant.

Complete manifold in the Lee's book.


ImportError and Django driving me crazy

Question: OK, I have the following directory structure (it's a django project):

-> project
--> app

and within the app folder, there is a scraper.py file which needs to reference a class defined within models.py
I'm trying to do the following:

import urllib2
import os
import sys
import time
import datetime
import re
import BeautifulSoup

sys.path.append('/home/userspace/Development/')
os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings'

from project.app.models import ClassName

and this code just isn't working.  I get an error of:

Traceback (most recent call last):
  File "scraper.py", line 14, in
    from project.app.models import ClassName
ImportError: No module named project.app.models

This code above used to work, but broke somewhere along the line and I'm extremely confused as to why I'm having problems.  On SnowLeopard using python2.5.
Answer: import sys
sys.path.append ('/path/to/the/project')
from django.core.management import setup_environ
import settings
setup_environ(settings)

from app.models import MyModel

Comment: OK, I think this worked.  I'm saying "think" because the model in question requires TineyMCE and it's barfing on an issue with that:

"ImportError: cannot import name smart_unicode"

Would it be possible to explain exactly what setup_environ(settings) does?
Comment: Having read `django\core\management\__init__.py`, I found that `setup_environ` 1. sets `os.environ['DJANGO_SETTINGS_MODULE']`; 2. imports the `project` as a module.
Comment: How do you import `smart_unicode`? Can the module with the function be found in the importing file's dir or in `sys.path`?
Comment: I figured it out.  Painful.  I had the library importing smart_unicode installed within the python2.5 system libraries AND in my project.  Once I got that resolved, everything works!

Many thanks!
Answer: Whoa whoa whoa. You should never ever have to put your project name in any of your app code. You should be able to reuse app code across multiple projects with no changes. Pinax does this really well and I highly recommend checking it out for a lot of django best practices.
The worst thing you could do here is to hard code your absolute path into your app or settings. You shouldn't do this because it will break during deployment unless you do some import local_settings hacking.
If you have to access the project root directory, try what pinax has in settings.py...
import os.path
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))

The thing is that it looks like you are trying to access the models module within the same app and this is waaay easier.
To import models.py inside scraper.py in the same directory just use import models or import models as app_models if you already have something named models in scraper.py (django.db.models for instance). Are you familiar with Python module conventions?
However, the best way is probably to stick with the django idiom, from ... import ... statement:
from app import models

If this doesn't work automatically, then something is wrong in your settings.py.
Answer: You don't indicate if project is located in /home/userspace/Development/.  I'll assume that it is.
Make sure there's an (empty by default) file named __init__.py in project and another one in app.
EDIT: Next thing to try: Fire up the Python command line in the script's directory and try the following:
import project
import project.app as app
import project.app.models as models
models.__dict__.keys()

Do they all work?  If so, what is the last line's output?  If not, which dies first?
Comment: You're correct that project is located in /home/userspace/Development and there is an empty __init__.py in both folders.
Comment: "import project" doesn't work.

ImportError: No module named "project"

it was an __init__.py (not init.py, sorry about that)

ImportError and Django driving me crazy


Wrong results joining places to create flow map

Question: I have to do a flow map (home->working place) for my area of interest (28
french cities).
I get a database .dbf created by a french institute. I imported it into
postgres/postgis.
One row = 1 people.
My table is composed by several fields :
id (primary key)
codgeo_res: residence (home) city 's id
x_resi: residence (home) city 's longitude(centroid)
y_resi : residence (home) city 's latitude(centroid)
codgeo_tr : work place city 's id
x_tr: work city 's longitude(centroid)
y_tr :work city 's latitude(centroid)
ipondi : poids de l'individu (weighting value assigned to each individual du to the sampling)
geom : residence (home) city 's ponctual geometry (centroid)

So my goal is to create a new table in order 1 row = 1 flow (city A toward
city B)
I have to generate useful  geometries (points + lines arrow). Moreover, have
to apply a SUM on the ipondi field and a GROUP BY on "codgeo_res" field.
Could you help me in order to translate this
objective to functional sql queries?
Up to now, i tried to run this query throw qgis interface called "virtual
layer creation" :
------------------------------------------------------
Code:

select
st_makeline(st_makepoint(entrants_only.x_resi,entrants_only.y_resi),st_makepoint(entrants_only.x_tr,entrants_only.y_tr))as
geometry,sum(entrants_only.ipondi) as sumipondi, entrants_only.codgeo_res as
codgeo_res, entrants.codgeo_tr as codgeo_tr

from entrants_only
group by entrants_only.codgeo_res
--------------------------------------------------------

But i get this error message :
---------------------------------------------------------
query preparation error on PRAGMA table_info(_tview): no such column
entrants_only.geom
---------------------------------------------------------

Here's a screenshot representing the error message.

The problem was due to the datatype of my XY fields (string). So I did a cast STRING to BIGINT (those fields are storing integer EPSG 2154 Lambert93).
So now, the query works. I attach a screenshot.

Indeed, the postgis temp linear layer is created.
But I have always a problem regarding the GROUP BY. I want to group by on one field only (codgeo_res), but I can't generate the query without put all
fields present in SELECT into GROUP BY!
This is my current query :
create table temp as select
st_makeline(st_makepoint(entrants_v2.x_resi,entrants_v2.y_resi),st_makepoint(entrants_v2.x_tr,entrants_v2.y_tr))as
geometry,sum(entrants_v2.ipondi) as sumipondi, entrants_v2.codgeo_res as
codgeo_res, entrants_v2.codgeo_tr as codgeo_tr

from entrants_v2
group by
entrants_v2.codgeo_res,entrants_v2.x_resi,entrants_v2.y_resi,entrants_v2.x_tr,entrants_v2.y_tr,entrants_v2.ipondi,entrants_v2.codgeo_tr

Is there a way to assign one field into group by with PostGIS?
My result is false.
Comment: Try geometry instead of geom
Answer: Try with subquery:
CREATE TABLE _temp AS
SELECT ST_MakeLine(
        ST_MakePoint(x_resi,y_resi)
        , ST_MakePoint(x_tr,y_tr)
    ) AS geometry
    , t.sumipondi
    , codgeo_res
    , codgeo_tr
FROM entrants_v2
    JOIN (SELECT codgeo_res,sum(ipondi) AS sumipondi FROM entrants_v2 GROUP BY codgeo_res) t USING(codgeo_res)


Web front-end for SQL Server Database Mail

Question: SQL Server 2005 introduced Database Mail for sending e-mail messages from the SQL Server Database Engine in a robust fashion. Database Mail comes with a number of interesting views like sysmail_allitems, sysmail_sentitems, sysmail_faileditems, sysmail_unsentitems, sysmail_mailattachments and sysmail_event_log. Is there any known stand-alone and friendly web front-end (preferably in ASP.NET) on top of these views that can be used by administrators (and ideally also users) for trouble-shooting and monitoring?
Answer: No there is not.  You can query the DMVs manually to view the data within them.  Setting up any sort of pretty interface wouldn't be of much use as you can't do anything with those DMVs besides look at them.
Database mail is a pretty robust system.
What specific issues are you trying to troubleshoot?
Comment: See my comments on Sam's answer for that kind of issues where an interface could help with some initial analysis without needing to pull up SQL Management Studio and querying views manually.
Answer: None that I know of.  What kind of users would be poking around in the back-end - what would they be doing?  Once things are set up, the mail process seems to run pretty smoothly.  Are you having frequent problems?
Comment: The idea is to enable some simple checking. For example, users may complain that they are not receiving e-mails when in actual fact the system may have dispatched them yet the junk mail filter on the client-end blocking. A front-end can enable an admin to quickly verify this.
Comment: Another case would be that the application actually has a bug and not dispatched an automated e-mail notification when it was meant to go out.
Comment: Yet another example would be to simply check on failed sends via the sysmail_faileditems view.


About Griffin's dialogue "Where there is death, there will always be death"

Question: In the ending of Men In Black 3, it depicts J's father's death as sort of replacing K's death. (as stated in Griffin's dialogue). But K also kills Borris, who didn't die in the original timeline or the altered one (where Borris kills K). So whose death is Borris replacing? And wouldn't it have been possible to save J's father instead and just have Borris die to cater for K's death?
Comment: Temporal mechanics give me a headache.
Comment: It may be argued that Young Boris' death was inconsequential as the timeline was restored by that point (deploying ArcNet and shooting off Boris' arm were conditions to that according to Griffin) and since the Old one was already dead, timeline is not affected drastically from that point. Which is totally not the case with K. It's easier if one thinks of it as two altered timelines, yet one is dependent on the outcome of the other. SO Col. Edwards dies in order to restore the K/J timeline, not the K/Boris one. Or, as Revenant wrote after Chief O'Brian: *I hate temporal mechanics*
Answer: As J's dad had died in the original timeline, young K's death in the rebooted timeline would have replaced J's dad's(meaning that J's dad was alive in the version of the timeline where Earth was invaded.  So, yay?).  By this logic, young Boris's death should have replaced both J's dad's and K's deaths.  However, because young Boris killed J's dad before K could kill him, this means that someone else's life was spared.  This is the only explanation that supports the "where there is death, there will always be death" idea.


Subview behaves strangely in navigation-based app

Question: I'm currently developing an app for iphone (my first) and I used several UITableViewController for navigation.
I then used a subview attached to self.view.superview to get a non-scroll image at the top.
The subview is created in IB, simple UIView with an UIImageView in it.
I'm adding the subview in viewDidAppear and this functions well.
But as soon as I'm tapping a cell and the navigationController pushes the next View animated, the previous view (scrolling out of sight) becomes completely white and my subview moves animated to the center. It's only for a half second or so, because then it's gone due to the next view arriving, but it's really unnerving.
I tried removing the subview in viewWillDisappear, that removes the UIImageView, but the screen still becomes completely white.
Does anybody how to fix this?
Oh, and PS: I'm working only on the Simulator, because I have no Developer Account yet. And I cannot change everything to a ViewController because I have a deadline to meet.
Answer: You shouldn't be surprised that things go wrong when you mess with the views of view controllers that don't belong to you. Rather than using a table view controller, you should replace it with a custom UIViewController whose view acts as a container view for both the table view and the non-scrolling view above it.


Solving the equation $\frac{\ln (x)}{\ln (1-x)} = \frac{1}{x} - 1$

Question: I'm trying to solve the following equation (which has solution $x = 1/2$)
$$\frac{\ln (x)}{\ln (1-x)} = \frac{1}{x} - 1 $$
I can't seem to do it analytically. Any ideas?
Comment: Sidenote: It can relatively easily be shown that this is equivalent to solving $x^x=\left(1-x\right)^{\left(1-x\right)}$ but I'm not sure if that leads anywhere.
Answer: Let $f(x)=x \ln x$. Then the given equation is
$$f(x)=f(1-x).$$
This is symmetric about $x=1/2$. Hence $x=1/2$ is a solution.
Comment: I think this is insufficient.  Proving that $x=\dfrac12$ is a solution is easy.  Proving that it is the only solution is not as easy, but I can see that one may approach it by showing that $$f(x)-f(1-x)<0\text{ for all }x\text{ such that }00\text{ for all }x\text{ such that }\frac12<x<1\,.$$
Comment: Very nice solution!
Comment: Yep, IMO too many upvotes as the existence of other solutions should be discussed.
Answer: The function $x\log x-(1-x)\log(1-x)$  is only defined in $(0,1)$, is differentiable, has a root at $x=\frac12$ (by inspection) and tends to zero at the interval endpoints.
The derivative,
$$\log x+\log(1-x)+2$$ has two roots in $(0,1)$, where $x(1-x)=e^{-2}$.
Hence the function is negative in $(0,\frac12)$, with a single minimum, and positive in $(\frac12,1)$, with a single maximum, and there are no other roots.
Answer: Let $g:I\to\mathbb{R}$, where $I:=\left[-\dfrac12,+\dfrac12\right]$, be the function defined by $$g(t):=\begin{cases}\left(\dfrac{1}{2}+t\right)\,\ln\left(\dfrac12+t\right)-\left(\dfrac{1}{2}-t\right)\,\ln\left(\dfrac12-t\right)&\text{if }t\in\left(-\dfrac12,+\dfrac12\right)\,,\\0&\text{if }t\in\left\{-\dfrac12,+\dfrac12\right\}\,.\end{cases}$$  (Observe that $g$ is continuous on the whole $I$, and is smooth on $\left(-\dfrac12,+\dfrac12\right)$.)  Then, we are to solve for $x\in(0,1)$ from $$g\left(x-\dfrac12\right)=0\,,$$
which is equivalent to solving for $y\in \left(-\dfrac12,+\dfrac12\right)$ such that
$$g(y)=0\text{ by setting }y:=x-\dfrac12\,.$$
We claim that $g$ has only three roots $-\dfrac12,0,+\dfrac12$, and this means the only $y\in\left(-\dfrac12,+\dfrac12\right)$ such that $g(y)=0$ is $y=0$, making $x=\dfrac12$ the sole solution to the required equation.  Suppose contrary that $g$ has more than three roots.  Then, by symmetry, on the interval $\left[0,\dfrac12\right]$, $g$ has at least three roots.  Using Rolle's Theorem, $g'$ has at least two roots on $\left(0,\dfrac12\right)$, and so $g''$ has at least one root on $\left(0,\dfrac12\right)$.  However, we have
$$g'(t)=\ln\left(\frac12+t\right)+\ln\left(\frac12-t\right)+2\,,$$
$$g''(t)=\frac{1}{\frac{1}{2}+t}-\frac{1}{\frac{1}{2}-t}\,,$$
and
$$g'''(t)=-\frac{1}{\left(\frac{1}{2}+t\right)^2}-\frac{1}{\left(\frac12-t\right)^2}<0$$
for all $t\in\left(0,\dfrac12\right)$, which is a contradiction we seek.


Parent Child Relationships

Question: This regarding handling parent child relationships in PowerPivot. I am facing a situation where the "PATH" dax function is giving me trouble with the set of data provided to the function.
My data set has a parent column and a column with the child ids. Roots of the hierarchies do not have a corresponding row in the child ids column. Due to this reason PowerPivot gives me the following error when the "PATH" function is applied:
"Calculation error in column 'CS_Comp'[]: The value '10' in 'CS_Comp'[ParentCol] must also exist in 'CS_Comp'[ChildCol].  Please add the missing data and try again."
Answer: can you post an example of your data? Why do you need a Parent and a ChildID. Normally you would need ID and ParentID only

Parent Child Relationships


Extracting data from ArcMap

Question: I am new to ArcMap, but I need to use it to extract data for my research work. I have shapefiles of the regions I want to work on. Now I want to extract data such as elevation, soil quality, rainfall, distance to coast, distance to capital city, etc on those regions. How can I go by it on ArcMap (version 10.5).
Comment: This is quite a broad question and is likely to be flagged for closure as such. I would recommend you visit ESRI's website and partake in some of their free tutorial lessons. Many of these will walk you through accomplishing the goals you have listed above.
Comment: Welcome to GIS SE!  We're a little different from other sites; this isn't a discussion forum but a Q&A site.  Your questions should as much as possible describe not just what you want to do, but precisely what you have tried and where you are stuck trying that.  Please check out our short [tour] which emphasizes that there should be only one question asked per question.
Answer: You need to obtain other map layers which contain the data that you seek to extract. A good place to start would be to google something like ' "myarea" shapefiles ' where myarea is the place you are looking at (i.e. Germany shapefiles, Alaska shapefiles, Madagascar Shapefiles, etc..) Once you find a data repository that has some open source layers, you can begin to view them in GIS individually to confirm that they align with your existing layers that show your area of interest. Then, you can begin to extract, consolidate, and clean the data appropriately.
Comment: Better than "myarea shapefile" that is a specific file format look for "myarea gis data" for a broader reach or even "myarea mysubject data" as non geographical data could also be used if you join it to geodata.

Extracting data from ArcMap


Colors/Lights drastically different in render (2.8 Eevee)

Question: Trying to get back into Blender after a bit of a hiatus. I am not sure what is going wrong. When I am in my rendered viewport the colors look perfect and then as soon as I go to render the animation/image the colors get blown out like crazy.
I have messed with color management settings (filmic, standard, none, etc) and they all look like garbage. If anyone has a suggestion that would be greatly appreciated.
Thanks!
Comment: Have you checked if any objects are hidden in the render? It would also help if you uploaded your blend to https://blend-exchange.giantcowfilms.com/ Just edit the given code into your question.
Answer: Try disabling "Bloom" or adjust it's settings and see if you have the same issue.


OCR Framework that can read text from images in iOS?

Question: I'm currently starting a project right. One of the requirements is to read details of a "Cheque"  .Meaning to say, the app should be able to read the account number, amount, etc of a certain "Cheque".
Answer: There is a similar question here
I tried something ago and works fine. Check the open source project called tesseract and also a demonstration here (with source code)


Is there a way to import several .txt files each becoming a separate dataframe using pandas?

Question: I have to work with 50+ .txt files each containing 2 columns and 631 rows where I have to do different operations to each (sometimes with each other) before doing data analysis. I was hoping there was a way to import each text file under a different dataframe in pandas instead of doing it individually. The code I've been using individually has been
df = pd.read_table(file_name, skiprows=1, index_col=0)
print(B)

I use index_col=0 because the first row is the x-value. I use skiprows=1 because I have to drop the title which is the first row (and file name in folder) of each .txt file. I was thinking maybe I could use glob package and importing all as a single data frame from the folder and then splitting it into different dataframes while keeping the first column as the name of each variable? Is there a feasible way to import all of these files at once under different dataframes from a folder and storing them under the first column name? All .txt files would be data frames of 2 col x 631 rows not including the first title row. All values in the columns are integers.
Thank you
Answer: Yes. If you store your file in a list named filelist (maybe using glob) you can use the following commands to read all files and store them on a dict.
dfdict = {f: pd.read_table(f,...) for f in filelist}

Then you can use each data frame with dfdict["filename.txt"].


Are there any interesting connections between Game Theory and Algebraic Topology?

Question: I've been learning game theory on my own and was just curious how it connected with previous things I've learned.  So are there any interesting connections between Game Theory and Algebraic Topology? or possibly other branches of topology?
Comment: Is there a category of games? Can I stabilize it? Let's just go ahead and stabilize it. Get to work.
Comment: I'll just point out that combinatorial game theory (one of the tags) is not the same thing as just plain game theory, and it seems that you are interested in the more general game theory. Could someone with the power to do so create a game-theory tag and apply it here?
Comment: A small nitpick: yes/no questions beg for a yes/no answer (http://homepages.tesco.net/~J.deBoynePollard/FGA/questions-with-yes-or-no-answers.html).
Answer: One example is in the concept of a Nash equilibrium, whose existence can be proved using various (topological) fixed point theorems. (Google "nash equilibrium proof" for a wide variety of examples... the main topological machinery that comes up is the Kakutani fixed point theorem or the plain-vanilla Brouwer theorem.)
Fixed point theorems come up in many other, similar settings; you see them a lot in certain kinds of mathematical economics. The overall intuition is that given a current set of known player strategies, people will generally want to change to better strategies. This defines a function on the "space of strategies". A fixed point of this function is interesting because it indicates an "equlibrium" of strategies that are in a sense optimal. Often topology is the best way to prove a fixed point exists.
Comment: For a proof of the existence of Nash equilibria using the Brouwer fixed point theorem, read Nash's thesis: http://www.princeton.edu/mudd/news/faq/topics/Non-Cooperative_Games_Nash.pdf (He also wrote a proof using the Kakutani fixed point theorem, published in a paper earlier than his thesis.)
Answer: There's a neat paper by David Gale on the connection between Brouwer's fixed point theorem and the game of Hex. The fixed point theorem is 'equivalent' to the theorem that the game cannot end in a tie.
Comment: This is really cool!
Answer: The Banach-Mazur game is an example of a game in a topological setting. There are various other games of this nature which are mostly related to foundational questions in point-set topology.
I'm afraid I can't think of a meaningful connection between game theory and algebraic topology. I think that real algebraic geometry plays a part in the study of various types of equilibria in a game-theoretic context, but that's about alll I can say about this.
Answer: Here is an article on topology and game theory:
Social choice and game theory: recent results with a topological approach
Chichilnisky, Graciela (1983): Social choice and game theory: recent results with a topological approach. Published in: Social Choice and Welfare Chap. 6 (1983): pp. 79-102.
Here is the abstract:
Abstract
This chapter presents a summary of recent results obtained in game and social choice theories, and highlights the application and the development of tools in algebraic topology. The purpose is expository: no attempt is made to provide complete proofs, for which references are given, nor to review the previous work in this area, which covers a significant subset of the economic literature. The aim is to provide an oriented guide to recent results, through economic examples with geometric interpretations, and to indicate possible fruitful avenues of research.
It is available here:
http://mpra.ub.uni-muenchen.de/8059/1/MPRA_paper_8059.pdf
Answer: Game theory makes me think of economics, so here's a paper you might be interested in:

Weinberger, Shmuel.  On the
  topological social choice model. J.
  Econom. Theory 115 (2004), no. 2,
  377--384. 91B14 (55P20 55Q05 57N60) MR2044787.

This paper looks at social choice (aggregating the desires of many people into a single outcome) from a topological perspective.
Comment: See also Eckmann, Beno, *Social choice and topology: a case of pure and applied mathematics*,
Expo. Math. 22 (2004), no. 4, 385–393.
Answer: In the theory of refinements of the Nash equilibrium concepts, people have looked at the topological structure of the Nash correspondence (the map from games to the set of equilibra). The seminal paper is by Kohlberg and Mertens in Econometrica 1986. They also introduced a refinement, stable sets. The theory of stable sets has been further developed, often using ideas and concepts from algebraic topology.
There is work by Jean-Jacques Herings on computation of Nash equilibria using homotopy methods.
In evolutionary game theory, one often studies complex dynamical systems and these sometimes give rise to problems where algebraic topology is useful. Stefano Demichelis did some work related to this.
Comment: The following papers by Metrens propose homological definitions for "stable equilibria":  Mertens, Jean-François Stable equilibria---a reformulation. I. Definition and basic properties. Math. Oper. Res. 14 (1989), 575--625; Stable equilibria---a reformulation. II. Discussion of the definition, and further results, Math. Oper. Res. 16 (1991), no. 4, 694--753.
Answer: Borel Determinacy and more modern improvements link game theory to topology, but more along the measure theory vein than algebraic topology
Answer: In combinatorial game theory (more specifically, the theory of impartial games), the set of winning options of a winning option is the empty set, which reminds me of the fact that the boundary of the boundary of a manifold-with-boundary is empty.
Also, when one takes a disjunctive sum of two impartial games $G$ and $H$, an option of $G+H$ is of the form $G'+H$ or $G+H'$, where $G'$ is an option of $G$ and $H'$ is an option of $H$.  This reminds me of the definition of a derivation: $D(fg) = (Df)g + f(Dg)$.  The two examples of derivations that come to mind are differentiation of functions and, as above, the boundary operation $\partial$ applied to manifolds-with-boundary: the boundary of $M_1 \times M_2$ is $\partial M_1 \times M_2 \cup M_1 \times \partial M_2$.
I have no idea whether there's an way to cash in on this formal resemblance.
Answer: I'm coming from the other side: familiar with game theory and learning about algebraic topology.

I know Kakutani's fixed point theorem was used to simplify Nash's seminal paper.
If you think about a simple normal-form game like Prisoner's Dilemma or Coordination Game,  (source: Wayback Machine)

the arrows between the payoff matrix are governed by $>_A$ and $>_B$ meaning the ordering of payoffs by players A and B. I know topological spaces aren't necessarily orderable, but this seems topological in flavour since distance doesn't matter. (Whether you lose £3 or get your head chopped off, I don't care as long as it doesn't affect me.) I think of this as like a "topological gravity" creating the Nash equilibria.
Answer: I haven't read the paper, and am not competent to judge its worth or novelty, but
math.AG/0301001 might be of interest here.
Answer: Sperner's Lemma comes to mind. It can be used to prove various results about fair division (being strongly related to the Brouwer Fixed Point Theorem). Ideas from homology can be used to simplify proofs of its generalized form. See Francis Su's papers (http://www.math.hmc.edu/~su/papers.html).
Answer: You may also want to see http://arxiv.org/abs/1005.2405
Flows and Decompositions of Games: Harmonic and Potential Games
Authors: Ozan Candogan, Ishai Menache, Asuman Ozdaglar, Pablo A. Parrilo
Abstract: In this paper we introduce a novel flow representation for finite games in strategic form. This representation allows us to develop a canonical direct sum decomposition of an arbitrary game into three components, which we refer to as the potential, harmonic and nonstrategic components. We analyze natural classes of games that are induced by this decomposition, and in particular, focus on games with no harmonic component and games with no potential component. We show that the first class corresponds to the well-known potential games. We refer to the second class of games as harmonic games, and study the structural and equilibrium properties of this new class of games. Intuitively, the potential component of a game describes the possibility of agreement and coordination between players, while the harmonic part represents the conflicts between their interests. We make this intuition precise, by studying the properties of these two classes, and show that indeed they have quite distinct and remarkable characteristics. For instance, while finite potential games always have pure Nash equilibria, harmonic games generically never do. Moreover, we show that the nonstrategic component does not affect the equilibria of a game, but plays a fundamental role in their efficiency properties, thus decoupling the location of equilibria and their payoff-related properties. Exploiting the properties of the decomposition framework, we obtain explicit expressions for the projections of games onto the subspaces of potential and harmonic games. This enables an extension of the properties of potential and harmonic games to 'nearby' games. We exemplify this point by showing that the set of approximate equilibria of an arbitrary game can be characterized through the equilibria of its projection onto the set of potential games.
Comment: The paper by Candogan et al. as well as Jiang, Xiaoye, et al. "Statistical ranking and combinatorial Hodge theory." arXiv preprint arXiv:0811.1067 (2008) do provide a beautiful application of algebraic topology to game theory. The idea is that of representing a game as a 1-dimensional simplicial complex and performing a discrete Hodge decomposition. Both papers use an Euclidean inner product to implicitly identify chains spaces and cochains spaces, so there is room for polishing and generalisation.


Trigger Windows Service when the new record insert in to DB

Question:
Possible Duplicate:
Change Notification with Sql Server 2008

Am just wondering is there's anyway i can write a windows service in C# that will be trigger when the new record get inserted into Database.
And i would like to connect DB thru wcf also. Please give any ideas or suggestion.
Thanks in Advance.
Based on demo.b Instruction,here is the code.
SQL Database Details

My Database Name : MyWeb,Table Name : StoryItems,
Columns: Location,Headline,Name,Genre.

<code> public partial class Triggers
{
    // Enter existing table or view for the target and uncomment the attribute line
    [Microsoft.SqlServer.Server.SqlTrigger(Name = "Trigger_Web", Target = "StoryItems", Event = "FOR INSERT")]
    public static void Trigger_Web()
    {

    SqlCommand command;
    SqlTriggerContext triggerContext = SqlContext.TriggerContext;
    SqlPipe pipe = SqlContext.Pipe;
    SqlDataReader reader;

    if (triggerContext.TriggerAction == TriggerAction.Insert)
    {
        using (SqlConnection connection = new SqlConnection(@"context connection=true"))
        {
            connection.Open();
            command = new SqlCommand(@"SELECT * FROM StoryItems", connection);
            reader = command.ExecuteReader();
            reader.Read();

            // get inserted value
            // ***********Here am trying to retrieve the location and name column value
            Location= (string)reader[9];
            Name= (String) reader[9];
            reader.Close();
            try
            {
                // try to pass parameter to windows service

                WindowsService param = new WindowService(InsertedValue1, InsertedValue2);
            }
            catch (Exception ex)
            {

            }

        // Replace with your own code
        SqlContext.Pipe.Send("Trigger FIRED");
      }
    }
}
}
</code>
Some how it doesn't like column name, am not sure what am missing here."Trigger_Web" is my CLR SP name.
Answer: First you need to create a trigger application in visual studios.
File --> new --> project --> Database --> select Visual C# CLR database project.
It will prompt you to connect to a database. Once done, ensure your trigger application listen to record insertion on any table you like (you can read more about CLR app in visual studios here).
from steps in link above, add a trigger. your method should look like this:
<code>[Microsoft.SqlServer.Server.SqlTrigger(Name = "GetTransaction", Target = "EvnLog", Event = "FOR INSERT")]
public static void GetTransaction()
{
    SqlCommand command;
    SqlTriggerContext triggerContext = SqlContext.TriggerContext;
    SqlPipe pipe = SqlContext.Pipe;
    SqlDataReader reader;

    if (triggerContext.TriggerAction == TriggerAction.Insert)
    {
        using (SqlConnection connection = new SqlConnection(@"context connection=true"))
        {
            connection.Open();
            command = new SqlCommand(@"SELECT * FROM INSERTED", connection);
            reader = command.ExecuteReader();
            reader.Read();
            // get inserted value
            InsertedValue1 = (DateTime)reader[0];
            InsertedValue2 = (string)reader[9];
            reader.Close();
            try
            {
                // try to pass parameter to windows service

                WindowsService param = new WindowService(InsertedValue1,InsertedValue2)
            }
            catch (Exception ex)
            {

            }

        }
</code>
Note: GetTransaction is the name of the trigger you want to create, in this case Evnlog is the name of the table
Comment: I appreciate what you've shown is an example (which pretty much solves the problem), but... I imagine if you're only getting one value then it should be `SELECT TOP 1 *` otherwise the SQL Server may continue to spool results. And `reader` should be `.Dispose`'d, not just `.Close`'d.
Comment: it doesn't matter where ur windows service is running from. it could be on the same server as the sql server or on a remote server. if it's on the same box, in visual studios, right click on trigger project, select properties. Under database settings, change permission level to "Save". if it is a remote box, you will set to "unsafe' or "External".  Once you are done developing the trigger application, you will need to deploy to database by right clicking and selecting deploy. deployment requires some privillages on database.
Comment: before you deploy to database, please read this to prepare database http://geekswithblogs.net/rasyadi/archive/2005/11/18/60459.aspx. To anser the other question, you need vs 2008/2010 and sql server 2005/2008
Comment: Thanks a lot demo.b,what's gonna happen my windows service is running on remote location or my sql server running on remote location.In that case,WCF or any service is the only option to communicate and trigger,please correct me if am wrong.
Comment: Quite Interesting warning i got when i try to create a new project "Note: If you do not have the .Net Framework Version 3.5 Installed on your development computer,you must install it if you want to develop SQL CLR assemblies for sql server 2005 or Sql Server 2008 support only those assemblies that target the 2.0,3.0 or 3.5 version of the .Net Framework. You specify the .Net Framework version in the Project properties. Press F1 for more info."
Comment: Thanks again demo.b, pretty much followed your instruction and so far going good,i have couple of queries.  1)@"SELECT * FROM INSERTED", what is this query does ? or Inserted is suppose to be my table name ? 2) InsertedValue1 = (DateTime)reader[0];
                   InsertedValue2 = (string)reader[9];
 I believe InsertedValue1 and InsertedValue2 suppose to be my Column Name,please correct me.
Comment: [Microsoft.SqlServer.Server.SqlTrigger(Name = "GetTransaction", Target = "EvnLog", Event = "FOR INSERT")]   "Name" is the method i created so you can give it any name. "Target" is the tablename in my example "EvnLog" is the tablename. "Event" is for the type of response the trigger is listening to, in the example insert.
Comment: The query @"SELECT * FROM INSERTED", selects newly inserted rows from the EvnLog table. In my example each row contains about 10 columns so only select the one i need. (DateTime)reader[0] gets the value in first column (which is a date) and (DateTime)reader[9] gets the value in column 10.
Answer: Use something like an Extended Stored Procedure in SQL server, that calls your C# class/executable, which then can execute the service.
You can also call command line functions from the triggers on the on_insert event on the table, which can start/stop a service, or run an exe or batch file.
Some ideas:
http://www.sqlservercentral.com/Forums/Topic960855-392-1.aspx
And
http://msdn.microsoft.com/en-us/library/ms189799.aspx


Speculative hand with a lot of draws

Question: Say you are playing 7♥ 8♥ in position and call a min raise pre.
Flop comes up Q♥ 7⋄ 6♣
On the flop villain bets 1/2 the pot.  How do you play it out?
Both deep stacked.
Answer: I think implied odds are the main focus of this hand, at least some of the time the pre-flop raiser is c-betting with absolutely nothing so there is immediate odds. Calling the half pot bet on the flop is something I would do most of the time depending on the player. Even if the pre-flop raiser has a hand like top pair or a pocket pair, there is a pretty good chance my hand will improve, so calling the flop would pay off in the long run. I would avoid calling something like this if there is a lot of action on the flop and the flop is multi-way, if that is the case then the chances of having the best hand are very slim.
Comment: What makes you believe you are not getting immediate odds to call here?
Comment: I would be, but if not there is good implied odds as well. Could be clearer i will edit
Answer: I will not accept my own answer.  I was curios about running the numbers.

Pre
I am good with calling with a speculative hand like this.  Would actually like more players in the pot.

Flop
Bottom pair is better than nothing but not great.  Back door straight and flush draws.  Villain could be on any ace, two overs, and 22-TT.  JJ+ probably would have raised more pre.  Even if you put 7 in his range the worse case scenario 99-22, A2s+, K7s+,Q7s+, J7s+, T9s, A2o+,K7o+, Q7o+, J7o+ you are 65:35.  I was surprised it was that high.  It kind of makes this a less interesting question.  Over 1/2 the time you are ahead here and with so many ways to improve almost don't mind if villain has pair of queens to get paid off.  5 immediate outs.  And 23 outs to fill in the back door draws.  Pretty clear call.  I don't see raise here.

Turn
Even if I don't improve on the turn I would call up to 1/2 pot.
If like the 9 hearts came up to give both draws I think I would raise back a pot to either take it down or build a pot.

River
If I miss and they bet 1/2 pot again on the river I think I need to let it go.  If I hit 2 pr I think I just call.  Trips or better then raise like the pot again.

Speculative hand with a lot of draws