Exchange 2003 missing default SMTP connector, but still routing through smarthost

Question: I have an Exchange 2003 server currently using MXLogic as a smarthost, relaying all outbound mail through it. I confirmed this by sending mail outside the domain and checking the headers.
I need to modify the smarthost I'm using, but I can't find these settings anywhere! The only SMTP connector visible to me is one for the *.yahoo.com address space, and it uses DNS to route mail, not MXLogic.
This is the only Exchange server in the organization.
Where did my SMTP connector go? How does mail leave this server if there's no SMTP connector matching the address space of the recipient?

I can't find any instance of 'mxlogic' in the system registry, or within files on disk besides the Exchange MDBs
No MXLogic or other Symantec software is installed on the server
I restarted all Exchange services.
Answer: Exchange Server 2003 doesn't automatically create or use an SMTP Connector. All mail flow is handled by the default SMTP Virtual Server component (listed under the Protocols node under your server in ESM). An SMTP Connector (as shown in your screen shot) is created and configured manually by the administrator when you need to define/apply specific conditions/restrictions for email. An SMTP Connector is only created automatically by Exchange when you have more than one Exchange server in your Exchange Organization.
In your case, all email is sent out via the default SMTP Virtual Server component of your server, but it's acted upon differently based on whether it matches the condition of your SMTP Connector. If you had more than one Exchange server in your Exchange Organization it would be easier to understand the purpose and use of SMTP Connectors, as you could have email matching a certain condition of the SMTP Connector being handled by a different Exchange server (via it's SMTP Virtual Server).
Here's a very good article on the subject:
http://www.msexchange.org/tutorials/configuring-smtp-connector.html
The concept of Routing Groups, SMTP Connectors and Routing Group Connectors is more intuitive if you have multiple Exchange servers in the Exchange organization. With only a single server it can get a little confusing as to what these components are for and how they work.
Comment: Thanks for the excellent reply, Joe. I feel silly for having missed that one- I forgot that it's possible to set a smarthost per-server. The exact place I needed to look was **Default SMTP Server properties>Delivery tab>Advanced** to find the Smart host field. Thank you!
Comment: Glad to help...


Select usando Enum

Question: Tenho um formulario onde um dos campos é um select, e esse select é um enum, eu consigo popular ele mas não consigo enviar o valor, sempre vai com valor 0 quando faço o post.
Eu queria um select com duas opçoes
HTML:
<form class="mat-dialog-content" (ngSubmit)="(submit)" #formControl="ngForm">

    <mat-form-field color="accent">
      <textarea matInput #input class="form-control" placeholder="Nome" [(ngModel)]="data.name" name="name" required></textarea>
      <mat-error *ngIf="formControl.invalid">{{ getErrorMessage() }}
      </mat-error>
    </mat-form-field>

    <mat-form-field>
      <mat-select matNativeControl required>
        <mat-option *ngFor="let item of (editoriaTipo | keys)" [value]="item.key" [(ngModel)]="data.type">{{ item.value }}</mat-option>
      </mat-select>
    </mat-form-field>

    <button mat-button [type]="submit" [disabled]="!formControl.valid" [mat-dialog-close]="1" (click)="confirmAdd()">
        Savar
      </button>
    <button mat-button (click)="onNoClick()" tabindex="-1">Cancelar</button>

</form>

Service:
  addEditorias(editorias: Editorias): void {
    this.httpClient.post(this.API_URL_Ed, editorias).subscribe(
      data => {
        this.dialogData = editorias;
        // this.editoriaService.showToaster("Successfully added", 3000);
      },
      (err: HttpErrorResponse) => {
        // this.editoriaService.showToaster(
        //   "Error occurred. Details: " + err.name + " " + err.message,
        //   8000
        // );
      }
    );
  }

Enum:
export enum EditoriaType {
  programa = 1,
  editoria = 2,
}

Objeto:
import { EditoriaType } from "../enum/editoria-type";

export interface Editorias {
  id: number;
  name: string;
  type: EditoriaType;
  dataDeCriacao: Date;
  dataDeAtualizacao: Date;
  deletado: boolean;
}

Ele tbm dá o erro:
EditoriaCriarComponent.html:68 ERROR Error: If ngModel is used within a form tag, either the name attribute must be set or the form
      control must be defined as 'standalone' in ngModelOptions.
Sempre cadastra assim com o tipo 0, mesmo eu escolhendo:
{
name: "1",
type: 0,
id: "950a1854-a66d-43cd-0bef-08d671c5dec9",
}

Answer: Olá,
você pode tentar utilizar dessa forma:
  ...

  listaEditoria = EditoriaType;
  keys:any;

  constructor(){
    this.keys = Object.keys( this.listaEditoria ).filter(Number)
    console.log( 'KEys', this.keys )
  }

e no select:
<mat-option *ngFor="let key of keys" [value]="key" >
   {{listaEditoria[ key ]}}
</mat-option>

Espero que isso ajude...

Select usando Enum


Continuity of a function and its restriction

Question: Let $(X,T)$ be a topological space and $A$ subset in $X$, and
$f:X\to (Y,t)$ a function.
If $A$ is open and $g:A\to Y$ is continuous (where $g$ is the restriction of $f$ on $A$) , then so is $f$.
Can someone prove it for me?
Comment: You could edit your question to state it correctly. What did you try, did you apply the definitions of continuity, and of subspace topology? Did you try to clarify to yourself what the question is asking?
Comment: Sure, and the stack-exchange community is very happy to help, but that part works a lot better if you give it a go first yourself, that's why @Mirko is asking.
Comment: As indicated in a now deleted comment, the statement is incorrect. You need to assume continuity on $X$ and prove continuity of the restriction on $A$, not the other way around. Also $g$ being a restriction of $f$ should in general go into $Y$, not into $X$. You did not specify, but $A\subseteq X$. Welcome to MSE! Usually you need to show more details of you attempted, to show understanding of the question and help people come up with a useful answer that would help your case.
Comment: Theorem. Every function $f:X\to Y$ is continuous. Proof. Let $A$ be the empty set $\emptyset$. Then the restriction $g:A\to Y$ is continuous. By @sarafkh question, $f$ is also continuous. QED
Comment: Welcome to MSE. Please use [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) to typeset math on this site.
Comment: it is clear (but you should state it in the question), and not difficult to prove. Do you use definition of continuity in terms of preimages of open sets being open? Then you use intersection of two open sets is open, and union of arbitrary many open (preimages) is open.
Comment: Your last comment is terse and unclear to me. Please edit your question, listing clearly what you assume,what you want answered, and what you have attempted, all in one place (not in comments) and preferably using mathjax. From your comments it also looks like you are asking different questions: These should be posted separately,each clearly stated. I almost posted an answer to the version where $A_i$ cover $X$, but I will not post it,as you seem to change the question repeatedly. If $A\subset X$ and $A\neq X$ then there is no such thing as $Id:X\to A$. If $y\in X\setminus A$ what is $Id(y)$?
Comment: The proposition with just one set $A$ is wrong. If the $A_i$ cover $X$ then the proposition is correct.
Comment: can someone write  the set of

 1. natural numbers
 2. rational
 3. irrational
 4. real
