Return AccessDenied for custom page

Question: I've setup a custom page in my system which is expecting 2 parameters that will be used to generate part of the content on that page, I'm able to retrieve the information from my page, but I'm wondering what is the best method of returning an access denied when my criteria fail
I found this page which shows how you can setup a custom access controller, but this example is passing the user entity, when what I'm more interested in is the 'slugs' of the URL they've hit
routing.yml
my_module.user_subscribe:
  path: /my-module/subscribe/{entity_type}/{entity_id}
  defaults:
    _controller: \Drupal\my-module\Controller\SubscriptionPages::subscribe
    _title: Email Subscription Sucessful
    type: node
    entity: 1
  requirements:
    _permission: 'access content'
    _entity_check: 'TRUE'

Services.yml
services:
  my_module.entity_check:
    class: Drupal\my-module\Access\EntityCheck
    tags:
      - { name: access_check, applies_to: _entity_check }

Then I have my src/Controller/SubscriptionPages file, and one for src/Access/EntityCheck etc, all that part seems to be working, I can manually enforce the code in my EntityCheck to return an access denied and it does, but what I want to know is how can I pull the {entity_type} and {entity_id} from the URL they've hit so I can check they aren't trying to access something they shouldn't
eg
mywebsite.com/my-module/subscribe/node/15 - would be fine
mywebsite.com/my-module/subscribe/foo/bar - would return access denied, because I want to run the check inside my EntityCheck code
Inside the link above it has  arguments: ['@current_user'] inside the services.yml file, is there an equivalent one for current URL, or ones where I can more specifically retrieve each of the items individually?
Answer: In your route, instead of _permission, you can use a custom access callback:
_custom_access: Drupal\[MODULE]\Controller::accessCallback()
Then you can return an AccessResult from the access callback:
public function accessCallback($entity_type, $entity_id) {
  if (!in_array($entity_type, $allowed_types)) {
    return \Drupal\Core\Access\AccessResult::forbidden();
  }

  ...

  return \Drupal\Core\Access\AAccessResult::neutral();
}

Or, you can use a _permission on the route, and instead throw a Symfony\Component\HttpKernel\Exception\NotFoundHttpException exception from the controller if the values are incorrect:
public function someRouteCallback($entity_type, $entity_id) {
  if (!$entity = \Drupal::entityTypeManager()->getStorage($entity_type)->load($entity_id)) {
    throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException();
  }
}

Comment: Be aware that access callbacks could be called for different reasons and they should return the access result, not act on it. You can throw the exception in the controller itself, this would be no problem, but it's not ideal. This is to have an access callback returning the access result, then any code checking the route access works as it should.
Comment: Ah perfect, even better, thank you
Comment: Whoops. Thanks, I was mixing things. I've updated the post accordingly. Andrew Morris you should review my updates and change your code accordingly.

Return AccessDenied for custom page


Time series forecast from STL using ARIMA method for specific order

Question: I am trying to forecast daily sales and have found that for the seasonally adjusted component a non-seasonal ARIMA (3,1,6) and a seasonal naive for seasonal component gives me the best result.
How can I use stlf or stlm functions to specify my order (3,1,6) in ARIMA method?
Currently, I am forecasting both components separately and merging them to obtain my forecasts.
Comment: I do not think you can do both using just `stlf` or `stlm`.
Answer: Here is an example.
fit <- stlm(USAccDeaths, modelfunction=Arima, order=c(3,1,6))
fc <- forecast(fit)
plot(fc)

Comment: Thank you for the example, Prof. @Hyndman. A big fan of your work! I am starting out with time-series forecasting and your book (Forecasting: principles and practice) has been a very informative guide.
Comment: I am getting slightly different results from my earlier approach (`stl` on timeseries followed by non-seasonal ARIMA (3,1,6) on seasadj component and seasonal naive on seasonal component) and from `stlm` function. Any particular reason for it?
Comment: Possible using different versions of the package?


Find all the solutions of $z^7=i$

Question:
Find all the solutions of $z^7=i$.

The modulus is 1 and the argument is $\frac{\pi}{2}$, so
$z^7=i=1\cdot e^{(\frac{\pi}{2}+2\pi n)i}$
$z=i^{1/7}=e^{(\frac{\pi}{14}+\frac{2\pi n}{7})i}$ with $0\leq n <7$
So $\cos(\frac{\pi}{14}+\frac{2\pi n}{7})+i\, \sin(\frac{\pi}{14}+\frac{2\pi n}{7})$ by De Moivre?
I this right so far? In the answers it says the first root is $-i$ but I'm not getting this, any help?
Comment: try setting $n=5$ in your set of answers
Answer: You are doing fine: there should be seven distinct solutions, and you cannot really call any of them the first.
If $n=5$ then $\frac{\pi}{14}+\frac{2\pi n}{7} = \frac{3 \pi}{2}$
Or if $n=-2$ then $\frac{\pi}{14}+\frac{2\pi n}{7} = -\frac{\pi}{2}$
Answer: You are on the right tracks.
$-i$ can also be expressed as $e^{-\frac{\pi}{2}i}$ or $e^{\frac{3\pi}{2}}i$. Which is the case when $n = 5$.
The rest you can get by sticking in the values for $n$

Find all the solutions of $z^7=i$


Returning null char array with rewriting Java's String.toUpperCase()

Question: I am originally a Java programmer and I have a deep love of the syntax, especially regarding the String object. With C++, I have tried to recreate the toUpperCase() method that Java has. The only problem is that it always returns a String object that has an empty/NULL char array.
String String::toUpperCase()
{
    char *a = new char[this->length + 1];
    memset(a, 0, this->capacity + 1);
    memcpy(a, this->characters, this->length);
    for (int i = 0; i < strlen(this->characters); i++)
    {
        toupper(a[i]);
    }
    return *new String(a);
}

Comment: You'd be wiser using something from here: http://stackoverflow.com/questions/735204/convert-a-string-in-c-to-upper-case?rq=1 and `std::string` in general. This function leaks memory every time it's called. Also, read some documentation for `toupper`.
Comment: Also: In Java and C# you use `new` a lot, in C++ you should avoid it when possible (no GC).
Comment: As a general rule, do not try to recreate java class APIs in C++ classes (they are optimized for Java, so what you end up with tends to be a variation of the "I can write C code in any language" theme). To convert a C++ string to upper case, see [this answer](http://stackoverflow.com/a/735215/186997).
Comment: On another note, stop abusing pointers (i.e. you should write `return String(a);` instead of 'return *new String(a);' and use a smart pointer on `a`, or better yet, a `std::vector`); Also, stop writing `this->`. It is unnecessary. Also consider using `std::fill` instead of `memset` and `std::copy` instead of `memcpy`.
Comment: Use std::string for strings
Answer: You have a few memory problems with your attempt, as well as a logical one.  All you need to return a copy of a string with the characters being upper case is:
std::string str = "My Original string";
std::string myCopy(str);
std::locale loc;
std::transform(myCopy.begin(), myCopy.end(), myCopy.begin(), [&](char c)
{
    return std::toupper(c, loc);
});

Comment: @japreiss, That won't always work out so well, although the answer won't either if `char` is signed and there are negative values. You can check the link I commented for more discussion on this method.
Comment: @japreiss I'd argue that not using a locale is always broken when operating on text – how can you exclude the need for using locales? Then again, locales in C++ are broken anyway (i.e. the above does the wrong thing for the German text "Maß", regardless of locale).
Comment: Thanks, I guess my incorrect comment turned out to be a good learning experience :)
Comment: or just `std::transform(myCopy.begin(), myCopy.end(), myCopy.begin(), std::toupper)` if you don't need locale sensitivity.
Comment: @japreiss The primary problem with using the version that does not take a locale is that it is the carry over from the C standard library, which takes, and returns, an `int` with very specific criteria.  If `char` is signed on a given platform, the call to `int std::toupper(int)` can lead to undefined behavior.


Can't select or change selection with jquery to jq-idealform radiofield

Question: I'm using jq-idealforms to build a nice and easy form. In It i have a radio-field that i would like to fill with jquery after getted info from db. Here there an example (at "step2".. section 2) you can watch how jq-ideal and radio-field work.
It doesn't provide an api to do that, but if i can fill an input[type='text'] element whit jquery, it must be possible whit radio-field too.
You can look here, how jq-idealforms manages radio-field.
I have tryed with the follow part of code:
  $(this).prop('checked', true);
  $(this).next().addClass('checked');

where $(this) is one of the 3 radio-field, and it is the one which i want select (rest of code is on the example):
  <input type="radio" name="radio" style="position: absolute; left: -9999px;" autocomplete="off">

The class "checked" is not putted in the element span.ideal-radio (sibling of input). I'm sure of the DOM, because if i use another class like "foo", this one is added. I think that is a bug from plugin, but what? how i can solve?
And at the and i reload form like explained on documentation:
      $(form).data('idealforms').reload().fresh();
