Convergence of polynomials

Question: Consider $x\in [0,1]$. I want to know if, in the limit as $n\rightarrow\infty$, the following remains a polynomial:
$$\sum_{k=1}^{n}\frac{x^k}{k!}.$$
For any finite n, this is a polynomial. But will the limiting function, whatever it is, be a polynomial?
Kindly let me know if there is something missing in the question/ if it is too ambiguous.
Comment: the limit as $n \, \rightarrow \, +\infty$ is $\exp(x)-1$.
Comment: How can it be a polynomial if it contains infinitely many terms? The limit is closely related to the [Taylor expansion of the exponential function](https://en.wikipedia.org/wiki/Exponential_function#Formal_definition).
Comment: As already told, the limit is far from being a polynomial. This can be connected  with, among other things, Weierstrass Theorem about the fact that any continuous function in a closed, finite interval is the *uniform* limit of a sequence of polynomials.
Comment: I know that it ultimately converges to exp(x), but what I want to know is does one really need to invoke the concept of "e" to prove that it is not a polynomial? also, @DonAntonio, thank you, but can you gimme some more details/references?
Answer: As
$$\begin{align}
\lim_{n\rightarrow  \infty}\displaystyle\sum_{k=1}^{n}\frac{x^k}{k!}&=\displaystyle\sum_{k=1}^{\infty}\frac{x^k}{k!}\\& =x+\frac{x^2}{2!}+\frac{x^3}{3!}+\ldots\ldots\\&=e^x-1
\end{align}$$
Answer: I think I understood your quest more clearly with your last comment below your question,@Avi_Iyer :
First, we must know the radius of convergence of the power series
$$\sum_{k=0}^\infty \frac{x^k}{k!}\;\;\text{ is infinite , and this means this series converges for all}\;\;x\in\Bbb R$$
With the above already known, the limit function of the series (which, btw, is the uniform limit of it in any compact subset of the reals)  cannot be a polynomial unless we'd know that all but a finite number of the series's coefficients vanish, which is trivial to see they don't.
From the above we deduce the limit function of the series cannot be a polynomial even if we don't know it actually is the exponential function.
Comment: OK. I get it. So it is a polynomial only if its degree is provably finite. Thanks very much.
Comment: Yes @Avi_Iyer. In order for a question to be taken out of the "unanswered questions" section, don't forget to upvote all the questions you found helpful. As the opener of the thread, you can **also** "accept" the question that you found the most helpful (but you can upvote all of the answers if you want to).

Convergence of polynomials


Finding tags in a string in iOS

Question: I don't know how I should do this, I have tried using code like:
NSString *stringToFind = @"Hi";
NSString *fullString = @"Hi Objective C!";
NSRange range = [fullString rangeOfString :stringToFind];
if (range.location != NSNotFound)
{
    NSLog(@"I found something.");
}

But it doesn't fit my needs, I want to search for a string like #customstring (# means a tag) where the tag is specified by the user so they enter something like this Something #hello #world, what I want to do is search for all the # and the string attached to it and save it somewhere.
EDIT: The tag string created, I am saving that in a plist, but when I save it, it only saves one tag because I simply specified the string as tag. So like this:
[db addNewItem:label tagString:tag];

I need all of the tags created. For example in my logs:
I log tag, this comes up #tag,
I log tag again with two tags like this Something #hello #world I get two tags like this:#hello & #world each separate logs.
The result I want is this:
#hello, #world and then store it in a string and save it to my DB.
Answer: You should use a regular expression:
NSString *input = @"Something #hello #world";

NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:@"#\\w+" options:0 error:nil];
NSArray *matches = [regex matchesInString:input options:0 range:NSMakeRange(0, input.length)];

NSLog(@"%d matches found.", matches.count);
for (NSTextCheckingResult *match in matches) {
    NSString *tag = [input substringWithRange:[match range]];
    NSLog(@"%@", tag);
}
// #hello
// #world

EDIT To get the tags without the hash character #, you should use a capturing group in the regex like the following:
NSString *input = @"Something #hello #world";

NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:@"#(\\w+)" options:0 error:nil];
NSArray *matches = [regex matchesInString:input options:0 range:NSMakeRange(0, input.length)];

NSLog(@"%d matches found.", matches.count);
for (NSTextCheckingResult *match in matches) {
    NSString *tag = [input substringWithRange:[match rangeAtIndex:1]];
    NSLog(@"%@", tag);
}
// hello
// world

EDIT To get a string that contains the input string except the tags, you can use the following method:
NSString *stringWithoutTags = [regex stringByReplacingMatchesInString:input options:0 range:NSMakeRange(0, input.length) withTemplate:@""];
NSLog(@"%@", stringWithoutTags);
// Something

Edit Now that you have the different tags, you can create a string that contains them like this:
NSMutableArray *tagsArray = [NSMutableArray array];
for (NSTextCheckingResult *match in matches) {
    NSString *tag = [input substringWithRange:[match range]];
    [tagsArray addObject:tag];
}
NSString *tagsString = [tagsArray componentsJoinedByString:@", "];
NSLog(@"tagsString: %@", tagsString);

Comment: if there any way I can get the the result string, like `hello` from the `#hello`.
Comment: One minor tweak to sch's solution: use this regex: @"#[\\p{Letter}]+". It matches all unicode letters. So it also works with non-english alphabets. Might be useful for european languages, for example.
Comment: Ravin455: Please read the NSString documentation. That is very, very basic string handling, to strip the # from the string. It's not hard. :)
Comment: Is there any way I can exclude the tags from a string?
Comment: I found an error when excluding the tag with `rangeAtIndex`, it says its out of range. I also found out that when logging the result the tag string only includes one tag, and no I didn't mean to exclude the tag string. I meant to exclude the tags out of the original input string.
Comment: @Ravin455 - Did you notice that the second version of the code (the one that uses `rangeAtIndex`) has a modified pattern: `@"#([A-Za-z]+)"`,? And do you get the error when you use it?
Comment: @Ravin455 -  I've updated my answer to show how to compute a string where the tags are excluded, If you need a different result, you should consider posting a new question because it is different from your original question.
Comment: @sch Theres another bug, which is when giving the tag string it only gives one which is the last tag you enter e.g. "Something #hello #world", world is given and hello is excluded. Do you have to change the range?
Comment: Are you sure? When I test the code I get the two tags. Don't forget that you need the for loop. Also, why *"another bug"*? What was the first one? Can you update your question with your current code that produces the two bugs?
Comment: Sorry, I think I misused the word `bug` but yeah I got the loop it's just that it creates two tag strings for each and I need to save them all in one.
Comment: Still not clear. Please update your question with the exact description of the result you want and with an example. For instance, what does *"I need to save them all in one"* mean?
Answer: I would split it into an array separated by # and then for each one split again by space and pick the first word for each:
  NSArray *chunks = [string componentsSeparatedByString: @"#"];

Finding tags in a string in iOS


Auto generate numbering list in HTML using CSS #Part II

Question: In my previous question, I've been using CSS to create auto generated list numbering for

 tags. In another task, I need to create another list that will have title in between of the list as picture shown below.

Above example can be achieve using below code
HTML

    Title

        Content

        Content

    Title

        Content

CSS
ul {counter-reset:section}
li {margin:15px 0;text-align:justify}
li:before {counter-increment:section;content:""}
.main {list-style-position:inside;list-style-type:none;padding:0}
.main span {font-weight:700;text-decoration:underline}
.inner {padding:0}
.inner ul {counter-reset:section}
.inner ul > li:before {content:""}
ul {list-style-type:lower-alpha}

However, this code doesn't work in some browser like Opera. This is because in HTML 5,  tag can't be nested within element

.
jsFiddle that work in Firefox, Chrome and Internet Explorer.
Comment: Well, it's against the rules (in all versions of HTML), so the better solution is to find something that is valid HTML first, then check if it works in the browsers.
Comment: Thats I've been looking for answer. Any work around to do that?
Comment: I came up with [this jsFiddle](http://jsfiddle.net/MrLister/JtFvR/), that works beautifully in Firefox and Opera. Unfortunately, not in IE9 or Chrome. Sorry! Back to the drawing board...
Answer: Here's a pure CSS version which works in Chrome 26 and FF 20 (Haven't tested on other browsers). The change from your earlier question is that you don't need to reset your counter every time.
/* Don't reset every time!!! */
/* ol.inner {counter-reset:section;} */

ol.inner li {counter-increment:section;}
ol.inner li:before {content: counters(section,"") ". ";}

Answer: You can nest the
 inside an unordered list and assign a start position for each:

Title Of Section

Content 1

Title Of Section

Content 1

Content 2

Content 3

I put together a quick fiddle which uses jquery to automatically update the atart positions of each ordered list.
Comment: Thanks for your reply. I would like to avoid using javascript. :)


Is it possible to have a default copy constructor and a templated conversion constructor?

Question: If I have a class like this
<code>template <typename T>
class MyClass
{
    T myData;

public:
    T getValue() { return myData; }

    template <typename V>
    MyClass(const MyClass<V>& other) :
        myData((T) other.getValue())
    {
    }
};
</code>
This would mean that I provide a copy constructor (for V=T) and thus according to this link Why no default move-assignment/move-constructor? I do not get default move constructors etc.
Is there a way to have the templated constructor only work as conversion constructors, so for V!=T?
Comment: Your class has no user-defined copy constructor. A copy constructor is never a template.
Answer: Your premise is wrong. A constructor template is never used to instantiate a copy (or move) constructor. In other words, a copy/move constructor is always a non-template member function, even if a member function template could produce a constructor with the appropriate copy/move signature.
So as is, your class will still have a normal copy constructor in addition to the template.
Comment: @Bathsheba I strongly doubt that. A deleted function exists, so it would still be chosen. It's just that its use is ill-formed.
Comment: Out of interest, if we explicitly `delete`d the copy constructor, then would the template be used in its place?


Autoload do composer não funciona?

Question: Estou tentando usar o autoload do composer e não consigo, ele fala que a classe not found e tentando carregar uma classe de uma biblioteca externa.
Já executei na linha de comando:
composer install

e
composer dump

sem sucesso.

composer.json
"autoload": {
    "psr-4":
    {
        "App\\":
        [
            "app/",
            "tests/"
        ]
    }
}

