why independence assumption not applicable on time series analysis?

Question: I just started my course in time series analysis. I saw a statement there: "Statistical methods that depend on independence assumption are no longer applicable in time series analysis". Why it so?
Comment: The present does depend on, and the future will depend on. whatever is past. Otherwise yesterday's temperature would have no possible bearing on today's and this year's sales would have no possible bearing on next year's sales. Independent noise does have a part to play in time series analysis, however.
Comment: As suggested by the remark at the end of @Nick's first comment, the quoted statement is not generally true.  For instance, ordinary regression methods that assume independent errors have many applications in the analysis of time series data.  This exposes the implicit meaning of "time series analysis" in the question: it refers to the analysis of particular *models* of time series data, ones that explicitly incorporate random variables that are not assumed to be independent.  For this *class of models,* statistical methods that assume independence obviously don't apply.
Comment: @NickCox: do you want to post your comment(s) as an answer? [Better to have a short answer than no answer at all.](https://stats.meta.stackexchange.com/a/5326/1352) Anyone who has a better answer can post it.
Comment: @StephanKolassa Thanks for the encouragement. (I was surprised not to find a duplicate of this, but I may also have missed it.)
Answer: The present does depend on, and the future will depend on, whatever is past. Without dependence, yesterday's temperature would have no possible bearing on today's and this year's sales would have no possible bearing on next year's sales.
That is true more broadly on many time scales, from astronomical or geological changes to short-term issues such as predicting tomorrow's weather or next year's economy. Translated into statistical terms, the overwhelming pattern is one of dependence in time series.
Naturally, it is often expected or hoped that the main structure of dependence can be caught by some fairly simple pattern of say trend, seasonality and the results of recent inputs. Conversely, time series analysis is often tricky if only because the future can be very unlike the past (qualitative changes can overwhelm quantitative changes) and because we may know little about a system beyond some data on its recent outputs and some fuzzy notions about its internal operations. Around 1900 there were many dire predictions that the increasing use of horses for transport in cities would overwhelm the means to cope with their direct and indirect consequences (stabling, feeding, accidents, waste removal, ...). Rise the internal combustion engine, and new worries emerged as the old problems faded away.
There are many different mechanisms underlying this, including memory, inertia or momentum in strict or broad senses and phenomena of growth or decay or decline.
Anticipatory behaviour is also important: buying presents or anything else ahead of the time you need them is standard at any scale from individual to international. In that sense the future can influence the present.
Independent noise does have a part to play in time series analysis, however, largely as a way to trying to mimic detailed variability that can't be explained otherwise.
Comment: +1. One aspect may be helpful: we may be able to model, say, seasonality using sine and cosine waves. Fair enough. But then typically the *residuals* from this "general" model will exhibit some kind of autocorrelation and dependence: if it is warmer than the (seasonally adjusted) average today, then it is likely that it will also be warmer than average tomorrow.
Answer: Many statistical methods assume independence of observations, because the probability of independent events happening simultaneously can be easily calculated as a product of their individual probabilities: $P(A \cap B) = P(A) \cdot P(B)$. This is extensively applied e.g. in maximum likelihood estimation of parameters. However, if your events are not independent, the above formula is not valid anymore.
It's a question of definition what constitutes a time series, but I think everyone agrees that time series include some memory effect. One can say that in time series, current observed value of a variable depends on the observed values (as opposed to modelled values!) at some previous time(s).
To take the above example of daily temperature: The temperature today depends in part on the season, which depends on the relative position of the Earth towards the Sun. Thus, you can model daily temperature through the Earth-Sun relationship. This relationship is physically a function of time, but that's not the reason why temperature is a time series. If we had the power to adjust the Earths position as we wish (as we do with independent variables in a controlled experiment) we could control the season and, consequently, the temperature---to a certain degree.
There is, however, another component to daily temperature: The heat capacity of the ground, the atmosphere, the oceans, etc. The heat that was absorbed yesterday is being emitted today, so yesterday's temperature by itself influences todays temperature. That's what makes daily temperature a time series.
For a counterexample, consider Moon's brightness. It oscillates monthly with Moon phases, but it is not a time series. Even if, due to some extraordinary event, tonight's brightness drastically changes (e.g. due to a Moon eclipse), this will have no effect whatsoever on the brightness tomorrow night! The Moon will be exactly as bright as if it would be without the tonight's eclipse.
You may argue that---barring extraordinary events---knowing yesternight's Moon brightness still allows you to quite precisely predict its brightness tonight. But, time is here just a correlate. It is conceptually the same as saying that knowing the force a spiral spring exerts at an elongation $x$ allows you to quite precisely predict the force exerted at the elongation $x + \Delta x$. If the spring oscillates, the force will vary with time, but it will not vary because of time.
Deciding whether a data set constitutes a time series can be tricky and require substantial domain knowledge. Asking yourself whether some magical manipulation of the outcome at one time point would affect it at some later time is, in my opinion, a useful approach.
Comment: Re "everyone agrees ... memory effect:" If "memory effect" implies non-independence of random variables, I beg to differ, and in support of that consider the answer at https://stats.stackexchange.com/a/126830/919. Your claim that [regular observations of the moon's brightness] is "not a time series" runs counter to most definitions and characterizations of time series.  That makes your answer appear idiosyncratic and in need of some authoritative support to be made more credible.


How to notate staccato on notes tied across a barline?

Question: I'm a bit stuck on how I feel it's most appropriate to place staccato in a piece I'm writing.
The excerpt below is not from the piece I'm working on -- I just wrote up a phrase to show how this situation presents in the piece.

How would you play this if you came across it in a piece you were practicing? Do the neighboring staccato crotchets provide enough context to indicate that the tied semiquavers should be played the same way?
Comment: Why would you do this in the first place? If the note is staccato, it won't be exactly _tied over_ anyway. Consider just notating all the syncopes as simple quavers without any dots. –Although, I will admit that that "feels" a bit different.
Comment: If this is a "swing" piece, then just add written instructions, as the final eighth note would be played very late, almost onto the next downbeat.   So it really depends on where you wanted the note to end.
Answer: If you want the note to be abbreviated, the dot must be on the last of the tied notes only.  If there is a dot (or even a tenuto bar) on the first note, this indicates that the first note is detached from the second, meaning that any accompanying slur will be a phrasing or technical slur (like on a violin where slurs indicate the absence of a bowing direction change) but not a tie forming a single note duration.
With regard to the execution, an eighth tied to a dotted eighth is executed like a dotted quarter note.  This can be counterintuitive when you articulate a dotted quarter as short or shorter than a full eighth since the "second note" formally can be over before it even starts.  But there really is no way to notate syncopes differently if the execution of staccato is left to the discretion of the performer.
Comment: Agreed.  If I wanted the last eighth note to "just barely last past the next downbeat" I'd use the tie and a dot on the downbeat's eighth note.
Comment: I really don't think this answer is correct, especially as you mention tenuto. Unlike staccato, tenuto on a tied-over note definitely can make sense, and in that case you should put certainly put it on the _first_ note (i.e. before the barline), so the accent-effect of the tenuto actually affects the whole note. Putting the tenuto on the downbeat would mean to emphasize that beat, i.e. that's what would basically un-tie the notes.
Comment: @user69878 you are correct, the dot must be in the second note. If the dot was on the first note it would be played separately from the second note. In order to avoid the whole problem it would be better to avoid the tie and instead write a short note without a tie. In the OP's example that would be an eight note which is followed by a pause in the next bar.
Answer: If you really want this, then put the dot just under the actual played note, not under the tied-over one.
X:1
L:1/8
M:C
K:C
%%score T1
V:T1           clef=treble
% 1
[V:T1] ([DB]2 [Gc]) z .[Fd]2 z .[DB]-| [DB] z .[B,DA]2 z .[B,FG]2 B,

Having multiple dots within a note, even a tied one, would imply you actually want multiple attacks on it. This is presumably never found in piano, but it's quite common with bowed string instruments. For instance, this
X:1
L:1/8
M:C
K:C
%%score T1
V:T1           clef=treble
% 1
[V:T1] (.c.c .c.c) (.c.c .c.c)

would mean you should only move the bow back and forth once, but bounce on each of the individual notes with the bow (spiccato).
Comment: Regarding spiccato: Spiccato is a technique used on bowed string instruments. Often it is up to the player whether to use a spiccato bowing technique or some other bowing technique when there are dots above or below the notes. It is wrong that spiccato would need to be a fast tempo. You can play spiccato in any tempo from slow to fast. But it will need practice to do it in any tempo, with any dynamic and with any string crossing. If the tempo gets very fast the spiccato stroke transforms into a sautillé stroke. Some people might use the term spiccato also when the stroke is actually sautillé.
Comment: Good points, but that's not spiccato - it's more just indicating not to change bow direction.  Spiccato is pretty much limited to fast note groups.   But the RealProblem(TM) is that the placement of a dot on the first eighth is confusing at best.
Comment: Well, it depends on the tempo whether to actually use spiccato, but the point is that each of the notes has a distinct attack in it.
Comment: About the RealProblem I disagree, but if you have references for your opinion then do bring them forth.


Cannot change date input format in views exposed filter

Question: I am unable to change the date format for an exposed field in views. I am using BEF datepicker popup. I overrode the jquery settings to get it to enter a UK date in the dd-mm-yy format but because views is expecting it in mm-dd-yy form, the results of the filter are wrong.
This problem is addressed in this discussion https://www.drupal.org/node/1409120 but supposedly has been fixed for other people in Date 7.x 2.x. I am using BEF 7.x-3.0-beta4, Date 7.x-2.9-alpha1+2-dev, and Views 7.x-3.8, and the problem isn't fixed. I can't see any extra options in the view settings or in the config menu to change the date format.
The field name is field_activity_date_time and I have created a custom module with the following code, based on other stackoverflow suggestions (I don't have a max and min field, just a single date)
function hook_form_views_exposed_form_alter(&$form, &$form_state) {
    if($form['#id'] == 'views-exposed-form-test-page') {
       $form['field_activity_date_time']['#date_format'] = 'd/m/Y';
      }
    }
}

I have tried a number of different possibilities for the array key, such as 'activity_date_time', and 'views_field_activity_date_time', none of which worked. This date field is coming from a CiviCRM table which may be why the other suggestions haven't worked, but it feels to me more of a drupal problem than a civicrm one.

as suggested by harsh in the comments, I have used a different hook, but the problem still persists...
function HOOK_form_alter(&$form, &$form_state, $form_id){
  if ($form_id == 'views_exposed_form' && $form_state['view']->name == 'test' && $form_state['view']->current_display == 'page') {
     $form['activity_date_time']['#date_format'] = 'd/m/Y';
     echo '
';
     print_r($form);
     echo '
';
 }
}

This gave me the following
Array
(
    ...

    [activity_date_time] => Array
        (
            [#type] => textfield
            [#size] => 30
            [#default_value] =>
            [#attributes] => Array
                (
                    [class] => Array
                        (
                            [0] => bef-datepicker
                        )

                )

            [#date_format] => d/m/Y
        )
)

Comment: function MYMODULE_form_alter(&$form, &$form_state, $form_id){

if ($form_id == 'views_exposed_form' && $form_state['view']->name == 'test' && $form_state['view']->current_display == 'page') {

print_r($form);exit;

}}
Comment: you can try this else if ($form_id == 'views_exposed_form' && $form_state['view']->name == 'abc_view_name' && $form_state['view']->current_display == 'page')
Comment: Using dpm() i added your code and tested which if statement it was executing, but it only enters my if statement in the OP.
Comment: you have to add form alter, in that fnction call this if statement where you can find the view name by using export your view display name in advance section
Comment: I did that, exporting the view to get the name (simply 'test') and still nothing... full code else if ($form_id == 'views_exposed_form' && $form_state['view']->name == 'test' && $form_state['view']->current_display == 'page')
{
 dpm($form);
}
Comment: Perhaps this is because of the hook I am using in the module - I have updated the OP
Comment: Thanks - I have updated the post but the problem still persists
Answer: Well, I am not proud of the clunky fix but it works!
function gmcvo_date_format_views_query_alter (&$view, &$query){
    $newDate = DateTime::createFromFormat('Y-d-m H:i:s', $query->where[1]['conditions'][0]['value']);
    $query->where[1]['conditions'][0]['value'] = $newDate->format('Y-m-d H:i:s');
}

If someone has a better way to do this it would be great to hear it...
edited to use the new datetime object instead of strtotime


How do I fix a "The requested URL /user/login was not found on this server." error?

Question: I am currently migrating a Drupal 8 site from one cloud server to another. The servers are Ubuntu and CentOS (AWS EC2) respectively. After copying the files and exporting-importing the database, I am able to see the home page successfully on the new server.
However, whenever I click on any link or enter any path in the browser, I get the following error:

Not Found
The requested URL /user/login was not found on this server.

What can I check to eliminate this error? I thought this may have something to do with clean URLs, but it seems that Drupal 8 deprecated that setting. What else can I try?
Edit:
Here is the .htaccess file in case it helps:
<code>#
# Apache/PHP/Drupal settings:
#

# Protect files and directories from prying eyes.
<FilesMatch "\.(engine|inc|install|make|module|profile|po|sh|.*sql|theme|twig|tpl(\.php)?|xtmpl|yml)(~|\.sw[op]|\.bak|\.orig|\.save)?$|^(\.(?!well-known).*|Entries.*|Repository|Root|Tag|Template|composer\.(json|lock))$|^#.*#$|\.php(~|\.sw[op]|\.bak|\.orig|\.save)$">
  <IfModule mod_authz_core.c>
    Require all denied
  </IfModule>
  <IfModule !mod_authz_core.c>
    Order allow,deny
  </IfModule>
</FilesMatch>

# Don't show directory listings for URLs which map to a directory.
Options -Indexes

# Set the default handler.
DirectoryIndex index.php index.html index.htm

# Add correct encoding for SVGZ.
AddType image/svg+xml svg svgz
AddEncoding gzip svgz

# Most of the following PHP settings cannot be changed at runtime. See
# sites/default/default.settings.php and
# Drupal\Core\DrupalKernel::bootEnvironment() for settings that can be
# changed at runtime.

# PHP 5, Apache 1 and 2.
<IfModule mod_php5.c>
  php_value assert.active                   0
  php_flag session.auto_start               off
  php_value mbstring.http_input             pass
  php_value mbstring.http_output            pass
  php_flag mbstring.encoding_translation    off
  # PHP 5.6 has deprecated $HTTP_RAW_POST_DATA and produces warnings if this is
  # not set.
  php_value always_populate_raw_post_data   -1
</IfModule>

# Requires mod_expires to be enabled.
<IfModule mod_expires.c>
  # Enable expirations.
  ExpiresActive On

  # Cache all files for 2 weeks after access (A).
  ExpiresDefault A1209600

  <FilesMatch \.php$>
    # Do not allow PHP scripts to be cached unless they explicitly send cache
    # headers themselves. Otherwise all scripts would have to overwrite the
    # headers set by mod_expires if they want another caching behavior. This may
    # fail if an error occurs early in the bootstrap process, and it may cause
    # problems if a non-Drupal PHP file is installed in a subdirectory.
    ExpiresActive Off
  </FilesMatch>
</IfModule>

# Set a fallback resource if mod_rewrite is not enabled. This allows Drupal to
# work without clean URLs. This requires Apache version >= 2.2.16. If Drupal is
# not accessed by the top level URL (i.e.: http://example.com/drupal/ instead of
# http://example.com/), the path to index.php will need to be adjusted.
<IfModule !mod_rewrite.c>
  FallbackResource /index.php
</IfModule>

# Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on

  # Set "protossl" to "s" if we were accessed via https://.  This is used later
  # if you enable "www." stripping or enforcement, in order to ensure that
  # you don't bounce between http and https.
  RewriteRule ^ - [E=protossl]
  RewriteCond %{HTTPS} on
  RewriteRule ^ - [E=protossl:s]

  # Make sure Authorization HTTP header is available to PHP
  # even when running as CGI or FastCGI.
  RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

  # Block access to "hidden" directories whose names begin with a period. This
  # includes directories used by version control systems such as Subversion or
  # Git to store control files. Files whose names begin with a period, as well
  # as the control files used by CVS, are protected by the FilesMatch directive
  # above.
  #
  # NOTE: This only works when mod_rewrite is loaded. Without mod_rewrite, it is
  # not possible to block access to entire directories from .htaccess because
  # <DirectoryMatch> is not allowed here.
  #
  # If you do not have mod_rewrite installed, you should remove these
  # directories from your webroot or otherwise protect them from being
  # downloaded.
  RewriteRule "(^|/)\.(?!well-known)" - [F]

  # If your site can be accessed both with and without the 'www.' prefix, you
  # can use one of the following settings to redirect users to your preferred
  # URL, either WITH or WITHOUT the 'www.' prefix. Choose ONLY one option:
  #
  # To redirect all users to access the site WITH the 'www.' prefix,
  # (http://example.com/foo will be redirected to http://www.example.com/foo)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} .
  # RewriteCond %{HTTP_HOST} !^www\. [NC]
  # RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
  #
  # To redirect all users to access the site WITHOUT the 'www.' prefix,
  # (http://www.example.com/foo will be redirected to http://example.com/foo)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  # RewriteRule ^ http%{ENV:protossl}://%1%{REQUEST_URI} [L,R=301]

  # Modify the RewriteBase if you are using Drupal in a subdirectory or in a
  # VirtualDocumentRoot and the rewrite rules are not working properly.
  # For example if your site is at http://example.com/drupal uncomment and
  # modify the following line:
  # RewriteBase /drupal
  #
  # If your site is running in a VirtualDocumentRoot at http://example.com/,
  # uncomment the following line:
  # RewriteBase /

  # Redirect common PHP files to their new locations.
  RewriteCond %{REQUEST_URI} ^(.*)?/(install.php) [OR]
  RewriteCond %{REQUEST_URI} ^(.*)?/(rebuild.php)
  RewriteCond %{REQUEST_URI} !core
  RewriteRule ^ %1/core/%2 [L,QSA,R=301]

  # Rewrite install.php during installation to see if mod_rewrite is working
  RewriteRule ^core/install.php core/install.php?rewrite=ok [QSA,L]

  # Pass all requests not referring directly to files in the filesystem to
  # index.php.
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^ index.php [L]

  # For security reasons, deny access to other PHP files on public sites.
  # Note: The following URI conditions are not anchored at the start (^),
  # because Drupal may be located in a subdirectory. To further improve
  # security, you can replace '!/' with '!^/'.
  # Allow access to PHP files in /core (like authorize.php or install.php):
  RewriteCond %{REQUEST_URI} !/core/[^/]*\.php$
  # Allow access to test-specific PHP files:
  RewriteCond %{REQUEST_URI} !/core/modules/system/tests/https?.php
  # Allow access to Statistics module's custom front controller.
  # Copy and adapt this rule to directly execute PHP files in contributed or
  # custom modules or to run another PHP application in the same directory.
  RewriteCond %{REQUEST_URI} !/core/modules/statistics/statistics.php$
  # Deny access to any other PHP files that do not match the rules above.
  # Specifically, disallow autoload.php from being served directly.
  RewriteRule "^(.+/.*|autoload)\.php($|/)" - [F]

  # Rules to correctly serve gzip compressed CSS and JS files.
  # Requires both mod_rewrite and mod_headers to be enabled.
  <IfModule mod_headers.c>
    # Serve gzip compressed CSS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.css $1\.css\.gz [QSA]

    # Serve gzip compressed JS files if they exist and the client accepts gzip.
    RewriteCond %{HTTP:Accept-encoding} gzip
    RewriteCond %{REQUEST_FILENAME}\.gz -s
    RewriteRule ^(.*)\.js $1\.js\.gz [QSA]

    # Serve correct content types, and prevent mod_deflate double gzip.
    RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1]
    RewriteRule \.js\.gz$ - [T=text/javascript,E=no-gzip:1]

    <FilesMatch "(\.js\.gz|\.css\.gz)$">
      # Serve correct encoding type.
      Header set Content-Encoding gzip
      # Force proxies to cache gzipped & non-gzipped css/js files separately.
      Header append Vary Accept-Encoding
    </FilesMatch>
  </IfModule>
</IfModule>

# Add headers to all responses.
<IfModule mod_headers.c>
  # Disable content sniffing, since it's an attack vector.
  Header always set X-Content-Type-Options nosniff
</IfModule>
</code>
Comment: does index.php/user/login work? sounds like some apache configuration is not correct, either it doesn't allow .htaccess overrides or mod_rewrite is disabled or something like that
Comment: The `user/login` URL does not work.
Comment: I enabled the rewrite using this tutorial: https://devops.profitbricks.com/tutorials/install-and-configure-mod_rewrite-for-apache-on-centos-7/
however, the URLs still do not work.
Comment: Do you run drush on production? Might help to run 'drush updb && drush cr'. What's you folder? Defaults '/web'?
Answer: It sounds like .htaccess does not exist in the root. Check that the provided Drupal 8 .htaccess file exists in the application root.
Comment: It does. Is there a way to check that it is working?
Comment: If it does then it sounds like mod_rewrite or related apache config is incorrect or missing.
Comment: I posted an edit to the question to include the  .htaccess.
Comment: Thanks. I uploaded an .htaccess file and it started working.
Answer: You can try to access like this? http://[domain-name]/~[user-name]/user/login
some check userDir directive in your apache configuration ...
https://www.drupal.org/project/drupal/issues/359540


Converter de decimal ou inteiro para horas em php

Question: Tenho o resultado em decimal ou inteiro das horas:

Utilizador 1 = 71.5 horas
Utilizador 2 = 137 horas

Queria converter dentro do php para horas, como exemplo:

Utilizador 1 = 71:30
Utilizador 2 = 137:00

Estou a utilizar este código no while para chegar às horas em decimal ou inteiro:
$Total = 0;
while ($rows_cursos = mysqli_fetch_array($resultado_cursos)) {
  $teste = $rows_cursos['Horas Consumidas'];
  $tempo = explode(":", $teste);
  $tempototal = $tempo[0]*60 + $tempo[1];
  $Total = $Total + $tempototal;
}
$Total = $Total/60;

Answer: De forma simples:
function convertHoras($horasInteiras) {

    // Define o formato de saida
    $formato = '%02d:%02d';
    // Converte para minutos
    $minutos = $horasInteiras * 60;

    // Converte para o formato hora
    $horas = floor($minutos / 60);
    $minutos = ($minutos % 60);

    // Retorna o valor
    return sprintf($formato, $horas, $minutos);
}

Em seu código:
$Utilizador1 = 0.5;
$Utilizador2 = 137;

echo 'Utilizador 1: ' . $Utilizador1 = convertHoras($Utilizador1) . ' horas';
echo PHP_EOL;
echo 'Utilizador 2: ' . $Utilizador2 = convertHoras($Utilizador2) . ' horas';

Resultado:
Utilizador 1: 00:30 horas
Utilizador 2: 137:00 horas

Veja funcionando no Ideone
Comment: Se `$minutos` é menor que 60, `$horas` sempre será 0, então aquela operação, `floor($minutos / 60)`, seria desnecessária.
Comment: @AndersonCarlosWoss verdade cara !
Comment: Mas como aplico com o código que tenho essa função?
Comment: @Iniciante Acabei de postar
Comment: Poderia até fazer um `if` para o cálculo de horas caso os minutos forem menores que 60, mas eu não vejo necessidade, pois se irá chegar condição e execução (no caso maior) seriam 2 passos contra 1, e caso minutos forem menor, será um passo de verificação ou já o `floor`direto.
Comment: Coloquei assim, mas não funciona: `$tabela4 .= 'Total de Horas Consumidas: ' . $Horas = convertHoras($Horas) . ' horas';`
Comment: Você está declarando a variável `$Horas` dessa forma. O correto é `' . echo convertHoras($Horas) . '`
Answer: Uso essa function:
function converterParaHora($dec)
{
    $seg = ($dec * 3600);
    $hor = floor($dec);
    $seg -= $hor * 3600;
    $min = floor($seg / 60);
    $seg -= $min * 60;
    return lz($hor).":".lz($min).":".lz($seg);
}

A ideia veio daqui: https://stackoverflow.com/questions/9102680/how-to-convert-a-decimal-into-time-eg-hhmmss


How to specify a condition on a @ManyToMany while still eager loading all entities?

Question: I have a Restaurant entity, that can have many Cuisines (Italian, Sushi, etc.):
/**
 * @ORM\Entity
 */
class Restaurant
{
    /**
     * @ORM\ManyToMany(targetEntity="Cuisine")
     */
    protected $cuisines;
}

When I load a list of restaurants, I want to eager load its cuisines, to avoid a round-trip to the database when calling getCuisines() on each restaurant. Using DQL:
SELECT r, c
FROM Model\Restaurant r
LEFT JOIN r.cuisines c

All good.
Now if I want to return all restaurants that contain a given cuisine, I can use this DQL:
SELECT r
FROM Model\Restaurant r
LEFT JOIN r.cuisines c
WHERE c.id IN (?)

That's fine as well. Now if I want to do both at the same time:
SELECT r, c
FROM Model\Restaurant r
LEFT JOIN r.cuisines c
WHERE c.id IN (?)

The list of restaurants will be correct, but their $cuisines will only be populated with the ones whose ID match the given list. This totally breaks the model.
How can I restrict the returned restaurants by cuisine, while still eager loading the full list of cuisines?
Comment: When you received the restaurants, couldn't you just get the cuisines by getting the ArrayCollection with r->getCousines()?
Answer: If you don't mind having it always eager load cuisines:
/**
 * @ManyToMany(targetEntity="Cuisine", fetch="EAGER")
 */

Otherwise... it's hard.  If it were OneToMany you could temporarily change it for just that query: http://doctrine-orm.readthedocs.org/en/latest/reference/dql-doctrine-query-language.html#temporarily-change-fetch-mode-in-dql
But with a ManyToMany you can't do it on a per-query basis.
Comment: Sorry, it *is* a `OneToMany` at the moment (maybe it shouldn't). I updated the question code to match the title. I didn't know that eager fetching actually executed a second query (this is good!): I thought that it transparently joined the second table. I can't find anywhere in the doc you pointed to, that this is specific to `OneToMany`, though? What prevents it from being used on a `ManyToMany`?
Comment: Argh, I'm getting confused. It **is** a `ManyToMany` with a join table at the moment. I updated the question again. still, is it anywhere mentioned that the temporary fetch mode doesn't work on `ManyToMany`?
Comment: It says on that page: "Changing the fetch mode during a query is only possible for one-to-one and many-to-one relations."
Comment: I needed sleep. Indeed, it's written pretty clearly. I'm not against setting it permanently in the annotation, but I just tested this, and it doesn't seem to be taken into account when using DQL. It still performs N+1 queries; is this fetch mode maybe only effective when using `find*()` methods in the entity manager / repositories?
Answer: Maybe I am getting this wrong, but normally you should be able to get the whole ArrayCollection without specifying it in the query.
$qb = $em->createQueryBuilder();
$qb->select('r')
   ->from('Model\Restaurant', 'r')
   ->leftJoin('r.cuisines', 'c')
   ->where('c.id IN ?1')
   ->setParameter(1, $ids);
$query = $qb->getQuery();
$result = $query->getResult();

foreach ($result as $restaurant){
    //contains the whole arrayCollection
    var_dump($restaurant->getCuisines());
}

In your Restaurant Entity make sure to have a constructor.
public function __construct() {
    $this->cuisines = new ArrayCollection();
}

Comment: As I'm mentioning in the question, it works, but it performs N+1 queries, where N is the number of restaurants. The whole point is to do it in 1 query with eager loading.
Answer: In your current query you limit the result set by the properties of the Cuisines model - thus you will not get all relations of the restaurant you are trying to fetch. Try using a subselect as follows:
SELECT r, c
FROM Model\Restaurant r
LEFT JOIN r.cuisines c
WHERE r.id IN (
    SELECT DISTINCT sr.id
    FROM Model\Restaurant sr
    LEFT JOIN sr.cuisines sc
    WHERE sc.id IN (?)
)

Explanation: The sub select executes the same query that you developed above to fetch both at the same time. However, we are only returning the restaurant ids that fulfill the criteria. Then, in the main select we fetch all those restaurants with all their cuisines.
Comment: It's a ManyToMany relationship, so Cuisines don't have a `restaurantId`!
Comment: You are absolutely right! I am sorry to not have seen the hint. I updated the query to reflect the `manyToMany` relationship. Now it should work how you expect it to work.


mean of $Y=|X|$?

Question: Given the pdf $f(x) = \frac{1}{\sqrt{2\pi}} \exp{\frac{-x^2}{2}}$ find the mean for $Y$.
I have calculated the pdf $g(y) = \frac{2}{\sqrt{2\pi}} \exp{\frac{-y^2}{2}}$.
Then working out the E(Y)
$E(Y) = \int_0^{\infty} \frac{2y}{\sqrt{2\pi}} \exp{\frac{-y^2}{2}}dy = \frac{-2}{\sqrt{2\pi}} \exp{\frac{-y^2}{2}}\vert_0^{\infty}-\int_0^{\infty}\frac{-1}{y\sqrt{2\pi}} \exp{\frac{-y^2}{2}}dy$
In the solutions that I have the last integral term doesn't exist. Where did I go wrong in my calculation or is there a reason why it is $=0$?
Answer: It appears you attempted to do some kind of integration by parts, where instead a simple substitution would suffice:  $$\int_{y=0}^\infty \frac{2y}{\sqrt{2\pi}} e^{-y^2/2} \, dy$$ with the substitution $$u = y^2/2, \quad du = y \, dy$$ gives $$\int_{u=0}^\infty \frac{2}{\sqrt{2\pi}} e^{-u} \, du = \sqrt{\frac{2}{\pi}} \left[ -e^{-u} \right]_{u=0}^\infty = \sqrt{\frac{2}{\pi}}. $$
Comment: wait i get it. if i take the derivative then it doesn't work. it's not equal. thanks!
Comment: make sense. thanks. Shouldnt integration by parts mathematically give the same answer though?
Comment: @LB2015 What is your choice of $u$, $du$, $v$, and $dv$ in your proposed integration by parts; that is to say, how would you apply the formula $$\int u \, dv = uv - \int v \, du?$$
Comment: $u = y$ and $dv = exp{-y^2/2}$
Comment: @LB2015 and if you choose $dv = e^{-y^2/2} \, dx$, what would $v$ be?
Comment: $\frac{-1}{y} exp(\frac{-y^2}{ 2})$ and thats where i get stuck .. because the $y$ doesnt disappear

mean of $Y=|X|$?


.class in css not working proplerly how to fix?

Question: Basically I made a class called botao for all the icons and buttons and icons or buttons image and put it in all of those elements in the html and then try to made their width and height equal to 10% so that I can see how it was but their sizes didn't change and I don't know why. Basically the css was supposed to change their size to 10% of the height and width of the whole page. What's going on here? How to solve it?

html, body {
  margin:0;
   min-height: 100%;
   font-family: "Helvetica Neue", Helvetica, sans-serif;
   color: #444;
   -webkit-font-smoothing: antialiased;
   background-image: url("http://wallpaperask.com/wp-content/uploads/Amazing-1920x1080-HD-wallpaper.jpg");
   background-position: center;
   background-repeat: no-repeat;
   -webkit-background-size: cover;
 -moz-background-size: cover;
 -o-background-size: cover;
 background-size: cover;
   font-family: Arial, Helvetica, sans-serif;
   zoom:100%;
}

.botao{
 width:10%;
 height:10%;
}
/************** TOGGLE BUTTON***********************/
.switch {
    position: relative;
    display: inline-block;
    right:0px;
    width: 200px;
    height: 34px;
    padding:20px;
  }

.switch input {display:none;}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ca2222;
  -webkit-transition: .30s;
  transition: .30s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 50px;
  width: 50px;
  left: 10px;
  bottom: 10px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked + .slider {
  background-color: #2ab934;
}

input:focus + .slider {
  box-shadow: 0 0 1px #2196F3;
}

input:checked + .slider:before {
  -webkit-transform: translateX(160px);
  -ms-transform: translateX(160px);
  transform: translateX(160px);
}

/*------ ADDED CSS ---------*/
.on
{
  display: none;
}

.on, .off
{
  color: white;
  position: absolute;
  transform: translate(-50%,-50%);
  top: 50%;
  left: 50%;
  font-size: 30px;
  font-family: Verdana, sans-serif;
}

input:checked+ .slider .on
{display: block;}

input:checked + .slider .off
{display: none;}

/*--------- END --------*/

/* Rounded sliders */
.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;}
/*******************************************SHUTDOWN BUTTON********************************/
#BtnTesteLogout{
  background-color: Transparent;
  background-repeat:no-repeat;
  border: none;
  cursor:pointer;
  overflow: hidden;
}

#LOGOUT{
    position: relative;
}

/*******************************************Split Screen, WIFI, Bluetooth*********************************/
#SSbutton, #WIFIButton, #BlueButton{
  background-color: Transparent;
  background-repeat:no-repeat;
  border: none;
  cursor:pointer;
  overflow: hidden;
}

#SplitScreen{

}

#WIFI{

}

