Why my JavaScript code is printing undefined with the exception throwed?

Question: The Problem here is that with the output coming JavaScript also says undefined. I have seen some codes on w3schools.com and developers.mozilla websites and tried some other sites also but didn't find any solution or any explanation about the problem that i encounter.
I want to throw an exception when 0 or negative value occur.

function isPositive(a) {

  try {
    if (a > 0) return "YES";

    if (a < 0) throw "Negative Value";

    if (a == 0) throw "Zero Value";
  } catch (error) {
    console.log(error);
  }
}

console.log(isPositive(0));

Output expected was
"Zero Value"
Actual Output is
"Zero Value"

undefined

Any suggestions why my code prints undefined along with the output? Thanks in Advance.
Comment: Where are you running this? Also, will you please post the rest of your code.
Comment: You don't return anything unless the result is positive. And why are you throwing in a `try`?
Comment: this is all code that i have. i am testing my code on jsbin.com. I have already tried without try and catch but it was not working.
Comment: You have *two* `console.log` in that code. What do you expect the second one to log?
Answer: This is because if any error is thrown in try it doesnot stop execution of code. If you want to stop the function on error just remove that try-catch and simply return

function isPositive(a){
    if(a>0) return "YES"
    if(a<0) return "Negative Value";
    if(a == 0) return "Zero Value";
}
console.log(isPositive(0));

If you want to throw error put the the statements out of try

function isPositive(a){
    if(a>0) return "YES"
    if(a<0) throw ("Negative Value");
    if(a == 0) throw ("Zero Value");
}
console.log(isPositive(0));
Comment: I have also tried to put the if statements out of the try and catch block but it still doesn't work and giving "Uncaught Zero Value (line 12)".
Comment: @Amit Khatri So whats problem it that. If you want `"Zero Value"` only then use the first snippet
Answer:

function isPositive(a){
try{
if(a>0) return "YES";

   if(a<0) throw "Negative Value";

   if(a == 0) throw "Zero Value";
}catch(err)
{
return err;
}
}

console.log(isPositive(0));

I find the answer and this code works for me and giving the proper results.
Answer: You have console.log(isPositive(a)) calling the function and if it throws error it returns "undefined" (and you will have it printed into console). But if you specify that you return the error it will print the "Negative Error". Code bellow.
function isPositive(a) {
    try{
        if (a > 0) return "YES"
        if (a  == 0) throw ('Zero Error');
        if (a < 0) throw ('Negative Error');
    }
    catch(error){
        return(error);
    }
}


Which table does the Phone module store data in?

Question: I have installed the Phone module to create a field to take input data as mobile number.
I would like to fetch the mobile number back from database to be displayed in a block. I am not getting the table in which the phone number is stored. So in which table is the phone number data is stored?
Comment: In Drupal there are many other ways than fetching the values from database directly by your code. But it depends on how, when and from which part of the module  you want to fetch data. https://drupal.org/node/1074360
Comment: To which entity did you add the phone number field?
Comment: In Administration->Structure->Profile types and added to main profile as a field
Answer: If this module defines a field, then the table is named after that field. So if your field is called field_phone, the table is called "field_data_field_phone". However, getting the value direct from the database is not the right "Drupal way" to do it.
You say you want to display the phone number in a block, but I assume this is within a specific context, such as on a page for a node or user. One way to do this would be to use the Views module to define a block with whatever fields you wish to display, using a contextual filter to get the node or user ID from the page arguments.
But more information is needed in order to say whether this is the right answer or not.


Integral Continuation $\Gamma(z)=\int_{0}^{1} e^{-t} t^{z-1} dt +\int_{1}^{\infty} e^{-t} t^{z-1}dt$

Question: I am trying to obtain an analytical continuation for $\Gamma(z)$ into the region of the complex plane characterized by $\Re(z) \leq 0$ but am stuck.
Starting from the integral definition of $\Gamma(z)$ which is valid for $\Re(z) \geq 0$, re-write
\begin{equation}
\Gamma(z)=\int_{0}^{1} e^{-t} t^{z-1} dt +\int_{1}^{\infty} e^{-t} t^{z-1}dt \equiv f_1(z)+f_2(z).
\end{equation}
We first show that $f_2(z)$ is holomorphic in the entire complex plane by writing
$$
f_2(z)=\int_{1}^{\infty} e^{-t} t^{-1} e^{z\ln t}dt=\int_{1}^{\infty} \frac{e^{-t}}{t} e^{i\Im(z)\ln t} t^{\Re(z)}dt
$$
where I used $z=\Re(z)+i\Im(z)$ and $\exp{(z\ln t)}=\exp[{\ln t(\Re(z)+i\Im(z))}].$  Now we take the magnitude of $f_2(z)$ to obtain
$$
\big|f_2(z)\big|=\bigg| \int_{1}^{\infty} \frac{e^{-t}}{t} e^{i\Im(z)\ln t} t^{\Re(z)}dt\bigg|\leq \int_{1}^{\infty} e^{-t} t^{\Re(z)-1}dt
$$
and we can see that this converges uniformly $\forall \ z.$  Thus we conclude that $f_2(z)$ is a holomorphic $\forall \ z$ and it is an entire function.  I am stuck here though, how to deal with the $f_1$ now?  Thanks
Answer: Where the integral is defined, we can integrate by parts:
$$\begin{align}
\int_0^1 e^{-t} t^{z-1}\,dt &= \frac{e^{-t}t^z}{z}\Biggr\rvert_0^1 + \frac{1}{z}\int_0^1 e^{-t} t^z\,dt\\
&= \frac{1}{ez} + \frac{1}{z}\int_0^1 e^{-t}t^z\,dt.
\end{align}$$
The integral now is defined for $\Re z > -1$, and for $\Re z > 0$, we have the missing part of $\Gamma$, so
$$\Gamma(z) = \frac{1}{ez} + \frac{1}{z}\int_0^1 e^{-t} t^z\,dt + \int_1^\infty e^{-t} t^{z-1}\,dt$$
is valid for $\Re z > -1$. Integrate by parts more often, and you get a representation valid for $\Re z > -k$.
Comment: what is k in the last line?
Comment: A positive integer, the number of times you integrated by parts. Every integration by parts pushes the region of existence of the integral one to the left.
Comment: That is very interesting.  Thanks a lot I didn't realize.


Find $x$ so that rational function is an integer

Question: Find all rational values of $x$ such that $$\frac{x^2-4x+4}{x^2+x-6}$$ is an integer.
How I attempt to solve this: rewrite as $x^2-4x+4=q(x)(x^2+x-6)+r(x)$. If we require that $r(x)$ be an integer then we can get some values of $r(x)$ by solving $x^2+x-6=0$, so that $x=-3$ or $x=2$. In the former case, $r=25$, and in the latter case $r=0$.
[I should note, however, that I'm not really convinced that this step is actually correct, because when $x$ is a root of $x^2+x-6$, the rational function above can have no remainder due to division by $0$. But I read about it as a possible step here and I can't explain it. Q1 How can this be justified?]
Now we want $(x^2+x-6)$ to divide $0$ (trivial) or $x^2+x-6$ to divide $25$. So we set $x^2+x-6=25k$ for some integer $k$ and solve. So $$x=\frac12 (\pm5\sqrt{4k+1}-1)$$
One of the trial-and-error substitutions for $k$ and then for $x$ gives $x=-8$, but that is just one number. Q2: So I'm wondering, how can we find all such $x$? The condition here is that $4k+1$ must be a perfect square, $k\ge 0$. Aren't there infinitely many perfect squares of this form?
I'd appreciate some clarifications about these two questions, Q1 and Q2.
Comment: Why not cancelling $x-2$ ??
Comment: @AmerYR While your observation does help for this problem, I'm wondering if there is a more general approach to this sort of problems. Suppose we couldn't factor and cancel any factors, then how would we proceed?
Comment: If you cancel then $\frac{x-2}{x+3}=1+\frac{-5}{x+3}$
Comment: @AmerYR I understand. Or you could say $\frac{x-2}{x+3}=k$ for some integer $k$ and then solve and get $x=\frac{2+3k}{1-k}$. So, again, we will get a formula for $x$, but actually this formula is better than what I got in my question. So maybe this is the solution itself.
Comment: We get just $x=-8$ the other choice is impossible zero of the denominator
Comment: Other choices are possible: $x=-\frac12$, $x=-\frac{11}{2}$ are just two possible choices. I think there are infinitely many.
Answer: $\frac{x^2-4x+4}{x^2+x-6}=\frac{x-2}{x+3}=1-\frac{5}{x+3}$, for this to be an integer, $\frac{5}{x+3}$ has to be an integer.
Say, $\frac{5}{x+3}=K$, where $K \in \Bbb Z$. This implies for each $K \in \Bbb Z$,  $x=\frac{5}{K}-3$ would make the given expression an integer.
Answer: For $x \neq 2$ is $$\frac{x^2-4x+4}{x^2+x-6}=\frac{x-2}{x+3}=1-\frac{5}{x+3}.$$
To obtain an integer with an integer $x,\;$ $x+3$ must be a divisor of $5,$ or equivalently $x+3 \in \{-1,1,-5,5\}.$
This gives the solutions $-4,-2$ and $8,$ because $x=2$ is excluded.
Comment: This gives integer solutions, but not all $x$, because there are also rational solutions (for example, $x=-\frac12, x=-\frac{11}{2}$, etc).
Comment: You're right, I've overlooked the "rational".
Answer: If we want $x$ rational such that  $ \frac{x^2-x+3}{x^2+5x-7}$ is integer I will simplify $1+\frac{-6x+10}{x^2+5x-7}$
Then I will
go let $a/b$ with  gcd 1 then I will search for solutions to $a^2+5ab-7b^2\mid -6ab+10b^2$
Number theory .
Answer: The set of all solutions can be described as $5n=k(m+3n)$, where $m \neq -3n$ and $m \neq 2n$ and $m,n,k \in \mathbb Z$. When solutions of the above are plugged into $x= \dfrac {m}{n}$ then those x´s are the required ones.
Comment: In the comments I also wrote that the solution can be expressed as $x=\frac{2+3k}{1-k}$, which seems to be more straightforward.
Comment: Yes, that seems even better if that expression covers all the cases covered by expression in this answer.


Python Linear Programming, Constrain Input to Zero or Range