using union of intervals?
Answer: So the data is: $(X, \mathcal{T})$ is a space, $f: (X,\mathcal{T}) \to (Y,\mathcal{T}')$ is a function to another space, $A\subseteq X$. You assume further that $A$ is open and $g=f \restriction A$ is continuous, and you want to show $f$ is continuous? This is clearly false: take as a trivial example $X=\{0,1\}$ with the Sierpinski topology, $Y=\{0,1\}$ in the discrete topology, $f=\text{id}$, which is not continuous even though $f\restriction A$ is continuous and open for $A=\{0\}$.
So you probably mean something else?
Comment: read the comments and the several edits to the problem, to get a clarification that it is not clear at all what is meant
Comment: @sarafkh You should ask clearer questions. It should be intuitively clear that assiming something on the restricted map does not give much info on the original unless maybe $A$ is somehow "big" in $X$, say (although in this trivial example $A$ is also dense)
Comment: @sarafkh What exactly is "*that*"
Comment: though the OP erased their comments, so too late now ...
Answer: Under the additional assumption, stated in the comments (by the OP and later deleted), that $X=\cup\{A_i:i\in I\}$ (for some index set $I$) where each $A_i$ is open and each restriction $f:A_i\to Y$ is continuous, then indeed $f:X\to Y$ is continuous$.
Take any open $U\subset Y$ we need to show that $f^{-1}(U)$ is open in $X$. Each $A_i\cap U$ is open, and hence, by continuity of $f$, we have that $f^{-1}(A_i\cap U)$ is open.
Finally $f^{-1}(U)=\cup\{f^{-1}(A_i\cap U):i\in I\}$ is open, as the union of open sets.
Regarding the question as originally stated:
Let $X$ be a topological space and $A$ subset in $X$, and $f:X\to Y$ a function. If $A$ is open and $g:A\to Y$ is continuous (where $g$ is the restriction of $f$ on $A$), then so is $f$. Can someone prove it for me?
The above statement cannot be proved as it is incorrect. If it were correct, then it would imply that all functions between all topological spaces are continuous. Indeed, let $A$ be the empty set $\emptyset$. Then the restriction $g:A\to Y$ is continuous. If the above statement were correct, Then $f$ would also be continuous.
For a specific example, let $X=[0,1]$, $A=[0,1)$ and $Y=\Bbb R$ (or $Y=[0,1]$, or $Y=\{0,1\}$, either way). Let $f(x)=0$ for $x\in A$, and $f(1)=1$. Then $f$ is not continuous (since $\lim\limits_{x\to1^-}f(x)=0\neq1=f(1)$), even if the restriction of $f$ to $A$ is constant (and hence continuous).
For an even better/intuitive understanding take the following point of view.
Start with $X,Y,A$ and continuous $g:A\to Y$. Then extend $g$ on all of $X$, arbitrarily, to obtain some function $f:X\to Y$. There are (in general) zillions of ways to obtain such extensions, and very few of them (under some special/additional conditions) would be continuous. Most of the time such an extension would be discontinuous. (@HennoBrandsma was also alluding to this, in a comment to his answer, I would believe.)
Comment: You need to also remark that $f^{-1}[U \cap A_i]$ is open in $A_i$ by the assumption and the fact that $A_i$ is open too implies the set is open in $X$ as well. An essential point to make IMO.
Comment: @HennoBrandsma thank you making that point for me. I didn't have to make it since you would :)
Comment: @sarafkh What is "*it*" that might or might not be true?


Evaluating the product containing the reciprocals of all primes $\prod_{k=1}^\infty\left(1+\frac{(-1)^k}{p_k}\right)$

Question: How to compute the following product:
$$\prod_{k=1}^\infty\left(1+\frac{(-1)^k}{p_k}\right)=\left(1-\frac{1}{2}\right)\left(1+\frac{1}{3}\right)\left(1-\frac{1}{5}\right)\left(1+\frac{1}{7}\right)\dots$$
where $p_k$ is the $k^\text{th}$ prime number?
My Observation, but NOT SURE:
Using $k=1$ to $k=18$, the product is almost $0.578282825\dots$ and that value is
$$\frac{\frac{\pi}{5}+\frac{\pi}{6}}{2}=\frac{11\pi}{60}\approx0.575958653\dots$$

So, is the product really tends to $\frac{11\pi}{60}$?

Any help/hint will be appreciated. THANKS!
Comment: This product doesn't have a closed-form because alternating the sign depending on the parity of the index of the prime doesn't have any arithmetical meaning (in particular in term of $\zeta(s)$ and other L-functions)
Comment: Why would you think this product has a closed form?
Comment: If you take the logarithm of the product, you get a sum of logarithms, which satisfies the hypotheses of the alternating series test.  Therefore [the product of the first 30 terms](https://www.wolframalpha.com/input/?i=product+(1%2B(-1)%5Ek%2Fprime(k))+for+k%3D1+to+30)  exceeds the final answer, but this is $.575671$ already comfortably less than ${11\pi\over60}$
Comment: Have a look at https://www.wolframalpha.com/input/?i=product+(1%2B(-1)%5Ek%2Fprime(k))+for+k%3D1+to100
Answer: Just to give a few numbers.
Let us consider the partial products
$$P_n=\prod _{k=1}^{10^n} \left(1+\frac{(-1)^k}{p_k}\right)$$ Computed exactly, here are the results (in decimal values)
$$\left(
\begin{array}{cc}
 n & P_n \\
 1 & 0.5849897151924156997471733 \\
 2 & 0.5738797348557373537954953 \\
 3 & 0.5733032174061992771374417 \\
 4 & 0.5732660657801225326295239 \\
 5 & 0.5732633085315702175401998 \\
 6 & 0.5732630922693932644226413
\end{array}
\right)$$


JS (No Jquery) - Change CSS when scrolled to a set point

Question: Sorry, but I am a complete noob with JS. I am using Bootstrap to try build my first website.
The website has a fixed top navbar. I want to change the navbar's border-bottom properties when it reaches the bottom of the header div (about 480/500px down the page).
Currently the border-bottom is white, but I want to change it to blue when scrolled beyond a certain point (bottom of header) and then change back to white if scrolled back up again. The effect I want is the appearance of the fixed nav 'picking up' the bottom border of the banner section when it scroll's past.
I have given the navbar div an id of id="n1", and created a class .navbar1{border-bottom: 1px solid rgba(46,152,255,1)!Important;} to add to override the existing css.
I am not using jQuery because I don't use much JS and I don't want to call it just for a few things - it is a big file. I have tried various things without any success. Probably because they relied on jQuery? I don't know. For example, the last one was:
$(window).scroll( function(){
    if($(window).scrollTop() > 50) $("n1").addClass("navbar1");
    else $("n1").removeClass("navbar1");
});

Anyway, I was hoping someone may be able to help me with the plain/pure JS to change the attribute properties as described. Thank you in advance for any assistance.
EDIT:
This has been kindly answered below. But given some comments, I thought it might be useful to clarify my use of JS: My website requires very little JS functionality so I have chosen to inline my JS, rather than call an external JS file or files - such as jquery.js and bootstrap.js which are relatively large files.
Although I lose the benefit of caching the JS, and my HTML is slightly larger, I am happy to do that because in my case I feel those losses are more than made up for the increased initial page load speed from:

not having to make additional http requests,
not having to load relatively large files.

It is certainly not for everyone, but I feel that it suits my case. Having said that, when all is done and my website is up and running I will probably do some testing to see whether a custom external JS file is better again. Basically, I am only using Bootstrap for its CSS functionality, not its JS functionality. I hope that makes sense.
Comment: @NaveenNiraula No it's not impossible, the OP wants pure JavaScript. I think people forget that jQuery **IS A PLUGIN BUILT ON JAVASCRIPT**
Comment: @NaveenNiraula, what do you think jQuery is, Magic?
Comment: the code in your example uses jquery, bootstrap plugins/components require jquery.
Comment: In a few words: you want to add a class to an element with bare JavaScript?
Comment: But surely bootstrap depends on jQuery anyway?
Comment: You are using bootstrap which requires jQuery! to do what you asked s impossible without jQuery!
Comment: "bootstrap depends on jQuery " is not always true. there is still a possibility that the OP is using https://github.com/tagawa/bootstrap-without-jquery
Comment: well maybe using jquery is better cuz its optimized for crosss browsers!
Answer: This demo may help you!
It doesn't use jQuery.
Here is the javascript code:
window.onscroll = function() {
    var nav = document.getElementById('nav');
    if ( window.pageYOffset > 100 ) {
        nav.classList.add("navbar1");
    } else {
        nav.classList.remove("navbar1");
    }
}

Comment: to add to this. Its better to use `nav.classList.add('navbar1')` and `nav.classList.remove('navbar1')` if the navbar already has classes.
Comment: This worked a treat. Thank you, people, you are awesome!  If anyone is replicating using my ID "n1", note that you need to change "nav" in the answer to "n1".
Answer: I did a small change on @radonirina-maminiaina amazing answer.
While it works, I do prefer avoiding doing unnecessary DOM calls during the onScroll event. The onScroll event can be triggered quite often on some devices, so it's best to keep its handler as fast as possible.
In my solution, I cache the nav DOM element on a closure and I only update its classes if the offset changes.
window.onscroll = function () {
  let isScrolled = false
  const scrollPoint = 100
  const nav = document.getElementById('navbar')

  function onScroll () {
    if ( window.pageYOffset > scrollPoint && !isScrolled ) {
      nav.classList.add("scroll");
      isScrolled = true
    } else if (window.pageYOffset <= scrollPoint && isScrolled) {
      nav.classList.remove("scroll");
      isScrolled = false
    }
  }

  onScroll()  // Makes sure that the class is attached on the first render
  return onScroll
}()


If $\int_{1}^{\infty} |f(t)|^{2}\,dt < \infty$, is $\int_{1}^{\infty} \frac{|f(t)|}{\sqrt{t}}\,dt < \infty$?

Question:
If $\int_{1}^{\infty} |f(t)|^{2}\,dt < \infty$, is $\int_{1}^{\infty} \frac{|f(t)|}{\sqrt{t}}\,dt < \infty$?
If Yes, give a proof. If no, give a counterexample.

I try to use Holder inequality to prove, but I couldn't prove and also I couldn't find counterexample.
Anyone can help me?
Comment: For ease of writing assume $f \geq 0$. What you would want to have happen is that $1/\sqrt{t}$ would be $L^2$ so you could use Cauchy-Schwarz, but it isn't, which suggests that $f$ should be "close" to $1/\sqrt{t}$ but decaying a little bit faster so that it is still $L^2$. Some tinkering with $x^{-p}$ for $p$ close to $1/2$  quickly fails. The usual trick is to then reach for logs to get something that decays just slightly faster, and this turns out to work as Clayton has showed.
Comment: Thank you for your explanation! I didn't think of logs. Thanks!
Comment: I'm unfamiliar with writing here, but thank you, Cameron Williams for editing and making others understand clearly!
Comment: I should rephrase a little bit: to prove the $\int f(t)/\sqrt{t} dt$ *converges* you would want to have $1/\sqrt{t}$ be $L^2$, but it isn't, which suggests that probably the integral doesn't have to converge if $f$ is just an arbitrary $L^2$ function. Generally to make integrals of products big you want to make the two factors close, so *for a counterexample* you want $f$ something in $L^2$ that is close to $1/\sqrt{t}$. You find that $t^{-p}$ doesn't help you, to make it $L^2$ you need $p>1/2$ which causes convergence. So you reach for logs to get just a little bit more decay and it works.
Answer: The statement is false. Take $$f(t)=\frac{1}{\sqrt{t}\log(1+ t)}.$$ Then $$\int_1^\infty|f(t)|^2\,dt=\int_1^\infty\frac{1}{t\log^2(1+t)}<\infty$$ while we have on the other hand $$\int_1^\infty \frac{|f(t)|}{\sqrt{t}}\,dt=\int_1^\infty\frac{1}{t\log(1+t)}\,dt=\infty.$$
Comment: Thanks!  It's the counterexample I was looking for!!!


In angularjs, show ng-message if email already exists based on boolean return from server.

Question: During registeration, when form submitted through ajax call and the response from the server is of boolean format.. how to handle the boolean value from the server to show ng-message indicating email already registered.. tried ng-show didn't work...
Comment: show us what have you tried
Comment: include more details of the issue and also some code so you can get quality answers, and to avoid removal of your post
Answer: Can you please provided the code snippet which you are trying? angular should automatically trigger the update if defined properly. Can provide you answer once I see the code..


TIMESTAMP function is updating when I open the Google Sheet to check the file

Question: I use a Google Excel file that I distribute to the store managers of a retail company with branches every month.
The Google Excel file has two locked sheets inside. The first is called "START" and the second "MASTER".
START & MASTER sheets
On the START sheet it has a button which when pressed creates a copy of the MASTER.
This sheet also, from the script it runs, renames it to DD/MM.
New Duplicated MASTER renamed
The user, who will use it, renames it to today's date that he created it and will use it.
Renamed to today's day
The MASTER file has a series of tasks in column D which through a drop-down list makes the selection (column D). Once he selects then, column E shows the date and time he made the selection.
Selection Col. D - Time-Date Col.E
When I open this file, it is updated to today's time & date, thus altering the real time.
[TIMESTAMP SAMPLE](https://docs.google.com/spreadsheets/d/1TUYrIkc6C2LYbEPvNzz_oa3rQMsJBJafOMCKu0e2SIg/edit?usp=sharing)

The script I run for TIMESTAMP is:
// This is from your showing script.
function TIMESTAMP() {
var today = new Date();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var date = today.getDate() + '/' + (today.getMonth() + 1) + '/' + today.getFullYear();
var dateTime = time + '-' + date;
var timestamp_format = "dd-MM";
return dateTime;
}

Which returns me HH:MM:SS – DD/MM/YYYY.
The script here that worked more correctly from Tanaike and I don't even need to add the formula "=IF(D4<>"";TIMESTAMP();"")" inside the cell:
// This is from your showing script.
function TIMESTAMP() {
var today = new Date();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var date = today.getDate() + '/' + (today.getMonth() + 1) + '/' + today.getFullYear();
var dateTime = time + '-' + date;
var timestamp_format = "dd-MM";
return dateTime;
}

function onEdit(e) {
const sheetName = "Sheet 1test"; // Please set your sheet name.

const { range } = e;
const sheet = range.getSheet();
if (sheet.getSheetName() != sheetName || range.columnStart != 4 || range.rowStart == 1) return;
range.offset(0, 1).setValue(TIMESTAMP());
}

Which has a problem, in order for it to work, I have to set it to the name of the sheet inside the script.
I also tried the below variation in the script here from TheMaster:
const sheetName=new Intl.DateTimeFormat('en-GB',{day:'2-digit',month:'2-digit'}).format(new Date())
But it only works for one date. If I add another day it doesn't work.
Is there a way to make it work automatically for all days (ie 01-30/31)?
Also, is it possible for the date it shows me to be in DD/MM format only without the year (ie HH:MM:DD - DD/MM) without the year with leading zeros for the time and for the date?
Comment: It looks like you included code from somewhere else. If you're using someone else's work without giving them credit, that constitutes plagiarism, which is not welcome on Stack Exchange. To fix it, [edit] to make sure you do **ALL** the following: 1.Include a [link](/editing-help#links) to the source, 2. Mention the author's name, and 3. [Quote](/editing-help#simple-blockquotes) the copied content. For more details, see [referencing help](/help/referencing) and [this FAQ](https://meta.stackexchange.com/q/160077/343832).
Comment: `. If I add another day it doesn't work.` How did you add another date?
Comment: Although I'm not sure whether I could correctly understand your actual expected result, I proposed an answer. Please confirm it. If I misunderstood your question and that was not useful, I apologize.
Answer: In your situation, how about giving the exclude sheet names? When I saw your provided Spreadsheet, I guessed that you might not want to run onEdit to only the sheets of "START" and "MASTER". If my understanding is correct, how about the following modification?
Modified script:
// This is from your showing script.
function TIMESTAMP() {
  var today = new Date();
  var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
  var date = today.getDate() + '/' + (today.getMonth() + 1) + '/' + today.getFullYear();
  var dateTime = time + '-' + date;
  var timestamp_format = "dd-MM";
  return dateTime;
}

function onEdit(e) {
  const excludeSheetNames = ["START", "MASTER"]; // Please set exclude sheet names.

  const { range } = e;
  const sheet = range.getSheet();
  if (excludeSheetNames.includes(sheet.getSheetName()) || range.columnStart != 4 || range.rowStart == 1) return;
  range.offset(0, 1).setValue(TIMESTAMP());
}

In this modified script, the script range.offset(0, 1).setValue(TIMESTAMP()); is run except for the sheets of excludeSheetNames.

Note:

By the way, when I saw your provided Spreadsheet, there are 2 onEdit functions in your Google Apps Script project. In this case, I'm worried that the script might not be correctly run. So, please remove onEdit except for the above sample script. And, test the script.

And, in your column "E", the formula like =IF(D3<>"";TIMESTAMP();"") is still existing. So, for example, when column "D" of "MASTER" is edited, the formula returns a value while onEdit is not run. Please be careful about this.
Comment: The formula works fine! Many thanks!! The only thing that remains is how to add the leading zero for hours, minutes, and seconds and the date needs to be only DD/MM without the year. Also, the other onEdit you saw in the App Script is for the checkbox in Column B that returns the start time in Column C which stopped working! How do I fix that?
Comment: @dek Thank you for replying. I'm glad your issue was resolved. About your new 2 questions of `The only thing that remains is how to add the leading zero for hours, minutes, and seconds and the date needs to be only DD/MM without the year.` and `Also, the other onEdit you saw in the App Script is for the checkbox in Column B that returns the start time in Column C which stopped working! How do I fix that?`, I would like to support you. But, I apologize for my poor English skill. Unfortunately, I cannot understand your new 2 questions.
Comment: @dek About 1st question of your new 2 questions, what actual value do you want to retrieve? About the 2nd question of your new 2 questions, I cannot understand what you want to do. I apologize for my poor English skill. In this case, can you post it as a new question? By this, it will help users think of a solution. If you can cooperate to resolve your new questions, I'm glad. Can you cooperate to do it?
Comment: Your English is fine probably mine is not. For the 1st question: I want to retrieve the time (hh:mm:ss) and the date 20/10 (DD/MM), not the year. For the 2nd question in the Excel sheet column B, rows 5-7 there is a tick box when ticked, time and date are retrieved in rows 5-7 column C. Check the examples in column F rows 3 & 4
Comment: @dek Thank you for replying. I apologize for my poor English skill. Unfortunately, from your reply, I cannot still understand your new 2 questions. But, I would like to support you. So, in this case, can you post it as a new question by including more information? By this, it will help users including me think of a solution. If you can cooperate to resolve your new questions, I'm glad. Can you cooperate to do it?
Comment: https://stackoverflow.com/questions/77334880/google-sheet-timestamp-script-format-time-with-milliseconds-date-with-day-and


confused about dangers of lock(this)

Question: I wanted to understand dangers of lock(this) with some code example. With the code, if everything works well I expect to see 1000 at the end of program.
And that's what I get every time I run it even though I am using lock(this). Why lock(this) works well here?
class Program
    {
        static void Main(string[] args)
        {
            Test t = new Test();
            for (int x = 0; x < 100; x++)
            {
                Thread[] threads = new Thread[10];
                for (int i = 0; i < 10; i++)
                {
                    threads[i] = new Thread(t.ProtectedMethod);
                    threads[i].Start();
                }

                for (int i = 0; i < 10; i++)
                    threads[i].Join();

                Console.WriteLine("Done with {0}", t.i);
            }

        }
    }

    class Test
    {
        public int i = 0;

        public void ProtectedMethod()
        {
            lock (this)
            {
                i++;
            }
        }
    }

Comment: What are the dangers you had in mind?
Comment: @tia I had seen that question also but it seem different. Based on that answer, I should have gotten different results than what I am currently getting in code example above.
Answer: The lock on this prevents multiple threads to enter the lock code block for the object at the same time. While one thread is in the code block, the other threads are waiting until the current lock on 'this' object is released.
Comment: How this will be different if in the Test class I have a local private object and use that for lock in place of lock this?
Comment: Locking on this is bad practice because you dont know if anyone locks the same object somewhere else
Comment: Making a private object is unique for that particular code block and cannot be affected by code outside your class
Comment: Can you add any example with lock(this) will not produce desired results?
Answer: It runs okay because example is too simple. It's equivalent to the case when you lock on some private variable. I say that it will even run fine if you wrap for loop with lock (t) since lock supports recursion.
But imagine if other thread had locked on your variable and entered some infinite loop? Just after you created variable? A deadlock would occur.
Now let's imagine you provide your code with lock (this) as 3rd party dll. You never know how smart will be the consumer of your library...

confused about dangers of lock(this)


Transform data to have specific mean, minimum and maximum?

Question: I have found this in regards to transforming to specific mean and maximum, but I need to specify a minimum as well. Is there a way to do so?
I believe it will be a more complicated solution similar to what's proposed here, but I haven't found in this second link a solution to what I need.
Thanks in advance!
Comment: Out of curiosity, what application requires you to both standardize to a different mean and normalize to a specific range?
Answer: There are many different transformations that could work for this (probably infinite), but here is a fairly simple one that works for the median instead of the mean (thanks @Glen_b for catching the mistake):

Subtract the current median from all data points (now the median will be 0).
Divide all the positive values by the current max, then multiply them by the difference between the desired max and the desired median.
Divide all the negative values by the absolute value of the current min, then multiply them by the difference between the desired median and the desired min.
Add the desired median to all points.

Now the data will have the desired min, max, and median.
If the ratio of the differences between the extremes and the mean and the desired extremes are close then this will be close as well, otherwise some additional shifting will be needed.
Another approach for the mean (that keeps the order of the points):

Subtract the minimum value from all values and divide all the new values by the new max (now the values will all be between 0 and 1).
Raise all the values to the same power ($x^p$), finding the correct value of $p$ will be the tricky part, but you could use trial and error or an optimization or root finding function.
Multiply by the difference between the desired max and min, then add the min.

The dataset will need to have at least 3 unique values for this (or anything that retains the order) to work.
Edit
Here is some example R code that uses the second option (tested this time to make sure that it works):
<code>scaleMMM <- function(x, min.target=-1, max.target=1, mean.target=0,
                     p.range=c(0.01,10)) {
  tmpfun <- function(p) {
    x2 <- x-min(x)
    x2 <- x2/max(x2)
    x2 <- x2^p
    x2 <- x2*(max.target-min.target) + min.target
    x2
  }

  p <- uniroot(function(p){mean(tmpfun(p))-mean.target}, p.range)$root

  out <- tmpfun(p)
  attr(out, 'p') <- p
  out
}

x1 <- rexp(25)
summary(x1)
x2 <- scaleMMM(x1)
summary(x2)

plot(x1,x2)
</code>
Comment: I don't think this works. Try observations 0,0,3 and rescale to have desired stats of min -1, max 1 and mean 0. The min and max will be correct but the mean is not 0. The problem is that when you take the divide step the mean is no longer 0.
Comment: I think your original linear-rescaling of positive and negative deviations approach could work, with a small modification
Comment: @Glen_b, oops, you are correct (this would work with the median instead of the mean.  A couple more steps will be needed.  Of course, with only 3 data points, just set one to the min, one to the max, and the last to whatever value will give the correct mean.
Comment: @Glen_b, any thoughts on what you would suggest for the modification?  I have thought of a few, but some of them could change the ordering in the data, which may or may not be an issue.
Comment: I don't think we have to change the order; see my answer that builds on yours. I'll have to come back to it later
Answer: This explains how to get Greg's original idea for rescaling positive and negative parts each in a linear way to give the desired outcome.
Let $P = (P_1,P_2,...,P_n)'$, and $N = (N_1,N_2,...,N_m)'$,
where the elements of $P$ and $N$ are all non-negative.
Let $\bar{P}$ and $\bar{N}$ be the mean of the vectors $P$ and $N$
respectively
Consider a set of data with both positive and negative elements (as might be obtained by mean-correcting or median-correcting an existing set of data), where $X=(-N,P)'$.
Now let $Y = (-aN,bP)+c$ for $a,b>0$.
Then $\min(Y)=-aN_{(m)}+c$, $\max(Y)=bP_{(n)}+c$ and $\bar{Y}=(nb\bar{P}-ma\bar{N})/(m+n)+c$.
To obtain a desired min, max and mean for $Y$, simply solve the above three (linear) equations for $a,b,c$
If $\min(Y)=l,\max(Y)=u$ and $\bar{Y}=d$ then we solve
\begin{eqnarray}
-aN_{(m)} + c &=& l\\
bP_{n}+c &=&u\\
(nb\bar{P}-ma\bar{N})/(m+n)+c&=&d
\end{eqnarray}
for $a,b,c$.
Let $v = (a,b,c)'$ and let $z=(l,u,d)'$. In matrix form we are trying to solve:
$$Av = z$$
where
$$A=
    \begin{bmatrix}
    -N_{(m)} & 0 & 1 \\
    0 & P_{(n)} & 1 \\
    -\frac{m}{m+n}\bar{N} & \frac{n}{m+n}\bar{P} & 1 \\
    \end{bmatrix}\,.
$$
with a few more lines of algebra we could write an explicit solution, but I'll have to come back to that later. As it is, this is straightforward to implement as is in many programs, since solving linear systems is easy, it would be a simple matter to write a few lines of code to get the scale factors $a,b$ and $c$.


Allow node author to assign edit rights for other users

Question: Use case: user X creates a node and wants to give user Y the ability to edit the node as well. Think page administrators on Facebook. An Entity Reference field can be used to allow the node author to associate other users with the node, but how to provide edit rights for selected users?
A simple and common use case is a business directory website where Employee X creates a listing for Company Y and wants to allow Employee Z to edit the listing as well. There are several similar solutions out there but I've not been able to find a specific module or recipe for this common use case. Any ideas?
Answer: As is usually the case, "there's a "module for that": Node access user reference meets the requirements for this use case by allowing node authors to select other users from a user reference or entity reference field and assign view, update or delete rights to the referenced users. Hope this is useful for anyone else who runs into this issue.


"Content Type Edit/Add" gives Whitescreen, no errors loged, what to do?

Question: I am running a Drupal Commerce Kickstart 1 on top of it (D7)site on localhost/xampp (1.7.7).
Now:
When I go to Content Type (/admin/structure/type), and click Edit on a given   type or New Content Type, i get the white screen or a server 500 error.
I can access manage fields and manage display on the same page.
When I go to drupal error logs, there is no trace of the error.
Neither can I find a trace of the problem in /opt/lampp/log/error_log.
Tried to increase allowef script time / php memory limit in php.ini - no result.
The site works without problems on a remote testing server, and has been  working without problems for a long time locally. So most probably it's local configuration, but I am not sure what to do.
Maybe some of you have an idea about what can I do?
Comment: PHP Fatal Error should be logging to syslog. Have you checked there?
Comment: when I do 'tail /opt/lampp/log/error_log' just after generating this error, I get '[Wed Mar 13 18:31:00 2013] [error] [client 127.0.0.1] PHP Fatal error:  require_once() [function.require]: Failed opening required '/opt/lampp/htdocs/woo/profiles/commerce_kickstart/modules/rules/includes/rules.core.inc' (include_path='.:/opt/lampp/lib/php') in /opt/lampp/htdocs/woo/includes/bootstrap.inc on line 3066' - that is, only one such error from more then an hour ago (during which i retried it many times with cache clearing, php memory etc).
Comment: Is the rules.core.inc file missing? If it is present, does the web server have permission to read and execute?
Comment: In fact, everything is OK with that file. It's just an error message form another drupal install on the same xampp, in which i tried to replicate the install that was (and still is) working on the remote server. The error reappered, and I tried to move the modules to standard location /sites/all/modules, so at fires the system failed to find the file. Still, there is no trace of any error anor 500 message (which were plenty
Comment: 'dmesg |grip PHP' gives an empty list. I'm not using an lampp installed from ubuntu repositories, but a tar.gz extracted to /opt/lampp/. Maybe that version has some pecularities, I'll try the Ubuntu one.
Comment: go to _/admin/config/development/logging_ and make sure your error logging is set for 'All Messages'. And the next time you get the WSOD, 'View Page Source' to see if you are getting anything, or if it is a true blank screen.
Answer: OK, resolved. Thanks for your help,  Triskelion - thanks to you, I understand  xampp better.
There were two things
1) xampp giving no error messages. After looking in vain for error messages, I upgraded to xampp 1.8.0, and when I tried to get to the page that caused problems, I got a full error message.
<code> Additional uncaught exception thrown while handling exception.Original ODOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT * FROM {system} WHERE type = 'theme' OR (type = 'module' AND status = 1) ORDER BY weight ASC, name ASC; Array ( ) in system_list() (line 165 of /opt/lampp/htdocs/twotrees/includes/module.inc). Additional
PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT ff.* FROM {filter_format} ff WHERE (status = :db_condition_placeholder_0) ORDER BY weight ASC; Array ( [:db_condition_placeholder_0] => 1 ) in filter_formats() (line 409 of /opt/lampp/htdocs/twotrees/modules/filter/filter.module).
Uncaught exception thrown in session handler.
PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away in _drupal_session_write() (line 209 of /opt/lampp/htdocs/twotrees/includes/session.inc).
</code>
Still, no messages in error_log. Where should I look for them?
2) I searched through the web, and found similar problems for example [http://drupal.org/node/1542432]. It turned out this is a XAMPP mysql memomry limit problem. I changed the value 'max_allowed_packet' to 100M in 'my.cnf'.
My site works now. I was really scared!


Construction of natural numbers in ZF/ZFC without class predicates.

Question: I'm told by some websites that it's possible to formally construct the naturals in ZF without recourse to either predicates involving classes ("all inductive sets", yuck) or some sort of "intuitive number system" provided outside of the logic.
The basic idea using the Von Neumann ordinal construction is to do get an inductive set (ie. $0\in N_{+} \wedge \forall x:x\in N_{+} \rightarrow (\lbrace x \rbrace \cup x) \in N_{+}:$), via $Infinity$, and then to pick out just $N$ from it  using $Specification$ with the predicate restriction $\forall x: (x=0 \vee \exists r:x=(\lbrace r \rbrace \cup r):) \wedge \forall y:y\in x \rightarrow (y=0 \vee \exists r:y=(\lbrace r \rbrace \cup r) \wedge  y \in x:):$
It "makes sense" to me - in my head where the numbers already are I can resort to induction and see that those are exactly the ordinals, and they're all in $N_+$. But, I can't seem to make the proof work with just the objects I already have (the ZF axioms).   It seems clear that it requires $Regularity$, but I can't find a proof online or in any of my books.
Can someone point me to one or provide a rough proof sketch?
Answer: The standard route goes something like this:
Let $A$ be the inductive set that the Axiom of Infinity guarantees us. Then using Separation let
$$ \omega=\{n\in A\mid \forall x: x\text{ is inductive} \to n\in x \}$$
One can then easily prove that $\omega$ is inductive and is a subset of every inductive set.
In particular an inductive subset of $\omega$ must be $\omega$ itself, so we have a set of naturals that satisfies the usual second-order induction axiom.
Is this definition what you denounce as "predicates involving classes"? If the unrestricted quantification on $x$ offends you (which it shouldn't) you can replace it by $\forall x\in\mathcal P(A)$. You then need to do slightly more footwork if you still want to prove that $\omega$ is a subset of an arbitrary inductive set $B$, but that's not hard: By definition $\omega$ is a subset of every inductive subset of $A$, and then we can prove that $A\cap B$ is inductive, so $\omega\subseteq A\cap B\subseteq B$).

It looks to me like your your predicate does pick out exactly the naturals once you have an $A$ that contains all of them, assuming Regularity is true (otherwise there are counterexample models). However, you'll need to prove that induction works on the $\mathbb N$ you get. In order to apply Regularity to show this, the natural strategy would be to assume that there's an inductive $B\subsetneq \mathbb N$ and let $x\in\mathbb N\setminus B$ and construct the set $$\bar B=\{x, f(x), f(f(x)), f(f(f(x)),\ldots\}$$ where $f$ is the predecessor function (and this set would then contradict Regularity).
However, constructing $\bar B$ requires Replacement applied to the functional relation $n\mapsto f^n(x)$, with a domain that needs to behave sufficiently much like $\omega$ that we must already have constructed a workable $\omega$ somehow. For example, it would seem that we need to be able to use induction on the domain in order to argue that $\bar B$ and $B$ are disjoint.
The outcome of this is that it is formally possible to go the way you sketch, but it looks like you would have encountered the naturals (or something very much like them) anyway along the way, and the rest of the exercise is then more or less a detour.
Answer: One can indeed avoid the "Axiom of Infinity" to define the notion of a natural number. One predicate that is satisfied precisely by (von Neumann) natural numbers is $\eta$ defined as follows:
\begin{align*}
    \eta(x) :=
        & (x=\emptyset \vee \exists y(x=S(y))) \\
        & \wedge \forall z(z\in x \rightarrow (z=\emptyset \vee \exists w(w\in x \wedge z=S(w)))) \\
        & \wedge \forall u((u\subset x\wedge u\neq\emptyset)\rightarrow \exists v(v\in u\wedge v\cap u=\emptyset))
\end{align*}
here:

$a\subset b:= \forall p(p\in a\rightarrow p\in b)$
$a\neq b:=\neg(a=b)$
$S(x):=x\cup\{x\}$.

This predicate is essentially the same as the one suggested in the question of the OP. The last (added) clause says that the "Axiom of Foundation" holds for subsets of $x$. One may choose to require it to hold for all sets, which is naturally a stronger hypothesis.
One easily shows that:

$\eta(\emptyset)$ holds.
$\eta(x)\rightarrow\eta(S(x))$ holds.

Suppose $\kappa$ is some predicate for sets such that:

$\kappa(\emptyset)$ holds.
$\kappa(x)\rightarrow\kappa(S(x))$ holds.

For example, $\kappa(x)$ could be the predicate that says that $x$ is a finite ordinal.
Claim: $\forall x(\eta(x)\rightarrow\kappa(x))$
This shows that $\eta(x)$ is another way of stating that $x$ is a finite ordinal. The following proof shows that $\eta$ provides a way to "pick out" natural numbers without having already proved all their properties. We also do not need to have constructed the set of all naturals.
To prove the claim, we assume $\eta(x)$ and try to prove that $\kappa(x)$ holds. Since $\kappa(\emptyset)$ holds, we also assume $x\neq\emptyset$.
We examine the set $z=\{y\in x:\neg\kappa(y)\}$.
Since $x\neq\emptyset$ the first clause of $\eta(x)$ says that $x=S(y)$; which also means $y\in x$. Thus, if we show that the set $z$ is empty, then $y\in x$ and $\neg(y\in z)$. This means that $\kappa(y)$ holds. Hence, $\kappa(x)=\kappa(S(y))$ holds.
Note that $\neg(\emptyset\in z)$ since $\kappa(\emptyset)$ holds.
If $z\neq\emptyset$, then by the last clause in $\eta(x)$ (or by the "Axiom of Foundation"), there is an element $v\in z$ such that $v\cap z=\emptyset$. Since $v\in z$, we have $v\neq\emptyset$ and $v\in x$. By the second clause in $\eta(x)$ we see that $v=S(u)$ for some $u\in x$. Now, $u\in v$ so $\neg(u\in z)$. Thus, $\kappa(u)$ holds, which means $\kappa(v)=\kappa(S(u))$ also holds which contradicts $v\in z$. The source of this contradiction is our assumption that $z\neq\emptyset$. Thus, we see that $z=\emptyset$.


Find tangent from other two trig ratios

Question: I understand the six trig ratios, and know that tangent= opposite/adjacent. I feel like, on a website, I've seen people use either cosine/sine or sine/cosine (can't remember which) to find the tangent.
Is one of these two (cos/sin or sin/cos) valid/does it work?
Comment: Have you read the [MathWorld](http://mathworld.wolfram.com/Tangent.html) or [Wikipedia](http://en.wikipedia.org/wiki/Trigonometric_functions#Sine.2C_cosine_and_tangent) articles?
Comment: I looked, but I don't think i found what I was looking for.
Comment: $\tan(x)=\frac{\sin x}{\cos x}$ and you can deduce it from your "six trigo ratios"!
Answer: The definition of tangent
$$\tan{x} = \frac{\sin{x}}{\cos{x}}$$
is what they are referring to.
Similarly, the other trigonometric ratios are defined as follows
$$\cot{x} = \frac{\cos{x}}{\sin{x}} \\ \sec{x} = \frac{1}{\cos{x}} \\ \csc{x} = \frac{1}{\sin{x}}$$
Comment: I thought so - I was not quite sure as to if it was correct.
Comment: Also $\cot x = \frac{\cos x}{\sin x}$
Comment: True, true. Haha.

Find tangent from other two trig ratios


Computational instability when computing covariance in `glm` or `optim`

Question: When we estimate parameters with the maximum likelihood method, then we can estimate the standard error with the Hessian.
The code below tries to estimate this for the case of the question: How to compute the standard error of the variable $- \frac{\hat{\beta}_0}{\hat{\beta}_1}$ of a logistic regression? I did this, because I wanted to try to use optim to get a direct estimate of the variable $\hat\beta_0/\hat\beta_1$ by using a re-parameterized function.

Problem: For the same model, optim does not give the same output as with the use of glm.
Question: What is the numerical instability that causes optim and glm to have a discrepancy? Are they both wrong, or is one better? Aren't both just different methods to optimize the same cost function and aren't they supposed to give the same result?

Note: When I use different data then both estimates of the covariance are the same. So it doesn't seem to be a mistake with a factor, like using deviance instead of likelihood.
set.seed(1)
y = c(FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, FALSE, TRUE, TRUE, FALSE, TRUE, TRUE, FALSE, FALSE, FALSE)
x = c(175, 175, 175, 175, 189, 189, 189, 189, 210, 210, 210, 210, 221, 221, 221, 221, 235, 235, 235, 235, 247, 247, 247, 247, 275, 275, 275, 275, 278, 278, 278, 278, 288, 288, 288, 288, 317, 317, 317, 317, 329, 329, 329, 329, 348, 348, 348, 348, 362, 362, 362, 362, 375, 375, 375, 375, 387, 387, 387, 387, 403, 403, 403, 403, 412, 412, 412, 412, 431, 431, 431, 431, 445, 445, 445, 445, 451, 451, 451, 451, 462, 462, 462, 462, 472, 472, 472, 472, 485, 485, 485, 485, 497, 497, 497, 497, 503, 503, 503, 503, 512, 512, 512, 512, 525, 525, 525, 525, 535, 535, 535, 535, 547, 547, 547, 547, 556, 556, 556, 556, 578, 578, 578, 578, 593, 593, 593, 593, 601, 601, 601, 601, 614, 614, 614, 614, 628, 628, 628, 628, 650, 650, 650, 650)

##### if I use this data instead it works
# x = rnorm(100)
# y = rbinom(100, 1, plogis(-x))

### modeling with glm
mod_glm = glm(y ~ x, data = data, family = binomial())

### modeling with optim
logL = function(par) {
  a = par[1]
  b = par[2]
  p = 1/(1+exp(-a-b*x))
  -sum(dbinom(y,1,p, log = TRUE))
}

opt = optim(c(-16,0.02),logL, hessian = TRUE, control = list(abstol = 10^-10))

### the same estimates

mod_glm$coefficients
#  (Intercept)            x
#  -16.35496868   0.02650619
opt$par
#   [1] -16.35551219   0.02650727

### different covariance estimates
solve(opt$hessian)
#              [,1]          [,2]
#  [1,] 23.22243513 -4.012676e-02
#  [2,] -0.04012676  6.970628e-05
vcov(mod_glm)
#              (Intercept)             x
#  (Intercept)  16.1995378 -2.764790e-02
#  x            -0.0276479  4.754875e-05

Below is an image of the data. There are only a few cases of $y = 1$. Also the $x$ variable has a large scale.
Answer: The function optim estimates the gradient using a finite difference approximation method. This can cause small deviations from the true gradient.
Using parameters parscale and ndeps we can change the stepsizes used in the approximation of the gradient. When we use
opt = optim(c(-16,0.02),logL, hessian = TRUE,
            control = list(parscale = c(16,0.03), ndeps = c(10^-6,10^-6)))

then the estimate of the variance is similar to the case when we use glm
solve(opt$hessian)
#              [,1]          [,2]
#  [1,] 16.20523400 -2.765783e-02
#  [2,] -0.02765783  4.756605e-05
vcov(mod_glm)
#              (Intercept)             x
#  (Intercept)  16.1995378 -2.764790e-02
#  x            -0.0276479  4.754875e-05


How to stretch column from nav-bar to bottom of window?

Question: I'm trying to stretch a column from the bottom of the nav bar to the bottom of the window.
But I'm running into 2 undesirable situations.

Column only takes up as much space as elements inside it

Column stretches entire height of window but covers up part of the nav bar

CSS
@media (min-width: 768px){
#left {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    width: 25%;
    overflow-y: scroll;
}

#right {
    position: absolute;
    top: 0;
    bottom: 0;
    right: 0;
    width: 75%;
}

}
View/Users/Show

                <%= render 'lists/form' %>
                <% @lists.each do |list| %>
                    <%= content_tag :li  do %>
                            <a href="#list-<%=list.id %>" data-toggle="tab"><%= list.name %>
                    <% end %>
                <% end %>

Views/Layouts/Application.html.erb

        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
          Toggle navigation

        </button>
        <% if current_user %>
          <%= link_to "App Name", @user, class: 'navbar-brand' %>
        <% else %>
          <%= link_to "App Name", root_path, class: 'navbar-brand' %>
        <% end %>

  <% end %>

    <%= yield %>

Bootstrap and ruby on rails are being used.
I'm new to web design. Would be amazing if someone can point me in the right direction?
Answer: Try this css (jsfiddle example here):
html, body, .container, .row, .tabbable{height:100%}
#left {
    position: relative;
    top: 0;
    bottom: 0;
    left: 0;
    width: 25%;
    overflow-y: scroll;
    height: calc(100% - 20px);
}

#right {
    position: relative;
    top: 0;
    bottom: 0;
    right: 0;
    width: 100%;
    height: 20px;
}

, where #right div should come before #left div.
And if you want to position them absolute,
 html, body, .container, .row, .tabbable{height:100%}
    #left {
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        width: 25%;
        overflow-y: scroll;
        height: calc(100% - 20px);
        margin-top:20px;//height of #right
    }

    #right {
        position: absolute;
        top: 0;
        bottom: 0;
        right: 0;
        width: 100%;
        height: 20px;
    }

