Django - Not being able to merge front end to backend

Question: Im learning programming and im completely new in it..i was working on a project and i have used django for back-end. Now the problem im currenctly facing is that i got no idea how should i link frontend and backend ?..
first we created backend (where there is login/signup/and dashboard) using django and boostrap,js .. and the backend work perfectly so below the folder structure of the backend
we are working on.

so this is the structure of the backend .. to be more clear check 2nd image.

Here you can see that, budgetwebsite folder which is just below the folder authentication.
budgetwebsite is our main thing or a part of our system..
then we did django startapp for authentication(for username validation and email)
then we did django startapp for userincome(here we worked on userincome like add/delete income)
then we did django startapp for expenses(here we worked on expenses like add/delete/expense)
and that userpreference is our admin panel.
thats for the backend section
Now lets move on the front end section aswell.
then we created a different folder name front end and we started working on it.

So now lets move to the problem... i just want to merge this front end and back end ..
below is my code of
setting.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'expenses',
    'userpreferences',
    'userincome',
]

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [os.path.join(BASE_DIR, 'main')],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
            },
        },
    ]

    WSGI_APPLICATION = 'budgetwebsite.wsgi.application'

    STATIC_URL = '/static/'
    STATICFILES_DIRS=[os.path.join(BASE_DIR,'budgetwebsite/static')]
    STATIC_ROOT = os.path.join(BASE_DIR,'static')

    MESSAGE_TAGS ={
        messages.ERROR : "danger"
    }

urls.py
from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('', include('expenses.urls')),
    path('authentication/', include('authentication.urls')),
    path('preferences/', include('userpreferences.urls')),
    path('income/', include('userincome.urls')),
    path('admin/', admin.site.urls),
]

now my question is do i again have to startapp which i did for like expenses , income and authentication or is there any way i can easly merge my front end with backend. If you didn't understood the question im sorry ..
and if the question is that appropriate then im sorry for that aswell.
Thanks.
Comment: Now there are so many things I see wrong with this, or could be wrong. You need to set up your views, templates etc properly. Looking at your settings for templates, it should be under the folder named 'main' where all the html files should go. I would suggest you follow [this tutorial](https://docs.djangoproject.com/en/4.0/intro/tutorial01/) and you can see what you are missing.
Comment: what do you exactly mean by merging frontend and beackend
Comment: @NaeemKhan i will add 'main' folder which consist of html file aswell .. i forgot to add it here.
Comment: @RitankarBhattacharjee like i mean if i have to open frontend of my site i need to open through my index.html and if i have to open backend of my site i can open through terminal like python manage.py runserver .... im just not being able to link the frontend [template or webpage] with my back end
Comment: @SusanKafle Okay i will try to post an answer
Answer: Let's assume you want the user to get the expense app to open when he first visits your wesite
So the expense app will have it's own views.py and you have to create a urls.py for it and also all the other apps too.
now in the urls.py file of the expense you have to write the url patternss for that app
urls.py
from django.urls import path

from . import views

urlpatterns=[
    path('expense', views.expense, name= 'expense'),

]

similarly all the urls you want to display under the expense app has to written here first connected to a view function
views.py
from django.shortcuts import render

def expense(request):

    return render(request, 'expense.html') #or any other html file related to expese

all the pages related to the expense app will have different view function to render them and also url patterns connected to then so that the user can request
This is the most basic codes that you have to write to render any page related to the apps you want to display


Sobrecarga de método sort

Question: Estudando polimorfismo em python. Tô tentando sobrecarregar o método sort do classe lista que foi herdado pela minha classe grupo. Acontece que o ordenamento não tá saindo certo. Não creio que o problema seja o algoritmo de ordenamento. Ele tem que ordenar de forma crescente pela idade, mas a saida depois do sort fica assim:
Nome: Ana || Idade: 13
Nome: Ana || Idade: 13
Nome: Maria || Idade: 45

Código:
class Grupo(list):
    def __init__(self):
        self.pessoas=Pessoa()
    def __str__(self): #sobrecarga do método print. Irá printar os dados de todas as pessoas do grupo
        str=""
        for pessoa in self.pessoas: #percorre a lista e vai adicionando os dados das pessoas há uma string única
            str+="\nNome: %s || Idade: %d"%(pessoa.nome,pessoa.idade)
        return str #retorna a string

    def sort(self):
        copia = self.pessoas.copy()
        tamanho = len(self.pessoas)
        self.pessoas.clear()
        while len(self.pessoas) < tamanho:
            min=copia[0]
            for pessoa in copia:
                if pessoa.idade < min.idade:
                    min = pessoa
            copia.remove(min)
            self.pessoas.append(min)

class Pessoa:
    def __init__(self, nome=None, idade=None):
        self.nome = nome
        self.idade = idade

pedro = Pessoa("Pedro", 23)
ana = Pessoa("Ana", 13)
maria = Pessoa("Maria", 45)
grupo = Grupo()
grupo.pessoas = [pedro, ana, maria]
print(grupo)
grupo.sort()
print(grupo)

Answer: Use a Slice Notation para realizar a cópia e a limpeza da sua lista self.pessoas:
def sort(self):
    copia = self.pessoas[:]
    tamanho = len(self.pessoas)
    self.pessoas[:] = []
    while len(self.pessoas) < tamanho:
        min=copia[0]
        for pessoa in copia:
            if pessoa.idade < min.idade:
                min = pessoa
        copia.remove(min)
        self.pessoas.append(min)

Segue código corrigido e melhorado:
class Grupo(list):
    def __init__(self):
        self.pessoas = []

    def __str__(self):
        str=""
        for pessoa in self.pessoas:
            str += "\nNome: %s || Idade: %d" % (pessoa.nome, pessoa.idade )
        return str

    def append( self, pessoa ):
        self.pessoas.append(pessoa)

    def sort(self,reverse=False):
        cp = self.pessoas[:]  # Slice Notation para copiar lista
        tam = len(cp)
        self.pessoas[:] = [] # Slice Notation para limpar lista
        while len(self.pessoas) < tam:
            x = cp[0]
            for p in cp:
                if reverse == False:
                    if p.idade < x.idade:  # Verifica se idade eh MENOR
                        x = p
                else:
                    if p.idade > x.idade: # Verifica se idade eh MAIOR
                        x = p
            cp.remove(x)
            self.pessoas.append(x)

class Pessoa:
    def __init__(self, nome=None, idade=None):
        self.nome = nome
        self.idade = idade

# Cria Grupo
grupo = Grupo()

# Adiciona Pessoas no Grupo
grupo.append( Pessoa("Pedro", 23) )
grupo.append( Pessoa("Ana", 13) )
grupo.append( Pessoa("Maria", 45 ) )
grupo.append( Pessoa("Joana", 9 ) )
grupo.append( Pessoa("Jesus", 33 ) )
grupo.append( Pessoa("Maria", 27 ) )

print(grupo)

# Ordena Pessoas do Grupo pela idade de forma Crescente
grupo.sort()
print(grupo)

# Ordena Pessoas do Grupo pela idade de forma Decrescente
grupo.sort(reverse=True)
print(grupo)

Saída:
Nome: Pedro || Idade: 23
Nome: Ana || Idade: 13
Nome: Maria || Idade: 45
Nome: Joana || Idade: 9
Nome: Jesus || Idade: 33
Nome: Maria || Idade: 27

Nome: Joana || Idade: 9
Nome: Ana || Idade: 13
Nome: Pedro || Idade: 23
Nome: Maria || Idade: 27
Nome: Jesus || Idade: 33
Nome: Maria || Idade: 45

Nome: Maria || Idade: 45
Nome: Jesus || Idade: 33
Nome: Maria || Idade: 27
Nome: Pedro || Idade: 23
Nome: Ana || Idade: 13
Nome: Joana || Idade: 9

Sobrecarga de método sort


Transforming system link into a button

Question: I have created a "button" class in my style.css file.
I can easily create a button by assigning the "button" class to it. I can do this when I write the html code in, say, a block that I place wherever on the page.
But how do I transform an existing link (like one automatically created by a module) into a button?
Do I need to hack the module?
Any help on this riddle would be greatly appreciated.
Thanks.
:)
Comment: What is generating the link you want to change?
Comment: Like @digital said, we need to know what link is being generated.
Comment: Well, I was thinking of Privatemsg for instance. To write a new message, there is a link in the inbox that I would like to transform into a button.
Comment: Do you know if this is a menu item or link inserted into a template? If it's a menu link then you could take a look at https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_menu_link_alter/7
Answer: I definitely don't recommend hacking the module - it's not good Drupal form, and it limits your ability to get module updates in the future.
I think the answer depends on how the module creates the link in question. That is, how is the link HTML being generated? If it's being generated and printed directly to the screen, then you'd have to do some CSS/JS work to intercept the HTML being generated and alter it. We have done this when necessary on our site to bend certain modules and functionality to suit our display needs. If the link has a specific ID, just alter it with JS in a custom module or custom theme. If not, you may have to get at it via jQuery based on what elements it's contained within, but it can be done.
If you're lucky and the module is well-written, the link will be part of content that's passed through Drupal's theming engine first through a theme() call. In this case, you can write your own function to grab anything being themed, inspect it for whatever markers indicate that it should become a button, and then alter the link code as need be. If you're not familiar with the theme() functionality in Drupal, you'll want to read up on it on Drupal.org first. Hope this helps!

Transforming system link into a button


Comparing NSDate + Period

Question: I have start date and a duration (period). For example startDate = '2014-02-12' period = 2. I desired dates 2014-02-12, 2014-02-14, 2014-02-16, .... I need to determine the current date is flagged during.
Comment: Can you add some sample code please?
Comment: Is the start date given as NSDate or NSString? What have you tried? What do you mean by "current date is flagged" ?
Comment: The start date given as NSDate. If the current date is equal to 2014-02-12, 2014-02-14, 2014-02-16, ....
Answer: You can get the desired dates using
- (id)dateByAddingTimeInterval:(NSTimeInterval)seconds
with seconds = period*3600*24
Comment: No. Not every day has 24 hours. Think of daylight saving time transitions.
Answer: To check if the difference between the start date and the current date is an even
number of days, use NSDateComponents:
NSDate *startDate = ...;
NSDate *currentDate = [NSDate date];
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *diff = [cal components:NSDayCalendarUnit fromDate:startDate
                                  toDate:currentDate options:0];
NSInteger days = diff.day;
if (days % 2 == 0) {
    // even number of days between start date and current date
}