Question: In an Linear Program I am minimizing the distance between weighted input vectors and a target vector. I used Scipyto compute values for the weights I need. Currently they are between zero and one, but I'd like them to be zero if they are smaller than .2 for example, so x_i should be 0 or [.2; 1]. I was pointed to mixed integer linear programming but I still can't find any approach for my problem. How can I fix this?
tldr: i want to use (0,0) or (.3,1) as bounds for each x, how do i implement this?
Here is my SciPy code:
<code>    # minimize the distance between weighted input vectors and a target vector
def milp_objective_function(weights):
    scaled_matrix = input_matrix * weights[:, np.newaxis] # scale input_matrix columns by weights
    sum_vector = sum(scaled_matrix) # sum weighted_input_matrix columns
    difference_vector = sum_vector - target_vector
    return np.sqrt(difference_vector.dot(difference_vector)) # return the distance between the sum_vector and the target_vector

# sum of weights should equal 100%
def milp_constraint(weights):
    return sum(weights) - 1

def main():
    # bounds should be 0 or [.2; 1] -> mixed integer linear programming?
    weight_bounds = tuple([(0, 1) for i in input_matrix])
    # random guess, will implement later
    initial_guess = milp_guess_weights()

    constraint_obj = {'type': 'eq', 'fun': milp_constraint}
    result = minimize(milp_objective_function, x0=initial_guess, bounds=weight_bounds, constraints=constraint_obj)
</code>
Answer: Variables that are in {0} ∪ [L,U] are called semi-continuous variables. Advanced MIP solvers have built-in support for these types of variables.
Note that SciPy does not have a MIP solver at all.
I also want to note that if your MIP solver does not support semi-continuous variables you can simulate them with binary variables:
<code> L ⋅ δ(i) ≤ x(i) ≤ U ⋅ δ(i)
 δ(i) ∈ {0,1}
</code>


How to display more than 10 items in link widget autocomplete?

Question: This is a question about the Link module. Since with the Link module you can enter external or internal links both, we strongly rely on it.
Unfortunately the number of items to be displayed from its autocomplete field is limited to 10. We have a lot of nodes with nearly identical titles and so it comes that the node we are searching for doesn't get displayed in the autocomplete field when there are more than 10 matching titles.
The limit is hardcoded in core/lib/Drupal/Core/Entity/EntityAutocompleteMatcher.php. Is there an elegant way to increase this little number from within a custom module? Do I have to extend class EntityAutocompleteMatcher? Where would I have to place my extension and how to ensure it gets executed from within the link widget?
Answer: If you can live with overriding all of the autocomplete limits, you can override a core service in Drupal 8;
The service you need to override is here in core.services.yml:
  entity.autocomplete_matcher:
    class: Drupal\Core\Entity\EntityAutocompleteMatcher
    arguments: ['@plugin.manager.entity_reference_selection']

In your custom module, add a class that implements ServiceModifierInterface
namespace Drupal\mymodule;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceModifierInterface;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;

class MyModuleServiceProvider implements ServiceModifierInterface {

  /**
   * Modifies existing service definitions.
   *
   * @param ContainerBuilder $container
   *   The ContainerBuilder whose service definitions can be altered.
   */
  public function alter(ContainerBuilder $container) {

    for ($id = 'entity.autocomplete_matcher'; $container->hasAlias($id); $id = (string) $container->getAlias($id));
    $definition = $container->getDefinition($id);
    $definition->setClass('Drupal\mymodule\Entity\EntityAutocompleteMatcherCustom');
    $container->setDefinition($id, $definition);
  }

}

Then copy EntityAutocompleteMatcher.php into your module at /src/Entity/EntityAutocompleteMatcherCustom.php
Then update the hardcoded 10 to a 50, or whatever limit you'd like:
namespace Drupal\mymodule\Entity;

use Drupal\Component\Utility\Html;
use Drupal\Component\Utility\Tags;
use Drupal\Core\Entity\EntityReferenceSelection\SelectionPluginManagerInterface;
use Drupal\Core\Entity\EntityAutocompleteMatcher;

/**
 * Matcher class to get autocompletion results for entity reference.
 */
class EntityAutocompleteMatcherCustom extends EntityAutocompleteMatcher {

  /*
   * {@inheritdoc]
   */
  public function getMatches($target_type, $selection_handler, $selection_settings, $string = '') {

    $matches = array();

    $options = array(
      'target_type' => $target_type,
      'handler' => $selection_handler,
      'handler_settings' => $selection_settings,
    );
    $handler = $this->selectionManager->getInstance($options);

    if (isset($string)) {
      // Get an array of matching entities.
      $match_operator = !empty($selection_settings['match_operator']) ? $selection_settings['match_operator'] : 'CONTAINS';
      // Changing limit from 10 to 50.
      $entity_labels = $handler->getReferenceableEntities($string, $match_operator, 50);

      // Loop through the entities and convert them into autocomplete output.
      foreach ($entity_labels as $values) {
        foreach ($values as $entity_id => $label) {
          $key = "$label ($entity_id)";
          // Strip things like starting/trailing white spaces, line breaks and
          // tags.
          $key = preg_replace('/\s\s+/', ' ', str_replace("\n", '', trim(Html::decodeEntities(strip_tags($key)))));
          // Names containing commas or quotes must be wrapped in quotes.
          $key = Tags::encode($key);
          $matches[] = array('value' => $key, 'label' => $label);
        }
      }
    }

    return $matches;
  }

}

Obviously override core services has some risks, but it's cool that you can do this.
What are the risks of overriding a core service?
1) You may lose the benefits of updates when you update core.  If there is a critical security fix in the service, and your altered copy has the security hole, you will not benefit from the community updating that code.
2) Other modules you install may have dependencies to the original service with its original feature set.  So let's say there is some code in another module that will break if the number of autocomplete entries are greater than or less than 10, you won't know about it, until it affects you.
3) It makes your codebase harder to maintain.  You have to remember that you are not using core Drupal, but an extended version.  Other developers who join your project after you left may have a hard time figuring out why a service is behaving in a non-standard way.
Is this hacking core?
Depends on how you look at it.  It's not going into the core module and changing code.  It's not even creating a patch and applying it and tracking it with a package manager such as composer.  It's more of a one-off customization that alters a sites core behavior, similiar to an ALTER hook. It's more self-contained that a core hack, because it's within your own custom module on your site.  So core updates to the original service will not be affected, the same way as if you patched or hacked the original service code.
But it does have some of the same risks as hacking core, as mentioned above.
In the original question, the issue was the node titles are not unique enough.  The better solution, other than changing the limit globally on drop downs would be solve the uniqueness problem.
What I would suggest is to add a new field field_display_title and use that on the page, and if you need it another field field_teaser_title for display on list pages where you need a shorter title.  Then the actual title that gets pulled into entity reference select dropdown can be useful to your editors and be unique, such as "My Article (page 1)" if the issue is each page has the same title.  Then you don't have to override a core service.
When you come across a problem with Drupal, try to find the solution that requires the least amount of custom code.  This makes your site more stable, easier to maintain and saves you time.
Comment: Basically overriding a core service has the same implications as implementing ALTER hooks. The risks take place but they are quite minor and can be mitigated with proper code documentation.
Comment: Of cause a good number of such overrides, hooks, patches can reduce project maintainability.
Comment: This seems to me like a perfect use case for a [service decorator] (https://www.blueoakinteractive.com/blog/service-decorators-drupal-8).
Answer: I suppose overriding EntityAutocompleteMatcher will affect all autocomplete form elements on your site. So that I would create a new entity selection plugin instead because it is more granular approach. The plugin could be enabled per field. Here is an example of such a plugin.
https://drupal.stackexchange.com/a/220136/433
In your case the implementation would be even more trivial:
File: modules/example/src/Plugin/EntityReferenceSelection/ExampleSelection.php
namespace Drupal\example\Plugin\EntityReferenceSelection;

use Drupal\node\Plugin\EntityReferenceSelection\NodeSelection;

/**
 * Entity reference selection.
 *
 * @EntityReferenceSelection(
 *   id = "example:node",
 *   label = @Translation("Example node"),
 *   group = "example",
 * )
 */
class ExampleSelection extends NodeSelection {

  /**
   * {@inheritdoc}
   */
  public function getReferenceableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
   return parent::getReferenceableEntities($match, $match_operator, 25);
  }

}

Using NodeSelection as base class instead of DefaultSelection would allow you to filter referenced nodes by their status. Note that referencing  other entity types is not supported yet.
Unlike entity reference  link widget does not allow to specify selection plugin through user interface, therefore you need to set it programmatically using hook_field_widget_WIDGET_TYPE_form_alter().
/**
 * Implements hook_field_widget_WIDGET_TYPE_form_alter().
 */
function example_field_widget_link_default_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context) {
  // Replace default selection handler to increase limit of displayed entities.
  $element['uri']['#selection_handler'] = 'example:node';
}

It is important that the plugin ID contains a semicolon.
Answer: An other easy way to modify the number of results is to alter the range value in the query:
/**
 * Implements hook_query_TAG_alter() for entity reference selection handlers.
 *
 * We like tho show always 30 results instead of the 10 definied in EntityAutocompleteMatcher::getMatches()
 */
function MODULE_query_entity_reference_alter(AlterableInterface $query) {
  $query->range(0, 30);
}

Answer: It looks like a proper fix for this has been added to the latest version of core, 8.8+, see #2863188 Hardcoded result size limit in the entity reference autocomplete widget.
Comment: Unfortunately this is only works for the entity reference widget, not for the link widget.
Answer: @Weri, I would avoid doing that, having just implemeted your suggestion and spent the best part of a day trying to fix another issue.
The query alter you suggest also affects entiry reference when linking paragraphs to nodes. A node I was woking on had 80+ paragraph item before I added the alter. Once added I was unable to save the node. Removing/Commenting out the alter fixed the issue.
Update
Wrapping the $query->range() in a route check fixes the issue for me, example,
function mymodule_query_entity_reference_alter($query) {
  $routeMatch = \Drupal::routeMatch();
  if ($routeMatch->getRouteName() == 'system.entity_autocomplete') {
    $query->range(0, 20);
  }
}

Answer: There is an issue on Drupal.org to extend link widget to have limit and operator settings the same way as for entity reference autocomplete widget https://www.drupal.org/project/drupal/issues/3341689#comment-15141098


Show that $\langle a^k \rangle=G$ if and only if $(n,k)=1$

Question:
If $G=\langle a \rangle$ is cyclic of order $n$ show that $a^k$ is a generator if and only if $(n,k)=1$