, and it's not important in which order the html divs come.


Testing an LSTM making predictions 1 timestep into the future

Question: Say I have a time series data set of 100 sequential timesteps, and I want to train and test an LSTM on the data set, but only on forecasting a single timestep into the future.
I want more than one prediction to evaluate the model's performance, so instead of using the first 99 data points for training and just the 100th one for testing, I will instead take the first, say, 80 data points as the training set and then test the model's performance on the final 20.
To do so, can I train on the first 80 alone, and then pass in the first 81, and use the 81st prediction as the first of my test set, then use the first 82 as input, and record the test prediction, and repeat this 20 times until I have the final prediction for the 100th data point, where I can then evaluate the accuracy on these final 20 unseen data points.
Otherwise, by the nature of how an LSTM works, can I train on the first 80 data points, and then pass in the full length 100 sequence and use the predictions at timesteps 81 - 100 as the test set predictions? In other words, with this method, is each prediction at every timestep a single timestep prediction based on all input data points up to this timestep? Or would the 100th timestep be more like a forecast 20 timepoints into the future?
Answer: My understanding is that your test and training sets should be completely separate if you want an accurate evaluation of performance.
If you train on the first 80 time points, they shouldn't be used as inputs when testing the next 20.
That is, the inputs for your testing should not have been used as inputs during training.