Código
<?php

  namespace App\Database;
  use Dotenv\Dotenv;

  $dotenv = new Dotenv('../../');
  $dotenv->load();

  class Database
  {...

Erro

Fatal error: Uncaught Error: Class 'Dotenv\Dotenv' not found in /home/vagrant/Projetos/qa-toll/src/Database/Database.php on line 7
Comment: No seu código aonde é carregado `vendor/autoload.php` não está descrito no código?
Comment: Ele não é carregado aumoáticamente para os namespaces App?
Comment: ele só vai carregar automaticamente quando no topo do `script` tive `require 'vendor/autoload.php';` ai você pode utilizar entendeu ... ? ou coisa tem que dar um `composer dump-autoload` para que ele crie as entradas no arquivo de carregamento.
Comment: Se a resposta for útil aceita ela como resposta?
Answer: O autoload do composer.phar funciona da seguinte forma, ao instalar os pacotes e ou configurar alguma classe existe um arquivo que é obrigatório a sua declaração no topo do script para que tenha acesso a todo código produzido pelo desenvolvedor ou baixado pelo composer.
Como seria um layout das pastas:

após fazer todas as suas configurações e baixar o seu pacote o seu arquivo composer.json tem as configurações abaixo:
{
    "require": {
        "vlucas/phpdotenv": "^2.4"
    },
    "autoload": {
        "psr-4": {
            "App\\": [
                "app/",
                "tests/"
            ]
        }
    }
}

e para que essas modificações entre em vigor, faça o comando:
php composer dump-autoload

pronto. Agora para utilizar todo o código, inclusive de pacotes instalados, deve colocar no topo do arquivo e incluir require vendor/autoload.php, exemplo:
index.php
<?php

    // aqui que define todo o carregamento e disponibilidade do código
    require_once 'vendor/autoload.php';

    use Dotenv\Dotenv;
    use App\Database;

    $dotEnv = new Dotenv(__DIR__);
    $dotEnv->load();

    $database = new Database();
    echo $database->getConfigServer();

Boa leitura:

Composer não instala pacotes
Gerenciando dependências Composer
Qual é a diferença entre o dump-autoload normal e o otimizado, no Composer?
NPM, Bower e Composer, qual usar?
Como definir a semântica de pacotes baixados com composer?
Composer - Autoload e PSR-0 vs PSR-4
Comment: Obrigado pela ajuda.
Comment: @tiagopaes se foi util aceite como resposta da sua pergunta!

Autoload do composer não funciona?


Let $\Phi : R \rightarrow R'$ be a ring homomorphism, where $R,R'$ are rings with unity. Then which of these is true?

Question: Let $\Phi : R \rightarrow R'$ be a ring homomorphism, where $R,R'$ are rings with unity. Then which of these is true :
$(i)~\Phi(1)=1 ~\forall~$ rings $R,R~'$ with unity
$(ii)~\Phi(1) \ne 1 $ for any rings $R,R~'$
$(iii)~ \Phi(1) \ne 1 $ if $R~'$ is an integral domain or if $\Phi$ is onto.
$(iv)~ \Phi(1) = 1 $ if $R~'$ is an integral domain or if $\Phi$ is onto.
Attempt:
$\Phi(1\cdot1)= [ \Phi(1)]^2 $
$\implies \Phi(1) [\Phi(1) - 1]=0$
Only when $R~'$ is an integral domain can we infer that the above statement means either $\Phi(1)=0$ or $\Phi(1)=1$
If $\Phi(1)=0,$ then $\Phi$ represents the trivial homomorphism as $\Phi(x) = \Phi(x) \Phi(1) = 0$.
Else, if $\Phi$ is onto and $R~'$ is an integral domain, then the only option for $\Phi(1)$ is being equal to $1$.
So, $(iv)$ should be the right option.
Could someone please confirm if I am right?
Thank you for your help.
Comment: A ring homomorphism of rings with unity is usually required to send $1$ to $1$. But if that is not part of your definition then it need indeed not hold.
Answer: Here's the problem with (i):
Suppose $R' = R = \Bbb Z \times \Bbb Z$, with component-wise addition and multiplication and:
$\Phi((a,b)) = (a,0)$. We have:
$\Phi((a,b) + (a',b')) = \Phi((a+a',b+b'))$
$ = (a+a',0) = (a,0) + (a',0) = \Phi((a,b)) + \Phi((a',b'))$
and: $\Phi((a,b)(a',b')) = \Phi((aa',bb')) = (aa',0) = (a,0)(a',0) = \Phi((a,b))\Phi((a',b'))$,
but $\Phi((1,1)) = (1,0)$ is not the multiplicative identity of $R$ (although it is the multiplicative identity of $\Phi(R)$).
Comment: Yeah, that means (iv) is more convincing?
Comment: You might try proving it is true.


bash: Copy last version of a file from a mask list

Question: There is a set of programs in a source folder, but only the most recent version must be copied to the destination USB drive.
From Bash Script - Copy latest version of a file in a directory recursively, it shows that my formula would be:
f=$(find . -name AdbeRdr\*.exe | sort -n | tail -1)

So how to make find work inside a for loop on a set of masks?
set1="AdbeRdr\*.exe jre-\*.exe LibreOffice\*.msi"
for m in $set1
do
    echo "m: $m"
    f=$(find . -name $m | sort -n | tail -1)
    echo "f: $f"
    cp $f /media/USB
done

$m outputs the correct values (AdbeRdr*.exe, etc.), $f is empty and cp copies the whole parent directory. If I specify the mask explicitly without a variable (find . -name AdbeRdr\*.exe | sort -n | tail -1), the last file is outputted correctly.
Where am I going wrong? And how can I handle spaces if those would occur in filenames?
Thanks!
Answer: Use an array rather than a string to hold your elements, like this:
set1=( 'AdbeRdr*.exe' 'jre-*.exe' 'LibreOffice*.msi' )
for m in "${set1[@]}"
do
    echo "m: $m"
    f=$(find . -name "$m" | sort -n | tail -1)
    echo "f: $f"
    cp "$f" /media/USB
done

Use double-quotes around your variables to handle spaces in filenames.


length of array in Javascript

Question: I am just going through coderbyete questions and I was doing vowel count. This is my program
     function VowelCount(str) {
        var count=0;
        str=str.toLowerCase();
        var split=str.split("");
      // code goes here
      for(var i=0;i<split.length();i++){
        if(split[i]=="a"||split[i]=="e"||split[i]=="i"||split[i]=="o"||split[i]=="u")
        {
        count++;}
      }
      return split;

}

I get an error
TypeError: Property 'length' of object [object Array] is not a function
Why is my code wrong? I can't seem to figure it out.
Comment: `length` is not a function/method but just a property. Just use `split.length` instead.
Comment: Remove the brakets after length ;)
Comment: length() is not a function !
Answer: Two mistakes
var split=str.split("");
    ^         ^