#Bluetooth{

}

#SplitScreen button img, #WIFI button img,#Bluetooth button img{

  background-color: Transparent;
}

.clockdate-wrapper {
  background-color: none;
  padding:25px;
  max-width:500px;
  width:100%;
  text-align:center;
  border-radius:5px;
  margin:0 auto;
  height:300px;
  position: absolute;
  top:40px;
  right: 100px;
  border-radius: 15%;
}
#clock{
  background-color:none;;
  font-family: sans-serif;
  font-size:100px;
  text-shadow:0px 0px 1px #fff;
  color:#fff;
}
#clock span {
  color:white;
  text-shadow:0px 0px 1px black;
  font-size:50px;
  position:relative;
  top:-27px;
  left:-10px;
}
#date {
  letter-spacing:10px;
  font-size:50px;
  font-family:arial,sans-serif;
  color:#fff;
}

/**************************************************************************WIFI DROPDOWN********************************************************/

/**************************************************************************BLUETTOTH WINDOW****************************************************/
#BlueWindow{
  position: absolute;
  width:1900px;
  height:1500px;
  left:1500px;
  top:550px;
  border-radius:10px black solid;
  z-index: 10000;
}

#BlueWindowheader{
  height: 100px;
    background: rgb(30,87,153); /* Old browsers */
    background: -moz-linear-gradient(top, rgba(30,87,153,1) 0%, rgba(41,137,216,1) 50%, rgba(32,124,202,1) 51%, rgba(125,185,232,1) 100%); /* FF3.6-15 */
    background: -webkit-linear-gradient(top, rgba(30,87,153,1) 0%,rgba(41,137,216,1) 50%,rgba(32,124,202,1) 51%,rgba(125,185,232,1) 100%); /* Chrome10-25,Safari5.1-6 */
    background: linear-gradient(to bottom, rgba(30,87,153,1) 0%,rgba(41,137,216,1) 50%,rgba(32,124,202,1) 51%,rgba(125,185,232,1) 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#1e5799', endColorstr='#7db9e8',GradientType=0 ); /* IE6-9 */
}