Textarea elements and input text type are filled correctly.
Edit:
The problems is more simple, i can't select the first element of my radio checkbox if jq-idealforms is enabled, if i don't use jq-idealforms, the first radio element is selected. Or if you put "checked" on the second radio-element and you use jq-idealforms, it works too.

    <link rel="stylesheet" href="css/jquery.idealforms.min.css" media="screen"/>

    <form id="form-doc" method="post" action="">

        Tipo doc:
        <input type="text" name="tipo_doc" />

        Ruolo ditta:

            <input type="radio" name="ruolo_ditta" checked/>Fornitore

            <input type="radio" name="ruolo_ditta" /> Cliente

        <button type="submit">Salva</button>
        <button id="reset" type="button">Reset</button>

    </form>
    `

It doesn't work with jquery-1.9.1 and jquery-1.10.1.
SOLUTION:
Documentation is wrong for radio button. You can read on site:

required
The field is required. This filter ONLY works with text inputs (text,
  password, textarea). For select use exclude to exclude the default
  option. For radio and checkbox use min: 1 which will require at least
  one option to be checked.

But using:
'ruolo_ditta' : {
    filters: 'min',
    data: { min: 1 },
}

or combinated whit 'required' filters (or only required filter) on idealforms option, where "ruolo_ditta" is the value of attribute name of radio elements. The form make a wrong and realy strange behavior.
Deleting it, using checked on the first radio html element works good and
$(this).prop('checked', true).trigger('change');

works as aspected.
thanks,
j.
Comment: A new release of jq-idealforms (version 3) are released. It's not compatible with the previous version so i have not tryed it, but the author say that it would fix this bug.
Answer: You must call reload on the form if you are altering values project doc
Comment: Yes, i do it. Now i have added this information on my original question.
Answer: The plugin abstracts the visual indication of check from the actual property of check, so you have to do one of two things:

trigger the check with a programmatic click:

$(this).trigger('click');
this is as if you were actually clicking on the checkbox. but this could also uncheck a previously checked box.  if that's not what you want, use option 2 which ensure that it's checked

ensure that it's checked:

$(this).prop('checked', true).trigger('change');
Comment: whit $(this).trigger('click') is setted the class "ideal-field-focus" on  (the constainer) and the radio button on which click is triggered is surrounded by a purple area adding "focus" class on , but not selected, whit the second trigger nothing at all.
Comment: $(this).prop('checked', true).trigger('change'); do the right thing only if i fire it for the second radio button. (There are 2 radio to chose and the form is created with nothing selected). For the first radio doesn't work properly. Sorry i have written the first comment trying it only in the first radio.
Comment: Now i'm trying to set the first radio by html. And i can't too. Looking on html input element i see that all slash at end are not present, but i insert it.
Comment: `$(this).trigger('click')` should have the exact same effect as clicking on the button with your mouse.  try and verify that this is referring the the right object.  you may need to specify the radio button or attached label being clicked, and not some element added by jq-idealform.
Comment: Thanks another time for your attention. I have tryed, and i am sure that $(this) refer to input element that i need to select. Looking on [source](https://github.com/elclanrs/jq-idealforms/blob/master/js/src/radiocheck.js#L24) of jq-idealforms you can see what's happen on click. `click: function() {$(this).trigger('focus') }`. `$(this).trigger('change')` works but only on the second radio buttons. And i still stuck on the same code. gh!


Maximal separable sub-extensions and Galois groups.

Question: I'm reading Neukirch's ANT book and at page 56 (bottom) it seems that the author is assuming the following fact:

Let $L|K$ be a finite and normal extension of fields and consider the maximal separable sub-extension $K(\theta)|K$. Then $\text{Gal}(L|K)=\text{Gal}(K(\theta)|K)$.

Why is this result true?
Many thanks in advance
Comment: What do you mean by $\text{Gal}$ here? Galois groups are defined only for separable extensions...
Comment: By Gal($L|K$) I mean the automorphisms of $L$ fixing $K$ pointwise.
Answer: I will only deal with the case $\operatorname{char} K = p > 0$, the other case being trivial.
Let $\phi \in \operatorname{Aut}_K(L)$; then note that $\phi(K(\theta)) \subseteq K(\theta)$. Indeed, if $x$ is separable, then so is $\phi(x)$, because they have the same minimal polynomial. Thus, we get a natural map
\begin{align*}
f \colon \operatorname{Aut}_K(L) &\to \operatorname{Aut}_K(K(\theta))\\
\phi &\mapsto \phi\big|_{K(\theta)}.
\end{align*}
A standard theorem of Galois theory shows that this map is surjective since $L/K(\theta)$ is normal (see e.g. Rotman's Galois Theory, Thm. 51(a)); we only need to show injectivity.
Since $K(\theta) \to L$ is purely inseparable, for any $x \in L$ there exists $n \in \mathbb N$ such that $x^{p^n} \in K(\theta)$. Note that
$$\phi(x^{p^n}) = \phi(x)^{p^n}.$$
Since $p$-th roots are unique, we conclude that knowing $\phi$ on $K(\theta)$ determines $\phi$ on $L$. That is, $f$ is injective. $\square$
Remark. In this case, you can actually use the above to construct a very explicit inverse map to $f$: Let $\phi \in \operatorname{Aut}_K(K(\theta))$, and let $x \in L$. For $n$ such that $x^{p^n} \in L$, there is at most one $y \in L$ such that
$$y^{p^n} = \phi(x^{p^n}).$$
Note that $x$ and $y$ have the same minimal polynomial, since $x^{p^n}$ and $y^{p^n}$ do (maybe choose $n$ minimal). Thus, this $y$ exists in $L$ since $L$ is normal. We then extend $\phi$ to $L$ by setting $\phi(x) = y$ for this $x$.
(Omitted: check that this does not depend on $n \gg 0$, that this gives a $K$-linear automorphism of $L$, and that the construction is actually a double-sided inverse of $f$.)


Static storage duration for a string

Question: In testing the following:
char* x = "Hello";
printf("%s %p %p %p", "Hello", x, "Hello", "Hello");

Hello
0x5618b7d478c7
0x5618b7d478c7
0x5618b7d478c7

I noticed that the "Hello" has the same memory address in all cases, meaning that the compiler stores the string "Hello" one time in .rodata (as it should).
Is this part of the language specification in that whenever a string-literal is used it should be looked up to see if it already exists before storing it? Or is this considered a compiler optimization to not store duplicate strings?
Answer: The compiler is allowed to do such optimizations with strings and compound literals. These may share storage, as long as their values are correctly presented to the application. But on the other hand there is no obligation to do so.
Other objects, variables, all are guaranteed to occupy storage of their own, even if the contents ist the same, such that all these objects have a unique address.
Answer: Regarding the arrays created for string literals, C 2018 6.4.5 7 says:

It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

This means the compiler is allowed to use the same or different memory for identical strings, as its designers choose. That includes strings that are substrings of others, such as "world" and "Hello world".
Comment: Yes. A compiler is allowed, but not required to do this optimization.
Comment: does that mean it's up to the compiler how it deals with repetitions?
Answer: In general the behavior depends on compiler options. You can set that the compiler will store identical string literals as one string literal or as different string literals.
So you should not relay on a condition like this
if ( "Hello" == "Hello" )

that it will be evaluated as true.
According to the C Standard (6.4.5 String literals)

7 It is unspecified whether these arrays are distinct provided their
elements have the appropriate values. If the program attempts to
modify such an array, the behavior is undefined.
Answer: Yes, it is considered a compiler optimization. It is named string interning. On GCC, it is enabled by -fmerge-constants.

Static storage duration for a string


How do I remove /web from the URL?

Question: I have a site using Drupal 8.5 I installed with Composer.
When users want to visit the site, they'd normally need to add /web after the domain to access it. I have a cpanel redirect that redirects users from domain abc.com to abc.com/web, so they don't have to add /web.
This solution is still a bit silly because the visitors still see the abc.com/web while I really want it to look like a regular website domain, domain.com.
I'm not allowed to use virtual hosts, but I am allowed to use htacces or symlinks.
How do I "redirect" visitors from domain localhost/temp-project to localhost/temp-project/web/index.php without having /web in the URL?
--Update 2--
I've tried to add a .htaccess snippet (from GitHub) in my root (localhost/temp-project) to point to /web and browsed to localhost/temp-project:
#Redirect to www location with subdirectory
RewriteEngine on
RewriteBase /
RewriteCond %{HTTP_HOST} localhost/temp-project [NC]
RewriteRule ^(.*)$ /web/index.php[R=301,NC]

This just doesn't do anything, what's going wrong here?
Comment: Maybe this can help: https://www.drupal.org/forum/support/post-installation/2015-10-15/solveddrupal-successfully-installed-in-subdirectory#comment-10457575
Answer: You should have your host point directly to the "web" directory instead of your project root. I've run into this issue on webfaction hosting and my solution (actually my co-worker's) was to have 2 "apps." The first app is not web accessible and this is where my drupal-composer/drupal-project's root is. Then I create a second app that is web accessible, e.g. domain.com and is a symlink to the first app's /web directory. Maybe you can use this same approach.
Comment: Hi Sonfd, what do you mean exactly with the term "app"?
Comment: I'm not sure what would be the equivalent on your hosting provider. But basically on webfaction an app could be a directory where you placed static html, or a php app, or a python app, or a symlink, etc. Maybe try the solution [here] (https://drupal.stackexchange.com/questions/241761/how-do-i-run-a-site-from-a-sub-directory).
Answer: If using cPanel:

Go to Domains > Domains.
Click "Manage" for the domain you want
Edit the path to the "New Document Root".
Answer: If you can't change the project root, then I'd suggest either doing a Rewrite directive within .htaccess or just making an alias on Drupal (or setting the homepage to be /web).
Answer: I have a very simple way I solve this issue. Instead of reconfiguring server to set new document root or writing rewrites, I think it is so far easier to make a 'modified install'. It is simple, takes a few minutes to modify your composer.json and complete your installation, and for the life of the website, you don't have to tamper with any server settings nor .htaccess nor settings.php nor any of such. It very easily saves tons of headache getting round the 'web/' folder issue, it neatly avoids it and gets you to set whatever you want as your web-root.
Read more in this my answer, How to remove subdir from base URL after installing site with Composer on a shared host?
Answer: Step 1. You have to install Drupal using this command composer create-project --no-install drupal/recommended-project my_site_name_dir  with the help of composer.
Step 2. You have to make some changes in the composer.json file as per the code listed below and you have to save file.
    "extra": {
    "drupal-scaffold": {
        "locations": {
            "web-root": "./"
        }
    },
    "installer-paths": {
        "core": [
            "type:drupal-core"
        ],
        "libraries/{$name}": [
            "type:drupal-library"
        ],
        "modules/contrib/{$name}": [
            "type:drupal-module"
        ],
        "profiles/contrib/{$name}": [
            "type:drupal-profile"
        ],
        "themes/contrib/{$name}": [
            "type:drupal-theme"
        ],
        "drush/Commands/contrib/{$name}": [
            "type:drupal-drush"
        ],
        "modules/custom/{$name}": [
            "type:drupal-custom-module"
        ],
        "profiles/custom/{$name}": [
            "type:drupal-custom-profile"
        ],
        "themes/custom/{$name}": [
            "type:drupal-custom-theme"
        ]
    },

Step 3. After that you have to enter in my_site_name_dir directory of the project and run this command composer install in composer.
Step 4 Your code is ready you need to setup your project accordingly.
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).

How do I remove /web from the URL?


Timer(unknown resolve error) xamarin

Question: To avoid initiating a search on every keypress in the search view, i want to add a countdown timer that is restarted on every change to the filter text to delay the search so we only search after the user stops typing. so that i tried to declare Timer in Core but it blinks in red colour and shows unknown resolve error but the Timer works in UI.Droid. I noticed that the system.dll is present in UI.Droid and UI.Touch but in Core it was located in References/.net portable subset. i tried to add the system.dll from .net assembly but i cannot able to find. hope u understand my problem. Thank You.
Answer: There is no way to use Timer in the PortableLibrary, only in Droid or Touch project
Comment: So what's the alternative?
Answer: You can copy the Core DLL from your Mono install and reference it in your PCL project. You'll want to add the .dll to the following directory on your Mac workstation:
/Library/Frameworks/Mono.framework/Versions/VERSION_NUMBER_HERE/lib/mono/.NET VERSION HERE/ mscorlib.dll
/Library/Frameworks/Mono.framework/Versions/VERSION_NUMBER_HERE/lib/mono/.NET VERSION HERE/ system.dll
However, you cannot move them out of the /.net portable subset folder on neither Mac nor Windows workstations because they are dependent on the .NET profile.
(thanks for the help Allie)

Timer(unknown resolve error) xamarin


Erro consulta mongoose

Question: Tenho uma consulta no NodeJS com MongoDB:
filter:['abertos','cancelados'];

schemas.chamados
    .find({STATUS_CHAMADO : {"$in" : filter}})
    .exec(function(err, dados) {
        if(err) return callback(err);
        else {
            return callback(dados);
        }
    });

Apresenta o seguinte erro:
Object {message: "Cast to string failed for value "undefined" at path "STATUS_CHAMADO"", name: "CastError", type: "string", path: "STATUS_CHAMADO"}

Alguem sabe o que pode ser ?
Quando o usuário selecionar o filtro no front-end com angular, o node buscaria estes valores.
Comment: Este filter vem de um uns checkbox passados pelo angular,
Se ele vier assim: ["aberto", null, null], acontece o erro, agora se ele vier ["aberto", "cancelado", "finalizado"]
vai normalmente.
Comment: Sim é constante, mesmo usando uma string não funciona !
So da erro se a variável filter vier do angular, se eu setar ela manualmente funciona.
Comment: Acontece o mesmo erro !!
Comment: mesmo se for `{'status_chamado' : { '$in': filter}}` aparece `"Cast to string failed for value "status_chamado" at path "status_chamado""` pq daí não precisaria fazer o cast, se já for string
Comment: Sim, mesmo assim aparece o erro, mais somente quando o filter é variável. Se eu definir var filter=['aberto','cancelado','finalizado'] não da erro.
Comment: (Removi os comentários anteriores) Talvez esse filter não esteja chegando como array, tente validar colocando algo como `console.log(typeof filter)`
Comment: Testei, retorna como object array
Comment: Já tentei de tudo ao meu conhecimento, alguem tem alguma ideia de que pode estar acontecendo ?
Comment: Então é isso.  Deveria ser um array. Converta para array que vai resolver
Comment: Caputo, resolvido. Você estava certo !
Muito obrigado.
Answer: Como @Caputo, disse, somente converti object em array conforme abaixo:
var arr = Object.keys(filter).map(function(k) { return filter[k] });

Erro consulta mongoose


How does a metronome help me play music better?

Question: I heard that anyone who received theoretical education in music should use a metronome to practice their timing. But I don't know how does a metronome help me? Or even how would better timing help me?
Also is it related with beats,and time signatures?
Comment: I'm mystified by the question "how would better timing help me." Rhythm (i.e. timing) is arguably the *most central and important element of music.* (The three "canonical" elements of music are melody, harmony, and rhythm.)
Comment: I'm a classical pianist, not a guitarist, so I can't recommend a specific book for learning guitar. But actively *listening* to music and *thinking* about what you hear is more important than any book could be anyway. In any case, it looks like this page does a reasonably decent job of explaining the fundamental "elements of music": http://historyofmusic.tripod.com/id6.html
Comment: Kyle, is there a book for guitar learners, that includes everything like melody and harmony, riffs, and ext. I don't really want to explore all these by asking random questions?
Answer: As humans, we're not naturally inclined to play music in time.  Our speech while rhythmic at times is vastly more complicated rhythmically than the majority of music out there.  Just check out this article by Steve Vai in which he talks about polyrhythms.  He talks about how one of the toughest challenges he has ever faced in music is transcribing speech.
But what does this have to do with metronomes?
I'm glad you asked, other Alex.   Well, our minds and ears are flexable to the complicated sounds of the world.  We're not naturally used to the constant pulse of set tempos.  Our heartbeats are variable, and slow and speed in phases, and there's not really that much in the natural world which exerts a constant audible tempo.  So, when we try to play a steady tempo without a metronome, what we will actually do is slightly speed up, slow down, and compensate when we fall behind the beat.  As soon as a group of musicians trained in such a way gets together, everyone will be in time with themselves, and out of time with others(I've been there, it's not pretty).
Enter the metronome.
The metronome is constant, unyeilding.  It does not forgive, it does not forget.  When you play 50 ms out of time and there's a metronome there, you can hear the difference, and it's not the metronome's fault that you were out.  Playing to a metronome makes you consistent.  It makes every one of the people playing along consistent, and it enables players to develop a sense of timing to use while they play with themselves and each other.
It can also help you with playing faster, and more accurately quicker,  see these questions:
Technique or exercise to play this part from a song which i'm stuck with
I find myself making the same mistake when practising - despite focussing on that part- how to remedy?
As a parting note I'd say I never used to practice with a metronome, and my skill went up rapidly as soon as I started doing it.  Getting into the habit of practicing with a metronome is a huuuuuuuuge benefit in both the short and the long run.
Hope that helps :)
Comment: I'm interested in the statement that we aren't naturally inclined to (fixed) rhythm. Do you have some sources that develops this further? Not saying that it's wrong, I'm interested in knowing more, since it goes against some intuitive notions. (And I'm definitely not saying that metronomes aren't a great aid in advancing musical skills...)
Comment: @leftaroundabout: I strongly agree, except plenty of great musicians benefit a lot from metronome practice as well.  They just use it differently, more as a checking than a corrective device.
Comment: OTOH, if a group of musicians has trained really a lot "syncing" their respective clocks, everyone will be in time with everyone else but not to any fixed tempo, which sounds [amazingly](http://www.youtube.com/watch?v=JvoG36nUcSU) better than anything you can achieve with practising to metronome (let alone, recording songs to a click track!) And good musicians will also find their way to others' tempo quite easily in a jam session. — That notwithstanding, many not-so-great musicians have timing that would indeed benefit a lot from metronome practise...
Answer: A metronome can do several things.  If a piece has a metronome marking, it can give you some idea of a composer's (or often an editor's) idea of how fast it should go.  Also, it can give you an idea of whether your tempos through a piece are consistent.  Especially when you are beginning to work on a piece, you can find that you are playing easier sections faster than harder ones without realizing it, and your tempo can get inconsistent.  A metronome will point this out to you in a hurry.
It can give you a sort of benchmark on how well you are coming along with a difficult piece as you are working it up.  It's especially useful in this last regard.  Try putting the metronome on at a speed where you can practice the entire piece without making (many) mistakes.  You'll be surprised to see how slow some easier parts sound when you're trying to play them at the same speed as more difficult parts elsewhere, at a tempo slow enough to accommodate the tougher sections.
Now, all that said, be very careful NOT to overdo it.  You have to always keep the music in mind before the notes.  If you just try to get the notes without playing the music, you'll find that you have trained your hands to play the piece unmusically.  ("Metronomic" is a criticism of a performance that sounds too slavish in its adherence to a tempo, to the point that all the music is squeezed out of it.)
The further along you are with the piece, the less useful the metronome is.  You can always use it to "spot check" your tempos; see if you're playing the whole piece faster than you think you are, see how consistent your tempos are from section to section, and so on.
Comment: 1) standard rock guitar method: play a part at a tempo where you can play it without error and without tension. Speed it up. Practice until you can play the part without tension and error at the new tempo. This is for better speed.

2) Victor Wooten's suggestion:  play a part at a tempo where you can play it without error and without tension. Drop the tempo by half and practice with the beats as 1 and 3, or 2 and 4. Drop by half again and have it be the 1. Then 2, etc. Then, from 1-and-2-and-3-and-4, put the beat on an "and". This is for a better sense of time.
Comment: @user139024 Your question doesn't really make sense...what VarLogRant is describing is practicing a section at a single tempo but with the metronome clicks on different beats or off-beats.
Comment: @KyleStrand, he explained it at a live event at Sweetwater Sound. Took some searching, but I found him explaining it here. https://www.youtube.com/watch?v=9X1fhVLVF_4
Comment: @user139024 Syncopation is a quality of the music-scanning itself, not of your practicing technique, but yes, this idea is similar to syncopation. However, it's not the *downbeats* that appear in unexpected places (since downbeats are always in the same place), but the *metronome clicks* (in syncopation, it's the *emphasized beats* (or "strong beats") that appear in unexpected places). I have no idea what your question about how to play the beats on the guitar means.
Comment: What is the best way to practice using a metro? In your idea
Comment: What is the difference between 1324 and 1234?
Comment: @VarLogRant I love Wooten, but I don't think I've heard that (I don't remember it being in *The Music Lesson*, at least). Sounds like an interesting suggestion. Do you by chance have a source?
Comment: Here's a semi-visual way of explaining it. One measure will be notated as `1 + 2 + 3 + 4 +`, where each number is a beat and each `+` is an off-beat. The beat(s) where the metronome will click will be in bold. "...practice with the beats as 1 and 3, or 2 and 4" means either **1** + 2 + **3** + 4 + or 1 + **2** + 3 + **4** +. "...from 1-and-2-and-3-and-4, put the beat on an 'and'" means something like 1 + 2 **+** 3 + 4 +. (Presumably you'd do this four times, once for each `+`.)
Answer: Two additional points beyond BobRodes's answer

For using the metronome as a gauge for progress with specific agility/speed exercises: e.g. taking a given exercise and increasing the metronome rate each day for a period of time.
Focusing on listening to the click is a basic step towards being able to listen to other performers when in an ensemble situation.
Answer: In relation to the last part of your question, yes, it's directly related to time sigs.There are metronomes which can be set to 'ping' on beat one, whether the time sig. is 2, 3 4 5 or 6 on the top.So you can hear when each new bar starts. The tempo can also be used as a good guide, in that, say it's 80 b.p.m. - if you wanted, you could set 160 to give a tick twice as quick, which sometimes helps to keep you in time better. When you got pretty good, you could go down to half speed, 40 b.p.m. and work harder to keep in time. B.p.m. incidentally, is beats per minute, in other words, how many ticks the metronome will sound in one minute. 60 b.p.m. = one tick per second.
Having said all that, I still prefer to have a drum track playing to keep time to. Probably used to playing with real drummers for many, many years...
Answer: When I practise with the metronome I often imagine the ticks are on the off-beats, so if I were counting out loud "one and two and three and four and" then a tick would fall on each "and", rather than on a number. If you don't already do this, you have to try it.
The skill in this is that you must mentally construct the unheard on-the-beat tick. With practice you can mentally flip between hearing the tick on the beat and off the beat. It's like the rhythmic equivalent of one of those optical illusions where you can interpret what you're seeing in more than one way.
Further practice with this is to play tuplets against the off-beat tick. This is hard(!) but worth while.


divisors on relative projective space

Question: Let $X$ be a separated irreducible variety which is regular in codimension $1$ (I want to talk about Weil divisors), and write $\mathbb{P}^n_X = \mathbb{P}^n_k \times X$ for the projective space over $X$. Now if $Y \subset \mathbb{P}^n_X$ is a prime Weil divisor, i.e. an irreducible closed subvariety of codimension $1$, we can consider the generic fiber $Y_K$ (here $K$ is the function field of $X$).
Since closed embeddings are stable under base change, $Y_K$ is a closed subscheme of $\mathbb{P}^n_K$, and clearly $Y_K \neq \varnothing$ if and only if the projection of $Y$ to $X$ is dense. My question: in this case ($Y_K \neq \varnothing$), can we conclude that $Y_K$ is an integral subvariety of $\mathbb{P}^n_K$ of codimension $1$? Hopefully this is true, since then we will have a well-defined degree map $\text{Pic } \mathbb{P}^n_X \to \mathbb{Z}$.
Edit: Maybe I should be asking a more general question: if $Y \to X$ is a dominant morphism of (separated, if necessary) irreducible varieties and $K$ denotes the function field of $X$, is $Y_K = Y \times_X \text{Spec } K$ an irreducible variety over $K$? The codimension $1$ assertion seems easier, since it is local, but I don't know a good criterion for irreducibility.
Comment: What about $Y_K$ being reduced? This seems to be wrong in general (but I haven't given it much thought).
Answer: I guess you mean by "irreducible varieties" integral scheme of finite type. Then the anwser is yes.
First the local rings of $Y_K$ are localizations of local rings of $Y$ (can replace $X$ by an affine dense open subvariety, then $K$ is a localization of $O(X)$), so $Y_K$ is locally integral.
Second, the generic point of $Y$ belongs to $Y_K$, so it is also the generic point of $Y_K$. This implies that $Y_K$ is irreducible.
Edit Codimension of $Y_K$. Let $d=\dim X$. Then $\dim Y=n+d-1$, and we have
$$\dim Y_K=\dim Y - \dim X=n-1$$
(dimension formula for irreducible algebraic varieties).
So $Y_K$ is of codimension $1$ in $\mathbb P^n_K$.
Comment: What about the codimension $1$ question?
Comment: @JustinCampbell: I didn't see the codimension 1 question.

divisors on relative projective space


Characterizing maximal ideals in $\mathbb{Z}[x]$

Question: I need to prove this:
Let $I\subset\mathbb{Z}$ be the ideal generated by $\{p,f(x)\}$, with $p$ prime in $\mathbb{Z}$. Then $I$ is maximal iff $f(x)$ is irreducible modulo $p$.
So I was trying to prove that if $f(x)$ is not irreducible modulo $p$ then $I$ is not maximal by taking the ideal generated by $\{p,g(x)\}$ where $g(x)$ divides $f(x)$ modulo $p$.
And for the other part I was trying to prove that $\mathbb{Z}[x]/I$ is a field, but it didn't go so well.
Comment: you have the right idea.  $\mathbb{Z}[x]/I\simeq(\mathbb{Z}[x]/(p))/(I/(p))\simeq\mathbb{Z}_p[x]/(f(x))$
Comment: and a maximal ideal is prime, so if $f(x)$ is reducible then it does not generate a prime ideal.
Answer: As you say, if $I$ was maximal then $f$ must be irreducible. Conversely, notice that $\mathbb{Z}[x]/(p,f(x))\cong\mathbb{Z}_p[x]/(f(x))$. If you know something about finite fields, you will be done. If you don't, then argue as follows: Since $f$ is irreducible, every non-zero element of the quotient comes from an element $g\in\mathbb{Z}_p[x]$ that is coprime to $f$. By the euclidean algorithm we can find $a,b\in\mathbb{Z}_p[x]$ such that $fa+gb=1$. Looking at this equality in the quotient gives us an inverse for $g$ i.e. we have a field.


cannot convert data (type interface {}) to type string: need type assertion

Question: I am pretty new to go and I was playing with this notify package.
At first I had code that looked like this:
func doit(w http.ResponseWriter, r *http.Request) {
    notify.Post("my_event", "Hello World!")
    fmt.Fprint(w, "+OK")
}

I wanted to append newline to Hello World! but not in the function doit above, because that would be pretty trivial, but in the handler afterwards like this below:
func handler(w http.ResponseWriter, r *http.Request) {
    myEventChan := make(chan interface{})
    notify.Start("my_event", myEventChan)
    data := <-myEventChan
    fmt.Fprint(w, data + "\n")
}

After go run:
$ go run lp.go
# command-line-arguments
./lp.go:15: invalid operation: data + "\n" (mismatched types interface {} and string)

After a little bit of Googling I found this question on SO.
Then I updated my code to:
func handler(w http.ResponseWriter, r *http.Request) {
    myEventChan := make(chan interface{})
    notify.Start("my_event", myEventChan)
    data := <-myEventChan
    s:= data.(string) + "\n"
    fmt.Fprint(w, s)
}

Is this what I was supposed to do? My compiler errors are gone so I guess that's pretty good? Is this efficient? Should you do it differently?
Answer: According to the Go specification:

For an expression x of interface type and a type T, the primary expression x.(T) asserts that x is not nil and that the value stored in x is of type T.

A "type assertion" allows you to declare an interface value contains a certain concrete type or that its concrete type satisfies another interface.
In your example, you were asserting data (type interface{}) has the concrete type string. If you are wrong, the program will panic at runtime. You do not need to worry about efficiency, checking just requires comparing two pointer values.
If you were unsure if it was a string or not, you could test using the two return syntax.
str, ok := data.(string)

If data is not a string, ok will be false. It is then common to wrap such a statement into an if statement like so:
if str, ok := data.(string); ok {
    /* act on str */
} else {
    /* not string */
}

Answer: Type Assertion
This is known as type assertion in golang, and it is a common practice.
Here is the explanation from a tour of go:

A type assertion provides access to an interface value's underlying concrete value.

t := i.(T)

This statement asserts that the interface value i holds the concrete type T and assigns the underlying T value to the variable t.
If i does not hold a T, the statement will trigger a panic.
To test whether an interface value holds a specific type, a type assertion can return two values: the underlying value and a boolean value that reports whether the assertion succeeded.

t, ok := i.(T)

If i holds a T, then t will be the underlying value and ok will be true.
If not, ok will be false and t will be the zero value of type T, and no panic occurs.

NOTE: value i should be interface type.
Pitfalls
Even if i is an interface type, []i is not interface type. As a result, in order to convert []i to its value type, we have to do it individually:
// var items []i
for _, item := range items {
    value, ok := item.(T)
    dosomethingWith(value)
}

Performance
As for performance, it can be slower than direct access to the actual value as show in this stackoverflow answer.
Answer: //an easy way:
str := fmt.Sprint(data)

Comment: Add some explanation with answer for how this answer help OP in fixing current issue
Comment: This is worked just convert interface{} into string.. thank you.
Answer: As asked for by @ρяσѕρєя an explanation can be found at https://golang.org/pkg/fmt/#Sprint. Related explanations can be found at https://stackoverflow.com/a/44027953/12817546 and at https://stackoverflow.com/a/42302709/12817546. Here is @Yuanbo's answer in full.
package main

import "fmt"

func main() {
    var data interface{} = 2
    str := fmt.Sprint(data)
    fmt.Println(str)
}

Comment: I guess you could combine both answers by simply editing @Yuanbo's — you both will be credited and add up your respective 'usefulness' score
Answer: In addition to other answers, I think it's good to have a look at "type switch":
package main

import "fmt"

func printType(i interface{}) {
    switch v := i.(type) {
    case int:
        fmt.Printf("type of %v is %v\n", i, v)
                 // type of 21 is int
    case string:
        fmt.Printf("type of %v is %v\n", i, v)
                 // type of hello is string
    default:
        fmt.Printf("type of %v is %v\n", i, v)
                 // type of true is bool
    }
}

func main() {
    printType(21)
    printType("hello")
    printType(true)
}

I hope it helps.
More information: https://go.dev/tour/methods/16


firebase cloud messaging (using app client)

Question: Google said FCM is free. What is this mean? Can anyone explain that?

registration_ids:
This parameter specifies a list of devices (registration tokens, or IDs)       receiving a multicast message. It must contain at least 1 and at most 1000 registration tokens.
At most 1000? What if i have 2000 users(tokens).
One more problem. there is some mistake in my php script, i could only send noticication to one token(top most row token from taken), plse check my send.php:
table is simple only 1 column with list of tokens.
<?php
require "info.php";
$message = $_POST["message"];
$title = $_POST["title"];
$path_to_fcm = "https://fcm.googleapis.com/fcm/send";
$server_key = "*******************************";
$sql="select token from fcm";
$result = mysqli_query($con,$sql);
$column = mysqli_fetch_row($result);

$key=$column[0];

$headers=array('Authorization:key=' .$server_key,
'content-Type:application/json');

$fields=array('registration_ids'=>$key,
'notification'=>array('title'=>$title,'body'=>$message));

$payload = json_encode($fields);
$curl_session = curl_init();
curl_setopt($curl_session, CURLOPT_URL, $path_to_fcm);
curl_setopt($curl_session, CURLOPT_POST, true);
curl_setopt($curl_session, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl_session, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl_session, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_setopt($curl_session, CURLOPT_POSTFIELDS, $payload);
$result=curl_exec($curl_session);
curl_close($curl_session);
mysqli_close($con);
?>

Please help I am stuck with my project.
Comment: Please limit yourself to one question per post.
Answer: Please review bellow example, and also take care of parameters sent to FCM server. like 'to','notification','data'
$registrationIds=array();

//select user RegistrationIDs/Token from DB
$con=mysqli_connect("localhost","my_user","my_password","my_db");
$sql="SELECT `reg_id` from users;";
$result=mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($result)) {
    array_push($registrationIds,$row["reg_id"]);
}
mysqli_close($con);

$msg = array(
    'body' => "My First Blog Description",
    'title' => "My First Blog"
);

$noti_key='YOUR_FCM_REGISTRATION_KEY';

$registrationIds_chunk=array_chunk($registrationIds,1000);
foreach($registrationIds_chunk as $single_chunk){
    if(count($single_chunk)==1){
        $fields = array
        (
            'to'=>$single_chunk[0],
            'notification'=> $msg
        );
    }else{
        $fields = array
        (
            'registration_ids'=>$single_chunk,
            'notification'=> $msg
        );
    }

    $headers = array
    (
        'Authorization: key='.$noti_key,
        'Content-Type: application/json'
    );

    $ch = curl_init();
    curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
    curl_setopt( $ch,CURLOPT_POST, true );
    curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
    curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
    curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields, true ) );
    $result = curl_exec($ch );
    curl_close( $ch );
}

Comment: Plse rewrite the above code with given paramaters, i am not experience developer so its making me confuse.
$token (plse extract from table table_name fcm with 1 column token)
$title
$message
(no to  need to pass extra data with notification)
use database to get tokens
plse plse
Comment: plse exclude $data (i dont want to send data)..instead include $title(notification title)..
Comment: try to print $result variable and reply here. let's check what response you got.
Answer: Yes Firebase is free for FCM service.
registration_ids is a ID that is generated by device(Mobile) and send to server, if your app using Firebase.
Firebase use that ID and send any type of notification to number of devices.
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

    private static final String TAG = "MyFirebaseIIDService";

    /**
     * Called if InstanceID token is updated. This may occur if the security of
     * the previous token had been compromised. Note that this is called when the InstanceID token
     * is initially generated so this is where you would retrieve the token.
     */
    // [START refresh_token]
    @Override
    public void onTokenRefresh() {
        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Refreshed token: " + refreshedToken);

        // TODO: Implement this method to send any registration to your app's servers.
        sendRegistrationToServer(refreshedToken);
    }
    // [END refresh_token]

    /**
     * Persist token to third-party servers.
     *
     * Modify this method to associate the user's FCM InstanceID token with any server-side account
     * maintained by your application.
     *
     * @param token The new token.
     */
    private void sendRegistrationToServer(String token) {
        // Add custom implementation, as needed.
    }
}


Show that $H_n(C_f)=0$

Question: Let $C=\{(C_n,\partial_n)\}_{n\in\mathbb{Z}}$ and $C'=\{(C_n',\partial_n')\}_{n\in\mathbb{Z}}$ be chain complexes of vector spaces. Let $f:C\to C'$ be a chain map. Define a new chain complex $C_f=\{(D_n,\overline{\partial}_n)\}$ as follows:
$D_n=C_{n-1}\oplus C_n'$
$\overline{\partial}_n(x,y)=(-\partial_{n-1}(x),\partial_n'(y)+f_{n-1}(x)).$
I've been proposed the following exercise:

If $f_*:H_n(C)\to H_n(C')$ is an isomorphism, then $H_n(C_f)=0$.

What I've done so far:
Let $[(x,y)]\in H_n(C_f)$. I will try to show that $[(x,y)]=[(0,0)]$ by showing that there exists $(c_1,c_2)\in C_n\oplus C_{n+1}'$ such that $\overline{\partial}_{n+1}(c_1,c_2)=(x,y)$.
By definition, $\overline{\partial}(x,y)=(-\partial_{n-1}(x),\partial_n'(y)+f_{n-1}(x))=(0,0)$. From this, I get $\partial_{n-1}(x)=0$, so $x\in Z_{n-1}(C)$ ($x$ is a cycle in $C$) and it makes sense to consider its homology class. On the other hand, from the second component I get
$[0]=[-\partial_n'(y)]=[f_{n-1}(x)]=f_*[x].$
Since $f_*$ is isomorphism, this implies $[x]=[0]$ and hence $x\in B_{n-1}(C)$ ($x$ is a boundary), which implies that there exists $c_1\in C_n$ such that $-\partial_n(c_1)=x$.

Now I've got left to find $c_2\in C_{n+1}'$ such that $y=\partial_{n+1}'(c_2)+f_n(c_1)$. I haven't still used the surjectivity of $f_*$, but I don't know how to use it since in general $y$ does not define a homology class.
How can I find $c_2$?
Comment: Do you know about the long exact sequence of a SEC of complexes?
Comment: @PedroTamaroff yes I do, how can I use it?
Answer: What underlies this problem is the long homology exact sequence associated to a short exact sequence of complexes, which I will explain.
As in your set-up, let $f: C\to C'$ be a map of complexes, and let $\text{cone}(f)$ denote the cone of the map, which you already explained how to construct. There is a short exact sequence of complexes
$$\tag 10\to C'\to \text{cone}(f) \to C[-1]\to 0$$
where the maps are the usual inclusion and projection.
Claim The connecting map $H(C[-1])= H(C)[-1] \to H(C')[-1]$ is the map induced by homology by $f$.
Proof. Suppose that $c\in C[-1]$ is a cycle. You can lift this to $(0,c)$, which has differential $(f(c),0)$. This certainly lifts to $f(c)$ in $C'$, so the snake lemma produces the map $[c]\to [f(c)]$, which is precisely $f_*$.
Now you can look at the LES of $(1)$ to conclude.
Answer: You can also solve this "by hand".
Suppose that $(c,c')$ represents a cycle in the cone. You want to find $(b,b')$ such that $d(b,b') = (f(b')-db,db') = (c,c')$.
Since $(c,c')$ is a cycle, $dc = f(c')$ and $dc'=0$. Note then that in particular $c'$ represents a cycle and $f(c')$ represents a boundary. Since $f$ induces an isomorphism in homology, this means that $c'$ must be a boundary, that is, $c' = db''$, so we have solved for the second coordinate. (Almost, in fact!)
Note, moreover, that $a = c-f(b'')$ is such that $da= dc-f(db'') = dc-f(c')=0$, that is, it is a cycle in $C'$. Since $f_*$ is onto, this means there is a cycle $a'$ and some $b$ such that $f(a')-db = c-f(b'')$.
Finally, note that $c' = d(b''+a')$ since $a'$ is a cycle, and that $f(a'+b'')-db = c$. Thus $d(b,a'+b'') = (c,c')$, as you wanted.
Comment: @Javi Well, they are equivalent results, anyways!
Comment: I liked more your other answer, but I wasn't supposed to use the Snake Lemma since it hasn't been seen in class. Therefore this one is more useful to me. Anyways, which one do you prefer to be accepted?
Comment: @Javi Which question you accept is not really relevant. However, how did you prove the existence of the LES *without* the Snake Lemma?
Comment: Explicitly defining the connecting map. In the exercises, we show the Snake Lemma as a consecquence of the LES.

Show that $H_n(C_f)=0$


Thread 1 Error on VC push?

Question: My app currently has 3 VCs. The rootVC modally presents the second VC via UIButton--which works fine--but I'm having trouble getting the third VC appear after a UILabel tap in the second VC.
This is the code in the SecondVC that handles the tap:
var goToStats : UILabel {
        var label = UILabel()
        label.frame = CGRect(x:0, y:0, width: 300, height: 60)
        label.center = CGPoint(x: view.center.x, y: view.center.y + 250)
        label.text = "Statistical Breakdown"
        label.font = UIFont(name: "Arial", size: 30)
        label.textAlignment = .center
        label.backgroundColor = UIColor(
                displayP3Red: 1/255,
                green: 102.0/255,
                blue: 102.0/255,
                alpha: 1)
        label.isUserInteractionEnabled = true
        label.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTap)))
        return label
        }

    view.addSubview(goToStats)
}

@objc func handleTap() {
    print("Tapped!")

    let thirdVC = ThirdVC()
    self.navigationController!.present(thirdVC, animated: true, completion: nil)
}

Upon running, I get the following error:
error
Is there any explanation? I thought maybe there is no navigation Controller associated with the second VC (since it's returning nil), but the VC itself sits on a navigational stack, so I don't think that's the case here. Is it a problem with my third VC? Here is the current code:
import Foundation
import UIKit

class thirdVC : ViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    view.backgroundColor = UIColor.green
}

}
Thanks for your time!
Comment: It appears that `SecondVC` is not in a navigation controller or `statsViewController` is `nil`. Don't you mean to present `thirdVC`?
Comment: statsViewController is a typo, sorry! I meant to replace it with thirdVC to make the code more readable. The root VC is definitely in a navigation controller because I used the same code to present the secondVC. Does that automatically make the second VC a navigational controller? Sorry I'm really new to all of this.
Answer: Your rootViewController could be a navigationController but when you present something like this,
let secondVC = SecondVC()
self.navigationController!.present(secondVC, animated: true, completion: nil)

This doesn't mean that SecondVC will have a navigationController. To have a navigationController for SecondVC, you need to embed this ViewController inside a navigationController as below,
let secondVC = SecondVC()
let secondNavC = UINavigationController(rootViewController: secondVC)
self.navigationController!.present(secondNavC, animated: true, completion: nil)

Now, if you will present ThirdVC as below from SecondVC then it will work
let thirdVC = ThirdVC()
self.navigationController!.present(thirdVC, animated: true, completion: nil)

If you haven't embedded second ViewController inside a UINavigationController, then you will get that crash because you are force unwrapping(!) the navigationController which is not available in second ViewController.
Comment: oh hey again! This question was ages back but thanks. So, if I'm understanding correctly, every VC needs to be embedded in it's own UINC? That seems to be at odds with the purpose of a NC in the first place. I'm doing this all programmtically, so that might change things, but whenever I see people handle multiple VCs it seems like they only have one NC. Or does it have to do with modall presentation? Like every VC that is presented modally needs to be in it's on NC if there are additional VCs
Comment: Yes this requirement is only valid for modal presentations. For push you don't really need to embed every viewcontroller.

Thread 1 Error on VC push?


Which tennis matches are best of 5?

Question: I am researching statistical characteristics of tennis matches. I need to know reliably which tennis matches are best of 3, and which ones are best of 5.
Is it strictly the case that only men grand slams are best of 5? Are the venues for the grand slams only used for grand slams (e.g. if I see that the venue of a tennis match is Wimbledon, am I guaranteed that this is the Wimbledon Grand slam)? Or are there sometimes some matches in these venues that are not part of the Grand slams?
Answer: Grand Slam mens singles and doubles are best of five sets.  The same is true of the Davis Cup.  However all other matches, male and female, and including the end of season ATP World Tour Finals, are best of three sets.
With regards the venues, I know that they can be used for Davis Cup as well as the Grand Slam, but as this just means the same number of sets, for your requirements, this is not a problem.
Comment: But last Olympics was played at Wimbledon & it was a best of 3 set matches
Comment: All matches at the last olympics where best of 3 except the final see (https://en.wikipedia.org/wiki/Tennis_at_the_2012_Summer_Olympics#Format)
Answer: All ATP tournamnet matches (singles/doubles) are best of three except for Grand Slam singles, that are best of five, Wimbledon doubles (best of five) and Olympics (best of five).
The only Grand Slam with doubles played best of five sets is Wimbledon.
The venues are used for Davis Cup matches.

Which tennis matches are best of 5?


Prevent User From Triggering Multiple Scrolling

Question: I have a HomePageContainers which holds the data for the AJAX requests and pass down to HomePage component. HomePage component is composed via an higher order function InfiniteScroll which supports scrolling.
The InfiniteScroll looks like this:
componentDidMount() {
    window.addEventListener('scroll', this.onScroll.bind(this), false);
}

componentWillUnmount() {
    window.removeEventListener('scroll', this.onScroll.bind(this), false);
}

onScroll() {
    if ((window.innerHeight + window.scrollY) >= (document.body.offsetHeight - 200)) {
        const { scrollFunc } = this.props;
        scrollFunc();
    }
}

I want the code to prevent scrolling once they fired one and wait till the data arrives from the request. Something like:
 ((window.innerHeight + window.scrollY) >= (document.body.offsetHeight - 200)) + //a new condition to make sure only scroll happens when data arrives or fails.

Note that the scrollFunc will be received from HomePageContainers which is going to update its state according to AJAX request/responses.
I can store the scrolling state in HomePageContainers as @Igorsvee mentioned but I want those state to go to InfiniteScroll component as its responsible for handling the scrolling events.
How will I do it?
Answer: Assuming that the HomePageContainers component issues ajax requests, you could add a new isFetching flag to it's state and pass it down along with scrollFunc so that you can conditionally invoke it:
if(this.props.isFetching){
   scrollFunc();
}

isFetching should be true when a request starts, false when it ends with success or error.
Or you could have the conditional logic inside the scrollFuncitself:
if(this.state.isFetching){
...
}

Comment: Yeah this way I can do it. `HomePageContainers` is just for handling the data. So the sate will be equal to AJAX response state. Was thinking whether its a good idea to have scrolling data in `HomePageContainers` as have `InfiniteScroll` separately which is responsible for scrolling and its activity (for which I feel its bad) .


Criar uma "tarja com opacidade" em cima de um

Question: Tenho uma tabela gerada dinamicamente:

Gostaria de criar uma classe no CSS que fizesse uma "camada" por cima, com transparência.
Exemplo:

Se eu usar o background-color, ele só irá mudar o fundo, então teria que ser algo por cima. Então não serviria.
O código da tabela é básico, são
 e , então não faz diferença postar o código dela.
Comment: @bfavaretto consegui fazer sem precisar clocar o border-collapse na table :), apesar de não ser muito elegante... Olha lá a opção 1 que editei na resposta.
Comment: Boa @hugocsl. Nesse caso gambiarra tá valendo, porque não é um problema trivial (como você sabe, não pode violar a sintaxe HTML das tabelas).
Comment: Uma forma usando JS: https://jsfiddle.net/zd3uwgsh/7/
Comment: Quase isso. Apenas tem a classe `.overlay` que precisa colocar no CSS, mas se não quiser mexer no CSS pode colocar as propriedades diretamente inline no span pelo JS. Como os spans tem posição e altura fixa, caso queira que seja responsivo, é preciso adicionar mais uns códigos, mas isso não seria problema.
Comment: Pintar o background e mexer na opacity da tr talvez dê um resultado muito semelhante. Já tentou?
Comment: Então, mas só muda o fundo, os elementos ficam por cima como eu disse sobre o `background-color`... a não ser que seja outra forma, e/ou tenha como "subir" o background do `` em cima dos ``.
Comment: Mas você mexeu também na opacidade da ``? Reduzindo a opacidade, tanto o fundo quanto o conteúdo vão ficar com transparência, talvez fique próximo do resultado que você quer.
Comment: @bfavaretto Acho que é o que o hugocsl respondeu... acho que era essa `position: absolute;` que manda pra frente! Agradecido! ✌
Comment: Sim, a resposta dele é o melhor caminho. Talvez seja o mais genérico possível. Só acho que não funciona sem border-collapse na tabela.
Comment: @bfavaretto realmente ele fugiu da ``...
Comment: @bfavaretto isso mesmo, se deixar o collapse da borda fica um espaço em brando entre uma célula e outra....
Comment: @sam Dessa forma você criou um `` por cima do ``, e assim não preciso nem alterar o CSS, somente adicionar a classe na `` que eu preciso por a tarja, seria isso?
Comment: Mas no geral é isso mesmo, basta colocar a classe .tarja na tr que vc quer.
Answer: Opção 1:
Nessa opção vc coloca um box-shadow: inset bem grande na TR, e coloca position:relative nas TD para poder colocar um z-index:-1 nelas e jogar pra traz da sombra da TR. A intensão do box-shadow e não precisar setar border-collapse na table devido ao seu framework.

.tab {
    width: 100%;
}
.tab tr.ativa  {
    box-shadow: inset 0 0 0 1000px rgba(255,0,0,0.5);
}
.tab tr td  {
    padding: 10px;
    position: relative;
    z-index: -1;
}

            <item>1</item>

            <item>2</item>

            <item>3</item>

            <item>4</item>

            <item>a</item>

            <item>s</item>

            <item>d</item>

            <item>f</item>

            <item>a</item>

            <item>s</item>

            <item>d</item>

            <item>f</item>

Opção 2:
Solução e criando um ::after nas tds e no hover na tr vc mostra o ::after. Veja que ele está por cima do conteúdo como vc queria.

.tab {
  width: 100%;
  border-collapse: collapse;
}
.tab td {
  padding: 10px;
  position: relative;
}
.tab tr:hover td::after {
  content: "";
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  background-color: red;
  opacity: 0.5;
}
.tab tr.ativa td::after {
  content: "";
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  background-color: red;
  opacity: 0.5;
}

      <item>1</item>

      <item>2</item>

      <item>3</item>

      <item>4</item>

      <item>a</item>

      <item>s</item>

      <item>d</item>

      <item>f</item>

      <item>a</item>

      <item>s</item>

      <item>d</item>

      <item>f</item>

Comment: Mas dessa forma ele ficaria em todos ao passar o ponteiro, não é? Se for, não seria isso. Eu preciso que fique fixo. Pois serão alguns que terão essa tarja. E aí a ideia por uma classe, assim eu consigo colocar ou não dinamicamente.
Comment: @RBZ Não, só vai ficar sobre a TR que vc passar o mouse. Veja na edição que fiz na resposta que inclui mais uma TR. Entendi vou editar novamelte
Comment: @RBZ editei novamente, agora repare que a TR com a classe .ativa fica vermelha direto, mesmo sem o mouse nela.
Comment: Isso! Exatamente! .. Só uma dúvida, tenho que manter o `tr:hover td::after`? Ou posso só fazer o `tr.ativa td::after`?
Comment: @RBZ pode retirar esse classe tranquilamente. e cloque a classe ativa na TR que quiser. Ou comente o CSS vai que vc precisa depois...
Comment: Cara, não funcionou. Ele começa a tarja no início da página. O maior problema é que uso framework, então preciso criar uma classe no final, sem alterar o resto, se não afeta outras partes. [Materializecss](https://materializecss.com/)
Comment: @RBZ eu não entendi direito o problema, mas editei a resposta, agora eu coloquei a `class="tab"` na tabela e ajustei o CSS para atingir apenas os elementos dentro da tabela com a classe .tab
Comment: Agora aparentemente funcionou. Mas infelizmente ele está matando alguns elementos da table do framework... Teria que tratar 1 a 1 né?
Comment: Calma jovem, to pensando em uma gambeta aqui que acho que vai funciona já te falo. só um min
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/80780/discussion-between-rbz-and-hugocsl).
Comment: Abri um chat, assim consigo te mandar print
Answer: Acho que dessa forma vai pode te ajudar. E é bem simples:

table, th, td {
border: 1px solid black;
padding: 5px 10px;
}
table{
background: #e0e0e0;
}
td{
border:none;
}

.red {
background: red;
opacity: .5;
}

   Nº
   HORA
   Placa
   Tipo
   Tara

   Nº
   HORA
   Placa
   Tipo
   Tara

   Nº
   HORA
   Placa
   Tipo
   Tara

Comment: Não está ficando por cima, mas funciona.
Answer: Pode criar um elemento qualquer (um div por exemplo) dentro da TD para fazer isso:

td {
  border: solid 1px;
  padding: 4px;
  text-align: center;
  position: relative
}

.tarja {
  position: absolute;
  width: 80%;
  height: 10px;
  left: 10% ;
  margin: -12px 0 0 0;
  background-color: #000;
  opacity: 0.8
}

    texto qualquer

    texto qualquer

    texto qualquer

Usei position na TD e na div para facilitar o posicionamento dentro da TD, dai pode usar o tamanho em porcentagem e facilitar o posicionamento.
Comment: Posso usar a `` pegando todos os ``?
Comment: nesse exemplo tem q ter uma div por td :(
Comment:  ... é aí salgou demais! rs ... Vou testar as respostas aqui, ver qual aplica de forma mais simples no meu caso. Mas agradeço! ✌
Comment: uma outra alternativa seria usar uma imagem que poderia ser posicionada no background da `td`
Comment: Mas aí ficaria atrás dos elementos, não é?


Collaboration. Is there a site that allows musicians to find and work with each other on compositions?

Question: There are hoards of sites on which to place finished products: scoreascore, sound cloud, etc. But, is there a site that allows musicians to find and work with each other on compositions?
For example, I compose in Musescore. I record bass and piano myself but my skills (and budget) in recording and mastering are rather weak.
Answer: It sounds like you are looking for a website that allows you to submit your work and combine with other people's work.  I know of two websites that allow you to do so.

CoCompose    http://www.cocompose.com
Here you have two options:

Start a Project and set restrictions on the type of content by making a
a) Private Project - Where you have to invite people to make changes
b) Public Project - Where you allow anyone to add their ideas (with the          power to choose who makes the final cut of course.)
Write and upload music with the intention of completing someone else's project.

There are three accounts you can register for and all of them are free. There is also a leaderboard that tracks whose composition has the most popularity.

http://www.kompoz.com
This website operates very similarly to the first, but it has a brighter interface to it.  The main music here is Singer/Songwriter, Country, Pop, Rock, and Blues

Hope this helps.
Comment: Sadly, CoCompose no longer exists. Kompoz is pretty good, though.
Answer: Another possibility is BandHub. This probably isn't quite what you're looking for, but it's essentially a multi-track youtube, with various people able to record & upload new video tracks to a song. It's focused more on recording, than on composing, arranging, mixing, or mastering.
My experience is that it's not so good with the post-production & editing side of things. For example, AFAICT, it doesn't really give you a chance to edit what you record before uploading; once you've recorded a track, you either upload it right then, or you don't. Of course, it's been a while since I've looked at it, so things may have changed.
Answer: Noteflight (https://www.noteflight.com/) and Flat (https://flat.io/) are both online music notation editors that support collaboration.


How do I theme a webform email?

Question: I have a subscription form created with webform. When the user submits the form I want to send a customised confirmation e-mail that includes some social links, images and site logo. I have looked for multiple solutions but none of them makes any sense?
Any help?
Answer: The Drupal module, Easy Email, might be worth looking at.  A YouTube presentation of the Easy Email module is at https://www.youtube.com/watch?v=5V3rMJwPhY8
Answer: This was pretty easy in the end. Webform by default doesn't provide you  an option of sending HTML emails. Here is a list of contrib modules you can use to send richly formatted HTML Emails:- https://firstname.lastname@example.com/how-to-send-richly-formatted-html-emails-in-drupal-8-deliver-the-experiences-that-your-customers-1a29626b7f2e
I used HTML MAIL because it is pretty easy to work around and also integrates contrib modules like Mail MIME modules, echo, Transliteration etc. and provides you much more options to customise your emails. You can download it here https://www.drupal.org/project/htmlmail. Also check for requirements.
Here is the documentation for HTML MAIL https://www.drupal.org/docs/8/modules/html-mail.
To make it simple. All you need to do is.
1. Download and enable the HTML Mail module.
2. Copy the htmlmail--htmlmail.html.twig template to your theme directory.
3. You can follow the naming convention from the above documentation. e.g:- if your form name is newsletter than your template name for that specific form will be htmlmail--webform--newsletter_email.html.twig
4. You also need to enable Mail system module. And in admin/config/system/mailsystem add the module specific configuration which in my case was webform.

How do I theme a webform email?


Install a certificate (SSL Encryption) on SQL Server 2005 Express

Question: I found some manual here : http://support.microsoft.com/kb/316898/ru
but can't make a step with :

The Certificate Request Wizard dialog
  box opens. Click Next. Select
  Certificate type is "computer".

On "Registration politics" step there is Active Directory registration politic by default and so it requests some registration server ... I got no some reg server , I just want to make some certificate and add it to my MS SQL 2005 Express
I also created some certificates using IIS, but when I setup it on my MSSQL Server fails to start at the end of starting with error like "Wrong query or service is inaccessible, see system log"
Also there was some manual about using makecert utility, but my MSSQL saw not certificate I created using this tool like
makecert -r -pe -n "CN= MySQLServerName" -b 01/01/2000 -e 01/01/2036
-eku 126.96.36.199.184.108.40.206.1 -ss my -sr localMachine -sky exchange
-sp "Microsoft RSA SChannel Cryptographic Provider" -sy 12

so maybe I'm doing wrong or you got something helpful about my task : how to Install a certificate (SSL Encryption) on SQL Server 2005 Express ?
finally : sorry for my English and Thank you.
Answer: In general the properties of the certificate which you create are OK. The usage of -sp "Microsoft RSA SChannel Cryptographic Provider" -sy 12 switches are not needed. See http://msdn.microsoft.com/en-us/library/ms189067.aspx#sectionToggle2. You should verify that the host name of the server where SQL Server are running is MySQLServerName. A blanks between CN and the hostname or DNS name are not needed (use "CN=MySQLServerHostName").
You should also verify that you installed certificate which you created in "Trusted Root Certification" certificate store of the local computer on the server where SQL Server are running.
If you have an error during SQL Server start could you post the exact error message from the evenl log or from the ERRORLOG (from the directory C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Log or something like that)


Showing email addresses as an image

Question: I'm trying to use Php's gd library to show emails on a my page as an image, so  they can't be used by spammers. The problem is that the tutorial I am following uses a header with Content-type: image/jpeg. This means that I can only have images on this page.
How can I use the GD library to show the image in an Html/Php page? Or is there any other way of doing it?
Comment: show your code, could/will help. Also, far as I know, showing the image in header is probably the only way. It's its way of showing the image. If someone else has an alternative way of doing it, I'd sure like to know. Just make sure you don't have any HTML output before your headers.
Comment: To add: In order to show the image in your HTML/PHP page, will depend on the output's variable's name. I.e. `$image` (variable) - you could then just `echo $image;`
Comment: Welcome to Stack Overflow User2471133. You should give the [about page](http://stackoverflow.com/about) a read if you haven't already. Also, there's one other way that involves the base64-encoded string of the image @Fred
Comment: @MisterMelancholy Thanks, I saw that, cheers. Glad to see there are more ways than one of doing it.
Answer: When you change the header of the page, the whole page is rendered according to that header. In the case of using something like emails, you have a few options if you want to keep it single-paged.
Your first option is to use base64 encoding.
//create the image, $im
//omit the header settings

ob_start();
    imagejpeg($im);
    $data = ob_get_contents();
ob_end_clean();

echo '';

Here we place an output buffer to stop anything from going to the client, and store it in our variable $data. Then we just encode it using base64_encode and output to the page the way that the browser can interpret it.
There's also a get method that you can use.
if(isset($_GET['email'])) {
    header("Content-type: image/jpeg");

    //create the image, $im

    imagejpeg($im);
    imagedestroy($im);

    die;
}

echo '';

Really, we're just sending an email input and processing with an if statement.
Comment: I think you'd need an `exit` at the end of the `if` block.
Comment: @MisterMelancholy Yes, fixed.
Comment: I saw it fix for a second, but then the edit was undone only second later. It's not there.
Comment: @MisterMelancholy That's odd.
Comment: Sorry, I don't understand. Will this allow me to display the image inside the html page. I I'm setting the content-type: image/jpeg, then how will the browser render it as text/html?
Comment: @user2471133 For the first solution you're not even changing the header. For the second, you're only changing the header if "email" is set (get).

Showing email addresses as an image


MCMC acceptance rate decreases when proposal variance gets smaller

Question: I am drawing a sample Y of size n from a p-dimensional Normal ($\mu, \Sigma$). Typically, p is 5. I have $\bar{Y}$ and $V = YY'$, the sum of squares. Now I want to draw samples from this $\bar{Y}$, given V. The density of $\bar{Y}$ given V is proportional to
$det(v - n \bar{y} \bar{y}')^{(n - p - 2)/2}$
with support$ \bar{y} : v - n \bar{y} \bar{y}'$ is positive definite.
This is not a Bayesian framework, but possibly (at least I wasn't able to figure out) MCMC is the only way to draw samples from this not-so-well-known density. I used Metropolis-Hasting's algorithm with a normal proposal density, mean being this $\bar{y}$ and proposal variance being the observed variance-covariance matrix, divided by n. This is the unconditional distribution of $\bar{y}$. This gives me good-looking traceplots but an acceptance rate of about 2%! I tried lowering the proposal variance (say, multiplying by 0.2), but that makes the acceptance rate even low! Isn't acceptance rate supposed to increase if you lower the proposal variance?
Is there any simpler way out other than using adaptive MCMC? I've also been thinking of using other proposal distributions but couldn't come up with anything reasonable.
Comment: Are you sure of this conditional distribution? I [would have thought](https://stats.stackexchange.com/a/255536/7224) $\bar Y$ and $V$ to be independent.
Comment: @Xi'an As functions of the same sample of random variables, I don't think they can be independent, but I'm also curious how the OP derived this density.
Answer: I can't diagnosis why the rejection rate increased without knowing more specifics about your implementation, but I can help with a better sampling method.
Using the matrix determinant lemma, we can rewrite the density as $$\mathop{\mathrm{det}} (V)^{\frac{n-p}{2}-1}(1-n\bar{y}^TV^{-1}\bar{y})^{\frac{n-p}{2}-1}$$ and we see that our desired support refers to those points such that $0\leq \bar{y}^TV^{-1}\bar{y} \leq \frac{1}{n}$ since the determinant of a PD matrix is positive and a quadratric form with a PD matrix is also positive. We see then that all vectors with equal values for $\bar{y}^TV^{-1}\bar{y}$ are equally probable, so we can first sample a value $c$ according to $(1-nc)^{\frac{n-p}{2}-1}$ and then choose a vector such that $\bar{y}^TV^{-1}\bar{y}=c$. Note that $c$ can be simulated as $x/n$ where $x\sim \mathrm{Beta}\left(1, \frac{n-p}{2}\right)$. Next we simulate a random vector $y\sim \mathcal{N}(0,V)$ and set $$\bar{y}=\left(\frac{c}{y^TV^{-1}y}\right)^{\frac{1}{2}}y$$
For the sake of efficiency, you will probably want to use Cholesky $V=U^TU$ to calculate the determinant, the matrix-vector products with $V^{-1}$ and to generate the random normal vectors as $y=U^Tw$ where $w\sim\mathcal{N}(0,I)$. Using Cholesky also leads to the simplification that $y^TV^{-1}y=w^Tw$ and thus $$\bar{y}=\frac{\sqrt{c}}{\|w\|_2}U^Tw$$


Incorrect syntax near 'UPDATE'

Question: I have 2 tables X and Y.
X is like

D100_PTRSORID
D100_LIB17
D100_LIB18
D100_LIB19
....

10
15000
2000
75000
...

11
12500
2500
7000
...

12
...
...
...
...

...
...
...
...
...

The amounts in the fields D100_LIBXX are not correct. I would like to update these amounts thanks to table Y, which is like

GAD_PTRSORID
GAD_CODE
GAD_CAPITAL
...
....

10
201**
11000
...
...

10
202**
1500
...
...

10
203**
8500
...
...

11
201**
12500
...
...

...
...
...
...
...

D100_LIB17 is related to GAD_CODE = '201**'
D100_LIB18 is related to GAD_CODE = '202**'
D100_LIB19 is related to GAD_CODE = '203**'
I started to write this following script for updating the data but I have an error at the "UPDATE" level (underlined in red) with error message Incorrect syntax near 'UPDATE'. Expected end-of-input -or- [...]
SELECT * FROM X

UPDATE Xx
SET Xx.D100_LIB17=Yy.GAD_CAPITAL
FROM X Xx
INNER JOIN Y Yy
ON Xx.D100_PTRSORID = Yy.GAD_PTRSORID and Yy.GAD_CODE = '201**'

SELECT * FROM X

Comment: This seems to be SQL, no PL/SQL; and if those three statement are in one script, do you actually have statement separators (typically a semicolon) or a slash between them? (Which client you are using, and how you run the script, might make a difference too.) Oracle also doesn't allow `UPDATE ... FROM`, but you can use a corelated update.
Comment: @AlexPoole do you mean that this piece of code does not work with PL/SQL? I checked on internet how to use the UPDATE statement for PL/SQL for writing this script... I don't put "statement separators". Should I ? The rest of the script (creation of table X and Y works fine without separators). Could you maybe suggest me a script which works please?
Comment: you haven't shown the rest of the script, or said how (or in which client) you're running it. You might be running the create statements individually, or with slashes after them. The vague error your client is giving suggests it's seeing the update as part of the previous select though.
Answer: The error is probably because you aren't terminating the individual statements; depending on your client and settings, that's usually done with a semicolon statement separator:
SELECT * FROM X;

UPDATE ... ;

SELECT * FROM X;

or slash, on a line on its own (particularly for PL/SQL blocks):
SELECT * FROM X
/

UPDATE ...
/

SELECT * FROM X
/

Your update syntax isn't valid for Oracle though - you can't UPDATE ... FROM a query. You can use a correlated update instead:
UPDATE X Xx
SET Xx.D100_LIB17 = (
  SELECT Yy.GAD_CAPITAL
  FROM Y Yy
  WHERE Yy.GAD_PTRSORID = Xx.D100_PTRSORID
  AND Yy.GAD_CODE = '201**'
);

That will update all rows in X, not just those that are different; and if you have a row in X without a matching row in Y that will be set to null.
You can also update multiple columns at once, and you might want to consider using a MERGE rather than an UPDATE, e.g.:
MERGE INTO X Xx
USING (
  SELECT GAD_PTRSORID,
    MAX(CASE GAD_CODE WHEN '201**' THEN GAD_CAPITAL END) AS D100_LIB17,
    MAX(CASE GAD_CODE WHEN '202**' THEN GAD_CAPITAL END) AS D100_LIB18,
    MAX(CASE GAD_CODE WHEN '203**' THEN GAD_CAPITAL END) AS D100_LIB19
  FROM Y
  GROUP BY GAD_PTRSORID
) Yy
ON (Yy.GAD_PTRSORID = Xx.D100_PTRSORID)
WHEN MATCHED THEN UPDATE SET
  Xx.D100_LIB17 = Yy.D100_LIB17,
  Xx.D100_LIB18 = Yy.D100_LIB18,
  Xx.D100_LIB19 = Yy.D100_LIB19;

db<>fiddle demo - notice that two values in that demo still end up as null, because the sample data only has one row for ID 11. If you always have all the matching data that might not be an issue. If you don't then you can use COALESCE() to keep the existing value for columns without a corresponding value in Y.
You could expand the merge to insert missing rows, of you have IDs in Y with no matching row in X. Or define X as a pivot view of Y so you don't have to maintain the same data in two places.
Comment: I almost never use `UPDATE` in Oracle any more.  `MERGE` is just so much more appropriate in the vast majority of cases.
Comment: @AlexPoole I replaced my script by the 2 scripts you proposed to me but I receive a new error message **Oracle Database Error. table or view does not exist** . Do you see why?
Comment: @Nassim - your earlier comment suggested the tables were created in the same script so you'd still need to do that, if this is an assignment and they aren't supposed to exist before you start. Or maybe you didn't change the X/Y names to your real table names.
Comment: I created 2 tables called X and Y thanks to the WITH statement. `WITH X AS (...) , Y as (...) SELECT * FROM X;` This part works fine. And below this script, I added you piece of code. Is it the right way to do this?
Comment: @Nassim - `WITH` doesn't create a table; it's a common table expression or subquery factoring clause ([see the documentation](https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/SELECT.html#GUID-CFA006CA-6FF1-4972-821E-6996142A51C6__GUID-DFD72C34-5CED-4F6D-BA6D-829BE525CF92)), and is treated "as either an inline view or as a temporary table", that only exist sat all for the duration of the query it's part of. Although you can use a CTE within an update, it doesn't make sense to try to update the result of that subquery.
Comment: You now seem to be saying that the results of the two `WITH` subqueries are different; so you'd need to modify those or update the real base tables those refer to. Without knowing what those subqueries are doing, what the base data looks like, or why they are different - including whether they should be, and if not which is correct, and why - it's hard to advise how you should proceed. You could ask another question with all that information, but it's probably better to ask whoever set you this task.
Comment: Very clear thank you. I wanted to make a kind of test with the X and Y tables before editing the "big" table. Does it mean that I cannot work on a temporary table for testing my modifications?
Comment: Not really with a CTE. If you have permission you could create a global or [(if you're on Oracle 18c+) private](https://oracle-base.com/articles/18c/private-temporary-tables-18c) temporary table, which you could populate from the base tables and then update and query that.

Incorrect syntax near 'UPDATE'


Scrolling through div with JavaScript

Question: I am trying to show one div at a time and scroll trough them over and over. I have modified a Fiddle I found and I  got it working on fiddle, but for some reason I cant implement a simple test page with the fiddle. It simply does not scroll trough the divs.
Here is the fiddle: http://jsfiddle.net/Twistar/d6nZP/86/
And here is my implemented code:

    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" type="text/css" href="styles/styles.css">

first box

second box

third box

forth box

Can anyone please tell me what i am doing wrong?
Comment: have you imported jQuery on your own page? It doesn't look like it
Comment: Don't see jQuery included in your code
Comment: So, it's working on fiddle and not on your page?
Comment: tried your code http://jsbin.com/odayuw/1/ and apart of invisible chars that I needed to delete, works normally... but **I would always append the interval line** inside a `$(function() { ... });` so it would only fire when the DOM is completely ready.
Comment: You miss jquery add this for test: http://ajax.googleapis.com/ajax/libs/jquery/latest/jquery.js
Comment: @badZoke yes, works on fiddle, not on my test page. Now i have imported jQuery
Answer: I would probably simplyfy and would go with something like this: http://jsbin.com/osepim/1/
$(function() {

  // hide all and show first
  $(".boxes").hide().first().show();

  setInterval(function(){
    moveNext();
  }, 1000);

});

function moveNext() {
  var box = $(".boxes:visible"),
      nextBox = box.next();

  if(nextBox.length === 0)
    nextBox = $(".boxes:first");

  //hide all
  $(".boxes").hide();

  // show next
  nextBox.fadeIn();
}

Comment: This works just the way I want it. I am still wondering why the my original code wont work..
Answer: I am guessing that you have a working fiddle but on your local test page its not working
your fiddle works because you got selected the default handlers from left handside dropdowns and its not working on your test page because your jquery handler is missing.
the reason is you are missing the document ready handler here:
$(function(){
    setInterval(go, 1000);
});

try replacing with this one and see if helps.
Comment: This is the solution! Thank you. I did try something similar: I wrapped the go function and the timer in the document ready handler, but then it did not work..
Answer: you need to wrap your javascripts code with the ready event $(document).ready() or use the short version $() and that will only excecute your codes when the page is finished loading so your codes should looks something like that
$(function(){
   function go() {
        var visibleBox = $('#container .boxes:visible');
        visibleBox.hide();
        var nextToShow = $(visibleBox).next('.boxes:hidden');
        if (nextToShow.length > 0) {
            nextToShow.show();
        } else {
            $('#container .boxes:hidden:first').show();
        }
        return false;
    }
        setInterval(go, 1000);

});

Answer: <!DOCTYPE html>

<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="styles/styles.css" />

first box

second box

third box

forth box

Comment: I copy pasted the code onto my test page. Still does not work.

Scrolling through div with JavaScript


Upload de um array de imagens com Node.js, Multer e Sharp

Question: Além de upar as imagens eu faço um tratamento nelas com o Sharp, upando somente 1 imagem com upload.single('image') o tratamento é executado e a imagem é salva, mas quando tento um array com upload.array('image', 10) as imagens são salvas sem receber o tratamento.
O tratamento acontece no controller:
async post (req, res) {
const { title, description, locale, resume } = req.body;
const { filename : image } = req.file;
const [name] = image.split('.');
const filename = `${name}.jpg`;
await sharp(req.file.path)
  .resize(600)
  .jpeg({ quality: 80 })
  .toFile(
    path.resolve(req.file.destination, 'obras', filename)
  )

fs.unlinkSync(req.file.path);

const obra = await Obra.create({
  success: true,
  title,
  description,
  resume,
  locale,
  image: filename,
});

return res.json( obra );

},
como fazer o mesmo tratamento em todas as imagens que eu enviar?
Answer: o problema basicamente estava no "req.file" que só é usado para single uploads, quando se usa array pra uploads é preciso usar "req.files[indice]".
então ficou assim:
const arrayImages = []; //Para retorna as imagens no response
let i; //indice
for (i = 0; i<req.files.length; i++) {
  const { filename : image } = req.files[i]; //pegando o nome da imagem
  const [name] = image.split('.');
  let filename = `${name}.jpg`; //mudando pra jpg
  await sharp(req.files[i].path)
    .resize(500) // redimensionando para 500px
    .jpeg({ quality: 80 }) //qualidade para 80%
    .toFile(
      path.resolve(req.files[i].destination, 'obras', filename) //salvando
    )

    arrayImages.push(filename); // adicionando no vetor
  fs.unlinkSync(req.files[i].path); //apagando a imagem original, deixando apenas a imagem tratada salva.
}


False alarm in Neyman-Pearson Test. A doubt in text?

Question: Neyman-Pearson Lemma says that the most powerful test, $\phi(x)$, of size $\alpha$ (probability of false alarm), for testing $H_0:\theta=\theta_0$ versus $H_1:\theta=\theta_1$ is the likelihood ratio test of the form:
$$
\phi(x)=\begin{cases}
      1 & l(x)>k \\
      \color{#C00}{p} & l(x)=k \\
      0 & l(x)<k \\
   \end{cases}
$$
where, $p$ is the probability of accepting $H_1$ at $k.$
$k$ is threshold.
$l(x)$ is the likelihood ratio, $l(x)=\frac{f_{\theta_1}(x)}{f_{\theta_0}(x)}.$
Probability of false alarm, $P_f=\color{#C00}{p}  \cdot P[l(x)=k \hspace{2 mm}| \hspace{2 mm} H_0 ]\hspace{2 mm}+\hspace{2 mm} P[l(x)>k \hspace{2 mm}| \hspace{2 mm} H_0 ].$
Probability of detection, $P_d=p \cdot P[l(x)=k \hspace{2 mm}| \hspace{2 mm} H_1 ]\hspace{2 mm}+\hspace{2 mm} P[l(x)>k \hspace{2 mm}| \hspace{2 mm} H_1 ].$
Question Why Probability of false alarm, $P_f$, is $\mathbf{not}$ defined as:
$P_f=\color{#C00}{(1-p)}  \cdot P[l(x)=k \hspace{2 mm}| \hspace{2 mm} H_0 ]\hspace{2 mm}+\hspace{2 mm} P[l(x)>k \hspace{2 mm}| \hspace{2 mm} H_0 ].$
My understanding for saying above equation is that: if the probability of occurring $H_1$ is $p$, then the probability of occurring $H_0$ is $(1-p).$ And therefore, the probability of selecting $H_0$ at $k$ is $(1-p).P[l(x)=k \hspace{2 mm}| \hspace{2 mm} H_0].$
Where my understanding is wrong? Any comments please.
Answer: I am not sure what you mean by 'probability of occurring $H_0$', but that might be where you are confused. Note that $H_1$ and $H_0$ are not treated as random events and thus they have no probability. Instead, we assume either that $H_1$ is true or that $H_0$ is true, and compute probabilities of random events given $H_0$ or given $H_1$.
False alarm is defined as rejecting $H_0$ (accepting $H_1$) while $H_0$ is actually true. 'Probability of false alarm' in this context means the probability of false alarm given that $H_0$ is true. That is,
\begin{equation}
P[\textrm{We accept }H_1 \mid H_0].
\end{equation}
We can divide this probability into 3 separate events depending on whether $l(x)<k,l(x)=k,l(x)>k$:
\begin{equation}
=P[\textrm{We accept }H_1 \cap l(x)<k \mid H_0] + P[\textrm{We accept }H_1 \cap l(x)=k \mid H_0] + P[\textrm{We accept }H_1 \cap l(x)>k \mid H_0]
\end{equation}
The first term is obviously $0$ as we never accept $H_1$ when $l(x)<k$. The third term is just $P[l(x)>k \mid H_0]$ as $H_0$ is always accepted when $l(x)>k$. For the second term,
\begin{equation}
P[\textrm{We accept }H_1 \cap l(x) = k \mid H_0] = P[\textrm{We accept }H_1 \mid l(x)=k, H_0]P[l(x)=k \mid H_0] = pP[l(x)=k \mid H_0]
\end{equation}
that is, for the event in question to occur, both $l(x)=k$ and acceptance of $H_1$ must occur. The probability of this is computed by multiplying the (marginal) probability of $l(x)=k$ by the conditional probability of accepting $H_1$ conditional on $l(x)=k$.
Combining the three terms, we get the probability of false alarm
\begin{equation}
= pP[l(x)=k \mid H_0] + P[l(x)>k \mid H_0].
\end{equation}
Note that if one treated $H_0$ as a random event, one could compute the marginal probability of false alarm, that is, to have false alarm, we need both $H_0$ to be true and $H_1$ to be accepted. This would result in multiplying the aforementioned probability by $P[H_0]$. But, outside Bayesian framework $H_0$ is not treated as a random event, and thus only probabilities of accepting $H_1$ that can be defined are the ones given $H_0$ or given $H_1$.


How to do tabbed view (in picture). Android

Question: How to do tabbed view like the picture? Is it possible?
[1]: https://i.stack.imgur.com/zz6gI.png
Comment: that isn't one view, it's 2
Comment: Have a look at the `FlexboxLayout` here https://github.com/google/flexbox-layout
Answer: To give photos in row ,column fashion grid layout can be used in which numcolumn attribute is used to specify total number of columns we want to give for all rows


How to access current amount of earned userpoints in a Rules Condition?

Question: I have no access from Rules to [points] field or any userpoints field (User points module).
I have enabled: Rules, Rules scheduled, Rules_ui, Userpoints, Userponints_rules_integration, Userpoints_role (from userpoints_contrib),
I have done un/installed several times one by one modules mentioned with clear cache and cron in between and nothing, no access to userponits fields.
My event is "before saving content", in the Rules Conditions I have "User has a role-->auth-user", also in Rules Conditions I have "content is of type-->My custom contentype" in that order (I have changed that order with no results).
I need to update userponits field value before (preferred) or after a node is saved.
I tried also via Rules Components with an element "User has a role-->auth-user", same thing: no access to Userpoints fields.
I have another rule applied and reacting on Rules Event: "After saving a new user account" and there YES I have access to those fields.
Any ideas? Reference module? Do I have to implement a hook in template file to load current user? Do I need a custom module? I've seen all the node.one screencasts about Rules several times. And I have read many post in here, and (think) I've done everything right, but no success.
Any suggestions?
In case that your suggestions are: hook or module (I'm not a skilled programmer) please submit some code within.
Comment: I enebeled also rules bonus pack (Miscellaneous module) and it did nor work either.
Comment: Merci for the "accept"! Next question?
Comment: Thank you Pierre, no questions at the moment, have a nice day, best regards from Mexico
Comment: OK, maybe in the near future then ... Similar regards from the land-that-Drupal-originates from (aka BE) ...
Answer: There doesn't seem to be some Rules Condition related to the current total user points for a user. Except by using custom PHP code as in this example (which you could use in a Rules Conditionn Execute custom PHP code condition, e.g. to do some type of comparison):
global $user;
$current_points = userpoints_get_current_points($user->uid, 'all');
if ($current_points < 0) {return TRUE;}

However, there is a Rules Action "Load user points of a user", whereas you can ask for either a specific category, or for all categories together. This Rules Action provides a Rules variable (for which you can specify its name and description) which contains the amount of user points for the requested category. You can then use this variable in subsequent Rules Actions.
If you then want to use that variable within a Rules Condition, you have 2 ways of doing so:

Include the condition in a Rules Component, whereas you trigger the execution of that Rules Component via a Rules Action following the "Load user points of a user" (and passing the variable containing the amount of user points as a variable for the Rules Component).
Use the Conditional Rules module, so that you can specify Rules Conditions within Rules Actions.

Here is a basic example that displays a message about the current total user points for a user, after the user performed an update of some node (= the Rules Event, which you can change to any Rules event that you want):
{ "rules_display_userpoints_after_updating_content" : {
    "LABEL" : "Display userpoints after updating content",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "userpoints_rules", "rules" ],
    "ON" : { "node_update" : [] },
    "DO" : [
      { "userpoints_rules_get_current_points" : {
          "USING" : { "user" : [ "site:current-user" ], "tid" : "all" },
          "PROVIDE" : { "loaded_points" : { "total_points" : "Number of points in all categories together" } }
        }
      },
      { "drupal_message" : { "message" : "You now have [total-points:value] points" } }
    ]
  }
}

Use the Rules UI to import the above rule in your own site if you want.