Comment: Note that, `components:fromDate:toDate:options:` method truncates the results of the calculation to the smallest unit supplied. For instance, if the fromDate: parameter corresponds to Jan 14, 2010 at 11:30 PM and the toDate: parameter corresponds to Jan 15, 2010 at 8:00 AM, there are only 8.5 hours between the two dates. If you ask for the number of days, you get 0, because 8.5 hours is less than 1 day. There may be situations where this should be 1 day. You have to decide which behavior your users expect in a particular case.
Comment: Check out my answer, if you need days between two dates, as the number of midnights between.
Comment: @lancy: You are right that I have assumed that `startDate` is the *beginning* of the first day (at 00:00). If that is not the case than it can easily be achieved with `[cal rangeOfUnit:NSDayCalendarUnit startDate:&beginningOfStartDate interval:NULL forDate:startDate];` .
Answer: Calc the days from startDate to givenData, check the result whether it can be divisible by the period.
+ (NSInteger)daysWithinEraFromDate:(NSDate *)startDate toDate:(NSDate *)endDate {
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSGregorianCalendar];
    [gregorian setTimeZone:[NSTimeZone localTimeZone]];
    // for timezone issue
    NSDate *newDate1 = [startDate dateByAddingTimeInterval:[[NSTimeZone localTimeZone] secondsFromGMT]];
    NSDate *newDate2 = [endDate dateByAddingTimeInterval:[[NSTimeZone localTimeZone] secondsFromGMT]];
    NSInteger startDay = [gregorian ordinalityOfUnit:NSDayCalendarUnit
                                            inUnit: NSEraCalendarUnit forDate:newDate1];
    NSInteger endDay = [gregorian ordinalityOfUnit:NSDayCalendarUnit
                                          inUnit: NSEraCalendarUnit forDate:newDate2];
    return endDay - startDay;
}

Comparing NSDate + Period


Rust Crossclip Print Type of Clipboard

Question: I'm trying to use the crossclip crate to copy/paste images to/from the clipboard. The provided example of setting a string to the clipboard is simple enough:
use crossclip::{Clipboard, SystemClipboard, Result};

fn main() -> Result<()> {
    let clipboard = SystemClipboard::new()?;
    clipboard.set_string_contents(String::from("Hello"))?;
    println!("{}", clipboard.get_string_contents()?);
}

get_string_contents returns a String. I'm assuming that to access in image in the clipboard I'll need the get_content method, described in the documentation as:
fn get_contents(
    &self
) -> Result<(Vec<u8>, ClipboardContentType), ClipboardError>

How can I print out the type of the result from get_contents so I can see if its an image?

fn printTypeOfClipboardContents() -> Result<(), ClipboardError> {
    let clipboard = SystemClipboard::new()?;
    let teststuff = clipboard.get_contents();
    //print the type of teststuff
    Ok(())
}

Answer: Directly underneath the documentation for get_contents you can see it says:

WARNING: Unimplemented, use get_string_contents

and if you click on the link to view the src, you can see the whole function is defined as:
fn get_contents(&self) -> Result<(Vec<u8>, ClipboardContentType), ClipboardError> {
    todo!("Unimplemented, use `get_string_contents`");
}

I conclude that this library does not yet support any way to access any type of data other than plain text.
Comment: I see. I can't seem to find a crate that enables copying images to the clipboard anywhere :/. any thoughts on an approach? @harmic

Rust Crossclip Print Type of Clipboard


Showing that $\sum_{i=1}^{n}\sum_{j=1}^{n}(a_{i} - a_{j})^2 = 2n \sum_{i=1}^{n}(a_{i} - \bar{a})^2$

Question: I wish to show $\sum_{i=1}^{n}\sum_{j=1}^{n}(a_{i} - a_{j})^2 = 2n \sum_{i=1}^{n}(a_{i} - \bar{a})^2$ for any numbers $a_1, a_2, ..., a_n$.
I assume the first step $+\bar{a}$ and $-\bar{a}$ in the first equation, to get $(a_{i} - \bar{a})^2$ in the end. But, I can't get it to the second equation.
Answer: Here is a hint, for any numbers the sum of the mean deviations is zero, i.e.
$$\sum_{i=1}^n \left(a_i - \bar{a} \right) = 0 $$
Recall also that
$$ \sum_{i=1}^n \left(a_i - \bar{a} \right)^2 =  \sum_{j=1}^n \left(a_j - \bar{a} \right)^2 $$
With these in mind, you should be able to reach the sum on the RHS.
Comment: That's exactly what I needed. I don't know why my mind didn't think of that first part. Thanks!


Scrapy CLOSESPIDER_PAGECOUNT setting don't work as should

Question: I use scrapy 1.0.3 and can't discover how works CLOSESPIDER extesnion.
For command:
scrapy crawl domain_links --set=CLOSESPIDER_PAGECOUNT=1
is correctly one requst, but for two pages count:
scrapy crawl domain_links --set CLOSESPIDER_PAGECOUNT=2
is infinity of requests.
So please explain me how it works in simple example.
This is my spider code:
class DomainLinksSpider(CrawlSpider):
    name = "domain_links"
    #allowed_domains = ["www.example.org"]
    start_urls = [ "www.example.org/",]

    rules = (

        # Extract links matching 'item.php' and parse them with the spider's method parse_item
        Rule(LinkExtractor(allow_domains="www.example.org"), callback='parse_page'),
    )

    def parse_page(self, response):
        print '<<<',response.url
        items = []
        item = PathsSpiderItem()

        selected_links = response.selector.xpath('//a[@href]')

        for link in LinkExtractor(allow_domains="www.example.org", unique=True).extract_links(response):
            item = PathsSpiderItem()
            item['url'] = link.url
            items.append(item)
        return items

even don't work for this simply spider:
# -*- coding: utf-8 -*-
import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor

class ExampleSpider(CrawlSpider):
    name = 'example'
    allowed_domains = ['karen.pl']
    start_urls = ['http://www.karen.pl']

    rules = (
        # Extract links matching 'category.php' (but not matching 'subsection.php')
        # and follow links from them (since no callback means follow=True by default).

        # Extract links matching 'item.php' and parse them with the spider's method parse_item
    Rule(LinkExtractor(allow_domains="www.karen.pl"), callback='parse_item'),
    )

    def parse_item(self, response):
        self.logger.info('Hi, this is an item page! %s', response.url)
        item = scrapy.Item()

        return item

but is not infinity:
scrapy crawl example --set CLOSESPIDER_PAGECOUNT=1
 'downloader/request_count': 1,
scrapy crawl example --set CLOSESPIDER_PAGECOUNT=2
 'downloader/request_count': 17,
scrapy crawl example --set CLOSESPIDER_PAGECOUNT=3
 'downloader/request_count': 19,
Maby it is because of parallel downolading.
Yes, for CONCURRENT_REQUESTS = 1, CLOSESPIDER_PAGECOUNT settings works for second example. I wil check the first - it works too.
It was almost infinity for me becouse, sitemap with many urls (my items) was crawled as next page :)
Comment: are you sure you want to return items, not "yield item" one by one? I prefer to use BaseSpider, but it looks like parse_page is called infinite amount of times, while not really yielding any item?
Comment: I think it does not matter. Inspired by:
https://github.com/scrapy/dirbot/blob/master/dirbot/spiders/dmoz.py
but of course this example is a bit updated.
Comment: Turo, thanks for advice - it is good memory optimization way.
Answer: CLOSESPIDER_PAGECOUNT is controlled by the CloseSpider extension, which counts every response until reaching its limit that's when it tells the crawler process to start ending (finishing requests and closing available slots).
Now the reason why your spider ends when you specify CLOSESPIDER_PAGECOUNT=1 is because at that moment (when it gets its first response) there are no pending requests, they are being created after your first one, so the crawler process is ready to end, not taking into account the following ones (because they will be born after the first).
When you specify CLOSESPIDER_PAGECOUNT>1, your spider is caught creating requests and filling the requests queue. When the spider knows when to finish there are still pending requests to process, which are executed as part of closing the spider.
Comment: This helped make sense of trying to understand closespider_pagecount too this week, thanks


dpm breaks only if used in form custom submit on edit node

Question: Problem
I have a case where the dpm printout is working fine in all cases except on a specific node type, in a very specific scenario.
If I edit the node type and place  dpm($form_state) in the custom node submit called by hook_form_alter, no messages display on submitting the form.
If I create the node it works fine. If I put dpm($form) in the custom node submit it works fine. It's only that exact scenario which breaks.
I've read other questions where dpm breaks, but never for something so utterly and irritatingly specific.
I've cut down my code to:
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id === 'mycustom_node_form_id') {
    $form['#validate'][] = 'mymodule_form_validate';
    $form['actions']['submit']['#submit'][] = 'mymodule_form_submit';
  }
}

function mymodule_form_validate ($form, &$form_state) {
  dpm($form_state);
  dpm($form);
}

function mymodule_form_submit ($form, &$form_state) {
  dpm($form_state); <-- THE PROBLEM
}

The node type itself, contains a fairly complex field collection, a bunch of ordinary fields and a fivestar field.
Can anyone provide any guesses or places to begin debugging this? I'm completely stumped.
Comment: Have you checked your php error logs to see if it's exceeding the memory limit (or another error)?
Comment: Is the submit button inside of 'actions' by default?
Comment: @thumbson spot on. I needed to increase my maximum mysql packet. Possibly because of the large nested field collection it was running out of memory space. Feel free to add that as an answer so I can mark it as correct
Answer: Thumbson was spot on. MySQL was hitting it's the packet limit and increasing maximum_allowed_packet in /etc/mysql/my.cnf solved the problem. (ubuntu path)
The error won't show in Drupal, the only place I could find it was in my php-fpm log. See below:
[13-Jan-2015 00:54:27] WARNING: [pool www1] child 21620 said into stderr: "NOTICE: PHP message: PHP Fatal error:  Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General error: 2006 MySQL server has gone away' in /srv/w$
[13-Jan-2015 00:54:27] WARNING: [pool www1] child 21620 said into stderr: "Stack trace:"
[13-Jan-2015 00:54:27] WARNING: [pool www1] child 21620 said into stderr: "#0 /srv/www/eslsearch.net/public/includes/database/database.inc(2171): PDOStatement->execute(Array)"
[13-Jan-2015 00:54:27] WARNING: [pool www1] child 21620 said into stderr: "#1 /srv/www/eslsearch.net/public/includes/database/database.inc(683): DatabaseStatementBase->execute(Array, Array)"
[13-Jan-2015 00:54:27] WARNING: [pool www1] child 21620 said into stderr: "#2 /srv/www/eslsearch.net/public/includes/database/database.inc(2350): DatabaseConnection->query('SELECT expire, ...', Array, Array)"
[13-Jan-2015 00:54:27] WARNING: [pool www1] child 21620 said into stderr: "#3 /srv/www/eslsearch.net/public/includes/lock.inc(167): db_query('SELECT expire, ...', Array)"
[13-Jan-2015 00:54:27] WARNING: [pool www1] child 21620 said into stderr: "#4 /srv/www/eslsearch.net/public/includes/lock.inc(146): lock_may_be_available('schema:runtime:...')"
[13-Jan-2015 00:54:27] WARNING: [pool www1] child 21620 said into stderr: "#5 /srv/www/eslsearch.net/public/includes/bootstrap.inc(433): lock_acquire('schema:runtime:...')"
[13-Jan-2015 00:54:27] WARNING: [pool www1] child 21620 said into stderr: "#6 /srv/www/eslsearch.net/public/includes/bootstrap.inc(455): DrupalCacheArray->set(Array)"
[13-Jan-2015 00:54:27] WARNING: [pool www1] child 21620 said into stderr: "#7 [internal function]: DrupalCacheArray->__destruct()..."