So I was able to show that if $(n,k)=1$ then $\langle a^k \rangle=G$. However im not being able to show the converse. Any hint from where to start?
Comment: If $(n,k)>1$, then $(a^k)^{n/(n,k)}=(a^n)^{k/(n,k)}=1$.
Comment: Hint: $a^k$ generates $G$ iff there exists $m$ such that $(a^k)^m = a$.
Answer: For the converse proof $a^k,a^{2k},......a^{nk}=1$ are all distinct elements. Let $(n,k)=t$, Let $(n,k)=t,$ and $n=tc,k=td$. Take $(a^k)^c=(a^{td})^c=(a^{tc})^d=(a^n)^d=e$ $\implies n|c$ also $c|n$ $\implies c=n$, $t=1$
Answer: Expanding on my hint, then.
We know $a^k$ generates $G$ iff there exists $m \in \mathbb{Z}$ such that $(a^k)^m = a$. Since $a$ has order $n$, this is the same as $mk + rn = 1$ for some $r \in \mathbb{Z}$. Bézout's identity implies this is equivalent to $(k,n)=1$.
(This proves both directions.)


Números em formatação de cpf (JS)

Question: Eu recebo números de um cpf vindo da API, aí ela vai pra uma table que eu fiz, só que os números nao estão em formato de cpf xxx.xxx.xxx-xx e eu gostaria que ficasse, mas nao sei como. É só clicar em logar e já vai pro site onde tem a tabela, aí la a API vai colocar os dados que tem nela do usuário, e nela vem junto o cpf, mas sem formato correto
Answer: Você pode usar o Plugin Jquery Mask
$(document).ready(function(){
  $('.cpf').mask('000.000.000-00', {reverse: true});
});

https://igorescobar.github.io/jQuery-Mask-Plugin/
Exemplo:

$(function() {
    $('.cpf').mask('000.000.000-00', {reverse: true});
});

<input type="text" class="cpf" id="cpf" maxlength="14">

Números em formatação de cpf (JS)


ORA-00907: missing right parenthesis, mas por quê?

Question: Já estava com problemas na criação desta tabela em relação a hora, mas finalmente, com ajuda consegui resolver o problema. No fim acabei me deparando com outro erro, mas não entendo o por que.
Segue o código:
create table horario (
codhorario number (8) primary key,
horainicio DATE to_char (horainicio, 'hh24:mi'),
horafim DATE to_char (horafim, 'hh24:mi'));

Meu erro:
ORA-00907: missing right parenthesis