#closeBlue{
    width: 75px;
    height: 75px;
    top:0px;
    left:0px;
    background-color: none;
    position:absolute;
}

#JoanaPTexto{
  color:black;
  text-align:center;
  text-shadow: 3px 2px grey;
  font-size:50px;
  top: 20px;
  position: relative;
}

#DocImgBlue{
  width: 400px;
  height: 400px;
  background-color: none;
  padding:40px;
}

#bottomBlue{
  background-color:white;
  height:1415px;
  border-bottom-left-radius:5%;
  border-bottom-right-radius:5%;
}

#MariaDoc{
  position: absolute;
  left:140px;
  top:575px;
}

#closeButtonBlue{
  width: 75px;
    height: 75px;
    background-color: none;
    padding:5px;
    top: 45px;
    position: absolute;
    right:10px;
    background-color: Transparent;
    background-repeat:no-repeat;
    border: none;
    cursor:pointer;
    overflow: hidden;
}
#doc1{
  z-index:10010;
}
/**************************************************************************BLUETOOTH DROPDOWN**************************************************/
#BlueButton{
}

#wrapperB {
  color: #ffcccc;
  top: 100px;
  width: 400px;
}

#dispos{
  color:black;
}

a {
  text-decoration: none;
  color: inherit;
}

nav ul ul {
  -webkit-transition: all 500ms ease-in-out 500ms;
  -moz-transition: all 500ms ease-in-out 500ms;
  -ms-transition: all 500ms ease-in-out 500ms;
  -o-transition: all 500ms ease-in-out 500ms;
  transition: all 500ms ease-in-out 500ms;
  -webkit-transform: rotateX(-90deg);
  -moz-transform: rotateX(-90deg);
  -ms-transform: rotateX(-90deg);
  -o-transform: rotateX(-90deg);
  transform: rotateX(-90deg);
  -webkit-transform-origin: 0% 0%;
  -moz-transform-origin: 0% 0%;
  -ms-transform-origin: 0% 0%;
  -o-transform-origin: 0% 0%;
  transform-origin: 0% 0%;
  -webkit-backface-visibility: hidden;
  -moz-backface-visibility: hidden;
  -ms-backface-visibility: hidden;
  -o-backface-visibility: hidden;
  backface-visibility: hidden;
  -webkit-box-shadow: 0px -100px 500px rgba(0,0,0,0);
  box-shadow: 0px -100px 500px rgba(0,0,0,0);
}