highly sporadic validation error during training with multilayer perceptron

Question: I'm encountering an issue where a classifier I'm developing reports validation errors during training that span a wide range of values without consistently decreasing over time. Unfortunately, I'm new to ML and related topics and can't seem to diagnose the problem as a result.
The base code of the classifier comes from the theano deep_learning tutorials, specifically from the multilayer perceptron tutorial: link
I have changed the code from the tutorial in two ways:
(1) Altered the data being used
(2) Altered the topography of the MLP to account for a different number of input and output nodes
Here is an image of typical results:
The data I'm using comes from a wine quality experiment: link
I would appreciate help understanding:
(1) Why this is happening
(2) How I should go about fixing it
Thanks
Answer: The amount of wiggle in your loss is related to the size of your batch.
If you compute the loss over a larger batch size you should see a smoothened loss function. This means that if your validation loss was calculated on a larger batchsize, you won't see the sporadicity that you observe.
Here is an excerpt from Stanford's CNN course notes

The amount of "wiggle" in the loss is related to the batch size. When
  the batch size is 1, the wiggle will be relatively high. When the
  batch size is the full dataset, the wiggle will be minimal because
  every gradient update should be improving the loss function
  monotonically (unless the learning rate is set too high).

You can also check out this link which gives some more insight on training loss:
http://cs231n.github.io/neural-networks-3/
Answer: I was having the same issue due to lack of centering of column features, once I did that my validation error smoothed out.
Comment: Could you please elaborate more on this ?
Answer: The issue I was having was that my learning rate was too high. I reduced it from .01 to .001 and that seems to have fixed the issue.
Answer: As mentioned in another answer, lowering the learning rate until the validation error stabilizes has worked for me. Also normalizing/standardizing input data (e.g. using sci-kit preprocessing) prior to running the model should help too!