Comment: Glad to help! It's good to this in mind when using dpm with large objects/arrays if you notice the output is not what you expect, or isn't updating like you think it should.
Comment: I think what got me was the fact it only broke in a specific certain function. Of course now you've said it, it makes perfect sense...
Comment: I have run into this with a custom submit handler on an incredibly simple content type: title and body only. Not sure this answer completely satisfies the question. A dpm of the $form_state shouldn't result in a massive packet of data shutting down the page load. Does anyone actually know how/why this happens, even with a super-simple content type? How else can you explore the $form_state to write the custom submit handler? Should you really be expected to increase the max_allowed_packet value just to see the info you need? I've been dpm'ing in Drupal forever and never run into this until now.


Multi MX records with nonidentical e-mails

Question: I have two domains, one forwarded to the other. I want to use 2 e-mail accounts on both domains as aliased but some e-mails only on the other domain. I will create 2 MX records for both domains with different priorities.
I wonder that if a mailserver checks domain MX and couldn't find the e-mail account on MX 10 priority server, will it skip to check MX 80 priority server or return "mailbox couldn't find" error?
My MX scenario is as below:
firstdomain.com MX 10 (with only 2 mailbox)
seconddomain.com MX 80 (with 2 mailbox and other mailboxes)
I hope I could explaing it clear. Thank you!
Update for theCleaner =================================
The story is:
domainA.com: New domain
domainB.com: Older domain
My client has an old domain domainB.com and redirected it to domainA.com after purchasing domainA.com.
He has many email accounts on domainB.com. Also his firstname.lastname@example.com mailbox is active and known by his clients.
He wants to buy Exchange mailbox from me. He wants email@example.com on Exchange server but also wants email@example.com as an Accepted-Domain on Exchange.
He will use only email@example.com and email@example.com on Exchange server.
His employees will continue to use emails on domainB.com
Comment: These would be 2 servers for the same domain? MX priorities are used in that sense, MX records for domain.com `IN MX 10 mail.domain.com`  `IN MX 40 backup.domain.com` the priorities are only recommendations, nothing says you can't send to the second priority, and obviously, they mail servers do not have to have the same domain name as the domain they are the mailserver for (but it isn't a bad idea).
Comment: Yes 2 server for same domain. 2 user will use Exchange mailbox for 2 domains, one of it will be aliased. The other users will use standart mailboxes on second domain. 2 Exchange users want to receive emails for both domains, second domain as Accepted-Domain.
Comment: I think that this isn't the situation you want to use MX priorities on, as in those situations, either server can be chosen.
Comment: Thank you NickW The best solution is trying I guess. Let's see if another solution advised.
Comment: you tagged this with "Exchange".  Are you using Exchange?  Two different Exchange organizations or one?  Maybe you can update your question with a real world example like "email@example.com, etc."  Just hoping to see what you are really trying to accomplish in the end.
Comment: $thecleaner please see my update
Comment: Ah, now I see why you ask, my answer still applies, a 550 means `end of the road` for any email.. I think that this situation MX record priorities are not going to be of any assistance to you, unless you can set up aliases for all the users on domainB.com
Answer: I'm not sure I've completely understood your question, but I'll try and answer.
MX priorities are there more for high availability or backup purposes, if two servers are going to be receiving mail for a single domain, they need to have the exact same users and aliases, though they could have different destinations, the primary server is where the mailboxes are, so the secondary server will accept mail then forward it to the primary. The priorities are there so that if one of the servers is unavailable, mail can still be accepted for that domain.
If a server responds, either priority 10 or priority 80, and says "550 mailbox not found" then that is the definitive answer for that email, and any functional mail server will then return the email to sender. Creating two mail servers for a domain means that both servers must be able to accept mail for any user configured @yourdomain.com.
Comment: Are you sure about sender's server won't lookup priority 80 server if it has answer 'not found' from priority 10?
Comment: Pretty sure, if it returns a 550 no, if you can configure both servers to return a 551, then it might, but that's not something I'd honestly bet any money on. From the RFCs, `Servers MAY reject or bounce messages when they are not deliverable when addressed.  When they do so, they MAY either provide address-updating information with a 551 code, or may reject the message as undeliverable with a 550 code and no address-specific information.  But, if a 551 code is used, they MUST NOT assume that the client will actually update address information or even return that information to the user.`


Cloud computing options for web mining a lot of data in parallel?

Question: I have a school project I'm working in a class on web mining where I need to collect a lot of data from certain social media sites. I need data from a large number of individual hashtags on the site. I have a python script that successfully grabs all the data I need for a single hashtag by making sequential HTTP requests until it captures all the records needed for the specified range of time and sales them to a large csv file. I need to run this program a couple thousand times for different hashtags. For some very popular hashtags, the program takes a few hours to run. Many of the hashtags will be much faster though. I wrote a bash script that runs the python program for each hashtag sequentially, but this will take a very long time to collect everything needed.
I wanted to utilize some kind of cloud computing service like google compute engine, AWS, or azure, to run multiple instances of this program separately in parallel so I could collect the data for many of the hashtags at once. Perhaps I could have a large number of cloud machines all running the program for different hashtags at the same time. This is just so I can collect all the data I need faster.
I'm not very experienced with cloud computing outside of a few times I've used google compute engine for simple programs I only needed to run once. I tried reading about instance groups but I'm still not exactly sure how I would use them for this purpose. I'm even less familiar with AWS and Azure offerings.
What's the best way to go about this?
Comment: Voting to close: Requests for product, service, or learning material recommendations are off-topic because they attract low quality, opinionated and spam answers, and the answers become obsolete quickly. Instead, describe the business problem you are working on, the research you have done, and the steps taken so far to solve it.
Comment: I'm not really asking for recommendation I'm just trying to find out what types of cloud computing services best suit this problem.
Comment: So, you do ask for a recommendation, you just try to weasel around the definition. No recommendation, just tell me what is best...
Comment: I mean it's not like I'm asking for your recommendation between AWS, compute engine, and azure. I have a specific task and I'm asking what specific service will allow me to do what I need to do because I'm not very familiar.
Answer: Without knowing more about your exact script you probably want something that can run lambda functions:

AWS Lambda
Azure Functions
Google Cloud Functions

No VMs to worry about, pay per-second-per-gig, and once you're done. No infrastructure to remember to tear down. It will just run your script in its own environment and tear it down when it's done.
Might get a bit more pricey for the longer running scripts, but should be very cheap for the fast ones.
Comment: Wherever you like.  An Amazon S3 bucket?  Azure Table store?
Comment: What more details should I have included. Essentially the script just makes requests to the URLs provided, formats stuff in a pandas data frame, and saves it to a CSV. If these kinds of services aren't VMs then where does the CSV get stored?
Comment: Oh god I just got done setting everything up in lambda but I had no idea there was a 15 minute execution time limit.


git tagging – using local tag also for remote?