nav ul li:hover > ul {
  -webkit-transition: all 500ms ease-in-out 0ms;
  -moz-transition: all 500ms ease-in-out 0ms;
  -ms-transition: all 500ms ease-in-out 0ms;
  -o-transition: all 500ms ease-in-out 0ms;
  transition: all 500ms ease-in-out 0ms;
  -webkit-transform: rotateX(0deg);
  -moz-transform: rotateX(0deg);
  -ms-transform: rotateX(0deg);
  -o-transform: rotateX(0deg);
  transform: rotateX(0deg);
  -webkit-box-shadow: 10px 10px 10px rgba(0,0,0,0.1);
  box-shadow: 10px 10px 10px rgba(0,0,0,0.1);
}

nav ul {
  padding: 0;
  list-style: none;
  position: relative;
  display: inline-table;
  border-radius: 5px;
  -webkit-transform-style: preserve-3d;
  transform-style: preserve-3d;
  -webkit-perspective: 200px;
  -ms-perspective: 200px;
  perspective: 200px;
}

nav ul:after {
  content: "";
  clear: both;
  display: block;
}

nav ul li {
  float: left;
  -webkit-transform-style: preserve-3d;
  transform-style: preserve-3d;
  -webkit-perspective: 200px;
  -ms-perspective: 200px;
  perspective: 200px;
  border-right: 1px solid #890456;
}

nav ul > li:last-of-type {
  border-right: none;
  border-radius: 0 5px 5px 0;
}

nav ul span li { border-right: 1px solid #890456; }

nav ul li:first-of-type { border-radius: 5px 0 0 5px; }

#mphone:hover>a,#jphone:hover > a { color: #fff; }
#dispos:hover > a {color:none}

nav ul li a {
  display: block;
  padding: 10px 31px 10px 32px;
}

#wrapperB #mainB #subB {
  position: absolute;
  top: 400px;
  padding: 0;
  right: 20px;
  width:1000px;
  height:400px;
  border-radius: 0 0 5px 5px;
/* Permalink - use to edit and share this gradient: http://colorzilla.com/gradient-editor/#a7cfdf+0,23538a+100;Blue+3d+%238 */
background: #a7cfdf; /* Old browsers */
background: -moz-linear-gradient(-45deg, #a7cfdf 0%, #23538a 100%); /* FF3.6-15 */
background: -webkit-linear-gradient(-45deg, #a7cfdf 0%,#23538a 100%); /* Chrome10-25,Safari5.1-6 */
background: linear-gradient(135deg, #a7cfdf 0%,#23538a 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#a7cfdf', endColorstr='#23538a',GradientType=1 ); /* IE6-9 fallback on horizontal gradient */
}

#wrapperB #mainB #subB li {
  float: none;
  position: relative;
  border: none;
}

.bottom{
  font-size:75px;
}

nav ul ul li:last-of-type { border-radius: 0 0 5px 5px; }

nav ul ul li a { padding: 8px 21px; }

/**************************************************************************SS DROPDOWN*************************************/
#SSButton{
}

#wrapperSS {
  color: black;
  top: 100px;
  width: 700px;
}

a {
  text-decoration: none;
  color: inherit;
}

nav ul ul {
  -webkit-transition: all 500ms ease-in-out 500ms;
  -moz-transition: all 500ms ease-in-out 500ms;
  -ms-transition: all 500ms ease-in-out 500ms;
  -o-transition: all 500ms ease-in-out 500ms;
  transition: all 500ms ease-in-out 500ms;
  -webkit-transform: rotateX(-90deg);
  -moz-transform: rotateX(-90deg);
  -ms-transform: rotateX(-90deg);
  -o-transform: rotateX(-90deg);
  transform: rotateX(-90deg);
  -webkit-transform-origin: 0% 0%;
  -moz-transform-origin: 0% 0%;
  -ms-transform-origin: 0% 0%;
  -o-transform-origin: 0% 0%;
  transform-origin: 0% 0%;
  -webkit-backface-visibility: hidden;
  -moz-backface-visibility: hidden;
  -ms-backface-visibility: hidden;
  -o-backface-visibility: hidden;
  backface-visibility: hidden;
  -webkit-box-shadow: 0px -100px 500px rgba(0,0,0,0);
  box-shadow: 0px -100px 500px rgba(0,0,0,0);
}

nav ul li:hover > ul {
  -webkit-transition: all 500ms ease-in-out 0ms;
  -moz-transition: all 500ms ease-in-out 0ms;
  -ms-transition: all 500ms ease-in-out 0ms;
  -o-transition: all 500ms ease-in-out 0ms;
  transition: all 500ms ease-in-out 0ms;
  -webkit-transform: rotateX(0deg);
  -moz-transform: rotateX(0deg);
  -ms-transform: rotateX(0deg);
  -o-transform: rotateX(0deg);
  transform: rotateX(0deg);
  -webkit-box-shadow: 10px 10px 10px rgba(0,0,0,0.1);
  box-shadow: 10px 10px 10px rgba(0,0,0,0.1);
}

nav ul {
  padding: 0;
  list-style: none;
  position: relative;
  display: inline-table;
  border-radius: 5px;
  -webkit-transform-style: preserve-3d;
  transform-style: preserve-3d;
  -webkit-perspective: 200px;
  -ms-perspective: 200px;
  perspective: 200px;
}

nav ul:after {
  content: "";
  clear: both;
  display: block;
}

nav ul li {
  float: left;
  -webkit-transform-style: preserve-3d;
  transform-style: preserve-3d;
  -webkit-perspective: 200px;
  -ms-perspective: 200px;
  perspective: 200px;
  border-right: 1px solid #890456;
}

nav ul > li:last-of-type {
  border-right: none;
  border-radius: 0 5px 5px 0;
}