Eu pesquisei na internet sobre e acabei encontrando que poderia ser parêntesis a mais ou a menos, mas que também poderia ser erro de sintaxe. Alguém pode ajudar?
Comment: Qual o motivo de chamar a função to_char durante a criação de uma tabela?
Comment: Hmm eu não sei exatamente como implementa-la, pensei que fosse nesse formato. Como seria então?
Comment: Você quer um campo para salvar horas?
Comment: Isso, 2 no caso de inicio e fim. Mas pelo que parece a função to_char está no lugar errado.
Comment: `to_char` retorna uma string, mas o campo é um `DATE`, então já não faz sentido isso. Se quer guardar apenas as horas, [existem algumas alternativas](https://dba.stackexchange.com/q/42084)
Comment: Como dito acima e sendo só hora eu faria como CHAR/VARCHAR2 , uma TRIGGER poderia validar o conteúdo.
Answer: O correto seria armazenar a data completa:
create table horario ( codhorario number(8) , horainicio DATE, horafim
DATE );

Caso você queira somente hora e minuto depois.
Através do select vc pode obter os dados.
select to_char(horainicio , 'hh24:mi') as horainicio ,
       to_char(horafim, 'hh24:mi') as horafim,
from horario


JQuery + Wordpress PHP variable

Question: I'm using the jquery cycle to create a slideshow in my Wordpress template. The "pager" is creating buttons that overlay the slideshow and rollover advances the slides. The trouble I'm running into is that I need the rollover to stay the same, but I also need to set an href so that clicking on the buttons takes the user to a specific page.

I need to retrieve the variable $target from my slideshow for the href.
I need the onclick to make the button clickable.

As I stated above, I'm new at this and it's quite possible that this is terrible code/can't be done/I'm a moron.
My jquery:

and my Wordpress slideshow:
        <?php if ( is_front_page() && $slides = get_posts(array('numberposts' => -1, 'orderby' => 'menu_order', 'order' => 'ASC', 'post_type' => 'slide')) ) : ?>

                <?php foreach ($slides as $slide) : ?>
                    <?php $title = $slide->post_title; ?>
                    <?php $content = wpautop($slide->post_content); ?>
                    <?php $description = get_post_meta($slide->ID, 'description', true); ?>
                    <?php $thumb = get_the_post_thumbnail($slide->ID, 'slide', array('title' => $title, 'alt' => $description)); ?>
                    <?php $url = get_post_meta($slide->ID, '_slide_url', true); ?>
                    <?php $target = (get_post_meta($slide->ID, '_slide_url_blank', true)) ? 'target="_blank"' : ''; ?>

                        <?php if ($url) : ?>
                            <a href="<?php echo $url; ?>" <?php echo $target; ?>><?php echo $thumb; ?>
                        <?php else: ?>
                            <?php echo $thumb; ?>
                        <?php endif; ?>

                <?php endforeach; ?>

    <?php endif; ?>

Thank you in advance for your help.
Comment: Do have Jquery itself linked? Like: ``
Comment: button should already be clickable when you use `'mouseover'` for pager event??
Answer: Where you have:
var slideURL = "<?php echo $target; ?>"

Replace it with:
var slideURL = $(slide).find('a').attr('target');

What you are doing above is getting the slide object, finding the 'a' tag in the slide, and then getting the "target" attribute of the 'a' tag. This value is then assigned to the slideURL variable (which will either be '_blank' or undefined). For more information on how to use jQuery to get HTML elements and/or their attributes, you should familiarise yourself more with jQuery's Traversing and Attributes methods.
You should never mix Javascript code with PHP or even HTML code anyway. Read up more on "Unobtrusive JavaScript".

JQuery + Wordpress PHP variable


Populating an array from another array

Question: I would like to create an array with the first letter from each element, but I keep just getting the entire element - what am I doing wrong?
def each_group_by_first_letter
  self.each do |x|
    first_letter = []
    first_letter = x[0, 1].to_s
  end

  x = ["abcd", "efgh", "able"]
  x.each_group_by_first_letter do |letter, words|
    printf("%s: %s\n", letter, words)
  end

Comment: First of all, you need another `end` here somewhere.  I deduce that you meant it to be before the line `x = ["abcd"....`
Comment: yes...i cut down the code to the relevant parts...there is another end in there...
Comment: Well, your each_group_by_first_letter isn't returning anything explicitly, so in this case it's just returning `self`.
Answer: There are several problems with your code. Among them:

You create an array called first_letter, but then overwrite it with a string on the next line instead of adding the string to it. (To add an item to an array you will usually use Array#push or Array#<<.)
You don't return first_letter, which means you're implicitly returning the array itself (assuming that's what self is--because that's what Array#each returns).
When you call each_group_by_first_letter you pass it a block (do ...) but your method doesn't take or use a block. You probably mean to call each on the result of each_group_by_first_letter.

Regardless, the Array class already has the tools you need--no need to define a new method for this.
x = [ 'abcd', 'efgh', 'able' ]

x.map {|word| word[0] }
# => [ 'a', 'e', 'a' ]

Answer: x = ["abcd", "efgh", "able"]
y = x.map{|e| e[0]}          # keeps x intact

or
x = ["abcd", "efgh", "able"]
x.map!{|e| e[0]}             # modifies x

 => ["a", "e", "a"]

Populating an array from another array


Show that $h(x) = h(x + \frac{1}{2013})$ for some x in $[0,1]$

Question: Edit: I very much appreciate alternate solutions to the problem, but I would also like to know if there are any problems or suggestions regarding the way I solved it.
This is a problem I'm attempting from a set of practice Putnam questions (it's also very similar to a problem in Spivak's Calculus.  I was wondering if there were any problems with my solution.
Problem:
Let $h(t)$ be a continuous function on the interval $[0, 1]$ such that $h(0) = h(1) = 0$.  Show that there exists a real number $x \in  [0, \frac{2012}{2013}]$ such that $h(x) = h(x + \frac{1}{2013})$.
My attempt at a solution:
I'm going to generalize it with the case $h(x) = h(x + \frac{1}{n})$ where $n \in \mathbb{N}$ (assuming that won't cause any difficulties).
Let $$g(x) = h(x) - h(x + \frac{1}{n}) \text{ on } [0, \frac{n-1}{n}]$$
We now attempt to prove the problem by contradiction. Assume $g(x) \neq 0$ for all $x$ in $[0, \frac{n-1}{n}]$.Then $h(x) \neq h(x + \frac{1}{n})$ for all $x$ in $[0, \frac{n-1}{n}]$.Certainly $g$ is continuous on the interval, since $h$ is continuous on the interval, so by the intermediate value theorem, it cannot be both positive and negative on the interval (for if it were, then we would have $g(a) > 0$ and $g(b) < 0$ (or vice versa) on some interval, which would mean that there is some $c \in [a, b]$ such that $g(c) = 0$, which we are assuming is not true).  First we assume that $g(x) > 0$ on $[0, \frac{n-1}{n}]$.  If this were the case, then $h(x) > h(x + \frac{1}{n})$ on $[0, \frac{n-1}{n}]$. This implies that $h$ is always decreasing on $[0, \frac{n-1}{n}]$, which is not possible, since $h(0) = h(1)$.  If we assume the opposite case, that $g(x) < 0$ on $[0,\frac{n-1}{n}]$, then $h(x + \frac{1}{n}) > h(x)$ on $[0, \frac{n-1}{n}]$, which is also not possible, because it would mean $h$ is always increasing on $[0,\frac{n-1}{n}]$.  Since neither of these cases is possible, then $g(x)$ must equal $0$ at some point in $[0, \frac{n-1}{n}]$, so by extension, $h(x) = h(x + \frac{1}{n})$ for some $x \in [0, \frac{n-1}{n}]$. To solve the given problem, we simply let $n = 2013$.
Comment: Since $n$ is given, $h(x) > h(x + \frac{1}{n})$ doesn't mean $h$ is decreasing.
Comment: [Universal Chord Theorem](http://math.stackexchange.com/questions/16374/universal-chord-theorem)
Comment: As @mfl says, the following conclusion is not valid: "This implies that $h$ is always decreasing...".
Comment: But if $g(x)>0$ on $[0,(n-1)/n]$, then $g(0)$ is positive, so $0=h(0)>h(1/n)$. And $g((n-1)/n)$ is positive, so $h((n-1)/n)>h(1)=0$. So $h$ is negative at $1/n$ and positive at $(n-1)/n$. Now $g(1/n)$ is positive, so $0>h(1/n)>h(2/n)$. And $g((n-2)/n)$ is positive, so $h((n-2)/n)>h((n-1)/n)>0$. So now $h$ is negative at $2/n$ and positive at $(n-2)/n$. See where this is going?
Comment: Yes, I see my faulty logic now. I'm assuming I'd have to deal with the possibility that h can increase between the natural numbers. As stated in the answers, it's clear to me now that such a condition isn't fully necessary. Perhaps more true to the original idea of the proof, I'm assuming it suffices to say: $g(0) > g(1/n) > ...> g(1)$, which is a clear contradiction.
Comment: My mistake. Those are supposed to be h, not g.
Comment: You say g is decreasing from 0 to n-1/n.  Okay, but you say that's impossible because g (1)=g (0). Well g can be decreasing from 0 to n-1/n but then jump right be to g(0) in the remaining n-1/n to 1.
Answer: By contradiction, assume that:
$$
  \forall x \in \left[0, \frac{n-1}{n} \right] \; h(x) > h \left(x + \frac{1}{n}\right)
$$
Then
$$
  h(0) > h \left( \frac{1}{n} \right) > h \left( \frac{2}{n} \right) > \dots > h(1)
$$
But $h(0) > h(1)$ is obviously false since $h(0) = h(1) = 0$, hence our assumption must be false, that is:
$$
 \exists x \in \left[0, \frac{n-1}{n} \right] : h(x) \leq h \left(x + \frac{1}{n}\right)
$$
And with an analogous argument we can prove that:
$$
 \exists x \in \left[0, \frac{n-1}{n} \right] : h(x) \geq h \left(x + \frac{1}{n}\right)
$$
This proves that the continuous function
$$
 g(x) = h(x) - h \left( x + \frac{1}{n} \right)
$$
assumes both positive and negative values on the interval (or is constant), and hence it must have a zero.
Answer: $$g(x)=h(x)-h\left(x+\frac{1}{n}\right)$$
$$g(0)=-h\left(\frac{1}{n}\right)$$
$$g\left(1-\frac{1}{n}\right)=h\left(\frac{1}{n}\right)$$
Because $g(0)$ and $g\left(1-\frac{1}{n}\right)$ have opposite signs...
Answer: Let:
$$g:x\in[0,1-\dfrac{1}{n}]\longmapsto h\left(x+\dfrac{1}{n}\right)-h(x)$$
Evaluate $g$  in $n$ different points:
$$\left\lbrace\begin{array}{rcl} g(0)&=&{\color{green}{h\left(\dfrac{1}{n}\right)}}-0 \\
g\left(\dfrac{1}{n}\right)&=&{\color{blue}{h\left(\dfrac{2}{n}\right)}}-{\color{green}{h\left(\dfrac{1}{n}\right)}}\\
g\left(\dfrac{2}{n}\right)&=&h\left(\dfrac{3}{n}\right)-{\color{blue}{h\left(\dfrac{2}{n}\right)}}\\
\dots & = & \dots  \\
g\left(\dfrac{n-1}{n}\right)  & = & 0-h\left(1-\dfrac{1}{n}\right) \\
\end{array}\right.$$
Let's sum:
$$\sum_{k=0}^{n-1} g\left(\dfrac{k}{n}\right)=0$$
So $g$ is either the zero function, or has strictly positive and strictly negative values. Conclude with continuity of $g$ and the intermediate value theorem!


Uniqueness of solutions to Schrödinger's equation

Question: Consider
\begin{cases}
u_t(x,t)=\sqrt{-1} u_{xx}(x,t), \quad (x,t)\in[0,2\pi]\times[0,\infty)\\
u(x,0)=f(x),\quad x\in[0,2\pi]
\end{cases}
where $f(\cdot) \in C^\infty$ is periodic with period $2\pi$. The problem asks to use Fourier series to express the solution to the above IVP problem with periodic boundary conditions
\begin{cases}
u(0,t)=u(2\pi,t)\\
u_x(0,t)=u_x(2\pi,t)\qquad \forall t\geq0
\end{cases}
and show that
$$\int_0^{2\pi}|u(x,t)|^2\ dx=\int_0^{2\pi}|f(x)|^2\ dx, \quad\forall t \geq 0$$
and that
$$\lim_{t \to 0+}\int_0^{2\pi}|u(x,t)-f(x)|^2\ dx=0$$
[Observation]
It is easy to check that
$$u(x,t):=\sum_{n \in \mathbb{Z}} e^{-\sqrt{-1}n^2 t} c_n e^{\sqrt{-1}nx}$$
where $c_n={1 \over {2\pi}}\int_0^{2\pi}f(x)e^{-\sqrt{-1}nx}\ dx$ converges absolutely since $f$ is smooth and its Fourier coefficients decay very quickly, and indeed gives one possible solution to the IVP problem. Now conclusion holds true for thus defined $u(x,t)$ simply by using Parseval's equality. If we can show this is the only possible form of solution, we can get the conclusion, and that's where the problem is.
Essentially the solution heat equation with initial condition can be uniquely determined in some functional space where both the heat function and its derivative can be controlled by at most exponentially growing function at space direction, and can be solved uniquely with appropriate boundary condition in real-valued version simply by applying energy estimate. But these methods do not work out in this situation anyway. I tried the possibility that with the periodic boundary conditions imposed on space, together with the given initial condition $f(x)$, the boundary conditions can be uniquely determined thus applying Cauchy-Kowalevski theorem, yet it does not work so well, so I am not sure how to do this. Any comment will be greatly appreciated!!
Comment: @Branimir Ćaćić I want to post a question today but find it become impossible since the bottom became gray. Does that mean my account is blocked or something like this?
Comment: I've no idea. However, when I open your user profile, it lists you as unregistered. Perhaps something here might be of use? http://meta.stackexchange.com/a/74049
Answer:
Now conclusion holds true for thus defined $u(x,t)$ simply by using Parseval's equality.

Parseval's theorem applies for the situation where an orthogonal expansion (like Fourier expansion in your case) is already there for you to use. In your situation, to prove
$$\int_0^{2\pi}|u(x,t)|^2\ dx=\int_0^{2\pi}|f(x)|^2\ dx, \quad\text{for any }\; t \geq 0,\tag{$\star$}$$
A general method w/o any expansion like brom mentioned in his answers is more preferable. His answer got a minor typo, so here is a more detailed version:
$$G'(t) = \int_0^{2\pi}  u(x,t)\overline{u}_t(x,t) + u_t(x,t)\overline{u}(x,t) \, dx
\\
= \int_0^{2\pi}   u(x,t)\overline{iu_{xx}(x,t)} + iu_{xx}(x,t)\overline{u}(x,t) \, dx
\\
= -i\int_0^{2\pi} u(x,t)\overline{u_{xx}(x,t)} \, dx+ i\int_0^{2\pi} u_{xx}(x,t)\overline{u(x,t)} \, dx
\\
= i\int_0^{2\pi} u_x(x,t)\overline{u_{x}(x,t)} \, dx - \color{blue}{iu(x,t)\overline{u_{x}(x,t)} \,\Big|_{0}^{2\pi}}
\\
-i \int_0^{2\pi} u_x(x,t)\overline{u_{x}(x,t)} \, dx + \color{blue}{iu_x(x,t)\overline{u(x,t)} \,\Big|_{0}^{2\pi}}.
$$
Blue terms vanish because of the periodic Cauchy boundary condition.

[Observation]
  It is easy to check that
  $$u(x,t):=\sum_{n \in \mathbb{Z}} e^{i n^2 t} c_n e^{i nx}.$$

Other than observation, this is a typical result from separation of variables:
$$
u(x,t) = X(x)T(t)\implies X(x)T'(x) = i X''(t) T(t)
\\
\implies -k X(x) = X''(x), \quad  T'(t) = -ik T(t)
\\
\implies X(x) = c_1 \cos(\sqrt{k}x) + c_2 \sin(\sqrt{k}x),\quad T(t) = c e^{-ikt}.
$$
To meet the Cauchy periodic boundary condition, $k$ must be $n^2$ for $n\in \mathbb{Z}$, so the choices of $X$ should be in the set of:
$$
\operatorname{span}\{\cos(nx),\sin(nx)\}_{n\in \mathbb{Z}} = \operatorname{span}\{e^{\pm i n x}\}_{n\in \mathbb{Z}} =  \operatorname{span}\{e^{i n x}\}_{n\in \mathbb{Z}},
$$
and the expression can be rewritten into the formula you gave:
$$u(x,t):=\sum_{n \in \mathbb{Z}}  c_n e^{i nx}\color{red}{e^{-i n^2 t}}.$$
Noitce I got a minus sign in the temporal separated solution. Lastly $u(x,0) = X(x)T(0) = X(x) = f(x)$ will give you the Fourier coefficients $\{c_n\}$.

If we can show this is the only possible form of solution, we can get the conclusion, and that's where the problem is.

You are just one step away from obtaining this fact if you have $(\star)$, now let
$$w = u_1 - u_2$$
where $u_1$ and $u_2$ solve the original equation while satisfying the same Cauchy boundary condition and the initial condition. $w$ will satisfy:
\begin{cases}
w_t(x,t)=i w_{xx}(x,t),  &\text{for }\; (x,t)\in[0,2\pi]\times[0,\infty),\\
w(x,0)= 0, &\text{for }\; x\in[0,2\pi].
\end{cases}
Then by $(\star)$, we have:
$$\int_0^{2\pi}|w(x,t)|^2\ dx= 0, \quad\text{for any }\; t \geq 0. $$
Knowing that the Fourier expansion of $f$ is unique (i.e. $c_n$'s are uniquely determined), what does above equality tell you about the uniqueness of the solution?
Comment: Thank you very much for your clear clarification for my error!
Comment: @RoyHan No problem :)


Domain user directory being created as /home/username@domain instead of /home/username

Question: I am using an amazon linux 2023 box and i joined the instance to domain using realmd.
The issue is that when i try to login with my AD credentials, the user directory is being created as /home/username@domain instead of /home/username.
Here is my /etc/sssd/sssd.conf file:
[sssd]
domains = avengers.local
config_file_version = 2
services = nss, pam
default_domain_suffix = AVENGERS.local

[domain/avengers.local]
default_shell = /bin/bash
krb5_store_password_if_offline = True
cache_credentials = True
krb5_realm = AVENGERS.LOCAL
realmd_tags = manages-system joined-with-adcli
id_provider = ad
fallback_homedir = /home/%u@%d
ad_domain = avengers.local
ldap_id_mapping = True
access_provider = ad
ad_gpo_access_control = disabled

Can someone please help me ?
Answer: Change
fallback_homedir = /home/%u@%d

to
fallback_homedir = /home/%u


Top 10 Commenters this Month

Question: We are trying to set up a view that shows a list of top commenters.
Played around with views but we can't figure it out.
Basically, aggregate all the comments left by each user let say this month.
Then list the usernames in descending order and also show the total number of comments of each user. Next to username for example.
Anyone has ideas on how to do this?
Answer: Take a look at this question. They're doing nearly the same thing but with nodes authored by the user.
After that, you just need to limit the view to 10 results.
Comment: Thanks for the reply. Thats a good starting point. The problem though is that I am getting a list of Questions nodes. What I mean by that is that everything is grouped by the node. And I get a number of comments shown for each node. Instead, I am looking to get a total number of comments by USER.

It doesn't matter which nodes they commented.

This is close, but I still can't get it to do what I am looking for.
Comment: Sounds like you need to make the view based on users and relate to the comments posted by that user. Not sure what you're talking about with Question nodes unless you're referencing the other question I liked to. If that's not the case, please update your answer to be more clear as to what you are trying to accomplish.
Comment: Our users also comment on Question content type. But unlike the linked answer, we are not trying to group by Question but by user. Total comments by user in all Question Nodes. The issue was that for some reason comments were getting grouped by Question nodes and not by Username.
Comment: I'd recommend taking a look at some views tutorials. With a basic understanding of views and a push in the right direction (such as the issue I linked to) you should have more than enough to get this working. If you're still stuck after that, I would recommend updating your question to more clearly answer what you've tried and specifically what is wrong with that implementation.

Top 10 Commenters this Month


app.yaml "login: required" is not working

Question: update
Is this html code inside the template read.html the problem? Does this hyperlink circumvent the app.yaml's login: required?
(edit )

update
My app.yaml contains several login: required directives, but they do not seem to stop access while I am developing locally on GAE.
application: myapp
version: 1
runtime: python27
api_version: 1
threadsafe: true

handlers:
- url: /static
  static_dir: static
- url: /.*
  script: main.app

- url: /create.*
  script: main.app
  login: required

- url: /createblog.*
  script: main.app
  login: required

- url: /editblog.*
  script: main.app
  login: required

My app's view.py begins as follows. Notice that toward the bottom, the template edit.html is triggered. But I want only logged in users to access that template. I don't even care if the user who is not logged is offered an opportunity to login.
import os
import jinja2
import webapp2

from google.appengine.ext import db
from google.appengine.api import users

TEMPLATE_DIR = os.path.join(os.path.dirname(__file__), 'templates')
JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(TEMPLATE_DIR ),
    extensions=['jinja2.ext.autoescape'],
    autoescape=True)

class BaseHandler(webapp2.RequestHandler):

    @webapp2.cached_property
    def jinja2(self):
        return jinja2.get_jinja2(app=self.app)

    def render_template(
        self,
        filename,
        template_values,
        **template_args
        ):
    template = JINJA_ENVIRONMENT.get_template(filename)
        self.response.out.write(template.render(template_values))

class EditReminder(BaseHandler):

    def get(self, blog_id, reminder_id):
        iden = int(reminder_id)
        reminder = db.get(db.Key.from_path('Blogs',blog_id,'Reminders', iden))
    self.render_template('edit.html', {'reminder': reminder, 'blog_id': blog_id})

The answer here is informative, but ...
a) My understanding is that the answer is referring to "static" files, which I assume are not like my templates in the sense that the templates are fed jinja inputs, and
b) Even if my templates are "static" files, I have not figured out how to implement the answer's recommendation.
So, how can these login: requireds be made to work?
Comment: How have you decided it isn't working? If you have already logged-in on localhost, then the cookie will still be there. Visit /_ah/login and force a log-out, and see what happens.
Comment: When I visit ` /_ah/login` I see a dialog that says "not logged in" and invites me to either login or logout. I don't know how to check other cookies. I am using localhost.
Answer: Place your catch-all route
- url: /.*
  script: main.app