Question: I am trying to make sense to myself about tagging with git. As far as understand tagging serves the purpose of marking certain points in development.
What I don't understand is – as far as I understand the documentation – that one can have entirely different tags for the same revision or version remote and local.
Let's say I am commiting my version and I tag it like
git tag v0.0.1 master
locally.
Now I am going to push my local commit to the remote repo. And since I might just have a bad day, I am messing up my remote tag with a typo like
git push origin master v0x.0.3
A few commits later I can't find my remote commit v0.0.1 anymore because of the typo.
I there no way I can tell git to use the tag I am using locally also on the remote repo?
Comment: `git push --tags`?
Comment: So `--follow-tags`, then
Comment: That's – again, from what I understand – not recommended. Anyway I just need it for one commit i.e. local tag at a time.
Comment: By whom? And why (does their reason apply to your situation)?
Comment: e.g. here (comments section) https://stackoverflow.com/questions/5195859/how-do-you-push-a-tag-to-a-remote-repository-using-git
Comment: I've totally missed that. Yay, thanks!
Comment: @LongHike: If that works for you, great, but be aware that `--follow-tags` is specifically for *annotated* tags.  The tag you created in your example is not annotated (and there's usually no reason for a version tag to be annotated)
Answer: It sounds like you're saying that when you do that push, you think it's going to create a new remote tag at master with a different name than your local tag.  That's not correct.
If a ref named v0x.0.3 exists, it will be pushed as is (not necessarily pointing to master).  If it doesn't - which is likely in the case of random fat-fingering as suggested by the command examples you suggest - it will cause the push command to error out with a message saying that it doesn't know what v0x.0.3 is.
Now, it's true that you can create a local tag on a commit independent of any tags the remote has pointed at that commit.  For that matter, you can have any number of local tags all pointed at the same commit, any number of which may or may not have been shared with the remote.
If you actually wanted to create a tag of a different name on the remote, you could; but I don't believe for one second that you'd do it accidentally.
git push origin local_tag_name:remote_tag_name

(because local_tag_name is a tag so git will infer that you want remote_tag_name to be a tag as well, but you have to go out of your way to change the name); or
git push origin master:refs/tags/remote_tag_name

(where you explicitly say that you want to create a new tag on the remote).
And there are use cases where you might want to do that.  In almost all situations, git provides the flexibility to do whatever you want, and then provides eas(ier)-to-use commands to do what most people want most of the time.  So your observation that you can create different tag names on the remote is correct; but that doesn't mean you have to, or should, or are going to be accidentally tricked into doing so.
To align this with git concepts:  Although you seem to be thinking of a tag as an attribute of a commit, it is not.  It is its own thing (which happens to refer to a commit[1]); and that thing might or might not exist in any given repo.  IF it exists locally, you can (but don't have to) push it to a remote; and if it exists in a remote, you can (but don't have to) fetch it to the local.

[1] Actually a tag happens to refer to some object, which is usually a commit but could be something else, e.g. a specific file


Tangent to conic stays outside or between (elementary)

Question:
Let $f$ be a function from $\mathbb{R}^2$ to $\mathbb{R}$ such that $f(X) = |XA| + |XB|$, where $A,B \in \mathbb{R}^2$. Let $T$ be a point on the ellipse $\varepsilon\colon f(X)=k$, for some $k\ge |AB|$. If $C \neq T$ is a point on the tangent line to $\varepsilon$ through $T$, then $f(C) > f(T)$.

The same goes for $g(X) = \bigl||XA| - |XB|\bigr|$, changing ellipse with hyperbola.
I've seen a proof to this (or a similar theorem) using partial derivative and gradients, which I don't know how to use. I'd like to find a more elementary proof. I know that the fibers of $f$ (or $g$) are confocal ellipses (or hyperbolas) which partition the plane. So the points "inside" an ellipse have smaller $f$ than the points on the ellipse and points "between" the branches of a hyperbola have greater $g$ than those ones on the hyperbola.
Even if it made sense, I can't prove that a tangent line to a conic stays "outside"/"between" that conic (except for the tangent point)... A line tangent to a conic intersect it only at one point (because it is algebraic curve of second degree), but I can't say more so far.
Comment: You might want to consider breaking this into paragraphs. It's really hard to penetrate a large block of text.
Comment: Is it more readable now?
Comment: With your permission, I've made one additional paragraph break. It's much easier to tackle this now (from a reading comprehension point of view; mathematically, that's another story).
Comment: It is easy to show, without calculus, that the bisector of the external angle at $T$ of triangle $ABT$ has all points (besides $T$) external to the ellipse and is thus tangent to it. I don't know if that might help.
Answer: Let's prove first of all that the bisector of the external angle at $T$ of triangle $ABT$ has only point $T$ in common with the ellipse. Consider any point $P\ne T$ on the bisector and point $B'$, reflection of $B$ around the bisector (see diagram below). Notice that $ATB'$ are aligned and $APB'$ form a triangle, so by triangle inequality you have:
$$
AP+BP=AP+PB'> AB'=AT+TB,
$$
proving that $P$ is outside the ellipse.

Now we want to prove that any other line $r$ through $T$, different from the bisector considered above, has at least one point inside the ellipse.
That is obvious if foci $A$ and $B$ lie on different sides of $r$, because in that case there is a point of segment $AB$ belonging to $r$.
If $A$ and $B$ are on the same side of $r$ (see diagram below), let $B'$ be the reflection of $B$ around $r$ and $P$ the point where $BB'$ intersects $r$.
Notice that $ATB'$ are not aligned, for in that case $r$ would be the bisector of the external angle at $T$ of triangle $ABT$. By triangle inequality we then have
$$
AP+BP=AB'<AT+TB'=AT+BT,
$$
which shows that $P$ is inside the ellipse.
Comment: This seems what I was looking for. I can't upvote because of the reputation... A similar argument can be applied to the hyperbola: just change _bisector of the external angle at $T$_ with _bisector of $\angle ATB$_ and reflect around the normal line to that bisector (through $T$). Is it correct?
Comment: Yes, you can repeat the argument for a hyperbola, with the obvious changes.
Comment: But what happens when $r$ intersects $AB$? And what if $P$ is not between $AB'$ (or $BA'$)?
Comment: I explained that in my answer: if $A$ and $B$ lie on different sides of $r$, then by the plane separation postulate there is a point $P$ of $r$ on segment $AB$. But such a point is by definition internal to the ellipse because $PA+PB=AB<k$. On the other hand, $B$ and $B'$ are always on different sides of $r$: if $A$ and $B$ lie on the same side, then $A$ and $B'$ are on different sides and by the plane separation postulate there is a point $P$ of $r$ on segment $AB'$.
Comment: Oh sorry, I must have skipped that bit... Anyway, thank you again!
Answer: (1) Assume that $$ F'(-k,0),\ F(k,0) $$
and $$ PF+PF'=2a,\ a>k>0 $$ where $PF$ is a distance from $P$ to $F$
So by direct computation
\begin{eqnarray*}
 2a&=& \sqrt{ (x-k)^2+ y^2} + \sqrt{(x+k)^2+y^2} \\
  \sqrt{ (x-k)^2+ y^2}  &=& 2a-  \sqrt{(x+k)^2+y^2}
  \\  (x-k)^2+ y^2 &=& 4a^2 + (x+k)^2+y^2 -4a   \sqrt{ (x+k)^2+
y^2}  \\
kx  +a^2 &=& a \sqrt{ (x+k)^2+ y^2} \\
(a^2-k^2)x^2 + a^2 y^2 &=& a^2(a^2-k^2)\end{eqnarray*}
Hence we have
$$
\frac{x^2}{a^2} + \frac{y^2}{a^2-k^2} =1,\ PF+PF'=2a,\ F,\ F'=
(\pm k,0)$$
(2) Tangent Line of Ellipse : If $Q$ is another point in
ellipse, and if line segment $tP+(1-t)Q$ for $t\in [0,1]$ is in a
region enclosed by ellipse, then ellipse is in one side of a
tangent line
Note that \begin{align*} &F (tP+(1-t)Q) + F'(tP+(1-t)Q) \\&\leq  tFP
+ (1-t) FQ + tF'P+ (1-t)F'Q \\&=2a \end{align*}
Answer: The interior of an ellipse is bounded. If a line $\ell$ pass through a point $p$ in the interior of an ellipse $\Gamma$, one may see that $\ell$ is divided into three parts: the point $p$, and two rays with endpoint $p$. Each of the ray contains some point in the interior of $\Gamma$, as well as some point in the exterior of $\Gamma$(since the ray is not bounded, hence cannot be contained in a bounded region). So the ray must intersect with $\Gamma$. Since the two rays have no common point except $p$, so we get two different intersection point of $\ell$ and $\Gamma$, a contradiction.

In the above proof we do not have to invoke Jordan's Curve Theorem to say the interior and exterior of $\Gamma$. Suppose $\Gamma$ is defined by $f(X)=K$. We just define the interior if $\Gamma$ as the set of points $X$ satisfying $f(X)<K$ and exterior as $f(X)>K$. It's easy to prove that the interior is bounded.


Inserir dados no banco pelo AlertDialog

Question: Boa noite, Criei um AlertDialog que pede o nome do jogador e coloca no editText... quando o usuário clica em confirmar ele salva no banco de dados... eu fiz o código e parece que não estou conseguindo relacionar id ou algo do tipo.
Alguém poderia me ajudar nessa parte por favor?
Codigo do dialog:
package com.allsport.miyonic.allsport;

import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;

import Base.Esporte;

public class DialogGol extends DialogFragment{

    private EditText caixa;

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState){

        caixa = (EditText) caixa.findViewById(R.id.caixa_dialog_1);

        AlertDialog.Builder bir = new AlertDialog.Builder(getActivity());

        bir.setMessage("Gol de ").setPositiveButton("Confirmar", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                Esporte inseri = new Esporte();
                inseri.setjogadores(caixa.getText().toString());

            }
        }).setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //nulo
            }
        });

        bir.setTitle("Gooolll!!!");

        View view = LayoutInflater.from(getContext()).inflate(R.layout.caixa_jogador_dialog, null);
        bir.setView(view);

        AlertDialog dialog = bir.create();

        return dialog;
    }

}

XML do editText:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:ems="10"
            android:id="@+id/caixa_dialog_1"
            android:hint="Nome do jogador que fez o gol"
            android:layout_weight="1"
            android:gravity="center_vertical|center"
            android:shadowColor="@color/preto"
            android:textColor="@color/preto"/>
    </LinearLayout>
</LinearLayout>

LogCat:
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.allsport.miyonic.allsport, PID: 2788
                  java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.widget.EditText.findViewById(int)' on a null object reference
                      at com.allsport.miyonic.allsport.DialogGol.onCreateDialog(DialogGol.java:24)
                      at android.support.v4.app.DialogFragment.getLayoutInflater(DialogFragment.java:308)
                      at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
                      at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
                      at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:742)
                      at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
                      at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
                      at android.os.Handler.handleCallback(Handler.java:739)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:148)
                      at android.app.ActivityThread.main(ActivityThread.java:5417)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Obrigado...
Comment: Poderia colocar o código do objeto Esporte? É bem provável que o problema esteja nessa classe.
Comment: @E.Thomas da uma olhada no meu LogCat... editei minha pergunta
Answer: Você deve trocar o
       caixa = (EditText) caixa.findViewById(R.id.caixa_dialog_1);

Por
View view = LayoutInflater.from(getContext()).inflate(R.layout.caixa_jogador_dialog, null);
caixa = (EditText) view.findViewById(R.id.caixa_dialog_1);

Pois você está tentando chamar o findViewById() em um EditText
Comment: Obrigado... funcionou aqui, e toda vez que quero relacionar um id de um xml separado tenho que fazer isso certo?

Inserir dados no banco pelo AlertDialog


autocomplete on several fields at the same time

Question: I have a Database managed entity called myPerson.
It contains a lot of attributes, but also two names attributes :  firstname, lastname
I want to use autocomplete to selecte myPersonobjects from the database.
The user should be able to type the firstname or the lastname and it should make suggestions of persons with the input data as their first name or last name.
Then when the user press submit, the selected myPersone shall be fully retrieved from the database (it is not fully loaded at the beginning for performance issue)
So I have