ImportError: No module named pyflakes

Question: This error occurred when I typed "vim FILENAME.py" in iTerm.
My screen looked like this every time I tried to add make .py
Screen shot:
https://www.dropbox.com/s/tadtiqqwc80vou6/%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%202014-11-03%20%E4%B8%8B%E5%8D%884.08.21.png?dl=0
I've tried to type "git submodule init && git submodule update" in pyflakes-vim but it did't work.
Can anybody help me?
Thanks in advance!
*I'm using python 2.7
Comment: It means what you think it means; the pyflakes module is not installed.
Answer: Run pip install pyflakes to install pyflakes first.

ImportError: No module named pyflakes


não consigo logar no Magento 1.9.2

Question: Estou com um problema na pagina de login do Admin, insiro os dados para conectar e nada acontece, não sou redirecionado, não aparece nenhum erro e os dados nem são verificados. Estava funcionando perfeitamente,mas hoje o mySQL não "startava" e precisei restaurar a pasta data, o que achei estranho pois não havia alterado nada, a unica coisa diferente que fiz foi instalar o WinHTTrack.
Answer: Você restaurou a pasta data do mysql? Então provavelmente perdeu os dados (espero que tenha um backup). Sobre o não iniciar do mysql (que foi o que desencadeou o problema) ao invés de sair deletando as coisas olhe no log, mas é preciso habilitar o log primeiro (How can I start and check my MySQL log?), acesse a sua pasta ./bin (supondo que seja windows) pelo cmd, algo como:
cd C:\wwamp\mysql\bin

Se tiver backup da pasta ./data restaure ele neste momento

Depois digite mysql no input do cmd e aperte Enter. Então execute isto:
mysql> SET GLOBAL general_log = 'ON';

Se falhar tente editar o arquivo my.conf aonde fica algo como:
# The MySQL server
[mysqld]
port        = 3306
socket      = /.tmp/mysql.sock
skip-external-locking
key_buffer_size = 16K
max_allowed_packet = 1M
table_open_cache = 4
sort_buffer_size = 64K
read_buffer_size = 256K
read_rnd_buffer_size = 256K
net_buffer_length = 2K
thread_stack = 128K
sync_binlog = 0

E adicione isto:
general_log = 1

Verifique no gerenciador de tarefas se tem algum processo do mysql, finalize todos eles (ou reiniciei o Windows).
Após isto será gerado um arquivo de log na pasta ./data chamado mysql.log, confira a causa do problema que havia afetado inicialização do mysql.
Comment: Sim, faço backup antes de qualquer alteração e agora esta tudo ok, mas muito obrigado por usa resposta, com certeza já saberei onde procurar caso ocorra novamente.
Answer: Existem alguns fatores que influenciam no login do admin, o mais comum é o caminho do cookie no banco está incorreto.
Verificar:
UPDATE core_config_data set value "www.seudominio.com.br" where path = 'web/cookie/cookie_domain';

não consigo logar no Magento 1.9.2


Distance between two random vectors