nav ul span li { border-right: 1px solid #890456; }

nav ul li:first-of-type { border-radius: 5px 0 0 5px; }

#mergeall:hover>a,#split2:hover > a,#split4:hover > a, #split6:hover > a  { color: green; }

nav ul li a {
  display: block;
  padding: 10px 31px 10px 32px;
}

#wrapperSS #mainSS #subSS {
  position: absolute;
  top: 400px;
  padding: 0;
  right: 20px;
  width:800px;
  height:400px;
  border-radius: 0 0 5px 5px;
  /* Permalink - use to edit and share this gradient: http://colorzilla.com/gradient-editor/#f6e6b4+0,ed9017+100;Yellow+3D+%231 */
background: #f6e6b4; /* Old browsers */
background: -moz-linear-gradient(-45deg, #f6e6b4 0%, #ed9017 100%); /* FF3.6-15 */
background: -webkit-linear-gradient(-45deg, #f6e6b4 0%,#ed9017 100%); /* Chrome10-25,Safari5.1-6 */
background: linear-gradient(135deg, #f6e6b4 0%,#ed9017 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f6e6b4', endColorstr='#ed9017',GradientType=1 ); /* IE6-9 fallback on horizontal gradient */
}

#wrapperSS #mainSS #subSS li {
  float: none;
  position: relative;
  border: none;
}

.bottom{
  font-size:75px;
}

nav ul ul li:last-of-type { border-radius: 0 0 5px 5px; }

nav ul ul li a { padding: 8px 21px; }
/********************************************BOTTOM BAR***********************************/
/* Place the navbar at the bottom of the page, and make it stick */
.navbar {
    background-color: none;
    left: 30%;
    position: absolute;
    bottom: 0;
    height: 500px;
    width: 1500px;
    margin-left: auto;
    margin-right: auto;
    padding-left: 10%;
    padding-right: 10%;
    border-top-right-radius: 30px;
    border-top-left-radius: 30px;
    text-align: center;
    overflow: hidden;
  }

  #NetImg, #contact{

      padding:20px;
      background: none;
  }

  /************************************************MAIN************************************/
  #net{
    position: absolute;
    width:3505px;
    height:1500px;
    left:1500px;
    top:550px;
    border-radius:10px black solid;
    z-index: 000;
  }

  #janela{
    position: absolute;
    width:1900px;
    height:1500px;
    left:1500px;
    top:550px;
    border-radius:10px black solid;
    z-index: 000;
  }

  #closeDocs, #closeNet{
    width: 75px;
    height: 75px;
    background-color: none;
    padding:5px;
    top: 35px;
    position: absolute;
    right:20px;
  }

  #docsHeadTexto,#NetTexto{
    color:black;
    text-align:center;
    text-shadow: 3px 2px grey;
    font-size:50px;
    top: 20px;
    position: relative;
  }

  #netBottom{
    background-color:white;
    height:2515px;
    width: 3500px;
    left:-1px;
    top:130px;
    position: absolute;
    border-bottom-left-radius:0%;
    border-bottom-right-radius:0%;
  }

  .windowTop,.windowTop2,.windowTop1{
    height: 100px;
    background: rgb(30,87,153); /* Old browsers */
    background: -moz-linear-gradient(top, rgba(30,87,153,1) 0%, rgba(41,137,216,1) 50%, rgba(32,124,202,1) 51%, rgba(125,185,232,1) 100%); /* FF3.6-15 */
    background: -webkit-linear-gradient(top, rgba(30,87,153,1) 0%,rgba(41,137,216,1) 50%,rgba(32,124,202,1) 51%,rgba(125,185,232,1) 100%); /* Chrome10-25,Safari5.1-6 */
    background: linear-gradient(to bottom, rgba(30,87,153,1) 0%,rgba(41,137,216,1) 50%,rgba(32,124,202,1) 51%,rgba(125,185,232,1) 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#1e5799', endColorstr='#7db9e8',GradientType=0 ); /* IE6-9 */
  }

  #DocImg{
    width: 400px;
    height: 400px;
    background-color: none;
    padding:40px;
  }

  #bottomWindowDocs{
    background-color:white;
    height:1415px;
    border-bottom-left-radius:5%;
    border-bottom-right-radius:5%;
  }

  #DocEx{
    position: absolute;
    left:140px;
    top:575px;
  }

  /****************************************************** CONTACTOS *************************************/
  /****************************************************** Calendario ************************************/
  #calendar{
    position:absolute;
    height:3000px;
    width:4000px;
    top:300px;
    left:800px;
  }

  #janelaCalendario{
    z-index:0000;
  }

  #iconeCal{
  }

  #janelaCalendarioHeader{
    position: absolute;
    top:200px;
    left:800px;
    width:4005px;
  }

  #closeCal{
    position: absolute;
    top:10px;
    left:3900px;
    height: 90px;
    width:90px;
  }
<!DOCTYPE html>

<title>Desk+ - Grupo 36</title>
<link rel="stylesheet" type="text/css" href="PF1.1.css">

    <button onclick="location.href = 'PF1.html';" id="BtnTesteLogout" class="float-left submit-button" ></button>

 <input type="checkbox" id="togBtn">
ONOFF

Dispositivos emparelhados:

Joana's Phone

Maria's Phone

Juntar todos os ecr&atildes

Dividir em 2

Dividir em 4

Dividir em 6

            <button id="WIFIButton" class=botao></button>

                <button id="closeButtonBlue"></button>

Joana's Phone

Doc-exemplo-Joana

Documentos

Doc-exemplo

Desk+ Browser