at the bottom.
Comment: I had just returned after discovering this myself, when I saw your answer.


Como obter apenas elementos específicos de uma página via axios.get()?

Question: Com o método axios.get da biblioteca axios.js eu consigo obter uma página HTML inteira, certo?
Exemplo:
<code>  axios.get('http://www.umaurl.com')
                .then(resp => {
                    console.log(resp)

                })
</code>
Mas agora, se eu quiser buscar apenas alguns elementos específicos dessa página, como algumas divs, como eu poderia fazer isso numa requisição get via Axios? Teria que passar um seletor por exemplo, no objeto que é o segundo parâmetro do axios.get, certo? Mas como exatamente ficaria a sintaxe disso?
Answer: Você pode usar o cheerio para fazer isso.
<code> const cheerio = require('cheerio');
 const axios   = require('axio');

 axios.get('http://www.umaurl.com')
                .then(resp => {
                  $ = cheerio.load(resp.data);
                  var elemento = $('input[id="elemento"]') /// sintax do jquery
                  /// agora você faz o que quiser com o elemento
                })

</code>
Comment: Eu testei o seu código aqui e eu não obtive o mesmo erro
Comment: Maravilha, vou testar primeiro
Comment: Ah, mas tem um detalhe: na verdade eu estou tentando dar GET, e não post. Eu quero dar GET em URLs externas, mas elas sempre recusam essas minhas requisições XMLHttpRequest do axios. Veja nesse tópico https://pt.stackoverflow.com/questions/452749/como-chamar-e-obter-via-get-uma-p%c3%a1gina-html-externa-usando-axios


On Windows Server 2003, permissions are not propagating to a group that is a member of a group

Question: Windows Server 2003 on i386.
FTP server is running as the SYSTEM user/group.
Some files we want served (read and write) are owned by the group 'ftp.'
ftp has full read/write/whatever permissions on those files and
directories.
SYSTEM can't read/write those directories.  So, I added SYSTEM to
the 'ftp' group. Windows happily complied, but even after restarting
Filezilla, it still could not read/write those files.
Is there any way to do what we want without "re-permissioning" all those
files?  Running the ftp server as 'ftp' isn't really an option because
it also serves files that are owned by SYSTEM (And not ftp).
Sigh... :)
Any insights?
Comment: Upon further investigation, it seems Windows treats the SYSTEM group differently.  Another user in the ftp group has all the same permissions as 'ftp' (as determined by the effective permissions tool), but the SYSTEM group does not seem to inherit those permissions. Wha?
Answer: System (Local system) is not a group, it's a local account with a fixed well known security identifier that is used to allow services to act with the highest level of privilege on the local system. When services running under this context need to act in a network context they present the system's Computer Account and not .\Localsystem or computername\localsystem.
If your service needs permissions to access something in a network context then you should add the Computer account into the group that provides those permissions.
Comment: Well, this is a local account.  Based on your answer, I'm wondering if the FTP server (Filezilla, which I forgot to mention, sorry!) is dropping privs.
Answer: Incidentally, SYSTEM should by default have Full Control access to everything (clicky) (assuming you're using Security and not Sharing here - you are, aren't you?) so I would certainly recommend repermissioning.  I know it's a pain in the face, but getting it right now will always save you from trouble later.
Comment: No, not sharing.
Answer: From the article linked by MH (emphasis mine):

The system account and the
  administrator account (Administrators
  group) have the same file privileges,
  but they have different functions. The
  system account is used by the
  operating system and by services that
  run under Windows. There are many
  services and processes within Windows
  that need the capability to log on
  internally (for example during a
  Windows installation). The system
  account was designed for that purpose;
  it is an internal account, does not
  show up in User Manager, cannot be
  added to any groups, and cannot have
  user rights assigned to it. On the
  other hand, the system account does
  show up on an NTFS volume in File
  Manager in the Permissions portion of
  the Security menu. By default, the
  system account is granted full control
  to all files on an NTFS volume. Here
  the system account has the same
  functional privileges as the
  administrator account.

This means you can't put the SYSTEM account in a group like any other user account; if you want it to be able to access some files (which you most definitely want, everywhere), then it should explicitly have NTFS full control rights assigned to it.


Do mounted folders get mirrored with RAID1?

Question: I have two drives  configured for RAID1 on a a centos 7.9 server. I have been running out of space, installed a third drive and relocated the /opt folder to this third drive.
I still seem to be running out of disk space.
With these two drives in a RAID1 configuration, and those drives mount a third drive, are the contents of this third drive included in the RAID1 mirror?
If so this would seem odd to me, as I do not want to have USB data backed up every time I mount it.
Comment: Honestly, this was a bad idea to move something to non-mirrored drive, if it's needed for the system to perform its task, especially USB drive (because USB has high latency — USB mass storage is *very slow*). This defeats the purpose of having RAID1. If you are running out of space, consider investigating **what** consumes all the space and **why** and solve that problem instead.
Answer: RAID1 is no backup. It's mirroring to improve availability. You still need to back up your data on a regular basis.
If you add a third drive, then you logically have two drives: the previous logical drive, backed by RAID1, and the new one. Mounting a volume just creates a reference, so both drives (or rather volumes) still stay separate on the file system level.
If you regularly back up your RAID1 volume, you need to check whether that job automatically includes your new drive. That depends on how the backup is set up and there's no standard rule.
Comment: Thanks @Zac67. I have edited the question title with the correct terminology.  I don't have a backup mechanism setup like rsync or borgbackup. That is something else I need to do.
Answer: This totally depends on the backup solution you use:

Proxmox Backup doesn't span file systems by itself, so if you point it to some directory in a parent system, it won't include contents of mountpoints, so if you need their contents, you must specify them individually.
Veeam also requires you to specify all the mounted file systems individually, else it "does not guarantee that OS will boot" (as if  people use it specifically to backup OS for bare metal recovery, and not for data backups. It has the worst explanation of all).
BareOS includes contents of mounted file systems into backup by default, but you can configure it to not to include by setting OneFS=no in the corresponding FileSet resource.
tar has an option --one-file-system which tells it not to descend into directory if it's a mountpoint, but by default it will. As Amanda uses tar to backup directories, it should inherit this behaviour. In other words, it behaves like BareOS.

and so on. I am not able to list them all; there are zillion of different backup solutions. You need to read manuals of your backup software carefully, and do your own tests if this is still not clear.
Comment: Thanks for the answer @Nikita. Some very good info which I appreciate. However I don't have a backup mechanism ... yet. Essentially I took the tools folder and placed in on a newly installed drive. The tools can be reproduced with an installation. The server is in a data centre. Again, thanks for the info. Much appreciated
Comment: veeam backup the data that has been configured. not more and not less. if you backup an entire machine then it is possible, if you backup only it's data... you know the way I mean ;)
Comment: @djdcomi I have `/dev/mapper/vg0-lv0` mounted to `/var/lib/mysql` and configured Veeam to backup `/var`, should I expect it to back up my volume with databases too? Does it think I configured this data to be backed up or not? Different solutions have **different answers** to this question and have **documented it**, of all Veeam's documentation has the most vague answer. This is the whole point of the answer.
Comment: the best way is just to open a case on veeam, and ask them for the best practice imho
Comment: Why would I worry? Let Veeam users worry. Hopefully, they won't face the reality the hard way. Everybody else was able to clearly document this caveat, except Veeam, I have a plenty of decent backup systems to choose.