Then in myBean :
I load at initialization the first names and last names in a list of strings (I do not load all the myPerson objects for performance issue.
Then my auto complete method looks like that
public List<String> autoComplete(String prefix) {
        ArrayList<String> result = new ArrayList<String>();
        if ((prefix == null) || (prefix.length() == 0)) {
            // safety nets
            // do nothing
        } else {
            Iterator<String> iterator = names.iterator();
            while (iterator.hasNext()) {
                String elem = ((String) iterator.next());
                if (elem.toLowerCase().indexOf(prefix.toLowerCase()) == 0) {
                    result.add(elem);
                }
            }
        }
        return result;
    }

This works fine. When the user types the beginning of a first name OR a last name, it gets suggested in the dropdown menu of the autocomplete component.
My problem lies in what comes after. How can I load the selected myPerson from the database.
The autocomplete value will be stored in #{myBean.autoCompleteValue}
But then I don't know anymore if the user typed a first name or a last name. I cannot efficiently searched in the database, and I would have to perform a search by first name, and if i'm not lucky a search by last name.
Do you know how this could be achieved more nicely ?
thanks
Answer: Construct another class, e.g. MyPersonTransfer which only contains firstname, lastname and the data-base id. Then use this class (instead of String) as a return type for your autoComplete() method and everywhere else (e.g. value="#{myBean.autoCompleteValue}").
This way you also save the db id which you can then use to load the complete person once it was chosen.


Constructors for subclasses

Question: Okay guys, im having trouble with these constructors for this code and some logic. I did most of it, just confused on how to finish this off.
Here is the main code i have. (it might be a little sloppy but its "good enough")
public class Accountdrv {
  public static void main (String[] args) {
    Account account = new Account(1122, 20000, 4.5);

    account.withdraw(2500);
    account.deposit(3000);
    System.out.println("Balance is " + account.getBalance());
    System.out.println("Monthly interest is " +
      account.getMonthlyInterest());
    System.out.println("This account was created at " +
      account.getDateCreated());
  }
}

class Account {
  private int id;
  private double balance;
  private double annualInterestRate;
  private java.util.Date dateCreated;

  public Account() {
    dateCreated = new java.util.Date();
  }

  public Account(int id, double balance, double annualInterestRate) {
    this.id = id;
    this.balance = balance;
    this.annualInterestRate = annualInterestRate;
    dateCreated = new java.util.Date();
  }

  public int getId() {
    return this.id;
  }

  public double getBalance() {
    return balance;
  }

  public double getAnnualInterestRate() {
    return annualInterestRate;
  }

  public void setId(int id) {
    this.id =id;
  }

  public void setBalance(double balance) {
    this.balance = balance;
  }

  public void setAnnualInterestRate(double annualInterestRate) {
    this.annualInterestRate = annualInterestRate;
  }

  public double getMonthlyInterest() {
    return balance * (annualInterestRate / 1200);
  }

  public java.util.Date getDateCreated() {
    return dateCreated;
  }

  public void withdraw(double amount) {
    balance -= amount;
  }

  public void deposit(double amount) {
    balance += amount;
  }
}

Now, i wanted to create a Savings, and Checking account. I need help with what i need to add for constructors, i put in the comments the parts i know im missing but confused on how to do them.
Savings:
class Savings extends Account{
//need to create a constructor
  public Savings(int id, double balance, double annualInterestRate) {
//need to invoke the constructor for Account
  super(id, balance, annualInterestRate);
 }

// need to override the withdraw method in Account
public void withdraw(double amount) {
    // place logic to prevent the account from being overdrawn
    // that is do not allow a negative balance
  }
}

Comment: This must be homework. A real bank would add logic to charge a fee, not prevent the account from being overdrawn.  ;)
Comment: @BilltheLizard haha yeah it is homework xb .. best place to go for help and questions.. soo.. yeah c:
Comment: Any reason why you don't just import java.util.Date?
Answer: You just need to check id the amount < balance Or whatever logic you have (eg: you want
some threshold amount to be present in the account).
Also I would recommend to look into synchronized methods as you should synchronize access to account of a given user to ensure that when a withdraw function is invoked...another withdraw on the same user account has to wait...or else it will lead to problems...I will leave that to you to figure out.
public void withdraw(double amount) {
// place logic to prevent the account from being overdrawn
// that is do not allow a negative balance

     if(balance < amount)
     {
        // print error message or do something
     }
     else
     {
        // withdraw the money
        balance -= amount;
        // print message or do something
     }
}

Comment: @Ryan what other query do you have ?
Comment: oh so the constructors look good? xD i felt like i did something wrong, or less sufficient or something.
Comment: Compile the code and let me know if you have any issues
Answer: super() invokes the constructor for the super-class, in the Savings case, Account.
Comment: do i need  `super(id, balance, annualInterestRate);` or can i just use `super();` ?
Comment: @Ryan You need the arguments, it is the constructor. Unless you have a constructor with no parameters you need to pass it arguments.

Constructors for subclasses


What Hook to Use to Execute a PHP on Header and Footer in Every Page?

Question: I have the following code that needs to be executed at the top of the page:
<?php
$time = microtime();
$time = explode(' ', $time);
$time = $time[1] + $time[0];
$start = $time;
?>

The code above should be used in my module:
<?php
/**
 * Implements hook_help.
 *
 * Displays help and module information.
 *
 * @param path
 *   Which path of the site we're using to display help
 * @param arg
 *   Array that holds the current path as returned from arg() function
 */
function site_visitors_help($path, $arg) {
    switch ($path) {
    case "admin/help#site_visitors":
        return '
' . t("Displays links to nodes created on this date") . '
';
        break;
    }
}

/**
 * Implements hook_init().
 */
function site_visitors_boot() {
    site_visitors_insert();
}

/**
 * Custom visitor function.
 *
 * Insert IP Address, URL to the database
 *
 * @return
 *   A result set of the targeted posts.
 */
function site_visitors_insert(){
    $tracker = array(
        'database' => 'c1tracker',
        'username' => 'c1tracker',
        'password' => 'mypass',
        'host' => 'localhost',
        'driver' => 'mysql',
    );

    Database::addConnectionInfo('tracker', 'default', $tracker);
    db_set_active('tracker');

    //This code requires the code above to compute the start time. This will compute the total page load.
    $time = microtime();
    $time = explode(' ', $time);
    $time = $time[1] + $time[0];
    $finish = $time;
    $total_time = round(($finish - $start), 4);
    $t = $total_time;
    //$url = $_GET['url'];
    $url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    $current_ip = $_SERVER['REMOTE_ADDR'];
    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    $date = date("Y-m-d");
    $time =  date("h:i:s");

    function is_bot()
    {
        $botlist = array("Teoma", "alexa", "froogle", "Gigabot", "inktomi",
        "looksmart", "URL_Spider_SQL", "Firefly", "NationalDirectory",
        "Ask Jeeves", "TECNOSEEK", "InfoSeek", "WebFindBot", "girafabot",
        "crawler", "www.galaxy.com", "Googlebot", "Scooter", "Slurp",
        "msnbot", "appie", "FAST", "WebBug", "Spade", "ZyBorg", "rabaz",
        "Baiduspider", "Feedfetcher-Google", "TechnoratiSnoop", "Rankivabot",
        "Mediapartners-Google", "Sogou web spider", "WebAlta Crawler","TweetmemeBot",
        "Butterfly","Twitturls","Me.dium","Twiceler");

        foreach($botlist as $bot)
        {
            if(strpos($_SERVER['HTTP_USER_AGENT'], $bot) !== false)
            return true;
        }
    return false;
    }

    if (is_bot())
        $isbot = 1;
    else
        $isbot = 0;

    db_insert('ap_visits')
        ->fields(array(
            'id' => NULL,
            'length' => $t,
            'url' => $url,
            'current_ip' => $current_ip,
            'user_agent' => $user_agent,
            'date_start' => date("Y-m-d H:i:s"),
            'is_bot' => $isbot,
            'is_logout' => 0
        ))
        ->execute();

    db_set_active();
}