Question: I have two random vectors,
$A$ and $B$ with each consisting of $n$ geographical co-ordinates $(x_1,y_1),(x_2,y_2)\dots (x_n,y_n)$ and $(\tilde{x}_1,\tilde{y}_1),(\tilde{x}_2,\tilde{y}_2)\dots (\tilde{x}_n,\tilde{y}_n)$, respectively. Suppose we have a given distribution; let $p_1,p_2,\dots,p_n$ be the probabilities associated with points in $A$ and $\tilde{p}_1,\tilde{p}_2,\dots,\tilde{p}_n$ be the respective probabilities for points in $B$.
My question is: What is the best way to find the distance between $A$ and $B$? I am looking for a distance measure which would give me zero value if co-ordinates in $A$ and $B$ are the same (appearing in any order) and it returns a large value when the co-ordinates in $A$ and $B$ are far apart. I considered using a covariance matrix but I don't get the intuition behind using that. In wikipedia, http://en.wikipedia.org/wiki/Statistical_distance, there are a lot of statistical measures listed. Can anybody help me with insights on how to choose a proper distance measure to suit the specifics of my problem?
Comment: I do not see how the probabilities play a role in your question. Could you edit your question to explain where they come from and what you plan to do with it?
Comment: Agreed with @gui11aume. Why don't you just consider the geodesic distance between the geodesic means?
Comment: Hey Emre! Geodesic distance is fine but I have no idea how do you go about calculating the geodesic means? Any help is appreciated.
Comment: I don't know if there's closed form expression, but it's easy to find [the distance between two points on a sphere](http://en.wikipedia.org/wiki/Great-circle_distance), so you could use numerical optimization to find the answer in the worst case. For an initial value you could use the projection of the center of mass onto the surface.
Answer: The usual measure of distance is the euclidean distance, which in two dimensions gives:
$d(x_1, y_1, \tilde x_1, \tilde x_2) = \sqrt{(x_1 - \tilde x_1)^2 + (y_1 - \tilde y_1)^2}$
There are an infinity of other possible distance measures, but this one is the most "natural" one, in which the shortest path is the straight line, etc.
Comment: Normally, geographic coordinates are given in latitude and longitude for which applying this Pythagorean formula is erroneous.  In many, if not most, applications the most natural distance for *geographic* coordinates is the geodetic distance on a spheroidal or ellipsoidal model of the earth.  Cartesian distances (based on the points as projected onto planar maps) are used primarily as convenient *proxies* for the geodetic distances.

Distance between two random vectors


centre text in a div which is inside a td

Question: I have the following:

CSS:
.in{
text-align:center;
-webkit-border-radius:8em;
font-size:25px;
height:120px;
width:120px;
vertical-align:middle;
}

td{
text-align:center;
padding:0px;
height:100%;
overflow:hidden;

I am trying to produce a circle inside a div which is inside the td. I dynamically (ajax) add text (a number) to the div. So essentially I want a Circle with a number in the centre. The problem is that the text is always at the top of the circle and not in the centre.
Help appreciated, thanks.
Comment: Could you provide us with a fiddle?
Answer: Try adding line-height:120px; to your .in class
Comment: Super, worked brilliantly :D. Will mark as correct in 5 minutes. Thanks.


DOMPDF not showing images and writing empty tmp files via print module

Question: I recently moved a Drupal 7 website from my development server to my pre-production server, and the rendering of the images from both the Body field and various images fields stopped working.
I now see "Image not found" and the URL of the image (which is working when I click on it by the way) on the generated PDFs.
The URLs from the Body field look like this "/mywebsite/sites/default/files/myimage.jpg" and the URLs of the "Image" fields are complete URLs with "http://mydomainname.com/mywebsite/……".
www-data has access to the images files and can also write in /tmp.
And it does, actually, every time I generate a PDF with images. But the files are empty:
$> find /tmp -name "*dompdf*" -ctime -1 | xargs ls -lArth
-rw------- 1 www-data www-data 0 janv.  4 15:30 /tmp/ca_dompdf_img_0DlQ4V
-rw------- 1 www-data www-data 0 janv.  4 16:01 /tmp/ca_dompdf_img_Tyvv8w
-rw------- 1 www-data www-data 0 janv.  4 16:27 /tmp/ca_dompdf_img_pa4m4V
-rw------- 1 www-data www-data 0 janv.  4 16:27 /tmp/ca_dompdf_img_5RzNHk
-rw------- 1 www-data www-data 0 janv.  4 16:28 /tmp/ca_dompdf_img_T21gUJ
-rw------- 1 www-data www-data 0 janv.  4 16:29 /tmp/ca_dompdf_img_OmWxt2
-rw------- 1 www-data www-data 0 janv.  4 16:33 /tmp/ca_dompdf_img_SmA57m

I tried checking "Access images via local file access" in the "print" configuration page, but with no luck.
This may be an issue related to the server configuration, since it was working before on the development server, but I'm running out of ideas…
Answer: It's because your permission is -rw------- which only has read and write, there is no execute.
Use chmod -R 0775 sites/default/files
Comment: Hmmm, not right I'm afraid - for a start you shouldn't change files to 755, just directories (there are exceptions but you'd know about them, and this isn't one of them) - files should be 644. Secondly the OP has a problem with the /tmp folder (not sites/default/files), which _does_ have the execute bit as the directory contents can be listed. Lastly, the fact that the files exist at all means it's not likely to be a permission issue, at least not with _that_ folder. To test: `sudo -u www-data touch /tmp/blah`. If the file exists, the user can write.
Comment: @Bertrand31 You should find more information in your server's error logs
Comment: Yeah you're right about the 755, especially since this directory contains user-uploaded content. I already tried to `su` into www-data, and I can write files in /tmp/.
I'll see if the logs tell me more.
Comment: Apache's access log showed me the HTTP request originating from my server and trying to retrieve the images resulted in 401 errors. This was actually all because of the htaccess authentication I had put up.
Thanks @Clive!
Answer: Apache's access log showed me the HTTP request originating from my server and trying to retrieve the images resulted in 401 errors.
This was because of the htaccess authentication I had put up.


Avoid duplicated external links

Question: I would like to add a section on my website (Drupal 7) which consists of articles with external links (as source). To avoid spam and duplicated content, I would like to avoid that users may add a URL more than one time. Basically, I need something which checks if the external URL is unique and not being used more than once.
I've looked for modules on Drupal.org, and tried googling some information. But I couldn't really find a solution. The Link checker module seems fine for checking if the URL is still available, but it doesn't avoid the same URL is used more than once.
Answer: You should take a look at the Unique Field module:

This module performs additional validation when a node is created or
  updated by a user to require that a node's title, author, language,
  and CCK fields are unique within a given context.
Comment: Considering the module has a setting for the scope of the unique values (e.g. content type, all nodes, the single node), this is the module I would suggest too.
Comment: Bit of a shame that I didn't looked into that direction. Anyway I did some testing seems to do the job so far, thanks for your help!

Avoid duplicated external links


How hidden the user_filter_form to a specific role?

Question: How can I hidden with alter_form to hide the user_filter_form in the page of list of users to a specific role?
Answer: hook_form_alter() wouldn't actually be the best place for this; the form is actually called in from user_admin() so the best place for your code would be hook_page_alter().
The first thing you should do is create a custom permission that you can assign to the role:
function MYMODULE_permission() {
  return array(
    'access user filter form' =>  array(
      'title' => t('Access User Filter Form')
    ),
  );
}

Then implement hook_page_alter() to hide the form:
function MYMODULE_page_alter(&$page) {
  // Make sure this is the right page
  if (arg(0) == 'admin' && arg(1) == 'people') {
    // Make sure filter form actually exists
    if (isset($page['content']['system_main']['user_filter_form'])) {
      // Check user access
      if (!user_access('access user filter form')) {
        // Deny access to the form if necessary
        $page['content']['system_main']['user_filter_form']['#access'] = FALSE;
      }
    }
  }
}


Android No destination with ID 2131362800 is on the NavController's back stack

Question: I've encountered a severe crash on Firebase that happens on average 6 times per user. But do you have any ideas, help for this error that I can never repeat?
It would be a good workaround though if I could at least remove the crash
Fatal Exception: java.lang.RuntimeException
Unable to start activity ComponentInfo{com.my.company/com.my.company.ui.MainActivity}: java.lang.IllegalArgumentException: No destination with ID 213136280 is on the NavController's back stack. The current destination is f0(com.my.company:id/nav_graph_home_page) startDestination={a(com.my.company:id/homeFragment) label=HomeFragment class=com.my.company.ui.home.HomeContainerFragment}
Comment: You should at least show us your navigation graph ti help us understand your problem.
Comment: Did you find solution? I have the same problem for a while, even opened an issue: https://issuetracker.google.com/issues/295991505
Answer: The problem is mostly happening to android 13 users and cause is most likely that system is killing activity after a while - more often then on previous versions (at least it is for me). When it happens, somehow it seems that navigation does not have full backstack available thus it cannot find last destination on it and showing this ridiculous exception.
Also, in my app I have SplashScreen that is deciding which fragment to show next and after app being killed by system, Splash is not shown again and activity does not know where to go. (again - my guess)
This can be tested when you enable "Don't keep activities" in Developer Options. System can kill your app when it needs resources for other apps in use (eg. RAM).
I could not find some good solution and I had asked Google to help, but they seem to be too busy googling:
https://issuetracker.google.com/issues/295991505 (no help at all)
I was trying:

safe navigation
different flags in navigation files
...

So, this may not be an answer, but maybe it explains different sides of the problem. Maybe, someone else has the same issue and may help me too :(
This is especially dangerous if you have less than 92% of crash-free users - Play Store is displaying users that their phone may be incompatible and it does not let them install.


Ignorar parâmetro caso esteja null

Question: Tenho o seguinte método que faz uma busca no banco de dados:
public Collection<Habilidade> pesquisar(HabilidadeForm form) throws Exception {
        String query = "select u from Habilidade u where u.nome like ?1 and u.geracao = ?2";
        Collection<Habilidade> resultado =
            em.createQuery(query).setParameter(1, "%" + form.getNome() + "%")
                .setParameter(2, form.getGeracao()).getResultList();

        return resultado.isEmpty() ? findAll() : resultado;
    }

Caso eu faça a mesma query no banco ficaria assim um exemplo:
select * from habilidade where nome like '%Bl%' and geracao_id = null;

Tenho um problema onde nenhuma geração é null, daí caio na pegadinha que ele não vai trazer nada caso geracao seja null. Como posso resolver fazer por exemplo: Se a geracao for null ignore ?
Answer: Douglas, na forma que entendi o problema, é recomendável criar a lógica para verificar se o seu formulário a geraçao_id não é null, montar o select e se necessário passar o parâmetro. No caso abaixo se a geracao_id for null, o select apenas considerará o nome.
public Collection<Habilidade> pesquisar(HabilidadeForm form) throws Exception {
    String query = "select u from Habilidade u where u.nome like ?1";

    if (form.getGeracao() != null) {
       query +=  " and u.geracao = ?2";
    }

    Query q = em.createQuery(query);
    q.setParameter(1, "%" + form.getNome() + "%");

    if (form.getGeracao() != null) {
        q.setParameter(2, form.getGeracao());
    }

    Collection<Habilidade> resultado = q.getResultList();

    return resultado.isEmpty() ? findAll() : resultado;
}

Ignorar parâmetro caso esteja null


c# : console application - static methods

Question: why in C#, console application, in "program" class , which is default, all methods have to be static along with
static void Main(string[] args)

Answer: Member functions don't have to be static; but if they are not static, that requires you to instantiate a Program object in order to call a member method.
With static methods:
public class Program
{
    public static void Main()
    {
        System.Console.WriteLine(Program.Foo());
    }

    public static string Foo()
    {
        return "Foo";
    }
}

Without static methods (in other words, requiring you to instantiate Program):
public class Program
{
    public static void Main()
    {
        System.Console.WriteLine(new Program().Foo());
    }

    public string Foo() // notice this is NOT static anymore
    {
        return "Foo";
    }
}

Main must be static because otherwise you'd have to tell the compiler how to instantiate the Program class, which may or may not be a trivial task.
Comment: Is instantiating the `Program` class a smart move in terms of memory? if it's a large program it sounds an awful thing to do.
Answer: You can write non static methods too, just you should use like this
static void Main(string[] args)
{
    Program p = new Program();
    p.NonStaticMethod();
}

The only requirement for C# application is that the executable assembly should have one static main method in any class in the assembly!
Answer: The Main method is static because it's the code entry point to the assembly. There is no instance of any object at first, only the class template loaded in memory and its static members including the Main entry point static method. Main is predefined by the C# compiler to be the entry point.
A static method can only call other static methods (unless there is an instance handle of something composited for use). This is why the Main method calls other static methods and why you get a compile error if you try to call a non-static (instance) method.
However, if you create an instance of any class, even of the Program class itself, then you start creating objects in your application on the heap area of memory. You can then start calling their instance members.
Answer: Not all methods have to be static, you can add instance methods and also create an instance of your Program class.
But for Main it has to be static beacause it's the entry point of your application and nobody is going to create an instance and call it.
Answer: So, technically correct answers are above :)
I should point out that generally you don't want to go in the direction of all static methods. Create an object, like windows form, a controller for it and go towards object-oriented code instead on procedural.


Encoding utf-8 permite acentos?

Question: Se fizermos
# encoding: utf-8

na primeira linha de um programa Python, conseguimos fazer acentos no código todo?
Answer: Na realidade, tudo depende da configuração do seu editor de texto. A maioria dos editores de texto salva, por padrão, os arquivos na codificação UTF-8 (e, pelo menos para os lusófonos, os editores que não o fazem salvam em ISO-8859-1).
Por que isso importa?
Pra resumir uma história bem complicada, que começou lá na época dos primeiros telégrafos, os códigos de caracteres do alfabeto latino foram padronizados bastante cedo (o ASCII foi padronizado em 1960), mas os caracteres "especiais" — cedilhas, acentos — foram "padronizados" por cada país (ou grupo de países) separadamente. A Europa Ocidental (e, portanto, países lusófonos, hispanófonos, …) convergiram no padrão ISO 8859-1.
O problema é que esse padrão não contém caracteres dos alfabetos grego, cirílico, …, então é impossível ter um documento neste padrão que, por exemplo, misture trechos de português com grego (e a situação fica pior ainda quando você inclui japonês, chinês, …)
A invenção do Unicode
Para unificar essas codificações e permitir textos polílingues (e evitar ambiguidades na hora de trocar textos entre computadores com codificações diferentes), foi inventado o Unicode, cujo objetivo é atribuir códigos distintos a todos os caracteres de todas as línguas do mundo.
Textos Unicode podem ser codificados de várias formas diferentes — internamente, .NET e Java usam UTF-16; Python 3 escolhe entre ASCII, UTF-16 e UTF-32 dependendo dos caracteres que estão no texto que você está processando.
Ainda assim, UTF-8 é a codificação mais popular para arquivos texto (e.g. arquivos-fonte Python)
Por que essa linha é necessária
Dado que um byte só pode ter 256 valores distintos, e o conjunto de todas as línguas do mundo tem mais de 256 caracteres, o UTF-8 precisa usar mais de um byte para representar alguns caracteres. Em geral, caracteres acentuados como na palavra "bênção" são representados em 2 bytes em UTF-8 (ao contrário de só 1 em ISO 8859-1):
             b |    ê   |  n |    ç   |    ã   |  o
ISO 8859-1: 62 |   EA   | 6E |   E7   |   E3   | 6F
     UTF-8: 62 | C3  AA | 6E | C3  A7 | C3  A3 | 6F

Isso é um problema quando você tenta ler um texto escrito em uma codificação como se fosse outra codificação: se o texto foi escrito como UTF-8 mas lido como ISO 8859-1, ele aparece como "bênção"; o contrário aparece como "b�n��o" (ou, no caso do Python, causa um UnicodeDecodeError).
O Python 2, como um caso especial, detecta a presença dessa linha e a usa para detectar o encoding do arquivo. Na ausência dessa linha, o Python entra num modo mais conservador, e só aceita caracteres ASCII (sem acento), lançando um erro se ele encontrar algum caractere "esquisito" (os detalhes desse mecanismo estão descritos na PEP 0263, que propôs a mudança).
Resumo da ópera
Se você quiser usar acentos no seu arquivo Python 2, coloque uma das três linhas a seguir no topo dos seus arquivos:
# encoding: utf-8
# encoding: iso-8859-1
# encoding: win-1252

Em ordem aproximadamente decrescente de probabilidade, esses são os encodings que o seu editor provavelmente usa.
Você também pode migrar para Python 3, onde o código abaixo é perfeitamente legal…
fmoreira@saucer tmp $ cat encoding.py
π = 3.14159265359
半径 = 2.5
área = π * 半径 ** 2
print('مساحة = {}'.format(área))

fmoreira@saucer tmp $ python3 encoding.py
مساحة = 19.6349540849375

…mas eu obviamente não recomendo essa técnica.
Comment: essa resposta está bem legal - mas pulou alguns assuntos essenciais para a questão: em particular muita getne acha que colocar a declaração de "encoding" no começo do arquivo é uma mágica que vai fazer todos os problemas de codificação do programa sumirem.
Comment: Para ver com mais detalhes a história do Unicode e entender o que é, é imortante ler esse artigo. (o título não é pra tirar onda - ele trata do _mínimo_ que se tem que saber para qualquer programa que use acentuação). http://local.joelonsoftware.com/wiki/O_M%C3%ADnimo_Absoluto_Que_Todos_os_Programadores_de_Software_Precisam,_Absolutamente,_Positivamente_de_Saber_Sobre_Unicode_e_Conjuntos_de_Caracteres_%28Sem_Desculpas!%29
Comment: sobre a resposta -tenho uma ressalva: longe de tentar usar outras codificações até achar uma "compatível com seu editor" como está sugerido na última parte da resposta, é importante _sim_ usar utf-8 e configurar seu editor pra usar utf-8 (e não o contrário)-  utf-8 permite caractéres especiais de várias linguas no mesmo arquivo, é o padrão no Mac Os e no Linux (e portanto em quase todos os servidores onde sua aplicação web vai estar e no Android) - só não é o padrão no Windows.
Comment: Excelente resposta, parabéns.
Comment: Eu cogitei colocar isso na resposta, mas eu tentei minimizar o escopo — um programa que só contém caracteres ASCII pode engasgar com Unicode por exemplo. A minha intenção é só lidar com o caso onde, por exemplo, você quer colocar um comentário em português num código que, sem comentários, seria ASCII puro.
Comment: Você sabe como fazer isso nos editores mais populares pra Windows? Eu mexo mais em Mac + Linux; por isso que eu me abstive de tocar no assunto. Se sim, cabe postar uma resposta em paralelo.
Comment: Acho que "configurar o editor" tem que ficar como lição de casa para uqme quer programar. :-)  Cada editor vai ter essa configuração em algum lugar razoavelemtne óbvio "editr->preferencias->editor->codifciação", ou "ferramentas->codificação"  -- na melhor das hipóterses poderia ser uma pergunta para o 'superuser.com' -- E coloqeui uma resposta aparalela abaixo falando um pouco sobre os conceitos de unicode que você não abordou ai, de qualquer forma.
Answer: A linha de declaração de encoding
#encoding: utf-8