Get only some fields with EntityFieldQuery?

Question: Drupal 7 has very promising ORM-like system of queries with EntityFieldQuery.
Currently, I understand how to make selection of nodes, but the result doesn't contain any specific information, like fileds, I'm looking for.
$query = new EntityFieldQuery();
$entities = $query->entityCondition('entity_type', 'node')
                        ->entityCondition('bundle', 'event')
                        ->propertyCondition('status', 1)
                        ->fieldCondition('field_date', 'value', array('2011-03-01', '2011-03-31'), 'BETWEEN')
                        ->fieldOrderBy('field_date', 'value', 'ASC')
                        ->execute();

So we need to load entire data of nodes, if we would like to get only values of one field, for example 'field_date' in current example.
$nodes = entity_load('node', array_keys($entities['node']));

If there is a way to get the value of fields, instead to load full data of all nodes, as it provokes some memory overload.
$nodesFieldDates = ???

Answer: Great question!
EntityFieldQuery  is truly good stuff,  but if you really want to get serious, you have to override the class in a custom module and add whatever behavior you need done in there.
I don't know your exact intentions, but I have referred myself to this article on the subject in the past.  Credits to Neil Hastings for this well written write-up.
Look for code examples a bit into the article for nice examples of overiding.
Hope that helps, happy coding!
Comment: Ok, I see ! So, probably, it's possible to redefine "EntityFieldQuery" "buildQuery" method, to alternate resulting fields. Probably, this could work.
Answer: I found the answer for this! The Apache Solr module extends the EntityFieldQuery class in order to make it happen. It adds a new method called addExtraField.
<?php
$query = new ApachesolrAttachmentsEntityFieldQuery();
$entities = $query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'event')
  ->propertyCondition('status', 1)
  ->fieldCondition('field_date', 'value', array('2011-03-01', '2011-03-31'), 'BETWEEN')
  ->fieldOrderBy('field_date', 'value', 'ASC')
  ->addExtraField('field_date', 'value', 'value')
  ->execute();
?>

If you don't have Apache Solr installed simply copy the code for extending that class.
Comment: Upvoted this answer simply for the (currently sandbox) module created by mikeytown2 (thanks!)
Comment: Created a sandbox for this as the Apache Solr module had some drawbacks https://drupal.org/sandbox/mikeytown2/2209909
Comment: The link in the answer doesn't seem to work. It says "You need to sign in or sign up before continuing."
Comment: @mbomb007 https://github.com/AmazeeLabs/apachesolr_attachments/blob/7.x-1.4-amazee/apachesolr_attachments.module#L783

Updated the link
Answer: You don't need to override anything or extend the class. You just need to use field_attach_load() to attach the field you want to the results from the EntityFieldQuery class.
See also Loading Only One Field From An Entity or Node in Drupal 7, a good article with examples on how to do it.
Answer: Anyone still wanting to get Fields from a EFQ take a look at the EFQ Extra Fields module.

Warning : This module abuses EntityFieldQuery to return data from your
  database. It does not work with entities or any modules that build on
  them.
It allows you to use addField within an EntityFieldQueryExtraFields
  object (extends EntityFieldQuery objects). Initially EntityFieldQuery
  only gives you back the entity id, bundle and entity type. This module
  adds an extra layer on top of that without doing some extra
  entity_loads! Important if you want to work with massive amounts of
  data and you want to reduce the sql queries. Since EFQ already queries
  the database for this information, why not alter that query to also
  give you some additional fields. This means that not a single extra
  query will be performed to get that data.
A word of caution, if you rely on some post-formatting/post-loading
  that happens in entity_load or similar functions, this module won't
  take care of that. You have to ensure the validity of the retrieved
  data yourselves.

Example

Fetching the node title

$query = new EntityFieldQueryExtraFields();
  $result = $query->entityCondition('entity_type', 'node')
  ->propertyCondition('type', 'my_bundle_type')
  ->propertyCondition('status', 1)
  ->addExtraField('field_myfield', value', value')
  ->addExtraField('field_mynodereffield', nid', nid')
  ->addExtraField('', 'title', 'title', 'node')
  ->fieldCondition('field_myfield', 'value', 'some_value_to_filter_on', '=')
  ->execute();
Possible combinations :
addExtraField($field_name, $column, $column_alias = NULL, $table = NULL)

field_name
Specify from which field the extra field should come. If it is from a base table, leave it empty and fill in the table argument

column
Specify the name of the column,

column_alias
Specify the alias of the column,

table
Optionally, add something like node or user here (the base table),
Comment: I've tried both this module (EFQ Extra Fields) and the (currently sandbox) module by mikeytown2 and the latter seemed much better (nicer to use, more sensible output) and also appears to be maintained a lot better than the former. mikeytown2 sandbox module is at https://www.drupal.org/sandbox/mikeytown2/2209909.


Split array into separate arrays

Question: I have an array $products which contains a non-fixed number of elements.
I need to split this array into 3 individual arrays. The first two arrays should contain an equal number of elements and the last array may contain less.
So for example if $products contains 16 elements, the output should be:

Array 1 contains: 6 elements
Array 2 contains: 6 elements
Array 3 contains: 4 elements

In the event that there are less than 3 elements in $products, then the relevant arrays need to just return empty.
How can I do this? I tried using array_chunk() but doesn't quite do what I want.
$distributed = array_chunk($products, 3, true);
Comment: In your example why 6,6,4? What is there that eliminates 7,7,2 or 8,8,0? Can you elaborate on what the goal is/what it is you require?
Comment: A few sample inputs and the exact desired output would make this question more clear and helpful.  The title is a little too vague to be helpful.
Answer: Just found the answer:
$distributed = array_chunk($products, (int)ceil(count($products)/3), true);

Split array into separate arrays


Countifs with many criteria

Question: I'm looking for help with a formula I've been struggling with:
I'm trying to have the number of occurrences of a word, which is spelled out in "A3", and I only want to count it in the following case:

it's located on my sheet called Source Data, in I2:I
in the same row, the word "Name1" is found in column B
in the same row, the word "Closed" is not found in column M