I'm wondering how can I put the first code to be called at the very top of the page and the second code (module) to be called in the footer. My purpose here is to compute the page load and put it in length variable.
BTW, I'm using drupal 7.
Comment: For what it's worth, I want to point out that putting a database write in hook_boot is an excellent way to create your very own denial of service attack.
Answer: hook_init() is run at the beginning of the page request. So this is where you should start your timer.
hook_exit() is run at the end of most regular page requests. And it's here you should stop your timer.
I did a search on similar modules and found Arooga, maybe you can find some ideas there. Also Devel has functionality to log page execution time, slow queries etc.
Comment: A variable exists only in it's function scope in PHP. To make a variable available in other functions you should be looking at making your variable global. define start first with global $start;
Comment: Thanks, should I use `hook_boot()` or `hook_init`? Because as what Jimajamma told me at this thread [link] (http://drupal.stackexchange.com/questions/81544/what-hook-to-use-to-execute-a-php-on-every-page), I need to use `hook_boot()`.
Comment: If you want to track even for cached pages yes, you should use hook_boot().
Comment: BTW, I received this error `PDOException: SQLSTATE[22003]: Numeric value out of range: 1264 Out of range value for column 'length' at row 1: INSERT INTO {ap_visits} (id, length, url, current_ip, user_agent, date_start, is_bot, is_logout) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :`. It seems that `$start` variable is not accessible in `hook_exit` function.


How is $-4/7$ the slope of $4x+7y=1$?

Question:
How is $-4/7$ the slope of $4x+7y=1$?

Can someone explain? I think they have divided the coefficients of $x$ and $y$.
Comment: Well, this raises the question of what the definition of a slope is.
Comment: Welcome to MSE! Yes indeed divide the entire equation by $7$ to "force" $y$ to have a coefficient of $1$ and then the other terms you take them to the other side and hence you get your equation in its standard form $y=ax+b$ where $a$ is the slope of the line.
Answer: It is a bit of algebra, but essentially you have:
$4x+7y=1,$
$7y=-4x+1,$
$y=-4/7x+1/7$
the slope is always a coefficient of the term containing $x$.
Comment: FYI [MathJax formula formatting guide](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference)
Comment: Speaking of algebra, what about that last $1$ in the last equation... ?
Comment: @user3733558 The 1 is called constant and if it is positive it shifts a graph in the direction of the y-axis, and if it is negative it shifts the function in the opposite direction. I recommend plotting it and play with constants in online graph software like https://www.desmos.com
Comment: If you divide the LHS by $7$, you probably need to divide *all* terms of the RHS by $7$ as well.
Comment: true, my mistake
Answer: Hints:-  For a linear equation $ax+by=c$, slop is always $-\dfrac{a}{b}$.
Answer: There's another neat way to think about slopes. Suppose $x$ is increased by $1$ unit. How should $y$ change so that that the resulting point is still on the line, i.e. the equation remains unchanged?
The new LHS is $$4(x+1) +7y = 4x+7y +4 $$ If $y$ is decreased by $\frac 47$, the change in $x$ cancels out: $$4x+7(y-\frac 47) +4 = 4x +7y -4+4 =4x+7y $$
The slope is therefore $-\frac 47$.
Comment: So effectively solving $4(x+1)+7(y+m)=4x+7y$ for $m$. That's good for linear equations, but should note that it won't work (straightforwardly) for other functions.
Comment: @Joffan Only linear functions are in question right now.
Comment: Yes; it's really a cautionary note for someone who comes to your answer looking for a general slope finding insight.
Comment: @Joffan Oh, I see.

How is $-4/7$ the slope of $4x+7y=1$?


add class to book navigation block links

Question: I use navigation block generated by block module. Tha block is displayes on all pages that belongs to book. I would like to add custom class to all links inside navigation block. I found that the block is generated by code here>
https://api.drupal.org/api/drupal/modules!book!book.module/function/book_block_view/7
But I am unable to figure out how to alter links. Any help appreciated. Thank you.
Answer: Give a try to Block class module: Block Class allows users to add classes to any block through the block's configuration interface. By adding a very short snippet of PHP to a theme's block.tpl.php file, classes can be added to the parent
 element of a block.
Comment: Hi, I need to add classes to links in menu, not to a block.
Comment: Try `menu attributes` module: https://www.drupal.org/project/menu_attributes for adding class to menu links.
Comment: I came across this, but one can not edit book menu.


where is the workingset info of an eclipse workspace stored?

Question: I have my eclipse workspace so setup so that everything required to run the eclipse IDE (eclipse neon, jdk and the workspace) are on the usb drive.
Before I created workingset in my workspace, this works all fine. I can move the usb drive to a different computer, mapping it to the same drive.
But after I created workingset on one computer, and move the usb drive to a different computer, I cannot get any of the projects displayed. The workingset I have created is available for selecting. But not matter I selected to use workingset or not, no project would show up in the project explorer.
The only solution I have right now is to recreate the workspace. But this defeat the purpose of having everything I need on the usb drive.
Comment: I think you should accept some of the answers which you got to your questions. As an act of gratitude you could also upvote the answers so the authors can get some reputation.
Answer: The working set information is kept in the workingsets.xml file in the workspace metadata folder .metadata/.plugins/org.eclipse.ui.workbench
Comment: My working sets have some duplicates that require fixing manually in `${workspace}\.metadata\.plugins\org.eclipse.jdt.ui\dialog_settings.xml`


Scrollbar in extjs tree panel does not work

Question: Sometimes it happens that the scrollbar of my tree panel does not work anymore. While it's still possible to move the scrollbar, the tree doesn't move at all anymore. That happens to me in Firefox and in Chrome as well.
Here is the source of my tree panel:

var treeStore = Ext.create('Ext.data.TreeStore', {
    proxy: {
        type: 'ajax',
        url: '../tree.pl'
    }
});
var tree = Ext.create('Ext.tree.Panel', {
    store: treeStore,
    renderTo: 'tree',
    title: 'Tree',
    width: 400,
    height: 450,
    rootVisible:false,
    dockedItems: [{
        xtype: 'toolbar',
        dock: 'bottom',
        items: [
        {
            xtype: 'tbspacer',
            width: 340
        },
        {
            text: 'Search',
            handler: function(){
                        names = [];
                        Ext.Array.each(tree.getView().getChecked(), function(rec){
                            names.push(rec.get('text'));
                        });
                    resultStore.load({
                        params:{
                            search_type: 'tree',
                            tree_nodes: names.join('II'),
                        }
                    });
                }
    }
    ]
}]

});
Comment: i dont see `autoScroll : true` in ur code
Comment: Yeah, that happened with me as well. I think this is extjs bug.
Comment: @astrocybernaute: I added the autoScroll config but it didn't help!?
Answer: I've had the same problem. They use custom scrollbar and it's pretty buggy (especialy in chrome). To remove custom scroller add the following to the config:
var tree = Ext.create('Ext.tree.Panel', {
  scroll          : false,
  viewConfig      : {
    style           : { overflow: 'auto', overflowX: 'hidden' }
  },
  // ...
});

I haven't tried it for treepanel. But it worked perfectly for the gridpanel (since both tree and grid are just extensions of Ext.panel.Table the solution should work for treepanel too).
Comment: This definitely works. Unfortunately I couldn't use it because it seems to break the scrolling when the up/down arrow keys are used to move through the tree. If anyone else needs that functionality, I shared a work-around here: http://stackoverflow.com/a/9036920/62694
Answer: The custom scrollers will be replaced with native scrolling again in Ext 4.1.  The virtualized scrollers were intended to support infinite scrolling, column locking, etc. but I believe in 4.1 they've managed to solve those and still retain native scrollbars.  I'd be surprised if the current issues in 4.0.x ever get resolved because of that.
Answer: In EXT 4.0, located within the ext-all.css file under resources of the main library, is the real reason that this doesn't work. The coders of this css file decided that the grid cell should have overflow: hidden; (around line 3324):
.x-grid-cell {
    overflow: hidden;
    font: normal 13px tahoma, arial, verdana, sans-serif;
    user-select: none;
    -o-user-select: none;
    -ms-user-select: none;
    -moz-user-select: -moz-none;
    -webkit-user-select: none;
    cursor: default
}

.x-grid-cell-inner {
    overflow: hidden;
    -o-text-overflow: ellipsis;
    text-overflow: ellipsis;
    padding: 3px 6px;
    white-space: nowrap
}

The best thing to do is to set the overflow to inherit for both classes and this problem is magically gone.
The only thing left is the border of the grid table, but that can be taken care of by just placing css styling in your css. I advice not to place it in the ext-all.css file.
.x-grid-table {
    border: none !important;
    width: auto !important;
}

Just remember that this will change it for any style that uses .x-grid-cell.
Answer: I'm using Ext 4.0.7.

scroll: true

works for me. But, for some reason, someone had added:

layout: anchor

to the configuration of the treepanel, which was causing it to stop working. If you find that scroll: true isn't working, try seeing if someone has added a layout and remove it.
Hope that helps.


Where did the octal/hex notations come from?

Question: After all of this time, I've never thought to ask this question; I understand this came from c++, but what was the reasoning behind it:

Specify decimal numbers as you
normally would
Specify octal numbers by a leading 0
Specify hexadecimal numbers by a leading 0x

Why 0?  Why 0x?  Is there a natural progression for base-32?
Comment: It came from C, not C++.  C++ simply kept it, since Stroustrup didn't want to introduce unnecessary incompatibilities between C and C++.
Comment: And hex constants weren't present in C in 1976.  http://www.cs.bell-labs.com/who/dmr/cman.ps
Comment: They're not present in BCPL or B.
Answer: C, the ancestor of C++ and Java, was originally developed by Dennis Richie on PDP-8s in the early 70s.  Those machines had a 12-bit address space, so pointers (addresses) were 12 bits long and most conveniently represented in code by four 3-bit octal digits (first addressable word would be 0000octal, last addressable word 7777octal).
Octal does not map well to 8 bit bytes because each octal digit represents three bits, so there will always be excess bits representable in the octal notation.   An all-TRUE-bits byte (1111 1111) is 377 in octal, but FF in hex.
Hex is easier for most people to convert to and from binary in their heads, since binary numbers are usually expressed in blocks of eight (because that's the size of a byte) and eight is exactly two Hex digits, but Hex notation would have been clunky and misleading in Dennis' time (implying the ability to address 16 bits).  Programmers need to think in binary when working with hardware (for which each bit typically represents a physical wire) and when working with bit-wise logic (for which each bit has a programmer-defined meaning).
I imagine Dennis added the 0 prefix as the simplest possible variation on everyday decimal numbers, and easiest for those early parsers to distinguish.
I believe Hex notation 0x__ was added to C slightly later.  The compiler parse tree to distinguish 1-9 (first digit of a decimal constant), 0 (first [insignificant] digit of an octal constant), and 0x (indicating a hex constant to follow in subsequent digits) from each other is considerably more complicated than just using a leading 0 as the indicator to switch from parsing subsequent digits as octal rather than decimal.
Why did Dennis design this way?  Contemporary programmers don't appreciate that those early computers were often controlled by toggling instructions to the CPU by physically flipping switches on the CPUs front panel, or with a punch card or paper tape; all environments where saving a few steps or instructions represented savings of significant manual labor.  Also, memory was limited and expensive, so saving even a few instructions had a high value.
In summary:
0 for octal because it was efficiently parseable and octal was user-friendly on PDP-8s (at least for address manipulation)
0x for hex probably because it was a natural and backward-compatible extension on the octal prefix standard and still relatively efficient to parse.
Answer: The zero prefix for octal, and 0x for hex, are from the early days of Unix.
The reason for octal's existence dates to when there was hardware with 6-bit bytes, which made octal the natural choice.  Each octal digit represents 3 bits, so a 6-bit byte is two octal digits.  The same goes for hex, from 8-bit bytes, where a hex digit is 4 bits and thus a byte is two hex digits.  Using octal for 8-bit bytes requires 3 octal digits, of which the first can only have the values 0, 1, 2 and 3 (the first digit is really 'tetral', not octal).
There is no reason to go to base32 unless somebody develops a system in which bytes are ten bits long, so a ten-bit byte could be represented as two 5-bit "nybbles".
Comment: I think the question relates to the origin of the syntax.
Answer: "New" numerals had to start with a digit, to work with existing syntax.
Established practice had variable names and other identifiers starting with a letter (or a few other symbols, perhaps underscore or dollar sign). So "a", "abc", and "a04" are all names. Numbers started with a digit. So "3" and "3e5" are numbers.
When you add new things to a programming language, you seek to make them fit into the existing syntax, grammar, and semantics, and you try to make existing code continue working. So, you would not want to change the syntax to make "x34" a hexadecimal number or "o34" an octal number.
So, how do you fit octal numerals into this syntax? Somebody realized that, except for "0", there is no need for numerals beginning with "0". Nobody needs to write "0123" for 123. So we use a leading zero to denote octal numerals.
What about hexadecimal numerals? You could use a suffix, so that "34x" means 3416. However, then the parser has to read all the way to the end of the numeral before it knows how to interpret the digits (unless it encounters one of the "a" to "f" digits, which would of course indicate hexadecimal). It is "easier" on the parser to know that the numeral is hexadecimal early. But you still have to start with a digit, and the zero trick has already been used, so we need something else. "x" was picked, and now we have "0x" for hexadecimal.
(The above is based on my understanding of parsing and some general history about language development, not on knowledge of specific decisions made by compiler developers or language committees.)
Answer: I dunno ...
0 is for 0ctal
0x is for, well, we've already used 0 to mean octal and there's an x in hexadecimal so bung that in there too
as for natural progression, best look to the latest programming languages which can affix subscripts such as
123_27 (interpret _ to mean subscript)
and so on
?
Mark
Comment: **x** sounds like **'ex** which is 18th century Cockney for "hexadecimal numeric literal."
Comment: Wow I was going to mark this -1 but then I saw @detly's comment and I realized that life is good, though this answer does start with "I dunno" and ends with a question mark and a signature.
Comment: Same. This is precisely how the rest of C was "designed".
Answer:
Is there a natural progression for base-32?

This is part of why Ada uses the form 16# to introduce hex constants, 8# for octal, 2# for binary, etc.
I wouldn't concern myself too much over needing space for "future growth" in basing though. This isn't like RAM or addressing space where you need an order of magnitude more every generation.
In fact, studies have shown that octal and hex are pretty much the sweet spot for human-readable representations that are binary-compatible. If you go any lower than octal, it starts to require a rediculous number of digits to represent larger numbers. If you go any higher than hex, the math tables get rediculously large. Hex is actually a bit too much already, but Octal has the problem that it doesn't evenly fit in a byte.
Answer: There is a standard encoding for Base32.  It is very similar to Base64.  But it isn't very convenient to read.  Hex is used because 2 hex digits can be used to represent 1 8-bit byte.  And octal was used primarily for older systems that used 12-bit bytes.  It made for a more compact representation of data when compared to displaying raw registers as binary.
It should also be noted that some languages use o### for octal and x## or h## for hex, as well as, many other variations.
Answer: I think it 0x actually came for the UNIX/Linux  world and was picked-up by C/C++ and other languages.  But I don't know the exact reason or true origin.
Comment: When it appeared in C, there was no such thing as Linux.  I'm not sure how many versions of Unix there were; it might have been just AT&T's.
Comment: C was created to help build the first Unix OSes. So early on the C "world" and the Unix "world" were the same world.
Comment: 0x is definitely post-unix and post-C. Both UNIX and C were shipping by 1976 without it.

it seems to have appeared by 1978 in "The C Programming Language", 1st Ed.
Comment: Ritchie's C History: http://cm.bell-labs.com/cm/cs/who/dmr/chist.html
Comment: Was Unix written is assembly and Linux in C?
Comment: Back in the old days of PDP computers, middle of the 60's, in assembly language programs numbers were implicitly written in octal.

See http://www.textfiles.com/bitsavers/pdf/dec/pdp8/software/DEC-08-CMAB-D_MACRO8.pdf  , 5-4-2.

So the convention of a leading 0 for octal was a step towards the use of the C programming language by mere mortals.


Change checkboxes in a node edit form alter

Question: I have a problem with an ajax function which doesn't work properly and I don't understand why. I done a similar thing long time ago in Drupal 7 and it seems I forget how it works.
I have a node type with terms references, a type and options. In the node edit, the selection for the type is a select list and for options it's a list of checkboxes. In function of this type, I want only show related options to my user.
Here my code:
function my_module_form_my_content_type_node_form_alter(&$form, &$form_state) {
  $form['field_options']['#prefix'] = '
';
  $form['field_options']['#suffix'] = '
';
  $form['field_types']['#ajax'] = [
    'callback' => 'ajax_options_choice',
    'wrapper' => 'options-choice',
    'method' => 'replace',
    'effect' => 'fade',
  ];
  if(isset($form_state['values']['field_types']) || isset($form['field_types'][LANGUAGE_NONE]['#default_value'][0])) {
    $type_tid = isset($form_state['values']['field_types'])? $form_state['values']['field_types']: $form['field_types'][LANGUAGE_NONE]['#default_value'][0];
    $type = taxonomy_term_load($type_tid);
    $type_option = $type->field_type_option[LANGUAGE_NONE][0]['value'];
    $bundle = "my_content_type";
    $results = db_query("SELECT nid, title FROM {node} as n inner join {field_data_field_is_$type_option} as fdf on n.nid = fdf.entity_id  WHERE n.type = :bundle AND n.status = '1' AND fdf.field_is_". $type_option . "_value = '1'", array(":bundle" => $bundle))->fetchAllKeyed(0, 1);
    $options = [];
    foreach ($results as $nid => $title) {
      $path_alias =  drupal_get_path_alias("node/$nid", "en");
      $value = ' ' . $title . ' ';
      $options[$nid] = $value;
    }
    $form['field_options'][LANGUAGE_NONE]['#options'] = $options;
  } else {
    $form['field_options'][LANGUAGE_NONE]['#options'] = [];
  }
}

function ajax_options_choice(&$form, &$form_state) {
  return $form['field_options'];
}

`

When I edit a content which have already a type, options are correctly limited. But when I change the value of the select list, the ajax doesn't seem work and options stay the same. I have no error in the firefox or chrome console so I suppose the ajax is simply not execute.
Additionnal questions:
Which ways can I test the ajax works or not? Is that possible to use dpm() in the callback?
Answer:
But when I change the value of the select list, the ajax doesn't seem
  work and options stay the same.

Simply because there is no db_query logic inside the ajax_options_choice callback.
How is Drupal suppose to know that it needs to run again the results db_query and then assign it to #options?
So essentially, currently, AJAX is executing, but you're just returning the same value that was calculated on initial page load.

Which ways can I test the ajax works or not?

function ajax_options_choice(&$form, &$form_state) {
  drupal_set_message('Yes AJAX was called');
  dpm('yay dpm works!');
  watchdog('my_module', 'ajax was fired', array(), WATCHDOG_NOTICE); // now check /admin/reports/dblog
  return $form['field_options'];
}

Comment: Thanks for your help. My condition was good (if my select has a value, Drupal relaunch correctly the db_query). My error was the field_types is a container which contains the select field form. So I finally fix my problem when I define my #ajax to the level of my "select", so $form['field_types'][LANGUAGE_NONE]['#ajax']. The ajax is finally call.


How can I write the text of QHeaderView's section into a file?

Question: I'm trying to write an exporter, which takes in a QTableView and writes all its data into a .csv-file, so it can be viewed in MS Excel.

Now I can't seem to find a way to read the text from the horizontal header's sections. There doesn't seem to be a method like QHeaderView::sections or something like that, so I can't access the QHeaderView's sections. There is a QHeaderView::count though, which makes me think that they are indeed saved in a container somewhere.

So is there a way to get the text of a section of QHeaderView?
Answer: You should use ::headerData method of your model.
To get number of columns you may use view->model()->columnCount(); method.
Comment: I fear it will come down to that. I was just hoping, there'd be a more convenient solution.
Comment: You should understand Qt MVC pattern. You could not pick data from view. View doesn't know anything about data.
Comment: Yes, of course, that makes sense. But why can I count the sections then? Isn't that a breach of the pattern?
Comment: No it doesn't. You should call `model->columnCount( QModelIndex() );` for that. In ideal case you should design your code to keep all data independend from view.
Comment: I probably _shouldn't_ get the count from the view, but i _could_ if I wanted to, which I find very strange. Anyway, I followed your suggestion and it works now. I also realized the benefits of keeping the data apart from the view. Thank you very much for your help.


Simulating potential outcomes with a binary outcome

Question: I want to create some simple simulations of potential outcomes to explore issues of confounding.  I start with a binary confounder X and a binary treatment A.  When my outcome is continuous, I can create the data generating model for the outcome Yc, and then simulate the counterfactuals by replacing A with 0 or 1.  In this case, Y=A*Y1.c + (1-A)*Y0.c is always true (the potential outcome under a given treatment A=a is always equal to the observed outcome when A=a).
library(tidyverse)

set.seed(0324)

x<- rbinom(100, 1, 0.3)
A<- rbinom(100, 1, (0.1 + 0.2*x))
Yc<- 4 + 3*x + 4*A
Y1.c<- 4 + 3*x + 4*1
Y0.c <-  4 + 3*x + 4*0

However, when I have a binary outcome, I'm not sure how to execute the same process.  I could start by simulating Y as a bernoulli random variable with  probability equal to some some linear combination of my treatment and confounder, where when x=0 and A=0 the probability is 0.1, when x=1 and A=0 the probability is 0.15, etc.
Yb <- rbinom(100, 1, (0.1 +0.05*x + 0.2*A))

However, this model is not deterministic like the linear equation was.  As a result, Y=A*Y1.c + (1-A)*Y0.c won't always be true (and in the below example, it's not true 27% of the time).
Y1.b <- rbinom(100, 1, (0.1 + 0.05*x + 0.2*1))
Y0.b <-rbinom(100, 1, (0.1 + 0.05*x + 0.2*0))

df <- data.frame(x,A,Yc, Y1.c, Y0.c, Yb, Y1.b, Y0.b) %>%
  mutate(discordant.b=ifelse(A==1 & Y1.b != Yb, 1,
                         ifelse(A==0 & Y0.b != Yb, 1, 0))) %>%
  mutate(discordant.c=ifelse(A==1 & Y1.c != Yc, 1,
                         ifelse(A==0 & Y0.c != Yc, 1, 0)))

summarize(df, mean(discordant.b), mean(discordant.c))

#  mean(discordant.b) mean(discordant.c)
1               0.27                  0

I can simulate it the other way, first by creating the potential outcomes and then by simply defining Y based the potential outcome
df <- df %>% mutate (Ynew= ifelse(A=1, Yb.1, Yb.0))

But this feels "backwards" to me.  Am I missing something? Is there a similar deterministic approach to a binary outcome? Or is the continuous outcome a special case where it's possible?
Comment: In my experience, it rarely makes sense to simulate potential outcomes. Instead, it is often easier to set up ("structural"/"causal") equations for the observed Y directly. In your case, this would simply be Y = 4 + 3*X + A + (error). Incidentally, this is what you are already doing for the X -> Y relationship.
Comment: Of possible interest: https://stats.stackexchange.com/questions/46523/how-to-simulate-artificial-data-for-logistic-regression
Answer: You are indeed simulating the data backward. You should simulate the potential outcomes first and then the outcomes from them. The "consistency equation" $Y = AY_1 + (1-A)Y_0$ describes the data-generating process for $Y$, the observed outcomes. The potential outcomes "occur" before the treatment is assigned in the formulation of causal inference that involves them. Potential outcomes exist for each individual prior to treatment assignment, and then treatment "reveals" one of the potential outcomes via the consistency equation. See my answer here about this very topic. This is also how you should generate your data.
The reason it appears to work in the reverse-ordered way you generated the potential outcomes for the continuous case is that you omitted a stochastic component to the potential outcomes, which is unrealistic. That is, if you generated your observed and potential outcomes more realistically as
Yc   <- 4 + 3*x + 4*A + rnorm(100)
Y1.c <- 4 + 3*x + 4*1 + rnorm(100)
Y0.c <- 4 + 3*x + 4*0 + rnorm(100)

you would also find disagreement between the generated observed outcome and the outcome implied by the consistency equation applied to the generated potential outcomes. Instead, you should generate your outcomes as follows:
Y1.c <- 4 + 3*x + 4*1 + rnorm(100)
Y0.c <- 4 + 3*x + 4*0 + rnorm(100)
Yc   <- A*Y1.c + (1-A)*Y0.c

which is more in line with the data-generating process implied by the consistency equation. For binary outcomes, you should do the same. Note that if you considered $p_Y = P(Y_i = 1)$ as the outcome in the binary case (i.e., omitting the step where you turn the probabilities into zeroes and ones using rbinom()), the probabilities would satisfy the consistency equation even in your reversed order because there is no stochastic component in generating them.


is "N -> N where g(n) = all integers > n" a function?

Question: I know this is probably not the best question, but I'm sitting on the fence about my answer because I'm not 100% sure of "Natural Numbers" definition. Does it include negatives or is it strictly positive? I'm just a tad confused for when I Google it the examples always include Z. ex. http://mathworld.wolfram.com/N.html
This is one side of the fence...(note: I'm not including 0 as a natural number)
"Not a function because g(1) has more than one value." (since it could be -ve or +ve?)
and this is the other..
"Is a function because g(1) is the lowest value since all others are greater" (If N only includes positive numbers)
Answer: The problem is that

$\Bbb N\to\Bbb N$ where $g(n)=\text{all integers }>n$

doesn't define anything. The notation $\Bbb N\to\Bbb N$ indicates that you're talking about a function whose domain is the set of positive integers, and that returns outputs that are also positive integers. That means that for each positive integer $n$, $g(n)$ has to be a single specific positive integer. It can't be a set of positive integers, because a set of positive integers isn't an element of the codomain ('target set') $\Bbb N$. It can't some indeterminate number greater than $n$, because it must be a specific value.
You could define a function $g:\Bbb N\to\Bbb N$ by setting $g(n)$ to be the smallest integer greater than $n$; that's the function $g(n)=n+1$. You could also define a function $g:\Bbb N\to\wp(\Bbb N)$ from $\Bbb N$ to the power set of $\Bbb N$, i.e., the set of all subsets of $\Bbb N$, by setting
$$g(n)=\{k\in\Bbb N:k>n\}\;,$$
i.e., by letting $g(n)$ be the set of all positive integers greater than $n$. This is a fine function; it just isn't a function from $\Bbb N$ to $\Bbb N$.


IIS 8.0 500.19 error on only the first request

Question: I am running IIS 8.0 locally on my machine for testing purposes. I have installed PHP through the web platform installer and everything is working correctly. The only issue I'm running into is the first request that's sent after the web server has started generates a 500.19 error. After the first initial request that generates the error everything works perfectly fine until the web server is shut down and started up again (or until my machine gets restarted). Here is a rundown of the error:
<code>Module             IIS Web Core
Notification       BeginRequest
Handler            Not yet determined
Error Code         0x80070005
Config Error       Cannot read configuration file due to insufficient permissions
Config File        \\?\C:\Users\Aaron\Programming\aaronjwood\web.config

Requested URL      http://dev:80/aaronjwood
Physical Path      C:\Users\Aaron\Programming\aaronjwood
Logon Method       Not yet determined
Logon User         Not yet determined
</code>
I'm not using any kind of web.config file since all of the code I'm working on is either written in PHP or Perl. Is this because it's looking for a web.config file but can't find one? Is there a way to tell IIS not to look for one? I am much more experienced with Apache so this error is new to me.
Answer: I figured this out. It was a silly mistake on my part. I didn't have the appropriate permissions on the directory. I needed to add the IIS_IUSRS group to the directory; I incorrectly had the IUSR user which allowed everything to work but not without throwing that initial error first.
Answer: Please check the folder that contains your web.config file. if that is shared on the network and remove the sharing. Doing this resolved the issue for me .


Disable links to username and date

Question: One of my tasks requires me to disable the links to username and date fields generated from diff_diffs_show() whose output is rendered as in the following screenshot.

The code outputting those links is the following one.
// Generate table header (date, username, log message).
$old_header = t('!date by !username', array(
  '!date' => l(format_date($old_node->revision_timestamp), "node/$node->nid/revisions/$old_node->vid/view", array('absolute' => 1)),
  '!username' => theme('username', array('account' => $node_revisions[$old_vid])),
));
$new_header = t('!date by !username', array(
  '!date' => l(format_date($new_node->revision_timestamp), "node/$node->nid/revisions/$new_node->vid/view", array('absolute' => 1)),
  '!username' => theme('username', array('account' => $node_revisions[$new_vid])),
));

How I can change the output of the function so that it doesn't output links?
Basically, I want the username  and date fields in plain texts instead of links.
Comment: Welcome to Drupal Answers! Is there any reason the link to the user accounts should be removed? Only users with the permission to access other user accounts would see the usernames are links. The users without that permission would just see the username as plain text. It's quite helpful to administrator users to have a link to the user account in revision pages. I would rather not change that.
Comment: The same is true for the link to the revision: Only users who can see revisions would see a link, and for those users is much helpful to see a link. I would not remove those links for users with the permission to administer nodes.
Answer: diff_diffs_show() is the page callback for the node/%node/revisions/view route. The only way to change the output for that route is changing the page callback with hook_menu_alter().
function mymodule_menu_alter(&$items) {
  $items['node/%node/revisions/view']['page callback'] = 'mymodule_diffs_show';
}

function mymodule_diffs_show($node, $old_vid, $new_vid, $state = NULL) {
  // Attaches the CSS.
  $build['#attached'] = diff_build_attachments();

  $default_state = variable_get('diff_default_state_node', 'raw');
  if (empty($state)) {
    $state = $default_state;
  }
  $state = str_replace('-', '_', $state);
  if (!array_key_exists($state, diff_available_states())) {
    $state = $default_state;
  }

  // Same title as the 'Revisions' tab. Blocked by non-page requests.
  if (node_is_page($node)) {
    drupal_set_title(t('Revisions for %title', array('%title' => $node->title)), PASS_THROUGH);
  }
  $node_revisions = node_revision_list($node);

  $old_node = node_load($node->nid, $old_vid);
  $new_node = node_load($node->nid, $new_vid);

  // Generate table header (date, username, log message).
  $old_header = t('!date by !username', array(
    '!date' => format_date($old_node->revision_timestamp),
    '!username' => format_username($node_revisions[$old_vid]),
  ));
  $new_header = t('!date by !username', array(
    '!date' => (format_date($new_node->revision_timestamp),
    '!username' => format_username($node_revisions[$new_vid]),
  ));

  $old_log = $old_node->log != '' ? '
' . filter_xss($old_node->log) . '
' : '';
  $new_log = $new_node->log != '' ? '
' . filter_xss($new_node->log) . '
' : '';

  // Generate previous diff/next diff links.
  $nav_suffix = ($default_state != $state) ? '/' . str_replace('_', '-', $state) : '';
  $next_vid = _diff_get_next_vid($node_revisions, $new_vid);
  if ($next_vid) {
    $next_link = l(t('Next difference >'), 'node/' . $node->nid . '/revisions/view/' . $new_vid . '/' . $next_vid . $nav_suffix, array('absolute' => 1));
  }
  else {
    $next_link = '';
  }
  $prev_vid = _diff_get_previous_vid($node_revisions, $old_vid);
  if ($prev_vid) {
    $prev_link = l(t('< Previous difference'), 'node/' . $node->nid . '/revisions/view/' . $prev_vid . '/' . $old_vid . $nav_suffix, array('absolute' => 1));
  }
  else {
    $prev_link = '';
  }

  $header = _diff_default_header($old_header, $new_header);
  $rows = array();
  if ($old_log || $new_log) {
    $rows['logs'] = array(
      array(
        'data' => $old_log,
        'colspan' => 2,
      ),
      array(
        'data' => $new_log,
        'colspan' => 2,
      ),
    );
  }
  $rows['navigation'] = array(
    array(
      'data' => $prev_link,
      'class' => array('diff-prevlink'),
      'colspan' => 2,
    ),
    array(
      'data' => $next_link,
      'class' => array('diff-nextlink'),
      'colspan' => 2,
    ),
  );

  $links = array();
  foreach (diff_available_states('node') as $alternative_state => $label) {
    $links[$alternative_state] = array(
      'title' => $label,
      'href' => "node/{$node->nid}/revisions/view/{$old_vid}/{$new_vid}" . ($alternative_state == $default_state ? '' : '/' . str_replace('_', '-', $alternative_state)),
    );
  }
  if (count($links) > 1) {
    $state_links = theme('links', array(
      'links' => $links,
      'attributes' => array('class' => array('links', 'inline')),
    ));
    $rows['states'] = array(
      array(
        'data' => $state_links,
        'class' => 'diff-links',
        'colspan' => 4,
      ),
    );
  }
  $rows = array_merge($rows, _diff_body_rows($old_node, $new_node, $state));

  $build['diff_table'] = array(
    '#theme' => 'table__diff__standard',
    '#header' => $header,
    '#rows' => $rows,
    '#attributes' => array('class' => array('diff')),
    '#colgroups' => _diff_default_cols(),
    '#sticky' => FALSE,
  );

  // Allow users to hide or set the display mode of the preview.
  if (node_is_page($node) && $view_mode = variable_get('diff_view_mode_preview_node_' . $new_node->type, 'full')) {
    $header = '';
    if ($node->vid == $new_vid) {
      $header .= '
' . t('Current revision:') . '
';
    }
    else {
      $header .= '
' . t('Revision of @new_date:', array('@new_date' => format_date($new_node->revision_timestamp))) . '
';
    }
    $build['diff_preview']['header']['#markup'] = $header;
    // Don't include node links or comments when viewing the diff.
    $build['diff_preview']['content'] = function_exists('entity_view') ? entity_view('node', array($new_node), $view_mode) : node_view($new_node, $view_mode);
    if (isset($build['diff_preview']['content']['links'])) {
      unset($build['diff_preview']['content']['links']);
    }
    if (isset($build['diff_preview']['content']['comments'])) {
      unset($build['diff_preview']['content']['comments']);
    }
  }
  return $build;
}

The part getting the username is simplified: The code should check the username length, and truncate it if it's longer than 20 characters; the username should also be sanitized via check_plain().
See template_preprocess_username() to understand how that can be implemented.
I would rather not implement the code shown in this answer, since:

The node/%node/revisions/view route is accessible by the users who have the administer nodes permission, who should be allowed to see any link to revision pages
The users without the access user profiles permission wouldn't see links to user accounts in any case, but the users with the administer users permission should be allowed to see link to user accounts in any page, as that simplifies their work
Comment: Thanks for answering my question. Actually I am using this diff module and token [node:diff-markdown] to send out the changes in a node in an email template. I don't want users who are getting these emails to have access to the links in the email they receive. I thought disabling the links here would solve the issue but the email template still contains the links for users and datefield. Is there a better way of achieving this solution?
Comment: Without more details, I would suggest to alter the sent email with [`hook_mail_alter()`](https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_mail_alter/7.x).

Disable links to username and date


Como não atualizar página ao fechar um modalPanel do RichFaces?

Question: Preciso que ao fechar um modalPanel do RichFaces a página na qual o modal foi chamado não seja renderizada.
A ação para fechar o modalPanel está assim:
<h:commandLink onclick="Richfaces.hideModalPanel('modalRegistroItemAnalise');">
    <h:graphicImage value="/img/delete2.jpg" width="15"></h:graphicImage>
</h:commandLink>

Quando estou clicando no botão fechar ao retornar à página ela está sendo renderizada e estou usando abas, ao renderizar a página está voltando para a primeira aba.
Como fazer?
Answer: Para não renderizar toda página basta aplicar o return false na sentença.
<h:commandLink onclick="Richfaces.hideModalPanel('modalRegistroItemAnalise'); return false;">
      <h:graphicImage value="/img/delete2.jpg" width="15"></h:graphicImage>
</h:commandLink>