Also some elements of the class .botao are not appearing
Comment: In the html, mention only one or two instances of the elements which are not working per your stylesheet. Helps in readability
Answer: One of the general rules of CSS specificity is that id is more specific than class.
Let's take a line of code from your code:
If you have a look in the element inspector for styles, you can see your botao class's width and height are being overwritten (stroked off) by #BlueButton's width and height.
This is the reason why your image size is not 10% and as a fix to this you can assign BlueButton to the preceding anchor tag (if you don't have any tight dependency on id and element type).
Comment: I've updated that I'll change the css now and tell me what u think the problem is still
Comment: Please let me know once you are done making edits to your question
Comment: With this change, your element with id WIFIButton works!
Answer: Try  .botao img{ width:10%; height:10%; }
here is your edited code:
<!DOCTYPE html>

<title>Desk+ - Grupo 36</title>
<link rel="stylesheet" type="text/css" href="PF1.1.css">

    <button onclick="location.href = 'PF1.html';" id="BtnTesteLogout" class="float-left submit-button" ></button>

 <input type="checkbox" id="togBtn">
ONOFF

Dispositivos emparelhados:

Joana's Phone

Maria's Phone

Juntar todos os ecr&atildes

Dividir em 2

Dividir em 4

Dividir em 6

            <button id="WIFIButton" class="botao"></button>

                <button id="closeButtonBlue"></button>

Joana's Phone

Doc-exemplo-Joana

Documentos

Doc-exemplo

Desk+ Browser

Comment: these is the wrong method  {class="botao" class="front" } instead of these  write class="botao  front"
Comment: i did it but because of that the backgroung got bugged
Comment: Please do not use class attribute twice in a single html element
Comment: Is it not possible?
Comment: If i write it like that if I do in css .front it still gets me that button or img?
Comment: yes, it will if your using twice class attribute in a single element then only left one is work , other is not going to work


Invariant under topologies under action of $S_n$

Question: Suppose we a set X of n elements. How many topologies invariant topologies do we have on X under the action of $S_n$ on it, i.e if $\tau$ is invariant under $S_n$ iff  $M \in \tau$, then $\sigma(M) \in \tau$, where $\sigma \in S_n$.
I think it is 2 the discrete and indiscrete topology as we can always permutate the singletons of the topologies, but only topology which doesn't have singletons is the indiscrete topology and the topology which contains all its singleton is the discrete topology. I don't have formal proof of this however.
Answer: If $\tau$ has a open set $A\ne \varnothing$ and $A\neq X$ then there are $a\in A$ and $b\not \in A$. The permutation $\sigma =(a\, b)$ send $A$ to $B=A\backslash \{a\}\cup \{b\}$, so $B$ is open.
Thus $B\cap A=A\backslash \{a\}$ is open and has $1$ element less than $A$. Keep doing so, we get a singleton which is an open set and $\tau$ is the discreet topology.
Comment: Why is B open ?
Comment: $B=\sigma(A)$, and $\tau$ is invariant under $S_n$.
Comment: Yeah I didn't notice that..
Answer: Yeah, it's only the discrete topologies and the indiscrete topologies. This follows from the fact that if every subset of size $k<|X|$ is in a topology on $X$, then the topology is discrete. Proof: By induction. Base case is trivial.
Let $S$ be any set of size $k-1$ and suppose every subset of size $k$ is in the topology. Choose any subset $U$ of size $k$ which contains $S$. Since $|X|$ is strictly larger than $k$, there is some element $e$ which is not in $U$, so define $V=S\cup\{e\}$. But then $U\cap V=S$.
Since $S$ was arbitrary, the topology contains all sets of size $k-1$, and so by induction it is discrete.
Comment: I don't follow your proof. "Base case is trivial" -- What is the base case here?
Comment: The base case is when you plug $k=1$ into the statement: "If every set of size $1$ is in a topology on $X$, then the topology is discrete".
Comment: Then why do you "suppose every subset of size $k$..." and show the statement for $k-1$?
Comment: Ah, I see the confusion. We're not showing the *statement* for $k-1$, we're assume the antecedent for the $k$ case, and proving the antecedent for the $k-1$ case. In other words, we assume that every subset of size $k$ is in the topology, and prove that therefore every subset of size $k-1$ is in the topology. Then the inductive hypothesis says that in this situation, we know the topology is discrete, and we are done. (My plan is actually the same as yours; just with some formalism around it.)
Comment: So the base case is $k=1$, and what does your argument imply?
Comment: Consider the $k=4$ case. I know all size-4 subsets are in there, so I take an appropriate intersection to show that all size-3 subsets are in there, and (then the induction gets me) that all size-2 subsets are in there, and so all size-1 subsets are in there, and so it's discrete.
Comment: I see that your idea is similar to mine now. It may be your wording is a little different (than mine).


How to open a div with button click and closing all other divs at the same time in jQuery

Question: How can I show a specific div element with a button click and close all other elements at the same time in jQuery?
For example, I tired:
   $('.button').each(function(i) {
    $(this).click(function() {
            $('.details').eq(i).slideToggle("slow")
            $('.button').eq(i);
        });
    });

.details {
  background: grey;
  display: none;
}

.is-open {
  display: block;
}

<button id="button0" class="button">button 1</button>
<button id="button1" class="button">button 2</button>
<button id="button2" class="button">button 3</button>

Details Person 1

Details Person 2

Details Person 3

But this only toggles one elements without closing the others. But I want to close every opened element by clicking the one which isn't opened already.
I tried it with the suggested siblings() method but this did not apply for my case because I have my button elements separated from the button elements.
What is the best solution to achieve such an effect described above?
Answer: Do you want to implement the tab?
https://jqueryui.com/tabs/
$('.button').each(function (i) {
  $(this).click(function () {
    $('.details').eq(i).show("slow").siblings('.details').hide();
  });
});

Answer: Here is my solution:

$('.button').each( function(index,button){
        //console.log(button.outerHTML);
    $(button).click(function(){
        let  id=this.id.replace("button","");
      $(".details").hide()
      $("#details"+id).show();
    })
});
.details {
  background: grey;
  display: none;
}

.is-open {
  display: block;
}

<button id="button0" class="button">button 1</button>
<button id="button1" class="button">button 2</button>
<button id="button2" class="button">button 3</button>

Details Person 1

Details Person 2

Details Person 3

Answer: If you adjust your HTML to have data attributes where each button data-id corresponds to a data-id on a details element it makes it much simpler.

// Use event delegation to listen to events from the buttons
$(document).on('click', 'button', handleClick)

function handleClick() {

  // Grab the id from the button
  const id = $(this).data('id');

  // Remove all the `show` classes from the details elements
  $('.details').removeClass('show');

  // And then add that class back on to the details element
  // that corresponds to the id
  $(`.details[data-id=${id}]`).addClass('show');
}
.details { background: grey; display: none; }
.show { display: block; }

<button data-id="1">button 1</button>
<button data-id="2">button 2</button>
<button data-id="3">button 3</button>

Details Person 1

Details Person 2

Details Person 3

Additional documentation

Event delegation
Template/string literals


Bootstrap: nav bar wont color

Question: I got a problem with my bootstrap nav bar. It wont color the way I want it too and I tried adding code even with the !import but I can't get it to work

        <button class="navbar-toggler navbar-toggler-right" type="button" style="background: green !important;" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">

        </button>
        Jeroen Hooge

                    Product (current)

                    Werk

                    Prijs

                    Team

                    Blog

                    Contact

This is what my code looks like but it won't color the background green only for the first milisecond or something.
If I inspect the website you can see on the left that it somehow makes it a different color and I don't know why There is nothing in the css making it that color. If I am on the top of the website it makes it transparent and if I scrol this color
Comment: change `background` to `background-color`
Comment: Doesnt matter it won't change either way @ZombieChowder
Comment: `"background: green !important;"` working for me !
Comment: May be other css is conflicting here,recheck all css by inspecting.
Comment: @Anuresh it isnt working for me.
Comment: Do u have a fiddle or site ?
Comment: @KhushbuVaghela it all links to the same css and there is nothing that makes it that color, not even in the css that are not even in use
Answer: In head tag
<link rel="stylesheet" href="/css/bootstrap.css">
    <link rel="stylesheet" href="/css/style.css">

Just before the closing of Body Tag

Just check if you have added this correctly (or all the files).
Answer: You might need to check whether you are trying to change a css of already having !important
And already you are using the class bg-light which color your nav too. Remove it.

        <button class="navbar-toggler navbar-toggler-right" type="button" style="background: green !important;" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">

        </button>
        Jeroen Hooge

                    Product (current)

                    Werk

                    Prijs

                    Team

                    Blog

                    Contact

Bootstrap: nav bar wont color


Retrieve data from two different tables and output into a column value

Question: I have 2 tables like
id  item deliveredon
 1    x   12/06/2016
 2    y   14/06/2016
 3    z   18/06/2016

and
id item Returnedon
4   a    20/06/2016
5   b    15/06/2016
6   c    22/06/2016

now i have only id's like 1, 3, 5, 6 in query(complaint)
 i want output like
id  item  status     date
1    x    delivered  12/06/2016
3    z    delivered  18/06/2016
5    b    returned   15/06/2016
6    c    returned   22/06/2016

sql query for above output in sql server 2008. I have tried some JOINS and CASE statements. Those ids come from a excel cell values in a column.
Answer: How about selecting from a union where you specify the status per table:
select id
, item
, status
, date
from (select id, item, deliveredon as date, 'delivered' as status from
table1
union all select id, item, Returnedon, 'returned' from
table2
) i
where id in (1, 3, 5, 6)

Answer: Maybe something like that?
SELECT * FROM
(
SELECT id,  item,  status, deliveredon as  date
FROM TableA
UNION
SELECT id,  item,  status, Returnedon  as  date
FROM TableB
) as TableAB Where id IN(1, 3, 5, 6)

I don't know your criterion to select that ID's but if you choose it manually it works perfectly.
Answer: select
Id,
Item,
"Status" = case
when R.ReturnedOn is not null then 'returned'
when D.DeliveredOn is not null then 'delivered'
end,
"Date" = ISNULL(R.ReturnedOn, D.DeliveredOn)
from [DeliveryDates] D
full outer join
[ReturnedDates] R
on R.Id = D.Id
where Id in (1,3,5,6)

Personally, here's how I would implement your design:
table [Shipments]

Id item DeliveredDate ReturnDate
 1    x   12/06/2016   NULL
 2    y   14/06/2016   NULL
 3    z   18/06/2016   NULL
 4    a    NULL      20/06/2016
 5    b    NULL      15/06/2016
 6    c    NULL      22/06/2016

then it would become:
select
Id,
Item,
"Status" = case
when ReturnedOn is not null then 'returned'
when DeliveredOn is not null then 'delivered'
end,
"Date" = ISNULL(ReturnedOn, DeliveredOn)
from [Shipments]
where Id in (1,3,5,6)

Answer: (select id,item,'delivered' as status,deliveredon from #table1 where id in (1,3,5,6))
UNION
(select id,item,'returned' as status,Returnedon from #table2 where id in (1,3,5,6))

or
    select id, item, status, date
    from (select id, item, 'delivered' as status, deliveredon as date from #table1
    UNION
    select id, item,'returned' as status, Returnedon from #table2 ) t
    where id in (1, 3, 5, 6)


Cauchy Principal Value Problem: Gaussian and exponential over a quadratic

Question: I need help with the following integral:
$$ \int_{-\infty}^{\infty}\frac{e^{-x^2}e^{iax}}{1-x^2}dx$$
Where $a$ is real.
Obviously the integral doesn't converge due to the singularities at $|x|=1$ but I am interested in the principal value of this integral. However I am confused about whether to take my contour above or below each of the singularities.
Any help will be appreciated :)
Comment: For $a=0$ we have $I=\dfrac\pi e\text{erfi}(1)$. Otherwise, even its principal value seems to diverge.
Answer: I'm not sure you can find this PV in closed form. But you can set the odd part to 0 and use symmetry to reduce it to
$$
2 PV \int_{0}^{\infty} \dfrac{e^{-x^2}\cos ax}{1-x^2} dx
$$
For a real PV, you would omit an interval of length $\epsilon$ on either side of the singularity.
$$
I = 2 \left ( \lim_{\epsilon \rightarrow 0 } \int_{0}^{1-\epsilon}\dfrac{e^{-x^2}\cos ax}{1-x^2} dx + \lim_{\epsilon \rightarrow 0 } \int_{1+\epsilon}^{\infty}\dfrac{e^{-x^2}\cos ax}{1-x^2} dx \right )
$$
In the complex plane, you would join the ends of the excised intervals by a semi-circle of radius $\epsilon$ above the x-axis to get a contour that excluded the singularities.
Don't know if that helps.


What does ABRSM mean by Musical Shape and Musical Tone?

Question: The marking criteria for ABRSM Performance exams comprises Pitch, Rhythm, Tone, Shape and Performance.

What is (Musical) Shape?
What is (Musical) Tone?

For context, I'm learning to play piano, essentially a percussion instrument with hammers and control pedals. Other instruments e.g. wind, string will be different.
Answer: According to ABRSM themselves, shape is 'effectiveness and clarity of musical shaping and detail'. And tone is 'control and projection of the sound, sensitivity and awareness in use of tonal qualities'.
So, put more simply, shape has to do with the phrasing used whilst playing, and tone to do with the dynamics.
Any piece can be phrased in different ways, rather like words in a sentence can be delivered differently, sometimes making the opposite sense from that which the writer wanted. So, playing the phrases in the style of the writer, or more musically, will give more marks,surely.
True, a piano has strings and hammers, but regardless, will be capable of being played in many different ways, and that's before pedalling gets involved. Dynamics include legato/staccato and volume changes from ppp to fff with all stops in between, let alone crescendo and diminuendo. Lots to think about!
Comment: Well, a hair-splitter might argue that legato and staccato are not "dynamics," but the point stands.


IPython Notebook Multiple Checkpoints

Question: I see that IPython Notebook has a menu item: File > Revert to Checkpoint, but this never contains more than a single entry for any of my notebooks.
Is there a way to allow this menu to hold multiple checkpoints? I can't find documentation about how to do this anywhere on the web.
Thanks.
Also, I put in the green box as a highlight.
Comment: What happened to this option?? I don't see it in 2.0
Answer: Bookstore (post on rackspace) is the only storage backend that supports multiple checkpoints for now. We hope that someone will write a git backend at some point. It will just not come from the core team soon.
If you are motivated to do so, we'll be happy to give you pointers.
Comment: @Matt if I wanted to write a git backend supporting multiple checkpoints, is there a good link to read to get started? I narrowly avoided some catastrophic data loss and I'm feeling motivated at the moment.
Comment: Does version 3 support multiple checkpoints? I did not find anything in the documentation.
Comment: All version have the **API** to support multiple checkpoint. It is just not in the default implementation. It's like asking "does my computer support multiple keyboard". Yes it does, but it probably only ship with one, but you can buy a second keyboard and plug it in.
Answer: maybe you can try this, I add multiple checkpoint for every time of saving . https://github.com/jupyter/notebook/issues/3563

IPython Notebook Multiple Checkpoints


Explaining Cook's Distance

Question: Does Cooks Distance tell us how much the estimated parameter values change when the ith observation is removed or how much the fitted values change when the ith observation is removed?
I'm being told both statements are true given that the fitted values are a function of the parameter values but not sure this statement 100% adds up.
Any help in understanding would be appreciated.
Answer: Cook's D is the sum of the squared changes in the fitted values when the ith case is deleted, divided by a scaling factor of the rank of the model multiplied by the MSE of the model.

Explaining Cook's Distance


Exchange Size problems

Question: I have an email mailbox that is giving me the following error
A non-delivery report with a status code of 5.2.2 was generated for recipient rfc822;email@example.com (Message-ID <firstname.lastname@example.com>).
Causes: In Exchange 2000, the delivery status notification(DSN)is generated because the recipientÆs mailbox exceeded its storage limit.  In Windows 2000 or Windows .NET, the DSN is generated when the storage size of drop directory exceeds the SMTP virtual server disk quota.  The quota size is 11 times the maximum messages size or 22 MB if there is no max message size.  If the storage size of the drop directory is within one maximum message size of the quota or 2MB is no maximum message size is defined), the system  assumes that this message  cause the storage size to exceed  the quota, so this DNS is generated.
Solution: Check the mailbox storage or the queue storage quota limit.
But I have increased the quota size so it shouldn't be producing this error any more, any one got any other suggestions?
Answer: There are several parameters to set the quota.

There are the organization's Global settings / Message delivery properties setting the default values for maximum message size for sent and received messages for your information stores, no matter which protocol is used
there is the virtual SMTP server's properties setting the maximum message size for SMTP reception only
there is the SMTP connector's property to only allow message smaller than X KB for SMTP outgoing mail only

To effectively change anything for mail reception, you would need to check at least 1. and 2.

Exchange Size problems


Does this mixed model violate assumptions of independence?

Question: A disturbance event caused damage to 5 streams (Set1).  To quantify this damage, five additional unimpacted streams (Set2) were picked for comparison.  During the selection process every effort was made for Set2 to be identical in every way except construction damage.  Then 6 years later, a second, larger disturbance event affected both stream sets so they were resampled.
I am using mixed models to measure how animals have responded to the two disturbance events.  I have these two Poisson models that I am picking from:
Model 1:
Count~Treatment+(1|StreamId)

Where Treatment has four levels: set1year1,set2year1,set1year2,set2year2
Model 2:
Count~StreamSet*Year+(1|StreamId)

Where StreamSet has two levels: Set1,Set2 and Year has two levels: Year1,Year2
Which to choose?
I recognize Model 2 as the traditional method for analyzing this type of experimental set up but a couple differences makes me lean toward Model 1:

The resampling is 6 years apart
This isn't technically a BACI design. We never recorded the "Before" measurement because the impact occurred before our first year of measurements.  Instead it is more of a continuum of disturbance: i)unimpacted, ii)somewhat impacted, iii)more impacted, iv)impacted twice.

So my question is: Does using StreamId allow me to use Treatment without violating assumptions of independence?
Answer: The results you obtained for the two models should not be just similar, but exactly the same -- because both models have exactly the same fixed effects and the same random effects. The only difference is that the fixed effects portion is parameterized differently.
Here is an example using an available dataset to illustrate this. This is a split-plot experiment with a blocking structure on the whole plots, Variety as the whole-plot factor, and nitro as the split-plot factor (similar to repeated measures).
> data(Oats, package="nlme")
> Oats = transform(Oats, nv = interaction(nitro, Variety))

The factor nv represents the combinations of nitro and Variety. To make things more interesting, I'll throw out 12 observations at random:
> set.seed(1234)
> Oats = Oats[sample(1:72, 60), ]

I will fit equivalent models using nitro*Variety and nv as the fixed effects:
> library(lme4)
> modsep = lmer(yield ~ factor(nitro)*Variety + (1|Block/Variety), data = Oats)
> modint = lmer(yield ~ nv + (1|Block/Variety), data = Oats)

Now, look at the lsmeans results:
> lsmeans(modsep, ~ nitro*Variety)
 nitro Variety        lsmean       SE    df  lower.CL  upper.CL
   0.0 Golden Rain  81.67595 9.889542 24.82  61.30070 102.05121
   0.2 Golden Rain  99.61801 9.216304 20.54  80.42536 118.81065
   0.4 Golden Rain 117.59085 9.216626 20.53  98.39732 136.78437
   0.6 Golden Rain 124.83333 8.742235 17.55 106.43258 143.23409
   0.0 Marvellous   86.66667 8.742235 17.55  68.26591 105.06742
   0.2 Marvellous  108.46275 9.905765 24.86  88.05572 128.86977
   0.4 Marvellous  117.16667 8.742235 17.55  98.76591 135.56742
   0.6 Marvellous  124.11076 9.244939 20.61 104.86242 143.35910
   0.0 Victory      71.50000 8.742235 17.55  53.09924  89.90076
   0.2 Victory      91.38669 9.250034 20.62  72.12846 110.64493
   0.4 Victory     107.83807 9.937062 24.94  87.36987 128.30627
   0.6 Victory     111.51815 9.920408 24.89  91.08223 131.95407

Confidence level used: 0.95

> lsmeans(modint, ~ nv)
 nv                 lsmean       SE    df  lower.CL  upper.CL
 0.Golden Rain    81.67595 9.889542 24.82  61.30070 102.05121
 0.2.Golden Rain  99.61801 9.216304 20.54  80.42536 118.81065
 0.4.Golden Rain 117.59085 9.216626 20.53  98.39732 136.78437
 0.6.Golden Rain 124.83333 8.742235 17.55 106.43258 143.23409
 0.Marvellous     86.66667 8.742235 17.55  68.26591 105.06742
 0.2.Marvellous  108.46275 9.905765 24.86  88.05572 128.86977
 0.4.Marvellous  117.16667 8.742235 17.55  98.76591 135.56742
 0.6.Marvellous  124.11076 9.244939 20.61 104.86242 143.35910
 0.Victory        71.50000 8.742235 17.55  53.09924  89.90076
 0.2.Victory      91.38669 9.250033 20.62  72.12846 110.64493
 0.4.Victory     107.83807 9.937062 24.94  87.36987 128.30627
 0.6.Victory     111.51815 9.920408 24.89  91.08223 131.95407

Confidence level used: 0.95

The results are identical for the two fitted models -- estimates, SEs, df, and confidence limits.
I think some spurious error somewhere caused your two models to look different. I suggest that you go back to square one and re-fit both models from scratch, and I think you will find the same.
Comment: Awesome, thanks for the repeatable code showing you're intuition was correct.  I tracked my issue down to using glmmadmb, instead of lmer.  I am not sure why the two glmmadmb models don't agree.  I tried to run your example using glmmadmb but the models failed to converge...  I am updating my first "answer" with this new information.
Comment: They failed to converge due to me using the wrong family.  Here is the code to add to your example showing glmmadmb producing different model results: `modsep2 = glmmadmb(yield ~ factor(nitro)*Variety , data = Oats, family="gaussian")`
`modint2 = glmmadmb(yield ~ nv , data = Oats, family="gaussian")`
Answer: After the very helpful answer from @rvl my understanding is improved significantly, but the issue remains unexplained.  It turns out the packages glmmADMB solves these two models slightly differently from each other, while the package lme4 gives the exact same answer.  See below.
glmmADMB models:
> mod1<-glmmadmb(count~Treatment+offset(area)+1|StreamId),
                 data=df,family="poisson")
> lsmeans(mod1,pairwise ~ Treatment, type="response")$lsmeans
 Treatment    rate         SE     df  asymp.LCL asymp.UCL
 Set1Year1   1.5157807 0.35555667 NA 0.95712798 2.4005055
 Set2Year1   0.5412894 0.23822837 NA 0.22845719 1.2824906
 Set1Year2   0.2816674 0.07497567 NA 0.16717037 0.4745847
 Set2Year2   0.1107805 0.05169448 NA 0.04438739 0.2764821

Confidence level used: 0.95

> mod2<-glmmadmb(count~StreamSet*Year+offset(area)+1|StreamId),
                data=df,family="poisson")