permite que o parser do Python possa entender os acentos no código fonte - ou seja, colocar qualquer caractere acentuado deixa de ser um "erro de sintaxe" em Python 2. Outras codificações, usadas por padrão no Windows, são mais limitadas que o utf-8, no sentido de permitirem apenas 256 caracteres distintos - então é importante colocar essa linha e configurar seu editor para usar utf-8.
Mas isso não é o suficiente para usar acentuação à vontade num programa de Python 2.x. Uma mudança grande que foi implementada no meio dos anos 2000, e que muita gente ainda não se deu conta, é que dados de TEXTO no Python 2 têm que ser do tipo "unicode", não do tipo "str". No Python3, o tipo "str" já tem uma representação interna em Unicode.
A maior diferença entre os dois é que para uma string de bytes (a str simples de Python2) um elemento da sequência corresponde a um byte. Quando se fala de texto (tipo unicode) um elemento da sequência corresponde sempre há um caractere.
Faça o seguinte experimento - (pode ser no terminal, se ele estiver configurado para utf-8):
>>> a = "maçã"
>>> for letra in a: print letra,
...
m a � � � �
>>> a = u"maçã"
>>> for letra in a: print letra,
...
m a ç ã
>>>

O que acontece é que a codificação padrão do Windows em português ("latin1") usa semrpe um byte por caractere, e então não se percebe isso - mas você vai ter um problema se tentar passar uma string acentuada para maiúsculas, mesmo com esse tipo de codificação. Por exemplo:
>>> a=  "maçã".upper()
>>> print a
MAçã
>>> a= u"maçã".upper()
>>> print a
MAÇÃ
>>>

A recomendação é entender bem o que é Unicode e o que são as codificações no artigo http://local.joelonsoftware.com/wiki/O_M%C3%ADnimo_Absoluto_Que_Todos_os_Programadores_de_Software_Precisam,_Absolutamente,_Positivamente_de_Saber_Sobre_Unicode_e_Conjuntos_de_Caracteres_%28Sem_Desculpas!%29
, usar sempre utf-8 nos programas, e - sempre usar a técnica que chamaos de "o sanduiche unicode":
Ao ler texto de alguma fonte externa do seu programa - seja um arquivo, entrada do usuário, banco de dados, sensor, ele vai estar em bytes, e com alguma codificação

você decodifica esse texto para unicode (com o método "decode")
trabalha com o texto no seu programa em Python
codifica de volta no encoding usado pela saída de dados (terminal, arquivo, banco de dados, impressora, etc...) com o método "encode".

Python 3 e algumas das bibliotecas - mesmo as usadas em Python2, já fazem o passo de codificação/decodifciação de forma transparente para você. Mas mesmo assim é vital entender o que está acontecendo.

Encoding utf-8 permite acentos?


sending query results via email

Question: if this is my function:
<?php
//dsm($query);

function customstatsB_menu() {
  $items['customstatsB'] = array(
    'title' => 'Maestros Inactivos + email',
    'page callback' => 'customstatsB_all',
    'access arguments' => array('access customstatsB content'),
    'type' => MENU_CALLBACK
  );
  return $items;
}
/**
* Valid permissions for this module
* @return array An array of valid permissions for the customstats module
 * No repetir permisos, este es únicamente un modulo, y cada query NO necesita permisos. PERMISOS A NIVEL MODULE x ROL.
 */

function customstatsB_perm() {
  return array('access customstatsB content');
} // function customstats_perm()