I'm having a hard time because of the number of arguments.
I'm stuck at this stage:if(countif('Source Data'!I2:I,A3)>0,countif('Source Data'!I2:I,A3),"")
I tried adding formulas such as AND( and FILTER( but got it wrong.
Do you have any idea how I could do this?
Answer: You're looking for COUNTIFS. Adding the extra S on the function allows you to specify multiple criteria.
e.g:
=COUNTIFS('Source Data'!I2:I, A3, B2, "Name1")

Answer: You could use FILTER() in a manner like so:
'ReportSheet'!A1:
  =COUNTIF(
    FILTER(
      'Source Data'!I2:I, // Range being manipulated
      'Source Data'!B2:B="Name1", // filtering predicate
      'Source Data'!M2:M<>"Closed" // filtering predicate
    ),
    $A$3 // criteria to check in the range returned by FILTER()
  )

Note the spreadsheet comparison operators are a touch different from their Apps Script / JavaScript counterparts:

= equality
<, <=, >=, > (as expected)
<> inequality
Comment: Thank you for your help!

Countifs with many criteria


Why should I be Bayesian when my dataset is large?

Question: From "Why should I be Bayesian when my model is wrong?", one of the key benefits of Bayesian inference to be able to inject exogenous domain knowledge into the model, in the form of a prior. This is especially useful when you don't have enough observed data to make good predictions.
However, the prior's influence diminishes (to zero?) as the dataset grows larger. So if you have enough data, the prior provides very little value.
What's the benefit of using Bayesian analysis in this case?
Maybe that we still get a posterior distribution over parameter values? (But for large enough data, wouldn't the posterior just collapse to the MLE?)
Comment: "However, the prior's influence diminishes (to zero?) as the dataset grows larger." -- This is not true in general. Every new data point is not necessarily "more useful." It can keep telling you about what you already know, and not about what you don't. For example, imagine that you're trying to estimate your position by measuring your bearing (angle) to a bunch of known landmarks you can see in the distance. Your prior is a Gaussian centered where you think you are. If all of the landmarks are roughly co-linear, your posterior will never reduce uncertainty / spread along that axis.
Comment: Check out the last gif in [this answer](https://math.stackexchange.com/a/2803948/295791) for a visualization of that Bayesian behavior. One cool thing about Bayesian reasoning is pretty much that is *doesn't* (necessarily) behave the way your question suggests. The remaining uncertainty in one's posterior can make clear what your data *can't* seem to tell you, no matter how much you get. This can be a specific combination of the variables, or some equi-dimensional irreducible variance. It tends to be very relevant for timeseries models, check out "observability analysis."
Comment: What is the goal of your analysis? Inference? Accurate predictions? Something else?
Comment: Your dataset is never large ;-)
Comment: @kutschkem in the demo from that other rather unrelated question, yes the data set is small; it was just for visualization purposes. If the landmarks are actually all in a straight line though, the uncertainty will never reduce. And perhaps even if the deviations from a straight line are much smaller than the error variance of the angle measurements.
Comment: Overall I think my comment is just an example of the kind of behavior pointed out in #6 of the accepted answer (by Bernhard).
Comment: @kutschkem whoops just realized you may have been making a joke about the OP's notion of ever having a large dataset lol
Comment: @jnez71 Yes it was just a joke, of course there are problems where your dataset can be large (enough). But a lot of problems have such a big feature space that it's basically impossible that the dataset is "large enough". As an example, I work in automotive and they are heavily looking into simulating situations that in a "normal" dataset would almost never appear but are important nonetheless (basically any accident situation, I guess).
Answer:
Being Bayesian is not only about information fed through the prior. But even then: Where the prior is zero, no amount of data will turn that over.

Having a full Bayesian posterior distribution to draw from opens loads and loads of ways to make inference from.

It is easy to explain a credible interval to any audience whilst you know that most audiences have a very vague understanding of what a confidence interval is.

Andrew Gelman said in one of his youtube videos, that $p$ is always slightly lower then $0.05$ because if it wasn't smaller then we would not read about it and if it was much smaller they'd examine subgroups. While that is not an absolute truth, indeed when you have large data you will be tempted to investigate defined subgroups ("is it still true when we only investigate caucasian single women under 30?") and that tends to shrink even large data quite a lot.

$p$-values tend to get worthless with large data as in real life no null hypthesis holds true in large data sets. It is part of the tradition about $p$ values that we keep the acceptable alpha error at $.05$ even in huge datasets where there is absolutely no need for such a large margin of error. Baysian analysis is not limited to point hyptheses and can find that the data is in  a region of practical equivalence to a null hypotheses, a Baysian factor can grow your believe in some sort of null hypothesis equivalent where a $p$ value can only accumulate evidence against it.  Could you find ways to emulate that via confidence intervals and other Frequentist methods? Probably yes, but Bayes comes with that approach as the standard.

"But for large enough data, wouldn't the posterior just collapse to the MLE" - what if a posterior was bimodal or if two predictors are correlated so you could have different combinations of e.g. $\beta_8$ and $\beta_9$ -  a posterior can represent these different combinations, an MLE point estimator does not.
Comment: I'm not sure about point 5: Composite null hypothesis are frequently true, I reckon. The point that $p$-values are worthless in large samples is expected: It's just the property of consistency of the test (its power approaches one to detect false nulls). It doesn't make sense to me to say a tests is okay in small samples but worthless in large samples.
Comment: Fair point taken. However, Frequentism is not only what you could do with it but also its tradition, what people usually do. Personally I was taught never to publish a one-tailed test (the obvious case of a composite null hypothesis) and I was taught to always setalpha at $.05$ or $.01$ or one of those multiplied by some Bonferroni correction. Neither rejection of one-tailed testing nor fixing alpha at some constant level for all research is inherent to Frequentism in theory, however in large parts of practice and teaching.
Comment: +1. I think point 1 could use expansion. It's a two-edged sword: where the prior is literally zero you're saying it's impossible and if you mean "highly-unlikely" you are in error. However, if you literally mean "impossible" (negative variance, negative weight, etc), then a Bayesian prior can enforce this strictly where parametric approximations/estimates of point values can't.
Comment: Oh yeah, absolutely. I think you're raising some excellent points in your answer (+1).
Answer: I'd like to echo some of the points in the other answer with slightly different emphasis.
To me the most important issue is that the Bayesian view of uncertainty/probability/randomness is the one that directly answers the questions we probably care about, whereas the Frequentist view of uncertainty directly answers other questions that are often somewhat besides the point. Bayesian inferences try to tell us what we (or an algorithm, machine, etc.) should believe given the data we have seen, or in other words "what can I learn about the world from this data?" Frequentist inferences try to tell us how different our results would be if the data that we actually saw were "re-generated" or "repeatedly sampled" an infinite number of times. Personally I sometimes find Frequentist questions interesting, but I can't think of a scenario where the Bayesian questions aren't what matter most (since at the end of the day I want to make a decision about what to believe or do now that I've seen new data). It's worth noting that often people (statisticians included) incorrectly interpret Frequentist analyses as answering Bayesian questions, probably betraying their actual interests. And while people get worried about the subjectivity inherent in Bayesian methods, I think of the Tukey line, "Far better an approximate answer to the right question, which is often vague, than an exact answer to the wrong question, which can always be made precise." For what it's worth, Frequentist methods are also subjective, and arguably in ways that are less obvious and convenient to critique.
Getting off my Bayesian high horse, you're right that answers to Frequentist questions (especially MLE) sometimes coincide closely (and in rare cases, exactly) with answers to Bayesian questions.
However, large data is a vague notion in a few senses that can make Bayesian and Frequentist (MLE) answers remain different:

Most results about large data are asymptotic as the sample size goes to infinity, meaning that they don't tell us when our sample size is actually large enough for the asymptotic result to be accurate enough (up to some known level of error). If you go through the trouble to do both Bayesian and Frequentist analyses of your data and find they're numerically similar then it doesn't matter so much.
Often with "large" data (e.g. many observations) we also have a large number of questions or parameters of interest. This is basically Bernhard's point #4.
A lot of large data sets are not perfectly designed and relate to our interests indirectly because of issues like measurement error or sampling bias. Treated honestly, these complications may not go away even asymptotically, meaning that the models that realistically relate the data to what we care about have non-identifiable sensitivity parameters that are most natural to deal with using priors and the Bayesian machinery.

Of course, the flip-side of this question is "Why should I be Frequentist when my dataset is large?"
Answer: The other answers address what's probably your actual question. But just to add a more concrete viewpoint: if you're already a Bayesian (for small/medium datasets) and you get a large data, why not use the methodology you're familiar with? It will be relatively slow but you are familiar with the steps so you're less likely to make mistakes and you're more likely to spot problems. And a Bayesian workflow includes things like posterior predictive checks, etc, which are useful for understanding your model.
Answer: One place where Bayesian approach meets large datasets is Bayesian deep learning. When using Bayesian approach to neural networks people usually use rather simplistic priors (Gaussians, centered at zero), this is mostly for computational reasons, but also because there is not much prior knowledge (neural network parameters are black-boxish). The reason why Bayesian approach is used, is because out-of-the-box it gives us uncertainty estimates.
Comment: @kennysong if your data is small, then the model can memorize the data (overfitt) and give exact predictions per each datapoint. In such case it would "feel" certain about it's predictions. If the data is big, than it cannot be certain, because same parameters need to be re-used for different data, so there is a variability.
Comment: @Tim Machine learning is not restricted to neural networks. There are several methods which do not require using a bayesian framework. What makes me rethink of using bayes in ML and when large data is the variance-bias trade-off. Bayesian methods tend to reduce variance but not bias, whereas data driven methods usually reduce bias but have larger scatter. Big data makes it possible to reduce the scatter in the latter, not sure the bias in the former.
Comment: @jpcgandre Bayesian neural networks were used in here just as an example, Bayesian models are not restricted to neural networks as well. The key point is that Bayesian approach gives you uncertainty estimates, having big data does nothing about giving you uncertainty estimates.
Comment: @Tim I agree that it gives you uncertainty estimates, but still uncertainty estimates around a biased posterior.
Comment: @jpcgandre when the data grows larger, the impact of priors diminishes. You can use Bayesian methods *with* large datasets. For many problems you need uncertainty estimates, Bayes methods are one of the possible solutions.
Comment: Is there some intuition of why the uncertainty estimates of BNNs don't collapse to certainty for large datasets? (Maybe they do?)
Comment: @kennysong BNNs do collapse to certainty for small datasets; I think larger datasets make that type of collapse less probable rather than necessarily prevent it.
Comment: @JeremyList Why is that the case? It seems counterintuitive to me


Drupal Mysql SSL Connections

Question: Cannot seem to find solid literature on using mysql-ssl connections with either Drupal 6 or Drupal 7. Piece of cake with wordpress. Is this a possibility, if not why?
Comment: Wow! Really? What is this 3rd grade? For the record I wasn't "comparing", I have a task at hand to make a bunch of sites - wordpress and drupal - work with mysql-ssl connections. Was just pointing out that I was able to get things working with wp.
Comment: @ram4nd That's not really what downvotes are for. If you think the question is of poor quality or unlikely to be useful to the site then you should downvote it, not because you disagree with a perceived comparison between Drupal and Wordpress. Personally I think it's a pretty good question, documentation is pretty scarce on the matter
Answer: The Drupal 7 database layer uses PDO which prior to PHP 5.3.7 did not support MySQL with SSL.
Assuming you're using PHP 5.3.7 or later there is a patch available for Drupal to allow "arbitrary PDO options" to be used, which would include the ability to specify an SSL option.
See this discussion for a fair bit more information and links to the issues on php.net.
EDIT
For Drupal 6 you can change the mysql_connect() line in includes/database.mysql.inc to:
$connection = @mysql_connect($url['host'], $url['user'], $url['pass'], TRUE, MYSQL_CLIENT_SSL);

Although you should really turn this into a patch and apply it to the includes/database.mysql.inc file as hacking core is never a good idea.
Comment: Did find the php.net link a bit after I posed the question. Thanks a ton. So for those stuck on debian(with a default php version 5.3.3) and Drupal 7, I assume that there is no way to connect to mysql using ssl.
Comment: @L0neRanger It does look that way yeah :/

Drupal Mysql SSL Connections


Why don't menu tabs show for a view generated page?

Question: Why don't menu tabs show for a view generated page?
Viewing my site as an administrator I see menu tabs above content pages for view, edit, and Devel (I have the developers module turned on).  When I generate a view page, the menu tabs are not displayed.  I have viewed video tutorials and they are present on a view page.  The view is working and generating the correct page. Is there a setting somewhere?
Added Question:
OK hansag answered my initial question below, so let me rephrase the question. The problem is I have created 3 pages in the view each with menu tabs assigned. The paths for each are:
default tab page= materials/%
page 2 = materials/%/general
page 3 = materials/%/scope
There is a contextual filter that takes the % value and finds articles with an attached taxonomy term.  The view page works since the placing a URL such as materials/termname finds the correct articles and displays them.
Why don't the menu tabs show?
Answer: Those tabs are used for node editing. When you create a "page" from the views module it is general collecting a series of nodes on the page, so it is not displaying the single node tabs.
You might consider using this module. Block Edit
It generates view/edit tabs for blocks and views.
Hope this helps!
Comment: Got it!!! But I have created several pages within the view with assigned menu tabs and they will not show either. Please see additions to my question.
Answer: I have found another answer as well.
In my example above, I had more than one tab defined, so even though the standard tabs such as "view" or "edit" did not show up, my additional tabs should have.
What I have found is that the menu tabs appear to only work if the path begins with 'user', 'comment, or perhaps a couple other key terms.  I was using 'materials' as the path root and this excluded the display.
I have posted an issue for the views module although I am not certain this is them or core.  Hopefully they can expand the functionality of the menu tabs to fit with path naming schemes of users.


how to unset session without destroying?

Question: How to Unset a session variable without destroying it so it can be used again
<?php
ini_set('display_errors', 0);
session_start();

     if(isset($_SESSION['username']))
      {
        if(isset($_POST['logout'])){

          session_unset();
          unset($_SESSION['username']);
          unset($_SESSION['password']);
          header('location:index.php');
        }

        if(isset($_POST['unset'])){
          session_destroy();
          header('location:registration.php');
        }
?>
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

Welcome

      <form action="" method="post">
      <input type="submit" name="logout" value="logout" class="btn btn-danger">
      <input type="submit" name="unset" value="remove user" class="btn btn-danger">

      </form>

<?php
}
else{
  echo "not login";
}
?>

Here on logout button , just want to unset the session variables so the session variables can be used again in login.php.
PS: I dont want to use Database.
Comment: $_SESSION['username']='' is the only option
Comment: but after unsetting how to get the value back?
Comment: I don't see the issue in your php? Are the sessions not being unset?
Answer: You can either
<?php
     if(isset($_POST['unset'])){
         //removes all the current variables in the
         //session and re-initializes them to nothing or null
         $_SESSION = array();

         //or
         //for each variable in your session unset like - to remove single values.
         unset($_SESSION["username"]);
     }
?>


k-means in R generates same number of clusters but different cluster label

Question: Hi there I am running a k-means code in R with the same data and with the same number of clusters, in this case 3, but each time that I run the code, the cluster label changes, for example.
In the first run I got this results
Col A  Cluster.K-means
FirstOBS Cluster1,
SecondOBS Cluster1,
ThirdOBS Cluster2,
FourthOBS Cluster3
then I run the code again, specifying the same number of clusters=3, and the output column changes the cluster number, for example
FirstOBS Cluster2,
SecondOBS Cluster2,
ThirdOBS Cluster3,
FourthOBS Cluster1
In this case the second run (with the same data, same code and same number of clusters) changed the (1 by 2), the (2 by 3) and the (3 by 1)
How can I fix the result? because in the next step I have to compare the cluster number between two different data, for instance the cluster results from January against March results.
This is the code
cv1.km3 <- kmeans(cv1.f, 3)
cv1.km3$size
So each time I run the cv1.km3$size I got different combinations
Thank you
Answer: Citing the reference documentation:

The algorithm of Hartigan and Wong (1979) is used by default. [...] The Hartigan–Wong algorithm generally does a better job than either of those, but trying several random starts (nstart> 1) is often recommended. In rare cases, when some of the points (rows of x) are extremely close, the algorithm may not converge in the "Quick-Transfer" stage, signalling a warning (and returning ifault = 4). Slight rounding of the data may be advisable in that case.

So at each iteration you get different results as expected. The way to avoid this, is to set the random seed to a fix number, so that the behaviour of the algorithm is deterministic. See set.seed for details.


Why is $x_t = x_{t-1}+w_t$ not wide-sense/second-order stationary?

Question: I understand that if $x_t$ is $\text{AR}(1)$, i.e.,
$$x_t = \phi x_{t-1}+w_t\tag{1}$$
with $x_t$ (second-order/wide-sense) stationary, $w_t \sim \mathcal{N}(0, \sigma^2_w)$ independent from $x_t$, as long as $\sup_t\text{Var}(x_t) < \infty$ and $|\phi| < 1$, we can write
$$x_t = \sum_{i=0}^{\infty}\phi^{i}w_{t-i}\text{.}$$
I also understand that the autocovariance is given by
$$\gamma(h) = \dfrac{\sigma^2_w \phi^h}{1-\phi^2}\tag{2}$$
as long as $h \geq 0$ and $|\phi| < 1$.
What I don't understand is this:

Suppose $\phi = 1$ in $(1)$. How do we know that $x_t$ isn't
  (wide-sense) stationary?

The sources I've seen online state that this is true because "the variance is infinite" (can't find them right now). This is probably because if $\phi > 0$, we obtain $\lim_{\phi \to 1}\gamma(h) = \infty$ from $(2)$. But, if this is using $(2)$ above, $(2)$ is derived under the assumption of stationarity, which doesn't make any sense.
Comment: Hint: when $\phi=1$, it's easy to work out from equation $(1)$ alone that the variance of $X_s$ conditional on $X_t$ (for $t\le s$) is proportional to $s-t$.  When you confront that observation with the definition of "stationary," something has to give.
Comment: @whuber Interesting. So if I did this right, the variance of $X_s \mid X_t$ is $(s-t)\sigma^2_w$. If we assumed $t \geq s$, we would obtain $(t-s)\sigma^2_w$. In either case, we obtain $|s-t|\sigma^2_w$ for the conditional variance... I must be missing something.
Comment: @whuber Gave it my best attempt as an answer. If you have time, please provide feedback.
Answer: We need to assume only that

There exists an index $t$ for which $\operatorname{Var}(X_{t})$ is finite.
$\sigma^2 = \sigma^2_w$ is nonzero.

The independence of $X_{t-1}$ and $w_t$ gives $$\operatorname{Var}(X_t) = \operatorname{Var}(X_{t-1}+w_t)=\operatorname{Var}(X_{t-1}) + \operatorname{Var}(w_t) = \operatorname{Var}(X_{t-1}) + \sigma^2.$$
Comparing the left and right sides in light of $(2)$ shows $\operatorname{Var}(X_{t-1})\ne \operatorname{Var}(X_{t}).$  (Assumption $(1)$ makes this a meaningful statement about finite numbers.)  Consequently $(X_t)$ cannot be stationary--which, among other things, implies every $X_t$ has the same distribution--because it's not even second-order stationary.
Comment: I did a facepalm when I read that. Thank you for your help.
Comment: Absolutely!  You need the mean, variance, and covariance not to change under translations of the index.  Put into math terminology, this means that for all $s$, $t$, and $h$, (1) $E[x_t]=E[x_{t+h}]$; (2) $\operatorname{Cov}(x_t,x_s)=\operatorname{Cov}(x_{t+h},x_{s+h})$.  These can be restated as (1') the expectation is constant and (2') the covariance depends only on $s-t$.  A special case of (2') is $s=t$, which states the variance is constant.
Comment: Ah, I have some clarifications to make (sorry about this... this is due to my limited exposure to time series). When I mentioned "stationary" above, Shumway and Stoffer (the text I'm using) mean second-order stationary (or "weak" stationary). I understand how your answer definitely implies that $(X_t)$ is not strictly stationary, but how can I see not second-order stationary from the above? By "second-order stationary," I mean having a constant mean wrt $t$ and an autocovariance $\text{Cov}(x_s, x_t)$ only dependent on $s$ and $t$ only through $|s-t|$. I will edit my post to clarify this.
Comment: Since $\operatorname{Var}(x_t) = \operatorname{Cov}(x_t,x_t)$, *a fortiori* the sequence is not second-order stationary according to your definition.
Comment: Hmm... so if I'm interpreting this correctly, from my definition of second-order stationary, it follows that $\text{Var}(x_t)$ must be constant with respect to $t$!
Answer: Now that I've finished a grad-level Time Series course, I can provide an answer. This is essentially exercise 2.8 in Brockwell and Davis' Introduction to Time Series and Forecasting, 3rd edition.
For the $\text{AR}(1)$ model indicated above, we have
$$x_t = \phi x_{t-1} + w_t\tag{*}$$
Using (*) above, for $n$ finite, we have
$$\begin{align}
x_t &= \phi x_{t-1} + w_t \\
&= \phi(\phi x_{t-2}+w_{t-1})+w_t \\
&= \phi^2 x_{t-2}+\phi w_{t-1}+w_t \\
&= \phi^2(\phi x_{t-3}+w_{t-2})+\phi w_{t-1}+w_t \\
&= \phi^3x_{t-3}+\phi^2w_{t-2}+\phi w_{t-1} + w_t \\
&\vdots \\
&= \phi^{n+1}x_{t-(n+1)}+\sum_{k=0}^{n}\phi^{k}w_{t-k}\text{.}
\end{align}$$
This yields the equation
$$x_t - \phi^{n+1}x_{t-(n+1)}  = \sum_{k=0}^{n}\phi^kw_{t-k}\text{.}$$
With $w_t \overset{\text{iid}}{\sim}\mathcal{N}(0, \sigma^2_w)$, then
$$\text{Var}\left(\sum_{k=0}^{n}\phi^kw_{t-k} \right) = \sum_{k=0}^{n}\phi^{2k}\sigma^2_w=(n+1)\sigma^2_w$$
with the assumption that $\phi = 1$.
Assume by contradiction that the $x_t$ are stationary. Because the $x_t$ are stationary, the covariances $\text{Cov}(x_t, x_{t+h})$ are independent of $t$; in particular, $\text{Cov}(x_t, x_{t}) = \text{Var}(x_t)$ is independent of $t$. Write $\sigma^2_{X} = \text{Var}(x_t)$. Then
$$\begin{align}
\text{Var}(x_t - \phi^{n+1}x_{t-(n+1)}) &= \sigma^2_X + \phi^{2(n+1)}\sigma^2_X +2\cdot \text{Cov}(x_t, - \phi^{n+1}x_{t-(n+1)}) \\
&= \sigma^2_X + \phi^{2(n+1)}\sigma^2_X  -2\phi^{n+1}\cdot\text{Cov}(x_t, x_{t-(n+1)}) \\
&\leq \sigma^2_X[1+\phi^{2(n+1)}] \tag{**} \\
&= 2\sigma^2_X
\end{align}$$
hence for any $n$,
$$(n+1)\sigma^2_w \leq 2\sigma^2_X\text{.}$$
Taking the limit as $n \to \infty$, it follows that $\sigma^2_X > \infty$, hence contradicting that $\sup_t \text{Var}(x_t) < \infty$ by stationarity.
In (**), I made an assumption that $\text{Cov}(x_t, x_{t-(n+1)}) \geq 0$. To see why this is the case, write
$$\begin{align}
\text{Cov}(x_t, x_{t-(n+1)}) &= \text{Cov}\left(x_t, \dfrac{x_t - \sum_{k=0}^{n}\phi^k w_{t-k}}{\phi^{n+1}}\right) \\
&= \dfrac{1}{\phi^{n+1}}\text{Cov}\left(x_t, x_t-w_t \right) \\
&= \dfrac{\sigma^2_X}{\phi^{n+1}} \\
&\geq 0
\end{align}$$
due to independence of the $w_t$ from the $x_t$.


Could someone give me a good progression of projects to grow my skills in python from novice to intermediate at least?

Question: I recently began to teach myself how to program in python. At the moment I am struggling to structure my learning through projects like I had in my programming classes. I was wondering if anyone had a short list of projects that they feel best develop the skills they find most useful in python or somewhere I could find good projects to challenge myself to grow.
Thanks
Comment: These kind of questions are [out of scope](https://stackoverflow.com/help/dont-ask) for stack overflow, but I recently saw [this](https://web.eecs.utk.edu/~azh/blog/challengingprojects.html) article and they may be worth a look. Some will need a lower level language but some will be perfectly doable in python.
Answer: The self-learning tool I found most useful was "Automate the Boring Stuff with Python". The chapters and hands-on projects stuck much better than DataCamp, CodeAcademy, Udemy, etc. Just set up an IDE or Jupyter Notebook and create along with the chapters. Then, once you've made some things, improv a little on them to make them your own.
Good luck and enjoy.
Comment: This is a very good resource indeed!
Answer: Download your bank statement and write a parser to generate a spending report.
Answer: Google (or alternatives like Lilo) is your friend.
Here is some of the results I got by typing "Python Exercises":

https://www.w3resource.com/python-exercises/
https://www.practicepython.org/exercise/2014/04/30/13-fibonacci.html

Some trainers also offer some paying "Weekly Practice": every week you got some challenge (usually different level to choose at the beginning), and at the end of the week you get the solution.
Can't give any name though because StackOverflow is not about promoting