> lsmeans(mod2,pairwise ~ Impact*Year, type="response")$lsmeans
 StreamSet Year      rate        SE   df  asymp.LCL asymp.UCL
 Set1     Year1  1.5157779 0.63536250 NA 0.66656250 3.4469127
 Set2     Year1  0.5412885 0.14797203 NA 0.31676400 0.9249574
 Set1     Year2  0.2816687 0.14814817 NA 0.10046981 0.7896628
 Set2     Year2  0.1107806 0.04002068 NA 0.05457054 0.2248896

lme4 models:
> mod1b<-glmer(count~Treatment+offset(area)+1|StreamId),
                data=df,family=poisson)
> lsmeans(mod1b,pairwise ~ Treatment, type="response")$lsmeans
 Treatment      rate         SE    df  asymp.LCL asymp.UCL
 Set1Year1    1.4423756 0.35036760 NA 0.89601011 2.3219016
 Set2Year1    0.5348784 0.14876125 NA 0.31011127 0.9225558
 Set1Year2    0.3277244 0.08150271 NA 0.20128947 0.5335762
 Set2Year2    0.1095906 0.03209355 NA 0.06173048 0.1945572

Confidence level used: 0.95

> mod2b<-glmer(count~StreamSet*Year+offset(area)+1|StreamId),
                data=df,family=poisson)
> lsmeans(mod2b,pairwise ~ StreamSet*Year, type="response")$lsmeans
 StreamSet  Year      rate         SE df asymp.LCL asymp.UCL
  Set1     Year1 1.4423708 0.35036019 NA 0.8960148 2.3218742
  Set2     Year1 0.5348812 0.14876006 NA 0.3101151 0.9225539
  Set1     Year2 0.3277193 0.08150026 NA 0.2012877 0.5335642
  Set2     Year2 0.1095903 0.03209306 NA 0.0617307 0.1945552

As you can see, Lme4 give identical results while glmmADMB gives different SE for the two models.  Here is a reproducible example:
library(glmmADMB); library(lsmeans); library(lme4)
data(Owls,package="glmmADMB")
Owls <- transform(Owls, FoodSex = interaction(FoodTreatment, SexParent),
                      NegCount=as.integer(NegPerChick*BroodSize))

mod1<-glmer(NegCount~FoodTreatment*SexParent+(1|Nest),data=Owls,family=poisson)
mod2<-glmer(NegCount~FoodSex+(1|Nest),data=Owls,family=poisson)
lsmeans(mod1,~FoodTreatment*SexParent)
lsmeans(mod2,~FoodSex)

mod1b<-glmmadmb(NegCount~FoodTreatment*SexParent+(1|Nest),data=Owls)
mod2b<-glmmadmb(NegCount~FoodSex+(1|Nest),data=Owls)
lsmeans(mod1b,~FoodTreatment*SexParent)
lsmeans(mod2b,~FoodSex)

Comment: Is `Impact` in this answer identical to `StreamSet` in the question? I guess I'm dumb, but I see no reason why there should be any difference at all between these two models. All you've done is parametrized the 3df for fixed effects in two different ways. So I am suspicious of your results -- and all the more so since the variable name changed.
Comment: I think you edited the output to make the variable names match-- that is not the same as re-doing the analysis. Also, use the `table` function to confirm that your `Treatment` factor is defined correctly. I just posted an "answer" to this question with an example that illustrates a similar situation.
Comment: I updated the answer to match the terms of the original question, sorry about that confusion. I changed the names of coded variables on here to make the question as unambiguous as possible.  It is true the difference is slight between model 1 and model 2, but it seems to be an important difference. Model 1 is coded as independent samples, while model 2 is coded as you would for a repeated measures experimental design.  I found this site to be helpful to clarify the distinction: [Repeated Measures](https://statistics.laerd.com/statistical-guides/repeated-measures-anova-statistical-guide.php).
Comment: I don't understand the discrepancy with glmmsdmb either. I considered perhaps that there is a bug in `lsmeans` support for those objects, but I did confirm with your examples that I obtain the same estimates and SEs as `lsmeans` does via the `predict` function with corresponding `newdata`.
Comment: Since the nature of this question has morphed significantly I guess I'll update the original title and question to reflect the new information.  Thanks for the help.


how much probability can be between mean and median?

Question: I have a unknown probability density function f(x).  It has bounded max value. and it is only positive between $[a,b]$
Let us say mean is $\mu$ and $m$ is the median. And the mean is greater, $\mu>m$
Is there any guarantee or properties for $\int_{m}^{\mu} f(x)dx$?
Comment: It may be helpful to know that $|\mu - m|\leq \sigma$ if the distribution has finite variance.
Answer: The most extreme difference between mean and median is when (just over) half the probability is at $a$ and (just under) half is at $b$.  The median is then $a$ and the mean is (just under) $\frac 12(a+b)$  This causes your integral to be zero.
On the other hand, you can again put (just over) half the weight at $a$, $\frac 1n$ of the weight at  $b$ and the rest uniform on $(a,a+\frac 1{n}(b-a))$.  The mean is now higher than $a+\frac 1n(b-a)$.  You can approach half the weight being between $m$ and $\mu$ with this.


Problema com Buscador PHP

Question: BOA TARDE GALERA
estou desenvolvendo um site para um cliente e ele deseja colocar um localizador (pesquisa), no caso colocar o nome da pessoa e aparecer o local de sepultamento dela.
so que eu fiz o código php e o banco de dados, porem quando eu faço o teste, aparece o resultado em branco.
aparece assim para mim:
Cemiterio Municipal Parque Águas Lindas
Localizador de Jazigos
Resultado da Pesquisa:
Resultado da Pesquisa:
Resultado da Pesquisa:
Resultado da Pesquisa:
Resultado da Pesquisa:

e no caso era para aparecer assim:
Cemiterio Municipal Parque Águas Lindas
Localizador de Jazigos
Resultado da Pesquisa:maria claudia
Resultado da Pesquisa:maria cunha
Resultado da Pesquisa:maria lina
Resultado da Pesquisa:maria da luz
Resultado da Pesquisa:maria costa

o código do formulário e esse que eu fiz:

Cemiterio Municipal Parque Águas Lindas

Localizador de Jazigos

<form method="POST" action="pesquisar.php">
     Pesquisar:<input type="text" name="pesquisar" placeholder="Nome do Falecido">
    <input type="submit" value="ENVIAR">
</form>

e o codigo da pesquisa e esse:

Cemiterio Municipal Parque Águas Lindas

Localizador de Jazigos

<?php
    $servidor = "localhost";
    $usuario = "root";
    $senha = "EU NAO POSTEI A SENHA";
    $database = "cemiterio";
    //Criar a conexao
    $conn = mysqli_connect($servidor, $usuario, $senha, $database);

    $pesquisar = $_POST['pesquisar'];
    $sql = "SELECT * FROM `jazigos` WHERE `NOME` LIKE '%$pesquisar%' LIMIT 5";
    $resultado_cemiterio = mysqli_query ($conn,$sql);

    while($rows_sql = mysqli_fetch_array($resultado_cemiterio)){
        echo "Resultado da Pesquisa:" ."
";
    }
?>

PRECISO MUITO DE AJUDA COM ESSE PROJETO
E aproveitando, preciso que o resultado apresente toda as informaçoes da linha do nome pesquisado ( a tabela tem 8 colunas) tipo pesquisa "maria lima"
ai aparece assim:
mome :maria lina Data de nascimento: 10/10/190  idade: 80 anos
 Data de falecimento: 01/10/2018 Quadra: 03 Jazigo: 1250 Gaveta: 03

ja nao sei mais oq fazer, fiz muita pesquisa, mais nao encontrei uma solução
deste ja agradeço a sua atenção e colaboração.
Comment: 'echo "Resultado da Pesquisa:" ."";' você tem um problema de lógica aqui, deveria ter algo do tipo: `echo "Resultado da Pesquisa:" . $rows_sql['col1'] . ""`
Comment: Posta o código para olharmos, senão ficará impossível de te ajudar.
Comment: Vc quer apenas fazer uma pesquisa simples por um texto digitado no formulário.
Answer: No caso você realmente está conseguindo fazer a pesquisa e ela está lhe retornando os resultados, o que está faltando é você exibi-los. Dentro do loop while substitua por esse:
 while($rows_sql = mysqli_fetch_array($resultado_cemiterio, MYSQLI_ASSOC)){
        echo "Resultado da Pesquisa:". $rows_sql["nome_da_coluna_da_sua_tabela"]  ."
";
    }

Troque a query por essa:
 $sql = "SELECT * FROM `jazigos` WHERE `NOME` LIKE '%{$pesquisar}%' LIMIT 5";

Você está esquecendo de exibir o resultado através dos índices da sua tabela no array retornado
Comment: cara, deu certo
Comment: voce pode mim tira mais uma duvida?
Comment: @KaduSilva Sim, pois não.
Comment: essa minha tabela ela tem 8 colunas assim:

nome -data de nascimento-idade-data de falecimento- quadra-jazigo-gaveta

o cliente quer que quando eu coloque o nome da pessoa apareca os resultados da linha
Comment: porque agora so mostra o nome da pessoa
Comment: @KaduSilva para você conseguir listar as 8 colunas basta você na linha de baixo, fazer o mesmo procedimento porém só alterando o o nome das colunas, como por exemplo:`echo "".$rows_sql["coluna_x"]." ".$rows_sql["coluna_y"]` e assim por diante.
Comment: ai mostra o dado da linha do nome da pessoa
Comment: mais em qual ponto eu coloco isso?
Comment: @KaduSilva é só ir acrescentando na mesma linha, por exemplo: `echo "Resultado da Pesquisa:".$rows_sql["coluna_x"]."".$rows_sql["coluna_y"]."".$rows_sql["coluna_z"];`
Comment: vou testar
desculpa a demora, sair do cemiterio, cheguei em casa agora a pouco e agora que vim para o escritorio
Comment: no caso seria assim:
Comment: ";
   echo "Resultado da Pesquisa:". $rows_sql["DATA_DE_NASCIMENTO"]  ."";

    }