//return array('access customstats content', 'administer customstats');

function customstatsB_all() {

/**
 * MAESTROS INACTIVOS
 */

$query = "
SELECT name, status, rid, mail
FROM users
JOIN users_roles ON users.uid = users_roles.uid
WHERE mail NOT LIKE '%@hotmail.com'
AND users_roles.rid =6
AND users.status =0
";

  // get the links (no range limit here)
  $queryResult =  db_query($query);
  while ($links = db_fetch_object($queryResult)) {
    //$page_content .= l($links->name, 'node/'.$links->mail) . '
';
    $page_content .=
    l($links->name, 'mailto:'.$links->mail) . '
';
  }

  // check to see if there was any content before
  // returning the page
  if ($page_content == '') {
    // let the user know there is no content to show
    $page_content = "No existe información para mostrar.";
  }

  return $page_content;
}

return array('access customstatsB content', 'administer customstatsB');

/**
 * Email configs
 */

function customstatsB_mail($key, &$message, $params)
  {
     $params = array(
        'subject' => t('SQL Results Tester'),
        'body' => t("Body of the email goes here"),
      );

      drupal_mail("customstatsB", "customstatsB_normal_mail", "email@example.com", language_default(), $params, "firstname.lastname@example.com");
      drupal_mail("customstatsB", "customstatsB_html_mail", "firstname.lastname@example.com", language_default(), $params, "firstname.lastname@example.com");
  }
      $language = $message['language'];
      switch ($key)
      {
           case 'customstats_normal_mail':
              $message['subject'] = t($params['subject'], $var, $language->language);
              $message['body'][] = $params['body'];
              break;
          case 'customstats_html_mail':

              $message['subject'] = t($params['subject'], $var, $language->language);

               $body = "

HTML Email Sample with Drupal

                  {$params['body']}
                  ";
              $message['body'][] = $body;
              $message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed';
              break;
      }
  }

and I am using hook_mail and drupal_mail to send an email, how should I insert the query results into the body of the mail?
Also, I have created pagecallbacks customstats1 to customstats15 via hook_menu and I need to send indivual mails when users visit each page independently. I have read a few tutorials but I haven't been able to do this.
Thanks in advance for your help.
Answer: You need to invoke hook_mail() to specify a 'body' parameter. It is a little confusing since it is two steps but well documented: http://api.drupal.org/api/drupal/includes%21mail.inc/function/drupal_mail/6
See 'example_notify()' and 'example_mail()' from the above link.
In your case yo need to call drupal_mail outside of your invocation of hook_mail. See below for an example. You can pass the body as in the $param when you call drupal_mail or you can edit it when you invoke hook_mail.
Be advised that this is not the best example since it would fire off an email any time somone visited that page, but I'm not sure where you are trying to call drupal_mail from:
$query = "
SELECT uid
FROM users
JOIN users_roles ON users.uid = users_roles.uid
WHERE mail NOT LIKE '%@mail.com'
AND users_roles.rid =6
AND users.status =0
";

 // get the links (no range limit here)
  $queryResult =  db_query($query);
  while ($links = db_fetch_object($queryResult)) {
    $account = user_load($links->uid);
    $body = t('Message for %name', array('%name' => $links->name));
    $subject = t('New email!');
    $params = array('body' => $body, 'subject' => $subject);
    drupal_mail('customstats', 'html_mail', $account->mail, user_preferred_language($account), $params);
    $page_content .= l($account->name, 'mailto:'.$account->mail) . '
';
   }

  if ($page_content == '') {
    $page_content = "No existe información para mostrar.";
  }

  return $page_content;
}

Comment: acouch, I´ve read that documentation a ton of times, i swear, but not being a programmer, I have absolutely no idea what the syntaxis for  'body' => t("Body of the email goes here"), needs to change in order to invoke the $query results of each function I have. I evidently bit much more that I could chew here. But thank you very much for your reply. I will read again. There has to be something I'm missing.
Comment: Don't get too frustrated! These things get easier with time. :) Can you post the entire code snippet you are using including your implementation of hook_mail()? I edited my answer, let me know if it helps.
Comment: acouch, I edited my original question for you to see the entire code. i left hook_mail almost untouched cause I just configured it to send empty emails, which is a start. Thanx again.
Comment: I updated the example. This should work for you. I changed 'customstatsB' to 'customstats'. It is not a good idea to use upper case for the module name so 'customstatsb' or 'customstats_b' might be better.
Comment: Thanx, acouch! I am about to make it! I just need to determine what this erros message (Sending of at least one e-mail failed. The error returned was: Invalid address: Object.") is all about. :)
Comment: i will stop using upper case in my module names, thanx for the notice.
Comment: yes, since this pages will be visible only to a staff profile, this is exactly what we want: that they fire off an email everytime you visit them.

i understand quite well what you have done by inserting drupal_mail within the $page_content of the query.

question: with the code you modified, do I still need to invoke hook_mail? i see that there's an email trying to fire, but there's that error I mentioned earlier.
Comment: You would still need to invoke hook_mail even though you are setting the subject and body in drupal_mail.
Comment: NP. You can help yourself by "accepting" answers which you find satisfactory. Some users might ignore a question from someone with a low acceptance rate.

sending query results via email


Can we calclulate R0 from logistic fit

Question: Suppose we are fitting covid19 data with logistic function,
$$\dot N(t)=rN(t)(1-\frac{N(t)}{K})$$
and get a good fit.
Can we get R0 from the optimal value of $r$ and $K$ ? If yes, how to?
Answer: The SIR model is slightly different and follows the following differential equation*:
$$\dot{u}(t) = u(t) \left( C_1 - \gamma \ln u(t)+ x_0 \beta^\prime u(t) \right)  $$
where

$S(t)$, $I(t)$, $R(t)$ are transforms of $u(t)$ following:
$$\begin{array}{}
S(t) &=& x_0 u\\
I(t) &=& \frac{\gamma}{\beta^\prime} \ln u(t) - x_0 u(t) - \frac{C_1}{\beta^\prime} \\
R(t) &=& - \frac{\gamma}{\beta^\prime} \ln u(t)
\end{array}$$
Also of interrest is $Q(t) = I(t) + R(t)$ which is the total of people that got sick (since the logisitic fit does not differentiate between infected and recovered)
$$Q(t) = - \frac{C_1}{\beta^\prime} - x_0 u(t)$$
The constant $C_1$ is an integration constant that can be fixed based on the boundary condition $S(t) + I(t) + R(t) = N$ where $N$ is the total people.
$$C_1 = -\beta^\prime N$$
The constant $x_0$ is another boundary/starting condition and relates to the initial number of recovered people $R(0)$
$$x_0 = N e^{\frac{\beta\prime}{\gamma}R(0)}$$
If we start with zero recovered people then
$$x_0 = N$$
We introduced the term $\beta^\prime$ because the differential equations for the SIR model can be written differently with a scaling $N$. The work of Harko, Lobo and Mak does not use the scaling with $N$ which makes the interpretation of $\beta$ different. We use $\beta^\prime$ for the parameter used in Harko, Lobo and Mak. We can transform as:
$$\beta^\prime = \frac{\beta}{N}$$

If $R(0) = 0$ and consequently $x_0 = 1$, then we can rewrite this as:
$$\frac{\dot{S}(t)}{S(t)} =  -\beta \left( 1 + \frac{\gamma}{\beta} \ln \frac{S(t)}{N} - \frac{S(t)}{N} \right)$$
or in terms of $Q(t)$
$$\frac{\dot{Q}(t)}{Q(t)} =  \beta \left(1 - \frac{Q(t)}{N} - \frac{\gamma}{\beta} \left(1- \frac{N}{ Q(t)}\right) \ln \left(1- \frac{ Q(t)}{N}\right)   \right)$$
which looks a bit like the equation for the logistic growth (the last term is different and becomes zero when $\gamma = 0$)
$$\frac{\dot{Q}(t)}{Q(t)} = r\left(1  - \frac{Q(t)}{K}\right) \hphantom{- \frac{\gamma}{\beta} \left(1- \frac{N}{ Q(t)}\right) \ln \left(1- \frac{ Q(t)}{N}\right) }$$

*Harko, Lobo and Mak 2014 Exact analytical solutions of the Susceptible-Infected-Recovered (SIR) epidemic model and of the SIR model with equal death and birth rates https://arxiv.org/abs/1403.2160

So you could see logistic growth as a special case of the SIR model with $\gamma = 0$ (no recovery) and $R_0 =\infty$.
Therefore based on logistic fits you can not derive the value of $R_0$ since a logistic fit is a SIR fit with fixed $R_0$.
Note that, when $Q(t) << N$ then for both the SIR model and the logistic model you get approximately exponential growth.
For the SIR model you get $\left(1- \frac{N}{ Q(t)}\right) \ln \left(1- \frac{ Q(t)}{N}\right)  \approx 1$ and
$$ \frac{\dot{Q}(t)}{Q(t)} = \beta - \gamma$$
for the logistic growth model you get
$$ \frac{\dot{Q}(t)}{Q(t)} = r $$
So fits with a logistic model, or anything else that has initial exponential growth, to data in an early phase, may be used to determine $\beta - \gamma$, but not the value of $R_0 = \frac{\beta}{\gamma}$ which requires data over a longer period.
(If it is covid-19 that you are after, then an $R_0$ value with more data will be wrong since the data does not relate to an SIR model which is a model for homogeneous mixing and parameters that are not changing in time)
Comment: great answer and really want to thank you for helping me to derive these. I think I need to read more books instead of searching online blogs. Many of the blogs are inaccurate on SIR model. BTW, do you have some Epidemiology background? or just strong at statistics and math?
Comment: @HaitaoDu I moved to studying Food Technology after a bsc in Astronomy. But I am still strong in math. Now I am modelling transport of aroma instead of transport of starlight. And it turns out that modelling food is much harder than modelling stars.
Comment: I have been working on "machine learning" and statistics for couple of years. I never fully understand differential equations because it seems statistics model is different kind of model. Until recent I work on this covid19 and I re-learned these differential equation stuff, thank you very much for all the knowledge and insights.
Comment: @HaitaoDu I believe that there is an interesting connection between differential equations and statistics when we take the thermodynamic limit (an infinite number of particles and related volume). For instance, diffusion, which can be explained with differential equations, is actually a probability process. When you get a puncture in your tire then the flow due to the leak is simply a matter of chance (there is a tiny probability that a punctured tire could inflate). The normal distribution also follows a nice differential equation that relates to diffusion $\frac{\text{d}}{\text{d}t} x =-tx$.

Can we calclulate R0 from logistic fit


Mathjax module does not render on edit ckeditor

Question: I have installed mathjax module and ckeditor module, but when I try to insert math code using math button on ckeditor, the math codes does not rendered correctely, math code become hidden. Math code rendered successly after content is submited.
is there anyone can help me to fix?
here my screenshot
Answer: Assuming you are using D7, it seems like the solution is in this MathJax issue.  Requires some patching / adding plug-ins to ckeditor.
Comment: I have tried to follow the step on that issue but no success. Could you give me some clues which one that i have to patch or add plug-ins?
Answer: Just copy the mathjax CDN url from the config/content authoring/mathjax, and paste it in CKEditor-full html-advanced options-custom Javascript configuration, then it works! Note the pasted format should be "config.mathJaxLib=url".