split is a method and you are naming a variable that in the same line
length is a property, it needs to be .length and not .length()
var pieces=str.split("");
for(var i=0;i<pieces.length;i++){

Comment: Even if it didn't, that's wrong practice and leads to writing bad codes. Should not use language's own terms as variables as long as that can be avoided. Try that in another language and that will be a problem.
Comment: Using variable name is split didn't mess up anything. It worked fine with just changing .length() to .length.
I guess I shouldn't name it the same anyway though
Answer: just use
split.length;

instead of
split.length();

Comment: Thanks that fixed it. Really daft of me *facepalm*

length of array in Javascript


Custom path for view scripts

Question: I use customized paths for my application based on Zend Framework (a.k.a. themes).
The view scripts are saved in public/themes/themename/modulename/..., so switching the application theme is just substituting themename in the path.
How to tell Zend Tool to generate the view scripts in this directory instead of the default one?
I suppose some kind of provider is needed?
How to register the provider to have it by default for all zf based projects?
Answer: Look at the default Zend Providers and extend the classes with your own, overloading the paths.
Answer: I cannot tell you how you can achieve what you want but I can point you to some great help.
Zendcast
If you don't know about zendcast its a great palce to look for tutorials about the zend framework.
Answer: In your bootstrap you can add a script path:
protected function _initViewScripts()
{
    $this->bootstrap('view');
    $view = $this->getComponent('view');

    $view->addScriptPath('path/to/view/scripts/');
}

Comment: Does Zend_Tool use Bootstrap? (I have already modified the paths in application resource and I'm asking how to tell the same to Zend_Tool)
Comment: Sorry, didn't see the part about using it with Zend_Tool.

Custom path for view scripts


How are these link colors behaving with regards to the CSS Inheritance?

Question:

body {
  color: green;
}

.my-class-1 a {
  color: inherit;
}

.my-class-2 a {
  color: initial;
}

.my-class-3 a {
  color: unset;
}

Default link color

Inherit the link color

Reset the link color

Unset the link color

Default link color
Inherit the link color
Reset the link color
Unset the link color

I am learning Web Development from the MDN Web Docs website and I am stuck when I am trying to understand the concept of inheritance in CSS.
There is an HTML and CSS code provided on the website and its result is also provided. The result is color of various links depending upon the classes and inheritance applied to them. I am not able to understand how the CSS is affecting the color of the links.
Webpage from the MDN Web Docs website
The code and its results have already been provided to me. I just want to understand this behavior.
Answer: Default link color
The  element is colored blue from the default styles that the browser has, called User Agent Stylesheets. Most browsers have a CSS rule in their user agent stylesheet roughly equivalent to:
a {
  color: blue;
}

Inherit the link color
Let's work top-down to better understand this case.
The
 has no explicit color applied to it in your CSS or in most user agent stylesheets. If we look at the Formal definition of the color property, we can see:

Inherited
yes

If we then refer to the Inheritance documentation, it says:

When no value for an inherited property has been specified on an element, the element gets the computed value of that property on its parent element.

Thus, for the
, since it effectively has no explicit value set for its color property, it inherits from , whose (computed) color value is green. The
 element's color property is computed to be green.
For the li.my-class-1, it again, has no explicit value set for its color property (from author or user agent stylesheets), so it inherits from
, whose (computed) color value is green. The li.my-class-1 element's color property is computed to be green.
For the  element inside li.my-class-1, it has the inherit value for its color property, which means it inherits from its parent
, whose (computed) color value is green. The  element's color property is thus computed to be green.
Reset the link color
We can look at what the value of initial means from the MDN documentation on initial:

The initial CSS keyword applies the initial (or default) value of a property to an element.

Furthermore, the initial (or default) value is defined as:

The initial value of a CSS property is its default value, as listed in its definition table in the specification.

If we look at the Formal definition of the color property, we can see:

Initial value
canvastext

Thus,  element's color value is canvastext.  This is a System Color, defined as:

CanvasText
Text color in application content or documents

For "typical" set ups, this would be equivalent to black. Thus color: initial is equivalent to color: black and hence why the  element is colored black.
Unset the link color
We can look at what the value of unset means from the MDN documentation on unset:

The unset CSS keyword resets a property to its inherited value if the property naturally inherits from its parent, and to its initial value if not.

If we look at the Formal definition of the color property, we can see:

Inherited
yes

Thus, the color property of the  element follows the same behavior as color: inherit, as specified in the Inherit the link color section detailed previously.


How to solve $y'''+2y''-y'-2y= e^x+x^2$?

Question: The equation that needs to be solved is: $$y'''+2y''-y'-2y= e^x+x^2$$
Steps: homogeneous solution and then the particular part.Bbut how do i handle the particular part? Do i need to take them once at a time?
Comment: The equation is linear, so you can handle them one at a time and then add.
Comment: Yes take them one at a time.   If $e^x$ is in the homogeneous solution, your particular solution will be of the form $ax e^x + p(x)$, where $p(x)$ is a polynomial.  If it is not, your particular solution will be of the form $a e^x + p(x)$
Comment: @Juembles Does my comment I put in your previous question apply here again? Hint: The answer lie in the roots of the characteristic equation...BTW, these are good problems +1
Comment: @imranfat I am having a little trouble with determining the characteristic equation, can't seem to factorize it.
Comment: it ends up being a factoring by grouping, working on an answer ofr you now
Comment: Related: [Initial Value Problem](http://math.stackexchange.com/questions/823286/initial-value-problem)
Comment: Char equation is $t^3+2t^2-t-2=0$ so by grouping $t^2(t+2)-1(t+2)=0$ from which we get $(t^2-1)(t+2)=0$, etc
Answer: Solving
$$
(*)\;\;y'''+2y''-y'-2y= e^x+x^2
$$
By the method of undetermined coefficients:
First, we find the solution to the homogeneous equation:
$$
(**)\;\;y'''+2y''-y'-2y= 0
$$
By the usual characteristic equation:
$$
m^3+2m^2-m-2=0\Rightarrow m^2(m+2)-1(m+2)=0\Rightarrow m^2=1,m=-2
$$
yielding our solution to $(**)$,
$$
y_h(x)=c_1e^{-x}+c_2e^{x}+c_3e^{-2x}
$$
Then, we need to find some solution $y_p$ to the original equation $(*)$, which we do by a sort of guess and check. We guess that the solution will be of the form
$$
y_p(x)=Axe^{x}+Bx^2+Cx+D
$$
I.e. a second order polynomial summed with an exponential multiplied by a linear factor (called a fix up factor), since an $e^x$ term is already present in our homogenous solution. Then by the conditions of $(*)$ we know that
$$
y_p'''+2y_p''-y_p'-2y_p= e^x+x^2\Rightarrow\\
Axe^{x}+3Ae^{x}+2Axe^x+4Ae^x+4B-Axe^x-Ae^x-2Bx-C-2Axe^x-2Bx^2-2Cx-2D-2Bx^2\\
=x^2+e^x\\
\Rightarrow 6Ae^x+(4B-2D-C)+x(-2B-2C)-2Bx^2=x^2+e^x \\
\Rightarrow 6A=1,4B-2D-C=0,-2B=1,-2B-2C=0
$$
By equating coefficients. Then solving the system of coefficients we see that
$$
A=1/6\\
B=-1/2\\
-B=C=1/2\\
4B-2D-C=0\Rightarrow D=-5/4
$$
$$
y_p(x)=1/6xe^{x}-1/2x^2+1/2x+-5/4
$$
Yielding the solution to $(*)$ of
$$
y_p+y_h=1/6xe^{x}-1/2x^2+1/2x+-5/4+c_1e^{-x}+c_2e^{x}+c_3e^{-2x}
$$
Comment: @TnilkImaniq the actual work required to get there? Not to mention I was almost done when you posted
Comment: I'm not sure what your point is here. You asked me what mine contributed over yours, I answered. The onus is on you (the one who attacked my answer) to make a point that I added NOTHING over your answer. I added the bit that I was already done when you posted to let you know that just because you arrive at an answer first, doesn't mean others working on the problem need to delete what they were doing and get up.


IntelliJ IDEA 2017.1 does not stop on breakpoints

Question: I have an old Gradle project that I've opened recently using the new IDEA 2017 and I have just noticed it will not stop on breakpoints anymore (these are active, but not "validated" - no checkmark on them.
The code is run locally (a gradle run/debug config without any options) with bootRun as the gradle task.
I have tried an Invalidate Caches/Restart without any success. I have also tried re-importing the project in IDEA.
A while back I had the same issue after upgrading to Spring 1.4.5 (if I remember correctly). I couldn't figure out why, so I downgraded back to 1.4.2 and everything worked fine. However, this time I'm running Spring 1.2.4 and I cannot upgrade to a newer version without changing some code (and I don't want that yet)
Comment: Have you tried different solutions from this question: http://stackoverflow.com/questions/11591662/cannot-set-java-breakpoint-in-intellij-idea?rq=1 ?
Comment: Yes, without success. When I start the project I get the expected ```22:21:01: Executing external task 'bootRun'...
:compileJava UP-TO-DATE
:bootRun
Listening for transport dt_socket at address: 5005```
Comment: I'm having this issue with maven failsafe. Not sure if it's because of failsafe or not.  I'll have to investigate.  Usually i use surefire, which has no such problem.
Comment: No idea about those, but have a look at the ports your application/debugger is working on. That tipped me off about the source of the problem
Answer: Confirm. Problem was that I try to debug using maven run configuration. Switching to Application configuration type helps. I've spend half of a day on it (
Comment: having same issue. can you expand on this? what do you mean by switching to application configuration? thanks
Comment: Run -> Edit Configuration - Plus -> Application ->Then point to main method
Comment: Saved me after 2 hours of head scratching
Comment: My friend, thank you for sharing, but how do you expect others make full use of your answer if you don't share steps, or more clarification: how exactly do I switch to app mode?!
Comment: Hi, I am also facing the same issue. But in my case, the project is an Spring-based project. So how to configure the Application config?
Answer: Well... for some reason, creating a Gradle run/debug config would make it connect to the wrong port (something random over 50000) while the application was running on 8080.
Anyway, long story short, creating an Application run/debug config solved the issue and everything works fine now.
Comment: I wish I had found this before I wasted a load of time of trying to maven and spring profiles
Answer: I have faced this problem.

Invalidate caches and restart
I was using Spring Boot rest api project in intellij so all debug breakponts were getting passed/ignored. But the programm started debug process whenI hit Api using postman
Answer: This problem happens due to different reasons and you could find some of the answers on Intellij Community pages.
That being said, one of the most common reasons are build plugins. If you really don't need the build plugins you could disable them and try again:
Answer: Although 2017.1 is long past this is the top answer for "intellij debugger not stopping at breakpoint java" so I'll add another tricky way to have this problem here and associated solution.
Another way to cause this is to set your gradle settings to run tests with gradle, and also have a configuration for your tests that does something like:
  doFirst {
    jvmArgs = [
        '--add-modules', 'ALL-MODULE-PATH',
        '--add-opens', 'java.base/java.lang.module=ALL-UNNAMED',
        '--add-opens', 'java.base/jdk.internal.loader=ALL-UNNAMED',

The mistake here is that this replaces ALL jvm args with the ones supplied including the args that IntelliJ passes to open the debugger port. The fix is just one character... use += instead of = like this:
  doFirst {
    jvmArgs += [
        '--add-modules', 'ALL-MODULE-PATH',
        '--add-opens', 'java.base/java.lang.module=ALL-UNNAMED',
        '--add-opens', 'java.base/jdk.internal.loader=ALL-UNNAMED',

Answer: The problem for me was that I was using bootrun as the command in Intellij's Gradle run config, instead of bootRun. Weirdly the application did start with the former, but it would not stop on any breakpoints. After switching to bootRun, breakpoints immediately started working.
Answer: If you are calling a rest api make sure the passed in param has the same fields as the param variable as shown here  @PostMapping("/user")
public ResponseEntity<?> updateUserProfile(@RequestBody UserDTO userDto) {
The passed in value for UserDTO obj should have the same instance variables list in the json passed....  also object reference from repos also should be checked.


O thread de chamada não pode acessar este objeto porque ele pertence a um thread diferente

Question: Segue o código:
private async void button_1_Click(object sender, RoutedEventArgs e)
{
    var listenPort = 11000;
    var listener = new TcpSocketListener();
    listener.ConnectionReceived += async (senders, args) =>
    {
        var client = args.SocketClient;
        var reader = new StreamReader(client.ReadStream);
        var data = await reader.ReadLineAsync() + "\n";

        var split = data.Split('#');

        button_proximo.RaiseEvent(new RoutedEventArgs(System.Windows.Controls.Primitives.ButtonBase.ClickEvent));

        var bytes = Encoding.UTF8.GetBytes(data);
        await client.WriteStream.WriteAsync(bytes, 0, bytes.Length);
        await client.WriteStream.FlushAsync();
    };

    await listener.StartListeningAsync(listenPort);
}

O erro que recebo:

System.InvalidOperationException: 'O thread de chamada não pode
  acessar este objeto porque ele pertence a um thread diferente.'

Esse erro acontece só dentro ConnectionReceived, se eu colocar a linha button_proximo.RaiseEvent(new RoutedEventArgs(System.Windows.Controls.Primitives.ButtonBase.ClickEvent)); fora do ConnectionReceived funciona normal.
Alguma solução ?
Answer: Voce tem que aceder aos componentes da interface na mesma thread onde eles foram criados (também conhecido pela thread da UI). Para fazer isso voce pode usar o dispatcher. Exemplo:
Application.Current.Dispatcher.BeginInvoke(
  DispatcherPriority.Background,
  new Action(() =>
    button_proximo.RaiseEvent(new RoutedEventArgs(System.Windows.Controls.Primitives.ButtonBase.ClickEvent));
);


What does the array_filter key in $form do?

Question: I'm following this tutorial on creating a settings form for a module in Drupal 8. The instructions say to implement the buildForm method of ConfigFormBase in the following way:
  public function buildForm(array $form, FormStateInterface $form_state, Request $request = NULL) {
    $types = node_type_get_names();
    $config = $this->config('rsvplist.settings');
    $form['rsvplist_types'] = array(
      '#type' => 'checkboxes',
      '#title' => $this->t('The content types to enable RSVP collection for'),
      '#default_value' => $config->get('allowed_types'),
      '#options' => $types,
      '#description' => t('On the specified node types, an RSVP option will be available and can be enabled while that node is being edited.'),
    );

    $form['array_filter'] = array('#type' => 'value', '#value' => TRUE);

    return parent::buildForm($form, $form_state);

Everything here makes sense to me except I can't find any documentation on the role that they 'array_filter' key in the $form variable plays. What does this value do? Where is it documented?
Comment: Consider switching to the short array syntax. Same as behind the link to the settings form in my answer. It's also coding standard now, see [Arrays should be formatted using short array syntax](https://www.drupal.org/docs/develop/standards/coding-standards#array).
Comment: @leymannx I wasn't aware that this notation existed, thanks for that. It's much neater.
Answer: Nice catch! It does nothing. You can safely remove it. Looks like some kind of forgotten relict.
Ah, yeah. The same pattern can be found in core's book module: BookSettingsForm.php.
And there is a 12(!) years old open issue to have it removed. [#315176] Clean-up remains of $form['array_filter'] hack with array_filter in book module


Connectivity problems - ARP, MACs and IPs

Question: I'm trying to diagnose some connection issues I was having last night while setting up my new PC based router.
For a while everything was working perfectly, but then suddenly I found that I couldn't ping the new PC, and I couldn't ping other machines from that PC. Eventually I set wireshark up collecting on my machine and pinged that machine from the new PC. I saw the ping requests reach my machine and the response sent, but I still saw nothing on the new PC. (which is running an embedded version of pfSense - a FreeBSD distribution)
Thinking back the only possibility I can see is that it's something to do with the fact I kept on giving the new PC the same IP address as our existing router, (192.168.1.1) and assigning the old router another IP address (192.168.1.42). I ended up doing this a couple of times and never restarted my main PC, so I wondered if the ARP tables got messed up somehow.
So, what happens to packets where the IP address matches, but the MAC address does not (or the other way around)? Are they just ignored?
Also, are there any more diagnosis tools or methods I can use? (other than just turning different things on and off again...)
Comment: Try arping (google it), also, you can modify ARP tables, have you tried correcting them?
Answer: What you describe indicates that:

The router knows where to address your PC on the L2 network in order to send the ping request -- so its ARP cache is presumed to be correct.
But your PC doesn't know where to address the router in order to send the ping response -- so its ARP cache might not be correct.

The first two really obvious things to rule out are that:

Your old router isn't still attempting to bring up the IP address 192.168.1.1
Your new router isn't firewalling the ping request (ICMP echo) when it comes in.

Assuming that it isn't these two things then you can proceed in checking that the ARP entries are correct. Bear in mind that unless you are using static ARP entries, which I assume that you aren't, then they are stored dynamically as required and will expire after a period of time. This means that they won't persist across reboots or long periods of time. So if your old router definitely isn't on the old IP address any more then it shouldn't be the cause of the problem.

Make a note of what the correct MAC addresses for your PC and new router are. You can obtain this information from ifconfig or ipconfig, OS dependent.
Double check this against the ARP entries on each device. You can view the current entries in the ARP cache with arp -a or arp -an to skip name resolution.
If the ARP cache from one machine isn't consistent with the MAC address of the other and vice versa then try deleting it with arp -d <ip>. If it comes back with the same address then perhaps you do have a rogue machine on the network.

Incidentally you can also make sure that the MAC addresses displayed in the request and response of the Wireshark capture match those which you have recorded from the machine's interfaces.
Comment: Thanks, that was exactly the answer I was looking for and I learnt something, but unfortunately it didnt solve my problem - all of the ARP tables seemed to be correct.
In the end I re-ran the pfSense configuration and it sorted itself out. I suppose it might have been a bug...


Retonar parte de uma string no return da função

Question: Estou tentando achar uma string, e depois percorrer alguns caracteres para ter a informação desejada. Consigo fazer isso, porém, ao invés de apresentar em tela eu gostaria de atribuir a outra variável, para que estes dados coletados após a string encontrada seja o return da minha função.
int RetornaString(char *pString1, char *pString2)
{

    char *aux;

    aux = strstr(*pString1,*pString2);

    if (aux != NULL)
    {
        int i;
        for (i = 8; i < 24; i++)
            printf("%c",*(aux + i));
    }
    return 0;
}

Desde já, agradeço o tempo dispensado por cada um de vocês, com a minha dúvida!
Answer: Olá! Pode mudar o tipo da função para:
char* RetornaString(char *pString1, char *pString2)

Assim, pode devolver uma parte de uma string qualquer, por exemplo:
char* RetornaString(char *pString1, char *pString2) {

    const char string1[20] = "exemplo_palavra";
    const char palavra[10] = "palavra";
    char *aux;
    char *retorno;

    aux = strstr(haystack, needle);
    retorno=malloc(sizeof(aux));
    strcpy(retorno,aux);
    return retorno;
 }

Ao utilizar memoria dinamica com o malloc garante que o conteudo da string retorno não será perdido quando a função terminar! (Não se esqueça de usar o free para libertar essa mesma memória quando não precisar mais dela!
Comment: Legal ficou muito bom, mas eu ainda preciso de um "for", porquê? Porque, eu quero pegar uma informação que é variável, e sempre vem após a palavra "dados", p.e. Digamos que minha string contenha "dados:HS73NSS9374N7ALW823", Então, estou tentandoi desenvolver uma função que identifique a palavra "dados" percorra 6 bytes e capture 19 bytes a seguir "HS73NSS9374N7ALW823".
Comment: O código que eu postei é um pouco mais genérico, mas deve fazer o que precisa
Answer:
eu quero pegar uma informação que é variável, e sempre vem após a palavra "dados", p.e. Digamos que minha string contenha "dados:HS73NSS9374N7ALW823", Então, estou tentando desenvolver uma função que identifique a palavra "dados" percorra 6 bytes e capture 19 bytes a seguir "HS73NSS9374N7ALW823"

Há uma certa ambiguidade na sua questão. Você diz que está procurando "dados" mas parece que está procurando "dados:" e diz que quer percorrer 6 bytes mas aparentemente quer extrair os dados imediatamente a partir da string que está buscando, que NESSE caso tem 6 bytes se ela for "dados:" e não "dados" como disse.
Mas o seu exemplo ajudou bem. Ou eu não entendi nada :) nem assim.
Imagine uma função assim:
    char* filtro19(
    const char*     origem,
    const char*     prefixo,
    const size_t    deslocamento,
    const size_t    comprimento);

Onde

origem é a string inicial,"dados:HS73NSS9374N7ALW823" no seu exemplo
prefixo é, quem diria, o prefixo, tipo "dados:" no seu exemplo
deslocamento é o deslocamento em bytes a partir de onde vai começar a copiar, 0 no seu exemplo
comprimento é o total de bytes que quer extrair, 19 no seu exemplo

O retorno é um ponteiro para uma string, alocada dinamicamente e que deve ser alvo de um free() em algum lugar por sua conta. Claro, retorna NULL se não achar os dados a extrair.
Escrevi um exemplo. Não testei além do que vou te mostrar abaixo.
Procurei não chamar nenhuma outra função, exceto malloc() e memcpy() ao final. Daria para evitar memcpy(), mas teria que copiar mesmo e como não dá pra saber se tem todos os bytes a extrair até achar o fim da entrada assim deve ser mais rápido.
Note que precisa testar se de fato tem dados suficientes a extrair antes de terminar a string de entrada, e precisa terminar a string de saída ao final.
Eis a função:
    char* filtro19(
    const char*     origem,
    const char*     prefixo,
    const size_t    deslocamento,
    const size_t    comprimento)
{
    size_t    ixIn = 0;
    size_t    ix = 0; // para o deslocamento
    char      st = 0;
    const char* alvo = prefixo;
    char* saida = NULL;
    // vai ate o fim da string de origem
    while (*origem != 0)
    {
        switch (st)
        {

        case 0: // buscando inicio do prefixo
            if (*origem != *prefixo)
            {   // ainda nada
                origem += 1;
                break;
            };  // if()
            origem += 1;
            prefixo += 1;
            st = 1;
            break;

        case 1: // buscando prefixo na string
            if (*prefixo == 0)
            {   // fim do prefixo
                st = 2;
                break;
            };  // if()
            if (*prefixo != *origem)
            {
                st = 0;
                prefixo = alvo; // reinicia prefixo
                break;
            };
            // igual por enquanto
            ixIn += 1; // precisa do tamanho
            origem += 1;
            prefixo += 1;
            break;
        case 2: // andando no intervalo
            if (ix == deslocamento)
            {
                st = 3;
                ix = 0; // agora vai contar a saida
                alvo = origem; // aqui comeca o alvo
                break;
            };
            ix += 1; // anda uma casa
            origem += 1;
            break;
        case 3: // agora aponta para a saida e conta
                // os bytes pedidos
            if (*origem == 0)
            {   // acabou antes: nao tem bytes suficientes
                // depois do prefixo e eventual deslocamento
                return NULL;
            };
            ix += 1;
            if (ix == comprimento)
            {   // achou tudo!
                saida = malloc(comprimento + 1);
                memcpy(saida, alvo, comprimento);
                *(saida + comprimento) = 0;
                return saida;
            };  // if()
            origem += 1;
            break;
        default:
            break;

        }
    };
    // se chegou aqui nao achou nada
    return NULL;
};

A lógica é simples: trata-se de um FSA, uma máquina de estados porque fica mais fácil de escrever. A ideia é simples: busca a o prefixo, calcula o deslocamento, verifica se tem o conteúdo pedido, aloca a memória, copia os dados e finaliza a string.
Eis a saída de um programa de teste, com uma função teste() para mostrar os parâmetros

        Filtro: Buscando 2 bytes
                0 bytes depois de
                '73' em
                'HS73NSS9374dados:HS73NSS9374N7ALW823'

filtro() retornou 'NS' [2]

        Filtro: Buscando 2 bytes
                0 bytes depois de
                '8' em
                'HS73NSS9374dados:HS73NSS9374N7ALW823'

filtro() retornou '23' [2]

        Filtro: Buscando 3 bytes
                0 bytes depois de
                '8' em
                'HS73NSS9374dados:HS73NSS9374N7ALW823'

filtro() nao encontrou resultado

        Filtro: Buscando 1 bytes
                0 bytes depois de
                '2' em
                'HS73NSS9374dados:HS73NSS9374N7ALW823'

filtro() retornou '3' [1]

        Filtro: Buscando 5 bytes
                2 bytes depois de
                ':' em
                'HS73NSS9374dados:HS73NSS9374N7ALW823'

filtro() retornou '73NSS' [5]

        Filtro: Buscando 19 bytes
                0 bytes depois de
                'dados:' em
                'HS73NSS9374dados:HS73NSS9374N7ALW823'

filtro() retornou 'HS73NSS9374N7ALW823' [19]

Entenda que o deslocamento pode ser zero como no caso de seu exemplo. E o valor entre [ ] no exemplo é o comprimento da string retornada
Não quero entrar em discussões religiosas aqui. Compilei só com o CL 19.27 da Microsoft.
Eis o programa todo
#include <memory.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* filtro19(
    const char*, const char*,
    const size_t, const size_t
);  // o filtro
void    teste(const char*, const char*,
    const size_t, const size_t); // o teste

int     main(void)
{
    teste("HS73NSS9374dados:HS73NSS9374N7ALW823",
        "73", 0, 2);

    teste("HS73NSS9374dados:HS73NSS9374N7ALW823",
        "8", 0, 2);

    teste("HS73NSS9374dados:HS73NSS9374N7ALW823",
        "8", 0, 3);

    teste("HS73NSS9374dados:HS73NSS9374N7ALW823",
        "2", 0, 1);

    teste("HS73NSS9374dados:HS73NSS9374N7ALW823",
        ":", 2, 5);

    teste("HS73NSS9374dados:HS73NSS9374N7ALW823",
        "dados:", 0, 19);

    return 0;
};  // main()

char* filtro19(
    const char*     origem,
    const char*     prefixo,
    const size_t    deslocamento,
    const size_t    comprimento)
{
    size_t    ixIn = 0;
    size_t    ix = 0; // para o deslocamento
    char        st = 0;
    const char* alvo = prefixo;
    char* saida = NULL;
    // vai ate o fim da string de origem
    while (*origem != 0)
    {
        switch (st)
        {

        case 0: // buscando inicio do prefixo
            if (*origem != *prefixo)
            {   // ainda nada
                origem += 1;
                break;
            };  // if()
            origem += 1;
            prefixo += 1;
            st = 1;
            break;

        case 1: // buscando prefixo na string
            if (*prefixo == 0)
            {   // fim do prefixo
                st = 2;
                break;
            };  // if()
            if (*prefixo != *origem)
            {
                st = 0;
                prefixo = alvo; // reinicia prefixo
                break;
            };
            // igual por enquanto
            ixIn += 1; // precisa do tamanho
            origem += 1;
            prefixo += 1;
            break;

        case 2: // andando no intervalo
            if (ix == deslocamento)
            {
                st = 3;
                ix = 0; // agora vai contar a saida
                alvo = origem; // aqui comeca o alvo
                break;
            };
            ix += 1; // anda uma casa
            origem += 1;
            break;

        case 3: // agora aponta para a saida e conta
                // os bytes pedidos
            if (*origem == 0)
            {   // acabou antes: nao tem bytes suficientes
                // depois do prefixo e eventual deslocamento
                return NULL;
            };
            ix += 1;
            if (ix == comprimento)
            {   // achou tudo!
                saida = malloc(comprimento + 1);
                memcpy(saida, alvo, comprimento);
                *(saida + comprimento) = 0;
                return saida;
            };  // if()
            origem += 1;
            break;
        default:
            break;

        }
    };
    // se chegou aqui nao achou nada
    return NULL;
};

void        teste(
    const char* origem,
    const char* prefixo,
    const size_t deslocamento,
    const size_t comprimento
)
{
    printf(
        "\n\tFiltro:\tBuscando %zd bytes\n\t\t%zd bytes depois de "
        "\n\t\t'%s' em\n\t\t'%s'\n",
        comprimento, deslocamento, prefixo, origem);
    char* valor = filtro19(origem, prefixo, deslocamento, comprimento);
    if (valor != NULL)
        printf("\nfiltro() retornou '%s' [%zd]\n", valor, strlen(valor));
    else
        printf("\nfiltro() nao encontrou resultado\n");
};  // teste()

// https://pt.stackoverflow.com/questions/470035/
// retonar-parte-de-uma-string-no-return-da-fun%c3%a7%c3%a3o


How to configure Cumulative Dividend Reinvestment with an initial Value

Question: I have an initial Investment turned into a number of Shares (Ex. $1000 is ~44.4 Shares)
My Data.frame() consists of finance yahoo data, being shortened to Date, Avg_Price, and Dividends.
My problem is getting both a Dividends payment and a Cumulative New Share number. I understand it's:
(Input + [former cumulative Shares] )* Dividend / Avg_Price)
I've tried a for loop so I could manipulate the values of i between 2:nrow(data.frame())
I'm not sure what other options I have at my disposal. I have created this same data.table in excel, but there I'm able to use 4 columns named:
New Shares, Cumulative New Shares, New Share Total, and Total Share Value
(They're all interdependent on each other, but I can't seem to replicate that in R)
I've tried:
data.frame1 <- fy.pull() # My own finance yahoo Data puller
  mutate(Col1 = ...lag(Col1)) # but I can't get a lag from the same column; or

  mutate(Col1 = ...cumsum()) # not sure why cumsum won't work for previous data

for (i in 2:nrow(data.frame)) {
  TSV[i] <- ((Input + TSV[i-1]) * data.frame$Dividends [i] / data.frame$Avg_Price[i]
}
data.frame$TSV <- TSV

I was hoping for a The Input + Shares (from cumulative Dividends payouts made back into new shares) to get the total Share Value after each monthly dividend payment of the said Stock
You can use the function: (to pull the data.frame() from finance yahoo)
D_NVDY_Pull <- function() {
  NVDY1 <- as.data.frame(read_csv("https://query1.finance.yahoo.com/v7/finance/download/NVDY?period1=1683811800&period2=1709314910&interval=1d&events=dividends&includeAdjustedClose=true"))
  NVDY2 <- as.data.frame(read_csv("https://query1.finance.yahoo.com/v7/finance/download/NVDY?period1=1683811800&period2=1709256228&interval=1d&events=history&includeAdjustedClose=true"))
  NVDY3 <- NVDY2 %>%
    left_join(NVDY1)
  NVDY4 <- NVDY3 %>%
    select(Date, Open, Close, `Adj Close`, Dividends) %>%
    na.omit() %>%
    mutate(Avg_Price = (Open + Close + `Adj Close`)/3) %>%
    select(Date, Avg_Price, Dividends) %>%
    arrange((Date))
}

Answer: Figured out the answer after some trial and error. Used a for loop. The code is here:
DivTest1 <- D_NVDY_Pull() # Pull the data frame
ShareCount <- c(Input,rep(NA,nrow(DivTest1)-1)) # makes NA value vector with input as starting value
Div_to_Shares <- as.numeric(rep(NA,nrow(DivTest1))) # another NA vector
DivTest1$ShareCount <- ShareCount # adds into data.frame
DivTest1$Div_to_Shares <- Div_to_Shares # adds second vector in
for (i in 1:nrow(DivTest1)) {
  DivTest1$Div_to_Shares[i] = (DivTest1$ShareCount[i] * DivTest1$Dividends[i])/ DivTest1$Avg_Price[i]
  if (i == nrow(DivTest1)) break
  if (is.na(DivTest1$ShareCount[i + 1])) {
    DivTest1$ShareCount[i + 1] = DivTest1$ShareCount[i] + DivTest1$Div_to_Shares[i]
  }
}


Inclusão de arquivos externos .js

Question: Galera, eu tenho um arquivo .js em meudominio.com/arquivo.js (exemplo). Esse arquivo contém funções que enviam requisições via Ajax para outro arquivo, o dados.php (faz a busca e retorna em json), que se encontra na mesma pasta da hospedagem do arquivo .js. A ideia é incluir esse arquivo .js em páginas localizadas em outra hospedagem e fazer uma espécie de api.
O problema é que quando eu incluo esse .js ele acredita que o dados.php está na hospedagem do arquivo onde estou incluindo o .js, aí a requisição falha por conta disso.
Eu queria saber como enviar o post para o dados.php da hospedagem onde o .js está, e não o da hospedagem do arquivo onde estou o incluindo.
Exemplo da requisição:
$.ajax({
method:"post",
url:"dados.php", <= aqui eu quero que ele busque o dados.php da hospedagem onde está o .js
...
})

É possível fazer isso?
Comment: Deixa ver se eu entendi. Você quer fazer uma requisição POST em uma página que está fora da sua hospedagem, usando PHP?
Answer: O nome disso é CORS. Os navegadores e servidores, por padrão, bloqueiam qualquer requisição que não tenha vindo do servidor original. Você pode configurar seu servidor para que este possa aceitar requisições de sites que ele "conhece" ou de qualquer outro lugar.

Como permitir CORS no Apache
Como permitir CORS no NginX

Se você não tiver acesso as configurações do servidor, você pode forçar o CORS pelo PHP, dessa forma (note que todas as suas páginas PHP vão precisar executar esse comando).
Answer: Access-Control-Allow-Origin chamado de cabeçalho CORS (Cross-Origin Resource Sharing).
Quando um site X tenta aceder o conteúdo de outro site Y, o site que fez a requisição (site X) pode enviar um cabeçalho de resposta Access-Control-Allow-Origin para dizer ao navegador que o conteúdo desta página está acessível a determinadas origens.
Por padrão, as páginas do site Y não são acessíveis a outras origens; usando o cabeçalho Access-Control-Allow-Origin abre uma porta para o acesso de origem cruzada por origens solicitando específicos.
Para cada recurso/página que Site Y quer tornar acessível para o site X, o Site Y deve servir suas páginas com o cabeçalho de resposta:
Access-Control-Allow-Origin: http://siteX.com

Os navegadores modernos não vao bloquear solicitações entre domínios. Se o Site X solicita uma página do Site Y, o navegador vai realmente aceder a página solicitada e verificar os cabeçalhos de resposta do Site X como um domínio solicitante permitido. Se o Site Y não indicou que o site X tem permissão para acessar esta página, o navegador irá desencadear um evento de erro no XMLHttpRequest e negar os dados de resposta ao código JavaScript requerente.
Pedidos não-simples
O que acontece ao nível da rede pode ser um pouco mais complexo do que foi explicado acima. Se o pedido é um pedido "não-simples", o primeiro navegador envia uma solicitação OPÇÕES "pré-impressão", para verificar que o servidor irá aceitar o pedido. Um pedido é considerado "não-simples" quando uma (ou ambas) situações:

Usa um método HTTP diferente do GET ou POST (por exemplo, PUT,
DELETE)
Usa cabeçalhos de solicitação "não-simples"; os únicos pedidos
cabeçalhos simples são:

Accept
Accept-Language
Content-Language
Content-Type (isto só é simples quando o seu valor é application /    x-www-form-urlencoded, multipart/form-data, ou text/plain)

Se o servidor responde às opções de comprovação com cabeçalhos de resposta adequados (Control-Allow-Headers para cabeçalhos "não-simples" e Access-Access-Control-Allow-Methods para metodos "não-simples") que correspondem ao método "não-simples" e/ou  cabeçalhos "não-simples", em seguida, o navegador envia o pedido real.
Supondo que Site X quer enviar uma solicitação PUT para /SomePage, com um valor Content-Type não-simples de application/json, o navegador primeiro enviar um pedido de comprovação:
OPTIONS /SomePage HTTP/1.1
Origin: http://siteX.com
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: Content-Type

Note que Access-Control-Request-Method e Access-Control-Request-Headers são adicionados pelo navegador automaticamente; você não precisa adicioná-los. Esta comprovação OPÇÕES recebe os cabeçalhos de resposta de sucesso:
Access-Control-Allow-Origin: http://siteX.com
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: Content-Type

Ao enviar a solicitação real (após a comprovação ser feita), o comportamento é idêntico à forma como um simples pedido é tratado. Em outras palavras, um pedido "não-simples", cuja comprovação é bem sucedida é tratada da mesma maneira que um pedido simples (ou seja, o servidor deve ainda enviar Access-Control-Allow-Origin novamente para a resposta real).
O navegadores envia a solicitação real:
PUT /SomePage HTTP/1.1
Origin: http://siteX.com
Content-Type: application/json

{ "myRequestContent": "JSON is so great" }

E o servidor envia de volta um Access-Control-Allow-Origin, da mesma forma que faria para um pedido simples:
Access-Control-Allow-Origin: http://siteX.com

Veja XMLHttpRequest Entendimento sobre CORS para um pouco mais de informação sobre os pedidos não-simples.
Fonte: apsillers

Inclusão de arquivos externos .js


NoClassDefFound Exception with gradle

Question: I am trying to import some gradle dependencies for my project. However, a specific package is generating a NoClassDefFound exception. If i understood correctly, this happens because the package is found at compilation but not at runtime. I have included the my gradle build below along with the generated error. I have tried to add the needed jar into the WAR lib file manually, without success.
I have tried adding the needed jar into the WAR lib file manually, without success.
<code>repositories {
     mavenCentral()
}

dependencies {
    providedCompile group: 'javax.faces', name: 'javax.faces-api', version: '2.2'
    runtime group: 'org.glassfish', name: 'javax.faces', version: '2.2.18'
    runtime group: 'com.liferay.faces', name: 'com.liferay.faces.bridge.ext', version: '5.0.3'
    runtime group: 'com.liferay.faces', name: 'com.liferay.faces.bridge.impl', version: '4.1.2'

    compileOnly group: 'javax.servlet', name: 'javax.servlet-api', version: '4.0.1'
    compileOnly group: 'com.sun.syndication', name: 'com.springsource.com.sun.syndication', version: '1.0.0'
    compileOnly group: 'javax.validation', name: 'validation-api', version: '2.0.1.Final'
    compileOnly group: 'org.springframework.security', name: 'spring-security-cas-client', version: '3.0.8.RELEASE'
    compileOnly group: 'javax.el', name: 'javax.el-api', version: '3.0.1-b06'
    compileOnly group: 'javax', name: 'javaee-api', version: '8.0.1'

    compile group: 'log4j', name: 'log4j', version: '1.2.14'
    compile group: 'org.richfaces', name: 'richfaces', version: '4.5.17.Final'
    compile group: 'org.springframework', name: 'spring-tx', version: '5.1.6.RELEASE'
    compile group: 'org.springframework.security', name: 'spring-security-core', version: '5.1.5.RELEASE'
    compile group: 'org.springframework.security', name: 'spring-security-web', version: '5.1.5.RELEASE'
    compile group: 'org.springframework.security.oauth', name: 'spring-security-oauth2', version: '2.3.5.RELEASE'
    compile group: 'org.springframework', name: 'org.springframework.web.servlet', version: '3.2.2.RELEASE'
    compile group: 'javax.validation', name: 'validation-api', version: '2.0.1.Final'
    compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.8.1'
    compile group: 'org.springframework', name: 'spring-test', version: '4.0.5.RELEASE'
    compile group: 'org.testng', name: 'testng', version: '6.14.3'
    compile group: 'javax.persistence', name: 'javax.persistence-api', version: '2.2'
    compile group: 'org.hibernate', name: 'hibernate-core', version: '4.0.0.CR1'
    compile group: 'javax.xml.parsers', name: 'jaxp-api', version: '1.4.5'
    compile group: 'javax.xml.bind', name: 'jaxb-api', version: '2.1'
    compile group: 'com.sun.xml.bind', name: 'jaxb-impl', version: '2.1'
    compile group: 'xerces', name: 'xercesImpl', version: '2.12.0'
}

Catastrophic initialization failure! Shutting down portlet WAB due to: java.lang.NoClassDefFoundError: Could not initialize class com.sun.xml.bind.DatatypeConverterImpl
java.lang.RuntimeException: java.lang.NoClassDefFoundError: Could not initialize class com.sun.xml.bind.DatatypeConverterImpl
    at com.sun.faces.config.ConfigureListener.contextInitialized(ConfigureListener.java:292)
    at com.liferay.portal.osgi.web.wab.extender.internal.adapter.ServletContextListenerExceptionAdapter._initializeContext(ServletContextListenerExceptionAdapter.java:119)
    at com.liferay.portal.osgi.web.wab.extender.internal.adapter.ServletContextListenerExceptionAdapter.contextInitialized(ServletContextListenerExceptionAdapter.java:99)
    at jdk.internal.reflect.GeneratedMethodAccessor465.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.eclipse.equinox.http.servlet.internal.registration.ListenerRegistration$EventListenerInvocationHandler.invoke(ListenerRegistration.java:145)
    at com.sun.proxy.$Proxy688.contextInitialized(Unknown Source)
    at org.eclipse.equinox.http.servlet.internal.context.ContextController.doAddListenerRegistration(ContextController.java:350)
    at org.eclipse.equinox.http.servlet.internal.context.ContextController.addListenerRegistration(ContextController.java:303)
    at org.eclipse.equinox.http.servlet.internal.customizer.ContextListenerTrackerCustomizer.addingService(ContextListenerTrackerCustomizer.java:67)
    at org.eclipse.equinox.http.servlet.internal.customizer.ContextListenerTrackerCustomizer.addingService(ContextListenerTrackerCustomizer.java:1)
    at org.osgi.util.tracker.ServiceTracker$Tracked.customizerAdding(ServiceTracker.java:943)
    at org.osgi.util.tracker.ServiceTracker$Tracked.customizerAdding(ServiceTracker.java:1)
    at org.osgi.util.tracker.AbstractTracked.trackAdding(AbstractTracked.java:256)
    at org.osgi.util.tracker.AbstractTracked.track(AbstractTracked.java:229)
    at org.osgi.util.tracker.ServiceTracker$Tracked.serviceChanged(ServiceTracker.java:903)
    at org.eclipse.osgi.internal.serviceregistry.FilteredServiceListener.serviceChanged(FilteredServiceListener.java:109)
    at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.publishServiceEventPrivileged(ServiceRegistry.java:891)
    at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.publishServiceEvent(ServiceRegistry.java:804)
    at org.eclipse.osgi.internal.serviceregistry.ServiceRegistrationImpl.register(ServiceRegistrationImpl.java:127)
    at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.registerService(ServiceRegistry.java:228)
    at org.eclipse.osgi.internal.framework.BundleContextImpl.registerService(BundleContextImpl.java:469)
    at org.eclipse.osgi.internal.framework.BundleContextImpl.registerService(BundleContextImpl.java:487)
    at org.eclipse.osgi.internal.framework.BundleContextImpl.registerService(BundleContextImpl.java:1004)
    at com.liferay.portal.osgi.web.wab.extender.internal.WabBundleProcessor.initListeners(WabBundleProcessor.java:571)
    at com.liferay.portal.osgi.web.wab.extender.internal.WabBundleProcessor.init(WabBundleProcessor.java:217)
    at com.liferay.portal.osgi.web.wab.extender.internal.WebBundleDeployer._initWabBundle(WebBundleDeployer.java:186)
    at com.liferay.portal.osgi.web.wab.extender.internal.WebBundleDeployer.doStart(WebBundleDeployer.java:106)
    at com.liferay.portal.osgi.web.wab.extender.internal.WabFactory$WABExtension.start(WabFactory.java:175)
    at org.apache.felix.utils.extender.AbstractExtender.createExtension(AbstractExtender.java:259)
    at org.apache.felix.utils.extender.AbstractExtender.modifiedBundle(AbstractExtender.java:232)
    at org.osgi.util.tracker.BundleTracker$Tracked.customizerModified(BundleTracker.java:488)
    at org.osgi.util.tracker.BundleTracker$Tracked.customizerModified(BundleTracker.java:1)
    at org.osgi.util.tracker.AbstractTracked.track(AbstractTracked.java:232)
    at org.osgi.util.tracker.BundleTracker$Tracked.bundleChanged(BundleTracker.java:450)
    at org.eclipse.osgi.internal.framework.BundleContextImpl.dispatchEvent(BundleContextImpl.java:908)
    at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230)
    at org.eclipse.osgi.framework.eventmgr.ListenerQueue.dispatchEventSynchronous(ListenerQueue.java:148)
    at org.eclipse.osgi.internal.framework.EquinoxEventPublisher.publishBundleEventPrivileged(EquinoxEventPublisher.java:230)
    at org.eclipse.osgi.internal.framework.EquinoxEventPublisher.publishBundleEvent(EquinoxEventPublisher.java:137)
    at org.eclipse.osgi.internal.framework.EquinoxEventPublisher.publishBundleEvent(EquinoxEventPublisher.java:129)
    at org.eclipse.osgi.internal.framework.EquinoxContainerAdaptor.publishModuleEvent(EquinoxContainerAdaptor.java:191)
    at org.eclipse.osgi.container.Module.publishEvent(Module.java:476)
    at org.eclipse.osgi.container.Module.start(Module.java:467)
    at org.eclipse.osgi.framework.util.SecureAction.start(SecureAction.java:468)
    at org.eclipse.osgi.container.ModuleContainer.start(ModuleContainer.java:777)
    at org.eclipse.osgi.container.ModuleContainer.applyDelta(ModuleContainer.java:768)
    at org.eclipse.osgi.container.ModuleContainer.resolveAndApply(ModuleContainer.java:538)
    at org.eclipse.osgi.container.ModuleContainer.resolve(ModuleContainer.java:484)
    at org.eclipse.osgi.container.ModuleContainer.refresh(ModuleContainer.java:1028)
    at org.eclipse.osgi.container.ModuleContainer$ContainerWiring.dispatchEvent(ModuleContainer.java:1409)
    at org.eclipse.osgi.container.ModuleContainer$ContainerWiring.dispatchEvent(ModuleContainer.java:1)
    at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230)
    at org.eclipse.osgi.framework.eventmgr.EventManager$EventThread.run(EventManager.java:340)
Caused by: java.lang.NoClassDefFoundError: Could not initialize class com.sun.xml.bind.DatatypeConverterImpl
    at com.sun.xml.bind.v2.runtime.JAXBContextImpl$3.run(JAXBContextImpl.java:295)
    at com.sun.xml.bind.v2.runtime.JAXBContextImpl$3.run(JAXBContextImpl.java:294)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at com.sun.xml.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:293)
    at com.sun.xml.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:146)
    at com.sun.xml.bind.v2.runtime.JAXBContextImpl$JAXBContextBuilder.build(JAXBContextImpl.java:1169)
    at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:147)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:288)
    at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:277)
    at javax.xml.bind.ContextFinder.find(ContextFinder.java:400)
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:721)
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:662)
    at javax.xml.bind.JAXB$Cache.<init>(JAXB.java:127)
    at javax.xml.bind.JAXB.getContext(JAXB.java:154)
    at javax.xml.bind.JAXB.unmarshal(JAXB.java:183)
    at org.richfaces.javascript.ClientServiceConfigParser.parse(ClientServiceConfigParser.java:81)
    at org.richfaces.javascript.ClientServiceConfigParser.parseConfig(ClientServiceConfigParser.java:70)
    at org.richfaces.application.ValidatorModule.createClientScriptService(ValidatorModule.java:65)
    at org.richfaces.application.ValidatorModule.configure(ValidatorModule.java:60)
    at org.richfaces.application.ServicesFactoryImpl.init(ServicesFactoryImpl.java:60)
    at org.richfaces.application.InitializationListener.createFactory(InitializationListener.java:110)
    at org.richfaces.application.InitializationListener.onStart(InitializationListener.java:69)
    at org.richfaces.application.InitializationListener.processEvent(InitializationListener.java:167)
    at javax.faces.event.SystemEvent.processListener(SystemEvent.java:108)
    at com.sun.faces.application.ApplicationImpl.processListeners(ApplicationImpl.java:2169)
    at com.sun.faces.application.ApplicationImpl.invokeListenersFor(ApplicationImpl.java:2142)
    at com.sun.faces.application.ApplicationImpl.publishEvent(ApplicationImpl.java:301)
    at javax.faces.application.ApplicationWrapper.publishEvent(ApplicationWrapper.java:739)
    at com.sun.faces.config.ConfigManager.publishPostConfigEvent(ConfigManager.java:704)
    at com.sun.faces.config.ConfigureListener.contextInitialized(ConfigureListener.java:270)
    ... 54 more
2019-04-16 12:20:16.699 INFO  [com.liferay.portal.kernel.deploy.auto.AutoDeployScanner][AutoDeployDir:261] Processing portlet.war
2019-04-16 12:20:27.087 INFO  [fileinstall-C:/Users/Argiris/Desktop/Liferay7.1/liferay-ce-portal-7.1.2-ga3/osgi/war][BundleStartStopLogger:42] STOPPED portlet_1.0.0 [1012]
2019-04-16 12:20:29.899 INFO  [fileinstall-C:/Users/Argiris/Desktop/Liferay7.1/liferay-ce-portal-7.1.2-ga3/osgi/war][BaseAutoDeployListener:43] Copying portlets for C:\Users\Argiris\Desktop\Liferay7.1\liferay-ce-portal-7.1.2-ga3\tomcat-9.0.10\temp\20190416122027087VBYVASCO\portlet.war
2019-04-16 12:20:32.023 INFO  [fileinstall-C:/Users/Argiris/Desktop/Liferay7.1/liferay-ce-portal-7.1.2-ga3/osgi/war][BaseDeployer:877] Deploying portlet.war
2019-04-16 12:21:04.566 INFO  [fileinstall-C:/Users/Argiris/Desktop/Liferay7.1/liferay-ce-portal-7.1.2-ga3/osgi/war][BaseAutoDeployListener:50] Portlets for C:\Users\Argiris\Desktop\Liferay7.1\liferay-ce-portal-7.1.2-ga3\tomcat-9.0.10\temp\20190416122027087VBYVASCO\portlet.war copied successfully
2019-04-16 12:21:29.627 INFO  [Refresh Thread: Equinox Container: 4507fbcc-c97b-4c9a-83d0-cc94415a5052][BundleStartStopLogger:39] STARTED portlet_1.0.0 [1012]
2019-04-16 12:22:06.848 ERROR [Refresh Thread: Equinox Container: 4507fbcc-c97b-4c9a-83d0-cc94415a5052][com_liferay_portal_osgi_web_wab_extender:97] Catastrophic initialization failure! Shutting down portlet WAB due to: java.lang.NoClassDefFoundError: Could not initialize class com.sun.xml.bind.DatatypeConverterImpl
java.lang.RuntimeException: java.lang.NoClassDefFoundError: Could not initialize class com.sun.xml.bind.DatatypeConverterImpl
    at com.sun.faces.config.ConfigureListener.contextInitialized(ConfigureListener.java:292)
    at com.liferay.portal.osgi.web.wab.extender.internal.adapter.ServletContextListenerExceptionAdapter._initializeContext(ServletContextListenerExceptionAdapter.java:119)
    at com.liferay.portal.osgi.web.wab.extender.internal.adapter.ServletContextListenerExceptionAdapter.contextInitialized(ServletContextListenerExceptionAdapter.java:99)
    at jdk.internal.reflect.GeneratedMethodAccessor465.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.eclipse.equinox.http.servlet.internal.registration.ListenerRegistration$EventListenerInvocationHandler.invoke(ListenerRegistration.java:145)
    at com.sun.proxy.$Proxy688.contextInitialized(Unknown Source)
    at org.eclipse.equinox.http.servlet.internal.context.ContextController.doAddListenerRegistration(ContextController.java:350)
    at org.eclipse.equinox.http.servlet.internal.context.ContextController.addListenerRegistration(ContextController.java:303)
    at org.eclipse.equinox.http.servlet.internal.customizer.ContextListenerTrackerCustomizer.addingService(ContextListenerTrackerCustomizer.java:67)
    at org.eclipse.equinox.http.servlet.internal.customizer.ContextListenerTrackerCustomizer.addingService(ContextListenerTrackerCustomizer.java:1)
    at org.osgi.util.tracker.ServiceTracker$Tracked.customizerAdding(ServiceTracker.java:943)
    at org.osgi.util.tracker.ServiceTracker$Tracked.customizerAdding(ServiceTracker.java:1)
    at org.osgi.util.tracker.AbstractTracked.trackAdding(AbstractTracked.java:256)
    at org.osgi.util.tracker.AbstractTracked.track(AbstractTracked.java:229)
    at org.osgi.util.tracker.ServiceTracker$Tracked.serviceChanged(ServiceTracker.java:903)
    at org.eclipse.osgi.internal.serviceregistry.FilteredServiceListener.serviceChanged(FilteredServiceListener.java:109)
    at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.publishServiceEventPrivileged(ServiceRegistry.java:891)
    at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.publishServiceEvent(ServiceRegistry.java:804)
    at org.eclipse.osgi.internal.serviceregistry.ServiceRegistrationImpl.register(ServiceRegistrationImpl.java:127)
    at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.registerService(ServiceRegistry.java:228)
    at org.eclipse.osgi.internal.framework.BundleContextImpl.registerService(BundleContextImpl.java:469)
    at org.eclipse.osgi.internal.framework.BundleContextImpl.registerService(BundleContextImpl.java:487)
    at org.eclipse.osgi.internal.framework.BundleContextImpl.registerService(BundleContextImpl.java:1004)
    at com.liferay.portal.osgi.web.wab.extender.internal.WabBundleProcessor.initListeners(WabBundleProcessor.java:571)
    at com.liferay.portal.osgi.web.wab.extender.internal.WabBundleProcessor.init(WabBundleProcessor.java:217)
    at com.liferay.portal.osgi.web.wab.extender.internal.WebBundleDeployer._initWabBundle(WebBundleDeployer.java:186)
    at com.liferay.portal.osgi.web.wab.extender.internal.WebBundleDeployer.doStart(WebBundleDeployer.java:106)
    at com.liferay.portal.osgi.web.wab.extender.internal.WabFactory$WABExtension.start(WabFactory.java:175)
    at org.apache.felix.utils.extender.AbstractExtender.createExtension(AbstractExtender.java:259)
    at org.apache.felix.utils.extender.AbstractExtender.modifiedBundle(AbstractExtender.java:232)
    at org.osgi.util.tracker.BundleTracker$Tracked.customizerModified(BundleTracker.java:488)
    at org.osgi.util.tracker.BundleTracker$Tracked.customizerModified(BundleTracker.java:1)
    at org.osgi.util.tracker.AbstractTracked.track(AbstractTracked.java:232)
    at org.osgi.util.tracker.BundleTracker$Tracked.bundleChanged(BundleTracker.java:450)
    at org.eclipse.osgi.internal.framework.BundleContextImpl.dispatchEvent(BundleContextImpl.java:908)
    at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230)
    at org.eclipse.osgi.framework.eventmgr.ListenerQueue.dispatchEventSynchronous(ListenerQueue.java:148)
    at org.eclipse.osgi.internal.framework.EquinoxEventPublisher.publishBundleEventPrivileged(EquinoxEventPublisher.java:230)
    at org.eclipse.osgi.internal.framework.EquinoxEventPublisher.publishBundleEvent(EquinoxEventPublisher.java:137)
    at org.eclipse.osgi.internal.framework.EquinoxEventPublisher.publishBundleEvent(EquinoxEventPublisher.java:129)
    at org.eclipse.osgi.internal.framework.EquinoxContainerAdaptor.publishModuleEvent(EquinoxContainerAdaptor.java:191)
    at org.eclipse.osgi.container.Module.publishEvent(Module.java:476)
    at org.eclipse.osgi.container.Module.start(Module.java:467)
    at org.eclipse.osgi.framework.util.SecureAction.start(SecureAction.java:468)
    at org.eclipse.osgi.container.ModuleContainer.start(ModuleContainer.java:777)
    at org.eclipse.osgi.container.ModuleContainer.applyDelta(ModuleContainer.java:768)
    at org.eclipse.osgi.container.ModuleContainer.resolveAndApply(ModuleContainer.java:538)
    at org.eclipse.osgi.container.ModuleContainer.resolve(ModuleContainer.java:484)
    at org.eclipse.osgi.container.ModuleContainer.refresh(ModuleContainer.java:1028)
    at org.eclipse.osgi.container.ModuleContainer$ContainerWiring.dispatchEvent(ModuleContainer.java:1409)
    at org.eclipse.osgi.container.ModuleContainer$ContainerWiring.dispatchEvent(ModuleContainer.java:1)
    at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230)
    at org.eclipse.osgi.framework.eventmgr.EventManager$EventThread.run(EventManager.java:340)
Caused by: java.lang.NoClassDefFoundError: Could not initialize class com.sun.xml.bind.DatatypeConverterImpl
    at com.sun.xml.bind.v2.runtime.JAXBContextImpl$3.run(JAXBContextImpl.java:295)
    at com.sun.xml.bind.v2.runtime.JAXBContextImpl$3.run(JAXBContextImpl.java:294)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at com.sun.xml.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:293)
    at com.sun.xml.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:146)
    at com.sun.xml.bind.v2.runtime.JAXBContextImpl$JAXBContextBuilder.build(JAXBContextImpl.java:1169)
    at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:147)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:211)
    at javax.xml.bind.ContextFinder.find(ContextFinder.java:372)
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:574)
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:522)
    at javax.xml.bind.JAXB$Cache.<init>(JAXB.java:87)
    at javax.xml.bind.JAXB.getContext(JAXB.java:114)
    at javax.xml.bind.JAXB.unmarshal(JAXB.java:143)
    at org.richfaces.javascript.ClientServiceConfigParser.parse(ClientServiceConfigParser.java:81)
    at org.richfaces.javascript.ClientServiceConfigParser.parseConfig(ClientServiceConfigParser.java:70)
    at org.richfaces.application.ValidatorModule.createClientScriptService(ValidatorModule.java:65)
    at org.richfaces.application.ValidatorModule.configure(ValidatorModule.java:60)
    at org.richfaces.application.ServicesFactoryImpl.init(ServicesFactoryImpl.java:60)
    at org.richfaces.application.InitializationListener.createFactory(InitializationListener.java:110)
    at org.richfaces.application.InitializationListener.onStart(InitializationListener.java:69)
    at org.richfaces.application.InitializationListener.processEvent(InitializationListener.java:167)
    at javax.faces.event.SystemEvent.processListener(SystemEvent.java:108)
    at com.sun.faces.application.ApplicationImpl.processListeners(ApplicationImpl.java:2169)
    at com.sun.faces.application.ApplicationImpl.invokeListenersFor(ApplicationImpl.java:2142)
    at com.sun.faces.application.ApplicationImpl.publishEvent(ApplicationImpl.java:301)
    at javax.faces.application.ApplicationWrapper.publishEvent(ApplicationWrapper.java:739)
    at com.sun.faces.config.ConfigManager.publishPostConfigEvent(ConfigManager.java:704)
    at com.sun.faces.config.ConfigureListener.contextInitialized(ConfigureListener.java:270)
    ... 54 more
</code>
Answer:
Import dependency first
implementation group: 'com.liferay', name: 'javax.xml.bind', version: '2.3.0.LIFERAY-PATCHED-2'

Then buildRest

Then deploy the module.
Answer: <code>NoClassDefFoundError: Could not initialize class com.sun.xml.bind.DatatypeConverterImpl</code> indicates that <code>DatatypeConverterImpl</code> could not be loaded. This class is present in Java 8, deprecated in Java 9 and no longer available in Java 11.
As per this answer you want to update your JAXB dependencies to 2.3.0 or newer. You are currently using 2.1 which was released back in 2008 and is not suited to run with modularized JVM (post Jigsaw in Java 9).

NoClassDefFound Exception with gradle


Measurablity of single maps from measurability of a composition

Question: Consider three measurable spaces $(X, \mathcal{X})$, $(Y, \mathcal{Y})$, $(Z, \mathcal{Z})$. Let $S$ and $T$ be maps from $X$ to $Y$ and from $Y$ to $Z$, respectively. Assume $S$ is $\mathcal{X}/\mathcal{Y}$-measurable and that the composition map $T \circ S$ is $\mathcal{X}/\mathcal{Z}$-measurable. Is then necessarily the case that $T$ is $\mathcal{Y}/\mathcal{Z}$-measurable?
Of course, for any set $B \in \mathcal{Z}$ we have $(T \circ S)^{-1}(B)=S^{-1}(T^{-1}(B)) \in \mathcal{X}$. Are we then allowed to conclude that $T^{-1}(B) \in \mathcal{X}$ because of the measurability of $S$?
Answer: Not true. Let $X=Y=Z=\mathbb R$ each with the Borel sigma algebra.Let  $T=I_A$ where $A$ is  a subset of  $(0,\infty)$ which is not a  Borel set. Let $Sx=-x^{2}$. Then $T\circ S=0$, hence $T\circ S$ is measurable and $S$ is measurable but $T$ is not.


Right censored survival analysis with interval data in R

Question: How do you perform a survival analysis on a data set that is right censored (i.e. some samples are removed before failure) where the measurement points are non-regular discreet intervals (i.e. failure between Left and Right or sometimes not at all).
Example data set:
| sample | Left (hours) | Right (hours) | Fail/Censored |
| A      | 10           | 20            | F             |
| B      | 40           | 60            | F             |
| C      | 40           | 60            | C             |

I am comfortable using R, but do not have enough experience with this branch of statistics. I would appreciate if someone could provide an R example or point me in the correct direction.
Answer: As implied by the tag, this is referred to as interval censoring. In this scenario, for each observation, we have a pair of values that I call observation intervals: $(L_i, R_i]$, where $L_i$ represents a lower bound on the true value of interest and $R_i$ presents an upper bound on the true value of interest. For example, suppose you go to a dentist at age 9 and have no cavities. You go again at age 12 and have one cavity. Then all you know about your "age at first cavity" is that it is in the interval $(9,12]$.
Note: you will need to slightly change your data to put it in this format. For example, you have the interval $(40, 60]$ for subject C but you also state that they are right censored. I assume this means that we know that for subject C, at time 60 the event of interest had not occurred yet. In that case, you should represent their observation interval as $(60, \infty)$.
There exists a variety of tools for analyzing interval censoring data. One of the most basic tools is the non-parametric maximum likelihood estimator (NPMLE). This is basically an extension of the Kaplan Meier curves that allows for interval censoring. For performing hypothesis testing to compare two groups, the log-rank statistics have been generalized to allow for interval censoring. Finally, survival regression models (proportional hazards, accelerated failure time and proportional odds, to name few) can be used.
In R, the NPMLE and regression models can be found in my icenReg package. The log-rank statistic can be found in the interval package.
Comment: Right. But remember that $(60, \infty)$ doesn't mean that the event happened at infinity, but rather we know that the event will be in the interval $(60, \infty)$, or in other words, the event time is greater than 60.
Comment: re. "you will need to slightly change your data ... 60 the event of interest had not occurred yet. In that case, you should represent their observation interval as (60,∞)." This is the part I am struggling with. If the test is terminated at 60 without observation of the event, this means you have only tested out to 60, its different to saying the part survives to infinity.
Comment: Ri is not infinity (as the sample will fail at some point in the future) and Ri is not the mean of 60 and infinity, so I'm not sure what approach to take...
Comment: Thank you. That makes a bit more sense. I'll have to dig around some more to build a working example in R.


Programmatically / by Rules, remove reference of a deleted user from contents created by that user.

Question: A user [content_editor] got deleted and the content created by this user is referring to anonymous user.  While an administrator is editing that content, administrator is receiving user doesn't exist. The error goes off when we re-assign the content to administrator or an existing user. As the user has created paragraphs, nodes etc how do we track contents created and referred by the user as user id is already deleted?
How can we remove these references and save the content without error message.
I thought we can use Rules API to create a simple rule which will force save any entity if an admin is saving the content, then save the content. But the rules API is providing me only nodes and not entities which means paragraphs will still refer to old deleted user. How can I overcome this. Is there a programmatic solution to this problem?
Answer: supposing the content you want to reassign is of node type, here is how to do it programatically (in a hook_update_N() per example or /devel/php or drush ev...)
<code>  $deleted_uid = 42;
  $reassigned_uid = 80;
  // Reassign nodes (current revisions).
  module_load_include('inc', 'node', 'node.admin');
  $nodes = \Drupal::entityQuery('node')
    ->condition('uid', $deleted_uid)
    ->execute();
  node_mass_update($nodes, ['uid' => $reassigned_uid], NULL, TRUE);
  // Reassign old revisions.
  db_update('node_field_revision')
    ->fields(['uid' => $reassigned_uid])
    ->condition('uid', $deleted_uid)
    ->execute();
</code>
hope this helps
Comment: Hi @izus, Thanks for the information, I will test this thoroughly and will get back to you on this. I have done a quick test on devel exec php on my local and it seems to work well, I  also need to update paragraph that are referenced by each nodes and I managed to loop through  the node and loaded referenced paragraphs using update them.


Single IP multiple domains SSL issue

Question: I've just noticed a small problem with a self signed SSL I am using for a webmail subdomain on one of my domains.
I was using https://webmail.website0.com just to secure it a bit but I've noticed that if I visit https://website1.com https://website2.com etc they all point to the webmail website. Is this normal? Can I avoid it somehow?
All the websites are sharing the same IP.
Answer: Yes, this is normal - by default all websites sharing an IP address will be pulled up if going to https://anydomainthatsharesthatip.com.  The reason why is that SSL is at a level before HTTP header communication so all Apache has to go on at that stage of the request is the IP address and port being requested (i.e. it hasn't received the HTTP Host: header yet).
There is a newer standard known as SNI which supports sending the Host: header earlier, but the most typical way to avoid this is to give website0.com a dedicated IP and problem's solved.  You could somewhat avoid it by creating a :443 VirtualHost later in the conf file which use website0's SSL certificate but which has website1.com, website2.com, etc. as ServerName / ServerAlias directives, but if people go to https://website1.com, they'll see website0's SSL certificate; however, website1 will be pulled up instead as expected.

Single IP multiple domains SSL issue


Como ler um array de arrays e salvar cada array[ ] em uma variável diferente para executar função com barplot?

Question: Como posso fazer para ler esse array de arrays:
[45 32 56 57 44 21 36 35 39 23 24 27 25 26 31 28 29 30 20 22 18  8 19  1
 33  2  3  4  0  6  7  9 17 10 11 12 49 55 13 14 15 16 52 46 43 34 41 37
 40  5 54 51 53 47 38 42 50 48] [50 34 46 45 48 24 27 28 26 43 32 19 10 25 18 12 20 13  7 15 17  9  8 14
 22 21  4  3  5 16  1  6  0 11  2 29 47 52 55 57 54 56 38 35 31 23 37 53
 33 42 36 49 51 44 39 41 30 40] [54 29 40 42 53 23 31 34 37 39 38 17 19 22 12 10 11  3  6 13 15  8 14 16
 25 27  4  5 21  0  1 18  9  7  2 32 28 46 48 57 56 55 20 44 33 26 41 52
 24 45 43 50 51 49 35 30 47 36] [57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34
 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10
  9  8  7  6  5  4  3  2  1  0]

Salvar cada array em uma variável diferente: ranks1, ranks2, ranks3, ranks4, ranks5 e conseguir executar estas funções:
Uma que está na main:
frk.plot_ranks(ranks1, ranks2, ranks3, ranks4, ranks5, ... )

E essa outra que funciona para plotar os gráficos em outro script:
def plot_ranks(bars1, bars2, bars3, bars4, bars5, features_train, title, RESULT_PATH='Results'):

    df = pd.DataFrame({'LA': bars1, 'DT': bars2, 'RF': bars3, 'PCA': bars4, 'ARD': bars5})
    index = X
    df.index = index
    ax = df.plot.barh(stacked=True)

    plt.show()

O que acontece é que se por exemplo não tem uma destas variáveis, digamos que bars5 não esteja no array a função plot_ranks() não executa e dá erro. Como eu posso separar este array de arrays nestas variáveis: ranks1, ranks2, ranks3, ranks4, ranks5 (da função que está na main) e mesmo na ausência de uma delas estas funções possam ser executadas para que o gráfico seja plotado e não dê erro?
Answer: Assumindo que sua array bidimensional de entrada seja algo como:
entrada = [
    [45,32,56,57,44,21,36,35,39,23,24,27,25,26,31,28,29,30,20,22,18,8,19,1,33,2,3,4,0,6,7,9,17,10,11,12,49,55,13,14,15,16,52,46,43,34,41,37,40,5,54,51,53,47,38,42,50,48],
    [50,34,46,45,48,24,27,28,26,43,32,19,10,25,18,12,20,13,7,15,17,9,8,14,22,21,4,3,5,16,1,6,0,11,2,29,47,52,55,57,54,56,38,35,31,23,37,53,33,42,36,49,51,44,39,41,30,40],
    [54,29,40,42,53,23,31,34,37,39,38,17,19,22,12,10,11,3,6,13,15,8,14,16,25,27,4,5,21,0,1,18,9,7,2,32,28,46,48,57,56,55,20,44,33,26,41,52,24,45,43,50,51,49,35,30,47,36],
    [57,56,55,54,53,52,51,50,49,48,47,46,45,44,43,42,41,40,39,38,37,36,35,34,33,32,31,30,29,28,27,26,25,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0]
]

Você pode convertê-la em um dicionário, criando uma chave para cada elemento da lista.
data = {
    'rank1': entrada[0],
    'rank2': entrada[1],
    'rank3': entrada[2],
    'rank4': entrada[3],
}

Ou melhor ainda:
data = {f'rank{i}' : e for i, e in enumerate(entrada,1)}

Uma vez com o dicionário criado, você será capaz de criar um DataFrame a partir dele:
df = pd.DataFrame(data)

Colocando tudo junto:
import pandas as pd
import matplotlib.pyplot as plot

entrada = [
    [45,32,56,57,44,21,36,35,39,23,24,27,25,26,31,28,29,30,20,22,18,8,19,1,33,2,3,4,0,6,7,9,17,10,11,12,49,55,13,14,15,16,52,46,43,34,41,37,40,5,54,51,53,47,38,42,50,48],
    [50,34,46,45,48,24,27,28,26,43,32,19,10,25,18,12,20,13,7,15,17,9,8,14,22,21,4,3,5,16,1,6,0,11,2,29,47,52,55,57,54,56,38,35,31,23,37,53,33,42,36,49,51,44,39,41,30,40],
    [54,29,40,42,53,23,31,34,37,39,38,17,19,22,12,10,11,3,6,13,15,8,14,16,25,27,4,5,21,0,1,18,9,7,2,32,28,46,48,57,56,55,20,44,33,26,41,52,24,45,43,50,51,49,35,30,47,36],
    [57,56,55,54,53,52,51,50,49,48,47,46,45,44,43,42,41,40,39,38,37,36,35,34,33,32,31,30,29,28,27,26,25,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0]
]

data = {f'rank{i}' : e for i, e in enumerate(entrada,1)}

df = pd.DataFrame(data);
df.plot.bar(stacked=True);
plot.show(block=True);

Saída:


Given two sets of vectors, how do I find the closest vector in the second set for each vector in the first set?

Question: Given: Two sets {S1, S2} of vectors of dimension D. S1 is represented by a N*D matrix and accordingly is S2 represented by a M*D matrix.
I am looking for an elegant way to get for every vector s1 in S1 the nearest neighbour s2 in S2 and the according distance.
A simple approach would of course be to have two for loops and get
dist = norm(s1 - s2);

However, there must be a more elegant and efficient way to do this.
Answer: Yup.  With the mighty power of bsxfun and permute, with a side of sum, and a dash of reshape.  This would be the first part, where you calculate the pair-wise distances between a point in S1 and another point in S2:
out = reshape(sqrt(sum(bsxfun(@minus, S1, permute(S2, [3 2 1])).^2, 2)), size(S1,1), size(S2,1));

The last thing you need now is to determine the closest vector in S2 to each of S1.  That can be done using min:
[dist,ind] = min(out, [], 2);

dist would contain the smallest distance between a point in S1 with a point in S2, and ind would tell you which point that was.

This code looks very intimidating, but let's break it up into pieces.

permute(S2, [3 2 1]):  This takes the matrix S2, which is a M x D matrix and shuffles the dimensions so that it becomes a 1 x D x M matrix.... now why would we want to do that?  Let's move onto the next part and it'll make more sense.
bsxfun(@minus, S1, ...): bsxfun stands for Binary Singleton EXpansion FUNction.  What bsxfun does is that if you have two inputs where either or both inputs has a singleton dimension, or if either of both inputs has only one dimension which has value of 1, each input is replicated in their singleton dimensions to match the size of the other input, and then an element-wise operation is applied to these inputs together to produce your output.  In this case, I want to subtract these two newly formed inputs together.
As such, given that S1 is N x D... or technically, this is N x D x 1, and given that S2 is M x D, which I permuted so that it becomes 1 x D x M, we will create a new matrix that is N x D x M long.  The first input will duplicate itself as a 3D matrix where each slice is equal to S1 and that is N x D.  S2 is now a 3D matrix, but it is represented in such a way where each row in the original matrix is a slice in the 3D matrix where each slice consists of just a single row.  This gets duplicated for N rows.
We now apply the @minus operation, and the effect of this is that for each output slice i in this new matrix, this gives you the component wise difference between the point i in S2 with all of the other points in S1.  For example, for slice #1, row #1 gives you the component wise differences between point #1 in S2 and point #1 in S1.  Row #2 gives you the component wise differences between point #1 in S2 and point #2 S1, and so on.
sum((...).^2, 2): We want to find the Euclidean distance between one point and another point, so we sum these distances squared over each column independently.  This results in a new 3D matrix where each slice contains N values where there are N distances for each of the M points.  For example, the first slice will give you the distances from point #1 in S2 with all of the other points in S1.
out = reshape(..., size(S1,1), size(S2,1));: We now reshape this so that it becomes a M x N matrix so that each row and column pair of (i,j) gives you the distances between points i in S1 and j in S2, thus completing the calculations.
Doing [dist,ind] = min(out, [], 2); determines the smallest distance between a point in S1 with the other points in S2.  dist will give you the smallest distances while ind will tell you which vector it is.  Therefore, for each element in dist, it gives you the smallest distance between a point i in S1 and one of S2, and ind tells you which vector that was that belonged to S2.

We can verify that this gives us correct results by using your proposed approach of looping through each pair of points and calculating the norm.  Let's create S1 and S2:
S1 = [1 2 3; 4 5 6; 7 8 9; 10 11 12];
S2 = [-1 -1 -1; 0 9 8];

More neatly displayed:
>> S1

S1 =

     1     2     3
     4     5     6
     7     8     9
    10    11    12

>> S2

S2 =

    -1    -1    -1
     0     9     8

Using the loop approach, we have this code:
out = zeros(size(S1,1), size(S2,1));
for ii = 1 : size(S1,1)
    for jj = 1 :size(S2,1)
        out(ii,jj) = norm(S1(ii,:) - S2(jj,:));
    end
end

We get this matrix:
>> out

out =

    5.3852    8.6603
   10.4881    6.0000
   15.6525    7.1414
   20.8327   10.9545

Similarly, if we ran the code I wrote, we also get:
>> out = reshape(sqrt(sum(bsxfun(@minus, S1, permute(S2, [3 2 1])).^2, 2)), size(S1,1), size(S2,1))

out =

    5.3852    8.6603
   10.4881    6.0000
   15.6525    7.1414
   20.8327   10.9545

To complete the process, let's find the smallest distances and the corresponding vectors:
>> [dist,ind] = min(out, [], 2);
>> dist

dist =

    5.3852
    6.0000
    7.1414
   10.9545

>> ind

ind =

     1
     2
     2
     2

Therefore, for the first vector in S1, the closest vector to this in S2 was first one, with a distance of 5.3852.  Similarly, the second vector of S1, the closest vector in S2 was the second one, with a distance of 6.  You can repeat this for the other values and see that it's correct.
Comment: This doesn't get out of calculating N*M norms, correct? It just gets rid of the for loop?
Comment: @MatthewGunn No it doesn't, but it's faster.
Comment: What I was writing before was all wrong. Let me think about it for a sec if there's a nice way to do it.
Comment: @MatthewGunn no problem at all.  I'm interested to see how you can do this with matrix multiplication.  I began that way, but couldn't see a way to do it, which is why I pulled out `bsxfun`.
Comment: Some way of iterating, either for loop or bsxfun is the way to go to get the vector difference for each combination.

Sorry for my earlier mindfart.
Comment: @MatthewGunn no problem at all.  I was actually excited when you came out with your answer because I didn't see how to do it with matrix multiplication... but it was your reasoning that ultimately led me to give up and I had to use `bsxfun`.  Either way, it was great to see your attempt.
Comment: @Simon I forgot that you wanted to find the closest vectors.  I just added that in as an edit.
Comment: @Simon so did what I write help you? Consider accepting one of our answers if you no longer need help. Good luck!
Comment: @MatthewGunn - I forgot about this post: http://stackoverflow.com/questions/23911670/efficiently-compute-pairwise-squared-euclidean-distance-in-matlab - This is how you'd do it with matrix multiplication, but you need to write a loop to set things up first.  It's certainly faster!
Answer: How about in one line?
[dist, ind] = min(pdist2(S2,S1));

ind is the index of the nearest vector in S2 for each vector in S1, and dist gives the corresponding minimum distance.
Borrowing @rayryeng's example,
S1 = [1 2 3; 4 5 6; 7 8 9; 10 11 12];
S2 = [-1 -1 -1; 0 9 8];

the results are
dist =
   5.385164807134504   6.000000000000000   7.141428428542850  10.954451150103322
ind =
    1     2     2     2

Comment: @Adriaan _Nothing_ is faster than `bsxfun` :-P Except for [matrix multiplication](http://stackoverflow.com/q/23911670/2586922)
Comment: Very nice.  I forgot to use `pdist2`, but I liked how I came up with `bsxfun/permute` all by myseslf!
Comment: Ghe, is it also faster than the might `bsxfun`?