?>
Answer: Seu resultado está em branco porque você não está escrevendo os dados no echo
while ($rows_sql = mysqli_fetch_array($resultado_cemiterio)) {
    //Aqui você escrever apenas um HTML fixo, não tem os dados do banco
    echo "Resultado da Pesquisa:" ."
";
}

O que você quer é algo assim:
echo "Resultado da Pesquisa:
";
while ($rows_sql = mysqli_fetch_array($resultado_cemiterio)) {
    echo implode(", ", $rows_sql)."
";
}

Nesse exemplo simples eu apenas uni as colunas do resultado com uma vírgula mas você pode arrumar como preferir pegando cada coluna separadamente através dos índices, de uma olhada na documentação do mysqli_fetch_array
Observação:

Do modo como está seu código está vulnerável a SQL Injection
Se por acaso não for enviada uma variável pesquisar pelo corpo da requisição, o código irá quebrar, seria necessário usar algo como $pesquisar = isset($_POST['pesquisar']) ? $_POST['pesquisar']; : '' ou $pesquisar = $_POST['pesquisar']; ?? '' (PHP 7)

Problema com Buscador PHP


How can I get a list of other Azure Active Directory organizations I'm a Guest User of using an API eg, Graph

Question: I want to be able to list the external Azure Active Directory organizations which my users are Guests of using an API call.
I can see this information readily in the the Azure Portal but so far cannot see how to get it from Microsoft Graph API
Organizations List
Hope somebody has solved this please
Thanks for any advice
Comment: Please elaborate
Comment: Sure -  for instance regarding Microsoft Teams it is easy to get a list of external Guest users in my organizations teams.  However, if I want to see what external organizations my users are Guests in this is not very clear to me how I would get such a list with an API call to MS Graph or Azure AD.        I know the information is there as I can see this in Azure AD.            Does that  explain a bit better ?
Answer: You can retrieve all Azure AD instances for your user using the tenants list endpoint:
https://learn.microsoft.com/en-us/rest/api/resources/tenants/list
If you have the Azure CLI installed, you can check it using:
<code>az rest --uri https://management.azure.com/tenants?api-version=2020-01-01 --method get
</code>
Comment: Thanks very much Martin for your help.    I had a look at that endpoint but unfortunately it only brings back the tenants for my own account which of course is what it is meant to do.   I wonder if you have any ideas on how I could get this information for other users in my tenant via such a REST api call - maybe its not possible.?      Thanks again for your generous suggestions.  Regards Liam
Comment: @LiamO'Neill Hi Liam, It is just my opinion and I might be wrong, but I doubt that this is possible because this would expose sensitive data, right? However, depending on what you are trying to achieve, you can write an application that gets this information on behalf of a user, after he signed in to your app. (See https://learn.microsoft.com/en-us/graph/auth-v2-user).
Comment: Hi Martin - I think you are right - thanks for the link to the document and for all your help. Regards  Liam
Comment: @LiamO'Neill You are welcome, wish you good luck with your requirement. Please consider accepting the answer if you think it could be helpful for others. Best - Martin


Magento how to display country flag in currency drop down?

Question: I am trying to add all country flag in currency change dropdown in magento?how may i do this in magento 1.4.2 ?
Comment: Images in select controls are [problematic](http://stackoverflow.com/q/2226666/471559). This is not a Magento limitation.
Answer: Very good example for flags. It may help others
http://www.phptechi.com/magento-show-country-flags-selector-in-header.html
As stated in that post:

Step 1: Make sure multiple language stores are available. Now open
  flags.phhml file located at
  app/design/frontend/default/theme/template/page/switch/flags.html If
  in case it does not exists then create it and replace existing code/
  add following code into file.
Note: Please modify href & src in following code.
< ?php if(count($this->getGroups())>1): ?>

< ?php foreach ($this->getGroups() as $_group): ?>
< ?php echo $this->htmlEscape($_group->getName()) ?>
< ?php endforeach; ?>
< ?php endif; ?>

Step 2: Now add entry into page.xml file and file header block i.e.
  "html_header". In case if you want to add flags in footer section then
  search for footer block and add following line in footer and do little
  css to align it correctly.
Step 3: Upload flag images into "skin/frontend/currentTheme/images/"
  directory and make sure the flag file names are having store name is
  part of flag name. (i.e. Image name is "flagEnglish.gif",
  "flagGerman.gif". So store names are "English", "German", etc)
Now clean the magento cache and reload the home page and you are
  done!!.
Answer: Currency selector with flag in magento

You need to prepare a flag list (images).
Upload flag list to root/media/flag directory
Rename flags to currency's code (EX: US Dollar -> usd-flag.jpg, Euro -> eur-flag.jpg, Hong Kong Dollar -> hkd-flag.jpg...)
In the template file: app/design/frontend/default/your_theme/template/directory/currency.phtml (or app/design/frontend/base/default/template/directory/currency.phtml), change code to:
<?php foreach ($this->getCurrencies() as $_code => $_name): ?>
       <a href="<?php echo $this->getSwitchCurrencyUrl($_code) ?>" onclick="setLocation(this.value);">
        <img src="<?php echo Mage::getBaseUrl('media').'flag/'.$_code.'.jpg'; ?>" title="<?php echo $_name ?> - <?php echo $_code ?>" alt="<?php echo $_name ?> - <?php echo $_code ?>" width="20" height="20" />

<?php endforeach; ?>


Usar hashcode como id é uma boa prática?

Question: Eu tenho uma pequena lista de strings (onde as strings nunca vão se repetir) e gostaria de usar hashcode como id, é uma boa prática?
Comment: Hashcode pode colidir. Qual seria a vantagem de não usar as strings? Se são únicas, você pode numerá-las na sequência, se o problema for espaço.
Comment: Boa prática em que sentido?
Answer: Depende.
Valor único
Não é boa prática se a ideia é criar um ID único.
Hashes são uma simplificação do conteúdo e toda simplificação perde informação porque não tem como você representar o todo com a parte.
Isso significa que é difícil, mas não impossível, que duas Strings ou objetos diferentes gerem o mesmo valor de hash. Quando isso ocorre, dizemos que houve uma colisão. Uma implementação séria deve tratar este tipo de situação, caso contrário estará comprometendo a integridade dos dados ou, como no caso do uso de hashes em segurança, até a privacidade dos seus usuários.
O máximo que você poderia fazer para diminuir o tamanho de uma String sem perder informação é comprimi-la, mas isso não seria muito prático.
Se você precisa criar chaves a partir Strings você tem basicamente duas opções:

Use as próprias Strings. Exemplo:

mapa.put("string1", valor1);
mapa.put("string2", valor2);

Atribua um número às Strings, como se fosse um id numa tabela:

mapeamento.put("String1", 1);
mapeamento.put("string2", 2);
...
mapa.put(1, valor1);
mapa.put(2, valor2);

Classificação
Por outro lado, hashes são bons para classificar conteúdos, o que significa que você pode encontrar rapidamente o que procura, mas não de forma única.
Vou usar o exemplo do HashMap para ilustrar isso.
Imagine que você tem um balde cheio de bolinhas coloridas e numeradas e alguém pede para você pegar uma bola azul de número 1. Você pode gastar um bom tempo procurando e no final pode ser que não a encontre. Isso é o equivalente a buscar itens numa lista, por exemplo.
Por outro lado, se você tiver vários baldes, cada um com bolinhas de uma só cor, basta ir até o balde com a etiqueta de bolinhas azuis e olhar lá dentro. Você ainda pode ter que procurar um pouco pelo número correto, mas vai ser muito mais eficiente.
É mais ou menos assim que funciona com o HashMap. Se você olhar a implementação do HashMap.put() vai ver que ele usa o hash para acessar o índice do vetor table. Neste caso, as posições dos vetores são como os baldes do exemplo acima. Cada item de table é o tipo Entry, cuja implementação funciona como uma lista encadeada (veja o atributo next). Quando você adiciona um item, se já houver outro item no mesmo balde (não necessariamente com o mesmo hash), ele é adicionado ao final da lista ligada.
Então, quando vocês faz um HashMap.get() ele primeiro usa o hash para ir no elemento certo do vetor table, depois ele percorre a lista ligada usando o equals para verificar se ele encontrou realmente a chave que você usou.
Conclusão
Hashing é um mecanismo excelente para classificar conteúdo de forma eficiente ou até mesmo para verificar a integridade de dados de forma relativamente segura (considerando que a probabilidade de colisão é pequena), mas não para identificar de forma única.
Answer: Note que não existe garantia de não colisão quando se usa funções de hash. Isso significa que strings diferentes podem produzir o mesmo número inteiro (isso é uma colisão). Um exemplo são as strings: "firstname.lastname@example.com" e "email@example.com". Ambas produzem o mesmo número inteiro na implementação de hashCode da classe String no Java.
Assim, tudo depende do contexto para o qual está sendo aplicado. Se é pra resolver um caso específico, eu tentaria primeiro a abordagem descrita aqui, pois é muito simples de implementar. Checar se houve colisão é também trivial de fazer. Caso ela não atenda, implementar outras é simples e, mais simples ainda, é usar algoritmos de hash prontos.
Veja a implementação em C++ de um algoritmo que se diz decente na geração de hashes para Strings: (facilmente adaptada para Java): https://stackoverflow.com/a/107657/2236741
Respostas relacionadas no SOen:
https://stackoverflow.com/questions/2624192/good-hash-function-for-strings
https://stackoverflow.com/questions/6120657/how-to-generate-a-unique-hash-code-for-string-input-in-android