How can I add a keypress event Angular

Question: I am setting an input field to a variable I am defining, this is used to filter through my table on the front-end. It does not want to return any values unless a key is entered within the input field. How can I get the filter to work without the input field expecting back a key event. I want it to return values immediately when the 'filteredValue' is assigned.
HTML
<mat-form-field appearance="outline" *ngIf="filteredValue">
  <mat-label>Filter 1</mat-label>
  <input matInput
         type="text"
         (input)="doFilter($event.target.value)"
         placeholder="Ex. BMW"
         value="{{filteredValue | lowercase }}">
</mat-form-field>

component.ts
ngOnInit() {
  if (this.urlMM) {
    this.filteredValue = this.urlMM + ' ' + this.urlMake + ' ' + this.urlYear;
  }
}

public doFilter = (value: string) => {
  this.dataSource.filter = value.trim().toLowerCase();
}

Comment: So you want your value as soon as you type something in your input field? If so you should check the answer of the user 'Saga' on here https://stackoverflow.com/questions/35359358/angular-2-change-event-on-every-keypress
Comment: I am already assigning a value to the input field. But the filter only returns values when I edit the textbox. I want the values to be filtered as soon as the page loads.
Answer:
You can use keypress

doFilter(filterKety) {
console.log(filterKey)
if(filterKey.length > 2){
// your logic

}
}
<mat-form-field appearance="outline" *ngIf="filteredValue">
  <mat-label>Filter 1</mat-label>
  <input matInput
         type="text"
         (keypress)="doFilter($event.target.value)"
         placeholder="Ex. BMW"
         value="{{filteredValue | lowercase }}">
</mat-form-field>
Comment: This still does not provide the desired solution. When the page loads the input field already has a value assigned ("filteredValue"). I want this value to filter through the table as soon as the data is returned within the table.

How can I add a keypress event Angular


SearchAPI Autocomplete - Pass in contextual filter to alter query

Question: I'm trying to modify the Autocomplete module query with hook_search_api_alter_query. I would like to pass in the contextual filter of the page I embed the search in into the module so I can add it to the query. In a hook_search_api_alter_query function I wrote, I just used arg(1), which works for the actual search, however when the autocomplete module runs, var_dump(arg(1)) returns Response Type: string(33) followed by the autocomplete results and their html tags.
Is it possible to pass in the contextual filter into the autocomplete module so that I can use it , since the contextual filter has been changed to /search_api_autocomplete/search_api_views_[view name]/-?
My current query alter hook:
    function hook_search_api_query_alter(SearchApiQueryInterface $query) {
      var_dump(arg(1));
        $prod_code = arg(1);
        $tid = taxonomy_get_term_by_name($prod_code);
        if (!empty($tid)) {
            $base_filter = $query->createFilter('AND');
            $or_filter = $query->createFilter('OR');
            while (!empty($tid)) {
                $or_filter->condition('field_prod_code', array_shift($tid)->tid);
            }
            $base_filter->filter($or_filter);
            $query->filter($base_filter);
        }
    }

My problem is that arg(1) within the autocomplete module isn't the taxonomy term, therefore the function doesn't go through the if statement. I need a way to get the contextual filter for the autocomplete function so that it can alter my query like it does when searching.
Answer: I ran into the same issue.
You could save your data in a session in hook_init or hook_boot.
/**
 * Implements hook_init().
 */
function hook_init() {
  $arg = arg();
  if (isset($arg[2]) && $arg[0] == 'taxonomy' && $arg[1] == 'term' && is_numeric($arg[2]) ) {
    $_SESSION['last_term'] = $arg[2];
  }
}


PostCSS plugin tailwindcss requires PostCSS 8 error in React

Question: I'm trying to update my tailwindcss but I encountered this issue:
PostCSS plugin tailwindcss requires PostCSS 8

I've tried:
npm uninstall tailwindcss postcss autoprefixer
npm i tailwindcss@latest postcss@latest autoprefixer@latest

But I see the above eror.
I'm curious that the error indicates that I need to have version postcss 8 or higher, then why doesn't it work while having its version "8.2.4" in "package.json".
Here is how my package.json looks like:
{
  "name": "my-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@coreui/react-chartjs": "^2.1.0",
    "@craco/craco": "^6.2.0",
    "@testing-library/jest-dom": "^5.14.1",
    "@testing-library/react": "^11.2.7",
    "@testing-library/user-event": "^12.8.3",
    "axios": "^1.3.4",
    "chart.js": "^4.0.1",
    "dayjs": "^1.11.7",
    "firebase-tools": "^9.23.3",
    "react": "^17.0.2",
    "react-chartjs-2": "^5.0.1",
    "react-circular-progressbar": "^2.1.0",
    "react-copy-to-clipboard": "^5.1.0",
    "react-device-detect": "^2.2.2",
    "react-dom": "^17.0.2",
    "react-loader-spinner": "^5.3.4",
    "react-router-dom": "^5.2.0",
    "react-scripts": "4.0.3",
    "react-toastify": "^8.1.0",
    "web-vitals": "^1.1.2"
  },
  "scripts": {
    "start": "craco start",
    "build": "craco build",
    "test": "craco test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "autoprefixer": "^10.4.14",
    "postcss": "^8.4.21",
    "tailwindcss": "^3.3.1"
  }
}

Also, tried deleting node_modules then adding again via npm i
Note:
I don't need this version of tailwind(v2)
npm install tailwindcss@npm:@tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9

instead, I want to have tailwindcss v3.
Edit:
Here is how my craco.config.js looks like:
// craco.config.js
module.exports = {
    style: {
      postcss: {
        plugins: [
          require('tailwindcss'),
          require('autoprefixer'),
        ],
      },
    },
  }

Answer: You don't need to install Post css for Tailwind V3.
Try this:

npm uninstall tailwindcss postcss autoprefixer
npm install -D tailwindcss
Comment: Didn't work. Same error.
Comment: Sorry, those didn't work. Please upload your carco.config,js file so I may assist you further.
Comment: Sure, I've updated my question. Please have a look.


How to render the 'actions' section of a form in twig template?

Question: given a form that is built like the following:
public function buildForm(array $form, FormStateInterface $form_state)
{
   $form['#theme'] = 'mymodule_testForm';
   $form['actions']['#type'] = 'actions';
   $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => t('submit'),
      '#button_type' => 'primary',
   );
   return $form;
}

How do I access the submit button in my twig template?
Comment: `{{ form.actions.submit }}` (assuming `'render element' => 'form'` in `hook_theme()`)?
Comment: But don't count to being able to alter anything in Twig. It's too late for that. If the variable in twig is not preprocessed, like attributes, you won't be able to do anything. I have created an issue for this in do.org already but I doubt anything will be done in 8.x branch. So back to good old hook_preprocess_hook.
Answer: Hat tip to Clive who already answered the question as a comment:
{{ form.actions}}

To render the rest of the form, you can do something like {{ form | without('actions') }}
So you whole code will look something like this:
In my_module.module:
/**
 * Implements hook_theme().
 */
function my_module_theme($existing, $type, $theme, $path) {
  $result = [
    'custom_form' => [
      'render element' => 'form',
      'template' => 'custom-form',
    ],
  ];

  return $result;
}

And in custom-form.html.twig:

Form

    {{ form | without('actions') }}

Action

    {{ form.actions }}

For more reading:

Similar Q&A:

https://stackoverflow.com/questions/48997506/how-to-render-specific-form-elements-drupal-8
How to pass a custom Form to a Twig template

Drupal.org documentation on Twig filters in Drupal: https://www.drupal.org/docs/8/theming/twig/filters-modifying-variables-in-twig-templates

Hope that helps!


Having troubles with Amazon Echo (Alexa) and SSML

Question: I'm trying to handle better phonetic pronunciations and pausing with Alexa+Lambda+Javascript. I see from the docs: https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/speech-synthesis-markup-language-ssml-reference that you are able to do so using Speech Synthesis Markup Language. However, when I build and send the Javascript object so Alexa may speak something, I receive error messages.
This is the attribute I'm sending Alexa to speak from the Lambda log files:
{ outputSpeech:  { type: 'SSML', ssml: '<speak>This output speech uses SSML.</speak>' } }

Any ideas of what exactly I'm missing?
Thanks in advance.
Comment: Can you also share the error message?
Answer: Make sure you updated your buildSSMLSpeechletResponse. I added a new function to use with the callback so that I can use the SSML output for the right areas.

function buildSSMLSpeechletResponse(title, output, repromptText, shouldEndSession) {
    return {
        outputSpeech: {
            type: "SSML",
            ssml: output
        },
        card: {
            type: "Simple",
            title: "SessionSpeechlet - " + title,
            content: "SessionSpeechlet - " + output
        },
        reprompt: {
            outputSpeech: {
                type: "SSML",
                text: repromptText
            }
        },
        shouldEndSession: shouldEndSession
    };
}
Answer: you can simply use SSMl tags in your speechOutput variable where you are storing your response. This way also works.


Salvar dados em formato .xlsx com pandas

Question: Boa tarde!
Eu quero salvar em uma arquivo .xlsx o número de loop que meu código está rodando, porém da forma que está, salva apenas o último loop.
import time
import pandas as pd

loop = 0

print('Loop')

writer = pd.ExcelWriter('/home/pi/Área de Trabalho/saidaCamera3.xlsx')

while True:
        loop = loop + 1

        df = pd.DataFrame({'Loop': [loop]})
        df.to_excel(writer, 'Camera RGB', index=False)
        writer.save()
        if loop>=32:
            break

writer.save()

Parece ser meio idiota, porém depois irei juntar com a leitura de meu sensor.
Answer: O problema é que a cada passagem no loop, você está criando um DataFrame novo.
Mude seu código para o seguinte:
import time
import pandas as pd

loop = 0

df = pd.DataFrame()

while True:
    loop = loop + 1
    print('Loop: ', loop)
    df = df.append({'Loop': [loop]}, ignore_index=True)

    if loop >= 32:
        break

print(df.shape)

df.to_excel('/home/pi/Área de Trabalho/saidaCamera3.xlsx', index = False)

Perceba que a inicialização do DataFrame está fora do loop, e que a cada passagem por este, uma nova linha é adicionada.
Ao final do loop, o DataFrame é persistido no arquivo Excel.


React isn't updating child properties in nextjs

Question: I've tried using event listeners, both in the component directly and as an effect and it does the same thing every time. It just passes the props to child on load and then doesn't update them afterwards.
    const [innerWidthProp, setInnerWidthProp] = useState<number>(0);

    useEffect(() => {
        window.onresize = () => {
            setInnerWidthProp(window.innerWidth)
            console.log(innerWidthProp)
            // logs inner width on resize.
        }
    }, [innerWidthProp, setInnerWidthProp])

    return (

            <NavLinks title={'SOLDIER'} scrollValue={innerWidthProp} onLinkClick={onLinkClick}  />

        )
}

And in the child component
console.log(props.scrollValue)
// logs the inner width on load, but doesn't update on resize

I don't understand how the parent props state variables are updating and not the childs...
Update: I feel like this is a nextjs issue as a counter I made, also only updates the parent
Update: I had another parent component which had the function that the use call back was referencing, and had I the state varibles somewhere in the middle of the two components...
This is the code now that it's working
parent.tsx

const Main: NextPage<GithubProps> = ({githubAccountData, githubSubscribe}) => {

    const [innerWidthProp, setInnerWidthProp] = useState<number>();

    const updateWidth = () => setInnerWidthProp(window.innerWidth)
            useEffect(() => {
            window.addEventListener('resize', updateWidth)
            console.log(innerWidthProp)
           updateWidth()
           return () => window.removeEventListener('resize', updateWidth)
            }, [innerWidthProp, setInnerWidthProp])
    //This useEffect updates the inner width value
    //the inner width value is passed to the child components

    const handleLinkClick = (props: number) => {
        console.log(props)
        window.scrollTo(props, 0)
        //this is the call back function used in the child component
        //this scrolls the page to the value defined in the child component
    }
    return (

 ...

        )

firstchild.tsx

const Header: FunctionComponent<LinkProps> = ({ onLinkClick, innerWidthProp }): JSX.Element => {

    return (

            <NavLinks title={'SOLDIER'} scrollValue={0} onLinkClick={onLinkClick} />
            <NavLinks title={'SOLDIER'} scrollValue={innerWidthProp} onLinkClick={onLinkClick} />
            <NavLinks title={'SOLDIER'} scrollValue={(innerWidthProp)*2} onLinkClick={onLinkClick}/>

    );
}

secondchild.tsx

export const NavLinks: FC<NavLinkProps> = ({scrollValue, title, onLinkClick}): JSX.Element => {

    const handleClick = useCallback(() => {
        onLinkClick(scrollValue);
        // scroll values is defined in the parent of this component
        // and this value is a modified version of innerwidth
    }, [onLinkClick])

    return (

...

        )

Answer: I don't see any problem here, at least with code that you have provided. Try using this snippet. When you run it the parent and child component both console.log the value.
import React from 'react';
import {useState, useEffect} from 'react'

const NavLinks = ({scrollValue}) => {
  console.log("Navlinks:", scrollValue)
  return

}

export function App(props) {
      const [innerWidthProp, setInnerWidthProp] = useState(0);

    useEffect(() => {
        window.onresize = () => {
            setInnerWidthProp(window.innerWidth)
            console.log("App:",innerWidthProp)
            // logs inner width on resize.
        }
    }, [innerWidthProp, setInnerWidthProp])

    return (

            <NavLinks title={'SOLDIER'} scrollValue={innerWidthProp} onLinkClick={"onLinkClick"}  />

        )
}

Console:
Navlinks:
0
App:
0
Navlinks:
1101
App:
1101
Navlinks:
1100
App:
1100
Navlinks:
1099
App:
1099
Navlinks:
1098
App:
1098

Answer: You can try this and let me know if it works:
const [innerWidthProp, setInnerWidthProp] = useState<number>(0);

const updateWidth = () => setInnerWidthProp(window.innerWidth)

    useEffect(() => {
       window.addEventListener('resize', updateWidth)
       updateWidth()

       return () => window.removeEventListener('resize', updateWidth)
    }, [])

    return (

            <NavLinks title={'SOLDIER'} scrollValue={innerWidthProp} onLinkClick={onLinkClick}  />

        )
}

Comment: Yeah this works as expected although my components are still bugged. I think ill drop the entire tsx file in case there's something else I missed, Thanks
Comment: Oh, that's weird... I tested it rendering the value on the child component and it succesfully updates on window's resize.
Comment: Btw, where's `onLinkClick` coming from? I can see you are wrapping `handleClick` with `useCallback` and putting `onLinkClick` as a dependency, this means `handleClick` function will not get re-created on re-renders unless `onLinkClick` changes. This could be the root of the problem.
Comment: its called in another parent component higher up -

const handleLinkClick = (props: number) => {
        console.log(props)
        window.scrollTo(props,0)
    }
Comment: OH I need to put the state in the up most component.... omfg -.-


Questions about MNIST samples training multilayer perceptron with the structure 784x2500x2000x1500x1000x500x10

Question: According to the MNIST database, the MLP with the configuration 784 input neurons, 2500, 2000, 1500, 1000, 500 neurons in the hidden layers, and 10 output neurons can be trained with a learning rate of 0.35% (=0.0035). The network trains by using stochastic gradient descent (without (mini-)batches) with backpropagation, and the sigmoid function is used as activation function for every neuron in every layer.

The weights and biases are both initialised randomly between a range of -1 and 1, is this correct?
How many epochs (1 epoch = all samples being trained once) are needed for the 60000 image dataset to get that accuracy close to 99.65% which is claimed by Cireşan, Meier, Gambardella and Schmidhuber (2010) (arXiv)?
My self-built neural network does 100 iterations (100 iterations = training 100 samples) in 20 seconds with this network configuration on a 8 GB RAM computer, using Java. Is this considered as average speed, or is Tensorflow faster, if so how many times?
Answer:
[...] The network trains by using stochastic gradient descent (without
(mini-)batches) with backpropagation, and the sigmoid function is used
as activation function for every neuron in every layer.

You are saying that you want to reproduce the accuracy figure from Ciresan et al (2010), but you are not using the same protocol as the authors, so you have no guarantees to reproduce it. One discrepancy is that they used variable learning rate, you don't.

The weights and biases are both initialised randomly between a range of -1 and 1, is this correct?

There's no such a thing as "correct" initialization, but if you want to reproduce the paper, use what they did i.e. "uniform random distribution in [−0.05,0.05]".

How many epochs (1 epoch = all samples being trained once) are needed for the 60000 image dataset to get that accuracy close to
99.65% which is claimed by Cireşan, Meier, Gambardella and Schmidhuber (2010) (arXiv)?

The paper doesn't say how many epochs did it take. You can always train with a stopping criterion that the training is stopped when it hits the desired accuracy. But, as said above, you are not using exactly the same settings as the authors, so it may train indefinitely.

My self-built neural network does 100 iterations (100 iterations = training 100 samples) in 20 seconds with this network configuration on
a 8 GB RAM computer, using Java. Is this considered as average speed,
or is Tensorflow faster, if so how many times?

There's no such a thing as "average speed". It depends on the implementation, your hardware, the data, etc. If you want to compare it to something, the authors of the paper say:

Networks with up to 12 million weights can successfully be trained by
plain gradient descent to achieve test errors below 1% after 20-30
epochs in less than 2 hours of training.

They had 50,000 images in train set, so it's 50,000 (samples) × 25 (epochs) / 120 (minutes) / 60 (seconds) = 173.61 iterations per second on hardware from 10 years ago. In TensorFlow's documentation, you can find an example of a simple feed-forward network trained on MNIST at speed of around one second per epoch.
Don't re-implement such stuff by hand, use the ready frameworks like PyTorch or TensorFlow. The frameworks are well-tested and optimized. The only two reasons to implement such stuff by yourself is when you are doing this just for fun, as a learning project, or if you already used the frameworks before but they do not work for you for some reason (e.g. you have some esoteric technical requirements, it's a research project that involves something that was not implemented in the frameworks, etc).
Comment: Thank you for your quick reply!!! `without
momentum, but with a variable learning rate that shrinks by a multiplicative constant after each epoch, from 10^−3 down to 10^−6
.` In what function does the learning rate decrease if we take y as learning rate and x as the amount of epochs? And question two: are there any biases used, if so are they being updated? (in that article I haven't seen that word). You are right, in that article they used multi-threading. I am not experienced in that area, so mine will always be slower.
Comment: @Randomuser (1) It sounds like they use a learning rate that decreases in a linear fashion at every step. (2) Biases are always used and updated. (3) The paper says that it took 114 hours to achieve the performance, so with the speed of your implementation it will take many days of non-stop training, so if this is a fun project, it's not worth the carbon footprint.


Best way to add items with properties to my nutritional iOS app (Swift 4)?

Question: I am developing a nutritional app that shows restaurants > food items > nutritional values for these food items. I want to display them in a table view structure. I was thinking of using a database with an API but I am in a time crunch and I am a beginner and figuring out how to use the USDA database which is completely alien to me, so I am going to manually input 200+ food items into the app. What is the best way to do this and how do I do it? I was trying to do a plist dictionary with restaurants (dictionary) > foods(dictionary)> nutritional values (dictionary) but I am not sure if so many dictionaries is the best/ easiest way to do it. I also thought about creating a separate class and creating an instance of the class with each property (name, restaurant, calories) etc but I am a bit lost on how to do that as well
anything helps thank you
Answer: Try making a dashboard application where you can enter the details of the food items that you want to display. For instance, make an app with all the TextFields to enter the data corresponding to a particular item.
Once you confirm the entry, send a request to a Firebase database to store these values.
Now, in your real app, you can use a Firebase extension to request data from this server and populate it in your app as required.


If $H$ is a subgroup of $G$ of index $n$, then $g^{n!} \in H \ \forall g \in G$

Question: Let $G$ be a finite group and $H$ a subgroup of $G$ of index $n$, i.e., $[G:H]=n$. Prove that $$\forall g \in G,\; g^{n!} \in H.$$
This is a question I've had in a past exam for Group Theory and I'm really struggling to come up with a solution.  There were two hints given in the question, namely that $\# G = n \cdot \# H$ (which is just from Lagrange's Theorem), and we were told to recall that $\#S_{n} = n!$.
I've thought about using Cayley's theorem, that every group is isomorphic to a subgroup of $S_{n}$, but can't figure out how to get the desired result.
Comment: For what values of $m$ we have $g^mH=H$?
Comment: See also http://math.stackexchange.com/questions/573050/if-h-is-a-subgroup-of-g-of-finite-index-n-then-under-what-condition-gn.
Answer: Alternatively, one can argue by contradiction.
So suppose there is a $g\in G$ with the property $g^{n!}\notin H$.
Then neither of the elements $g,g^{2},...,g^{n}$ can belong to $H$. This implies that $$H, Hg, Hg^{2},...,Hg^{n}$$ are distinct Right-cosets. But this violates the assumption $[G:H]=n$.
Comment: Brilliant, kudos. This also shows clearly that the results holds with $n!$ replaced by the lcm of $1,2,\dots,n$, which is indeed the exponent of $S_n$.
Answer: Do it in two steps.
First you prove that there is normal subgroup $K$ of $G$ that is contained in $H$, and has index a divisor of $n!$
For this, as in the previous answer, you let $G$ act on the left cosets of $H$ by multiplication, regard this action as a homomorphism $G \to S_{n}$, and consider the kernel $K$.
Then you consider the factor group $G/K$, and use the fact that if a group $L$ has order $m$, then $g^{m} = 1$ for each $g \in L$.
Comment: Sorry, I'm not too confident on the topic of group actions.  I've been told they're homomorphisms that map from the group to the set of permutations of the set (that the group is acting on).  Is this correct?  If so, why do we form a group action from $G$ to $S_{n}$?
Comment: I've just seen that in the question we've defined $[G:H]=n$.
Comment: Yes, that's it. You have the set of $n$ right cosets, say, of $H$ in $G$, and an element $g$ acts as a permutation on this set by $Ha \mapsto H a g$. If you associate to $g \in G$ this permutations, you get a homomorphism $G \to S_{n}$.
Comment: Okay, so the kernel of (what I'm calling) $\varphi$ is going to be the elements of $G$ that map to the identity permutation.  So is this going to be $g \in G$ s.t. $g \in Ha$ for each right coset?  Or should it be more general than that, and should it hold regardless of which coset $g$ is in?
Comment: The kernel is $K = \{ g \in G : H a g = H a\ \text{for all $a \in G$} \} =  \{ g \in G : H a g a^{-1} = H\ \text{for all $a \in G$} \} =  \{ g \in G : a g a^{-1} \in H a\ \text{for all $a \in G$} \} =  \{ g \in G : g \in a^{-1} H a\ \text{for all $a \in G$} \} = \bigcap_{a \in G} a^{-1} H a$. But what's important is that $K$ is normal in $G$, and $G/K$ is isomorphic to a subgroup of $S_{n}$.
Comment: I see.  So then because $K$ is normal we say $G/K$ is isomorphic to a subgroup of $S_{n}$, so it has order dividing $n!$.  Therefore $\forall a \in G, \ (Ka)^{n!} = K \implies \forall a \in G, \ K(a^{n!}) = K \implies \forall a \in G, \ a^{n!} \in K \subseteq H$.  Is that correct?
Comment: That's it, exactly!
Comment: Sorry can I ask one more thing?  I've revisited this today but now can't prove to myself that $K \subseteq H$ holds.  I've tried to let some $g \in K \implies g = aha^{-1}$ for some $a \in G$, but I don't see that this is always in $H$.  Am I missing something?
Comment: Look at the formula I wrote above. $K$ is the intersection of all conjugates of $H$, and $H$ is one of them.
Answer: Hint Consider the left cosets $X=G/H$ and the group action of $G$ on this set.
Since $X$ has $n$ elements, what can you say about the orbit of $g$ under this action?


Rules: Set a data value for a taxonomy term reference on the user profile

Question: I am trying to attach zodiac signs (stored as terms in a vocabulary) to user profiles.
I have a rule with a "Set data field" action that, upon updating a user profile, sets account:field-user-zodiac (a term reference to a vocabulary with 12 terms, one for each sign of the zodiac) to an arbitrary sign (Capricorn) using direct input mode (a select box of all of the terms appears).
However, upon doing so, when I update a user profile I experience a white screen of death.  Disabling the rule makes the site work normally again, so obviously the rule is the problem, but I don't know how to go about fixing it.
Again, I'm trying to use "Set data value" to set a term reference field in a user profile to an arbitrary term.  Any insights about how to set this up in rules?
UPDATE (Feb. 2)
I figured out how to enable PHP error reporting.  The error is shown below.
I'm confused as to why the fatal error is "cannot redeclare getStarSign()", because getStarSign() is a function in my computed field, yet the part of the rule causing the white screen of death is the "set data value" action, which does not refer to the computed field; "set data value" sets the taxonomy reference field.  I know this is the cause because if I delete the "set data value" action the error disappears.  Any ideas?

Fatal error: Cannot redeclare getStarSign() (previously declared in /home/quickstart/websites/omj.dev/sites/all/modules/contrib/computed_field/computed_field.module(465) : eval()'d code:1) in /home/quickstart/websites/omj.dev/sites/all/modules/contrib/computed_field/computed_field.module(465) : eval()'d code on line 22
      Call Stack:
      0.0001 668296 1. {main}() /home/quickstart/websites/omj.dev/index.php:0
      0.1744 48404872 2. menu_execute_active_handler() /home/quickstart/websites/omj.dev/index.php:21
      0.1753 48642216 3. call_user_func_array() /home/quickstart/websites/omj.dev/includes/menu.inc:517
      0.1753 48642832 4. drupal_get_form() /home/quickstart/websites/omj.dev/includes/menu.inc:0
      0.1754 48644232 5. drupal_build_form() /home/quickstart/websites/omj.dev/includes/form.inc:123
      0.2481 51569552 6. drupal_process_form() /home/quickstart/websites/omj.dev/includes/form.inc:366
      0.2766 52599888 7. form_execute_handlers() /home/quickstart/websites/omj.dev/includes/form.inc:846
      0.2766 52607608 8. user_profile_form_submit() /home/quickstart/websites/omj.dev/includes/form.inc:1432
      0.2774 52625928 9. user_save() /home/quickstart/websites/omj.dev/modules/user/user.pages.inc:317
      0.3132 55387344 10. module_invoke_all() /home/quickstart/websites/omj.dev/modules/user/user.module:557
      0.3134 55389880 11. call_user_func_array() /home/quickstart/websites/omj.dev/includes/module.inc:819
      0.3134 55390496 12. rules_entity_update() /home/quickstart/websites/omj.dev/includes/module.inc:0
      0.3134 55392016 13. rules_invoke_event() /home/quickstart/websites/omj.dev/sites/all/modules/contrib/rules/modules/events.inc:77
      0.3209 58050816 14. RulesEventSet->executeByArgs() /home/quickstart/websites/omj.dev/sites/all/modules/contrib/rules/rules.module:777
      0.3351 60502680 15. RulesState->cleanUp() /home/quickstart/websites/omj.dev/sites/all/modules/contrib/rules/includes/rules.plugins.inc:685
      0.3351 60503256 16. RulesState->saveNow() /home/quickstart/websites/omj.dev/sites/all/modules/contrib/rules/includes/rules.state.inc:74
      0.3352 60503808 17. EntityDrupalWrapper->save() /home/quickstart/websites/omj.dev/sites/all/modules/contrib/rules/includes/rules.state.inc:229
      0.3352 60503808 18. entity_save() /home/quickstart/websites/omj.dev/sites/all/modules/contrib/entity/includes/entity.wrapper.inc:807
      0.3352 60503808 19. entity_metadata_user_save() /home/quickstart/websites/omj.dev/sites/all/modules/contrib/entity/entity.module:181
      0.3352 60509520 20. user_save() /home/quickstart/websites/omj.dev/sites/all/modules/contrib/entity/modules/callbacks.inc:707
      0.3363 60525136 21. field_attach_update() /home/quickstart/websites/omj.dev/modules/user/user.module:541
      0.3363 60525272 22. _field_invoke() /home/quickstart/websites/omj.dev/modules/field/field.attach.inc:958
      0.3367 60535912 23. computed_field_field_update() /home/quickstart/websites/omj.dev/modules/field/field.attach.inc:209
      0.3367 60535912 24. _computed_field_compute_value() /home/quickstart/websites/omj.dev/sites/all/modules/contrib/computed_field/computed_field.module:239
Comment: On the white screen of death issue, see http://drupal.org/node/158043
Comment: I trust what you described in your own answer solved your issue (or should I say "prevented it from happening". However **if** that term reference field was multi value field (was it?), **then** the cause of your issue might have been that you should not have used "Add an item to a list" instead of  "set a data value". For more details about that, refer to my answer to [this question](http://drupal.stackexchange.com/a/228927/39516).
Comment: Please can you add the rules export?
Comment: Here is the rules export:    { "rules_zodiac_set_up" : {
    "LABEL" : "Zodiac Set Up",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "user_update" ],
    "DO" : [
      { "data_set" : { "data" : [ "account:field-user-west-zodiac" ], "value" : "22" } }
    ]
  }
}     @WestieUK
Answer: I finally located the cause of this error.  I was using a computed_field which was getting called in such a way that it was being re-declared, causing the error.  Rewriting the function solved the problem.


A good reference to begin Operator Semigroups

Question: I have finished a course in Functional Analysis and am currently taking a course in Operator Theory. I would like to read some Operator semigroups on my own. I'd like to know if there would be a book that I could find (or online notes) that would introduce me to the classical results.
Comment: https://www.amazon.com/Semigroups-Operators-Applications-Differential-Mathematical/dp/0387908455/ref=sr_1_1?ie=UTF8&qid=1484681817&sr=8-1&keywords=pazy
Comment: I like the book by Davies ("One-parameter semigroups")...
Answer: To give you some introductory insights, I'd suggest the texts

What is a semi-group? by Einar Hille, which can be found in the book Studies in Real and Complex Analysis edited by I. Hirschman.
A Heuristic Survey of the Theory and Applications of Semigroups of Operators, which is the Chapter 0 of the book Semigroups of linear operators and applications written by J. Goldstein.

To introduce you the classical results with focus on the applications to (well posedness of) PDE, I'd suggest the book

C$\mathbf{_0}$-Semigroups and Applications by  Ioan I. Vrabie

which is similar (in content and purpose) to the classic Semigroups of Linear Operators and Applications to Partial Differential Equations written by A. Pazy but, in a sense, more complete (the first chapter presents some preliminaries) and easier to read (in my opinion).
If you want an approach without focus on the applications to PDE, I'd suggest the book

One-Parameter Semigroups for Linear Evolution Equations by K. Engel and R. Nagel

which has the shorter version

A Short Course on Operator Semigroups.


Google Universal Analytics not working for eCommerce tracking

Question: I've used the previous version of analytics many times to setup ecommerce tracking, but not getting the new universal analytics version to work.
I have this so far on the receipt page (all the variables populate correctly when I run a test transaction, I just put in placeholder variables for below example), but no pixel is fired it seems for the transaction:

Firing a pageview first worked for me in the previous version of analytics; is this the wrong way to structure this for the Universal analytics snippet?
Answer: The following piece of code is from our test domain which you can compare and it does send the correct data to GA for sure.

If you don't mind spending some bucks then the following module could do the job for you.
For Magento 1
https://www.scommerce-mage.com/magento-google-enhanced-ecommerce-tracking.html
For Magento 2
https://www.scommerce-mage.com/magento2-google-enhanced-ecommerce-tracking.html
Answer: So, with a regular Universal Analytics snippet in the header doing the pageview, this works in the receipt page body:


Erro ao tentar incluir um mapfragment em uma activity

Question: Tenho uma activity que deve subir com o map (GoogleMaps). Mas ao implementar alguns metodos, para que eu possa por exemplo, clicar e adicionar um marcador, ele quebra, com o seguinte erro:

Attempt to invoke virtual method 'void
  com.google.android.gms.maps.MapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)'
  on a null object reference

Como posso resolver esta questão?
Segue código:
package app.app_app.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.net.Uri;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.os.Bundle;
import android.support.v7.widget.ShareActionProvider;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMapOptions;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;

import java.util.ArrayList;
import java.util.List;

import app.app_app.R;
import app.app_app.domain.MapCoo;
import app.app_app.persistence.SaveSharedPreferences;
import app.app_app.util.GPSUtils;

public class MapActivity extends BaseActivity implements NavigationView.OnNavigationItemSelectedListener, OnMapReadyCallback, GoogleMap.OnCameraChangeListener,
        GoogleMap.OnMapClickListener, GoogleMap.OnMyLocationButtonClickListener {

    Intent intent;
    private ShareActionProvider mShareActionProvider;
    public static MainActivity mainActivity;
    public static Boolean isVisible = false;
    private static final String TAG = "MainActivity";
    private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
    SaveSharedPreferences saveSharedPreferences = new SaveSharedPreferences();
    static boolean status = false;

    protected static final String TAG_app = "app";
    private SupportMapFragment mapFragment;
    protected GoogleMap map;
    private LatLng ultimaLocation = null;
    private Acompanhamento acompanhamento = null;
    private PolylineOptions rota = null;
    private LatLng origem;
    private LatLng destino;
    private GPSUtils gpsUtils;
    private GoogleApiClient mGoogleApiClient;

    LocationRequest mLocationRequest;
    LatLng latLng;
    SupportMapFragment mFragment;
    Marker currLocationMarker;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_prevencao);

        //Incluindo a toolbar
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        gpsUtils = GPSUtils.getInstance();

        MapFragment mapFragment = (MapFragment) getFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        GoogleMapOptions options = new GoogleMapOptions();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

/*        if (id == R.id.btn_tracar_rota) {
            intent = new Intent(MainActivity.this,RotaActivity.class);
            startActivity(intent);
            return true;
        }else */if (id == R.id.btn_notificacao){
            intent = new Intent(MapActivity.this,NotificacaoActivity.class);
            startActivity(intent);
        }else if (id == R.id.btn_call){
            String celular = saveSharedPreferences.getKeeperNumber(getContext());
            intent = new Intent(Intent.ACTION_CALL);
            intent.setData(Uri.parse("tel:"+celular));
            startActivity(intent);
        }else if (id == R.id.btn_favoritos){
            Intent intent = new Intent(this, FavoritosActivity.class);
            startActivity(intent);
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction t = fm.beginTransaction();

        if (id == R.id.nav_account) {
            intent = new Intent(MapActivity.this,AlterarContaActivity.class);
            startActivity(intent);
        } if (id == R.id.nav_favoritos) {
            intent = new Intent(MapActivity.this, FavoritosActivity.class);
            startActivity(intent);
        } else if (id == R.id.nav_keeper) {
            intent = new Intent(MapActivity.this,KeeperActivity.class);
            startActivity(intent);
        } else if (id == R.id.nav_prevencao) {
            if (getActivity(this) == this) {
                Toast("Já está na tela de Map");
            }
/*        } else if (id == R.id.nav_prevencao) {
            PrevencaoFragment f = new PrevencaoFragment();
            t.replace(R.id.layoutFrag, f, "PrevencaoFragment");
        } else if (id == R.id.nav_share) {
                // Fetch and store ShareActionProvider
                mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(item);
                Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
                sharingIntent.setType("text/plain");
                String shareBody = "www.app.com.br";
                sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Compartilhe o app!");
                sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
                startActivity(Intent.createChooser(sharingIntent, "Share via"));
                ConfiguracaoFragment f = new ConfiguracaoFragment();*/
        } else if (id == R.id.nav_configuracao) {
            Intent intent = new Intent(this, ConfiguracoesActivity.class);
            startActivity(intent);
        } else if (id == R.id.nav_logout) {
            SaveSharedPreferences.clearLoginPreferences(this);
            intent = new Intent(MapActivity.this,NewLoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);

        }
        t.addToBackStack(null);
        t.commit();

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        }else {
            super.onBackPressed();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        status = false;
    }

    @Override
    public void onStart() {
        super.onStart();
        status = true;
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        gpsUtils.stopLocationUpdates();
        //Cancela os agendamentos do handler
        handler.removeCallbacksAndMessages(null);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        googleMap.setOnCameraChangeListener(this);
        googleMap.setOnMapClickListener(this);
        googleMap.setOnMyLocationButtonClickListener(this);
    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {

    }

    @Override
    public void onMapClick(LatLng latLng) {

    }

    @Override
    public boolean onMyLocationButtonClick() {
        return false;
    }
}

Segue XML:
<?xml version="1.0" encoding="utf-8"?>

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start"
    android:background="@drawable/fundo">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <include
            layout="@layout/app_bar_main"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <android.support.design.widget.CoordinatorLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <fragment
                android:id="@+id/map"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                class="com.google.android.gms.maps.SupportMapFragment" />

            <EditText
                android:id="@+id/rota_edt_quer_cia"
                android:layout_width="250dp"
                android:layout_height="34dp"
                android:layout_alignParentLeft="true"
                android:layout_alignParentTop="true"
                android:layout_marginLeft="18dp"
                android:layout_marginTop="14dp"
                android:hint="@string/edt_Map_rota"
                android:textColor="@android:color/black"
                android:background="@android:color/white"/>

        </android.support.design.widget.CoordinatorLayout>
    </LinearLayout>

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer"/>

</android.support.v4.widget.DrawerLayout>

Answer: No XML está SupportMapFragment e na sua classe está MapFragment.
No lugar de:
MapFragment mapFragment = (MapFragment) getFragmentManager()
                .findFragmentById(R.id.map);

Use:
SupportMapFragment mapFragment = (SupportMapFragment) ...

Veja mais detalhes na documentação.
Comment: realmente n percebi, obrigado!


VMWare ESXi + LetsEncrypt - SSL certificate renewal

Question: With VMWare ESXi (I'm running ESXi 6.7), I'm regularly go through an SSL issue. Chrome & Firefox do not allow self-signed certificated provided by internal VMWare system.
In my case, the only way to access to VMWare Sphere Web Client is to use Safari (on macOS) and allow manually certificate as a trusted certificate.

The point is to declare signed certificate.
As VSphere Client is only for administrator use, I'd rather not paying a ~100$-a-year third-part signed certificate.
Until a few months ago, I used ZeroSSL which is not totally free anymore (blocked after 3 renewals). I was following these instructions
Is there a way to use Let'sEncrypt process to get a valid signed certificate and push it my VMWare Server ?
Comment: As an aside, you can get a one year commercial SSL certificate for less than $4.00 USD.
Comment: Previously, I had bad experience on this → some of SSL certificates discouters have "exoctic" root CA, and my websites went as failure in chrome i.e.
Comment: I have about 100 services behind SSL encryption, 4... makes a lot ;-)
And letsencrypt can be automated easily is most of the cases (web servers)
Answer: 3 main steps for setting up this.
1. Let's Encrypt certificate generation with DNS challenge.
Default challenge process with let's encrypt is HTTP-01 / acme-challenge file generation.
It's not convenient with ESXi use.
I switch to DNS-01 Challenge which is compliant with my DNS provider.
I use certbot tool.
You can install it with
apt install python3-pip
pip install certbot

I found a dedicated python certbot tool extension for challenge automation.
See OVH specific extension and complete tutorial
Specific tool is pip install certbot-dns-ovh

The final command is certbot itself :
certbot certonly -d mydomain.com

Specific version for OVH is certbot certonly -d mydomain.com --dns-ovh --dns-ovh-credentials ~/.ovh-api
You'll have to create .ovh-api file with these instructions

Thanks to his, I've got quickly a list of .pem files
2. Certificate format transform
Certificate are directly generated in .pem format so you do not need to change format. You just have to rename files
cp fullchain.pem rui.crt
cp privkey.pem rui.key

Be carefull, do not use cert.pem but fullchain.pem.
cert.pem is not compliant with ESXi

3. Renew certificate on VMWare esxi

On ESXi host, backup your old certificate
cd /etc/vmware/ssl/
mv rui.crt rui.crt.`date +%Y%m%d-%H%M%S`.bak
mv rui.key rui.key.`date +%Y%m%d-%H%M%S`.bak

Actually, you should backup these 2 files on your workstation.
scp myhost:/etc/vmware/ssl/*.bak ./
If ssl certificates are not compliant with vmware host client requirements, web ui will not start again... particulary boring and stressfull to fix  ...
If you need to rollback and reset ssl, you can use /sbin/generate-certificates && reboot command

From your workstation:
Replace your certificate
scp rui.key rui.crt myhost:/etc/vmware/ssl/

On ESXi host, restart the host
reboot
Comment: Aha, [here](https://docs.vmware.com/en/VMware-vSphere/6.7/com.vmware.vsphere.security.doc/GUID-A261E6D8-03E4-48ED-ADB6-473C2DAAB7AD.html) is the answer: "Alternatively, you can put the host into maintenance mode, install the new certificate, use the Direct Console User Interface (DCUI) to restart the management agents, and set the host to exit maintenance mode." Not quite as disruptive as a reboot, but still a real pain.
Comment: Is there really no less disruptive way to start using the new certificates than to reboot the host?
Comment: @MichaelHampton You don't need to reboot nor to put your host in maintenance. Simply restart the relevant services... e.g. hostd and vpxa.

The downside of the DNS challenge is that you only perform it once hosts are already added to vCenter, so initial trust still needs to be verified using thumbprints.
Answer: Restarting the Management agents in ESXi (1003490) https://kb.vmware.com/s/article/1003490
using DCUI or SSH shell


Question about homological algebra

Question: Let $G$ be a finite group of order $m$ and $A$ a $G$-module of order $n$ with $(n, m) = 1$. From homological algebra, we know that $mH^{1}(G, A) = 0$ (in fact the 1 can be replaced by any integer $r \geq 1$). Does the $(n, m) = 1$ imply that $H^{1}(G, A) = 0$?
Answer: The answer is yes. Recall that an Abelian group $A$ is uniquely divisible by $m$ for some $m\in\mathbb{N}$ if for each $x\in A$ there is a unique $y\in A$ such that $x=my$. The following holds:

If $G$ is a finite group of order $m$ and $A$ is a $G$-module uniquely
  divisible by $m$ then $H^k(G,A)$ is trivial for all $k$.

In your example, since $(m,n)=1$, the map $x\mapsto mx$ is an injective endomorphism of $A$, so it must be an automorphism, which means that $A$ is uniquely divisible by $m$.
As a side note, you do not need to assume $(m,n)=1$ to get $mH^k(G,A)=0$ for any $k$.
Answer: As mentioned (entirely correctly) already, the answer is yes.  Here is a slightly different take on this:
If $A = A[n]$ is an $n$-torsion $G$-module, then even at the cocycle level one has
$Z^k(G,A) = Z^k(G,A)[n]$ for all $k \geq 0$, hence certainly upon passage to cohomology one has $H^k(G,A) = H^k(G,A)[n]$ for all $k \geq 0$.  Thus for a finite group $G$ and an $n$-torsion $G$-module $A$, for all $k > 0$ the groups $H^k(G,A)$ are $\# G$-torsion and $n$-torsion, hence $\operatorname{gcd}(\#G,n)$-torsion.

Question about homological algebra


What's the cross ratio of 4 planes?

Question: For example, $H_1 : 3X_0 + 2X_3 = 0\\H_2 : −X_0 − X_1 + X_2 = 0\\H_3 : 4X_0 + X_1 −
X_2 + 2X_3 = 0\\H_4 : 5X_0 + 2X_1 − 2X_2 + 2X_3 = 0$
Comment: What book are you using?
Comment: No book, it's an excercise our teacher told us to do.
Answer: Assuming they have a common line, find the normals of the planes and treat them as if they are a pencil of lines.  Compute the cross ratio of those lines (using the usual ratio of sines of angles).  Or, for fun, compute a ratio of cross products.

What's the cross ratio of 4 planes?


Como validar CPF no lado do cliente com script?

Question: Estou trabalhando com uma validação de CPF em meu controller, porém necessito validar quando o cliente sair do input do CPF e então retornar uma mensagem avisando quando o CPF estiver incorreto, através de um alert ou algo parecido.
Tentei fazer algo do tipo, mas recebo uma mensagem de erro no console do Chrome:

Uncaught ReferenceError: validarCPF is not definedRelatar:363 onblur

Input HTML:
<form id="meuform">
    <input type="text" data-id="NrCpf" disabled name="NrCpf" id="NrCpf" class="form-control" onblur="javascript: validarCPF(this.value);" maxlength="14">
</form>

Alguém já precisou fazer algo do tipo, ou teria alguma ideia de como me ajudar?
Comment: Este link mostra como validar um CPF enquanto a pessoa esta digitando-o http://www.tutsup.com/2014/11/17/como-validar-cpf-e-cnpj-com-javascript-ou-jquery/ . Acho que é isto que procura
Comment: O script foi declarado *antes* do `input`?
Comment: @Eduardo eu fiz o download do projeto no site, mas o mesmo está com um erro na linha **   if ( valida_cpf_cnpj( cpf_cnpj ) ) {** e não está funcionando aqui.
Comment: @AndréRibeiro não, eu apenas inverti a ordem do post. O script está em aquivo JS separado, eu apenas juntei para postar.
Answer: Seu código não funciona por muitos motivos, entre eles, quando você copiou o source vieram algumas tags como entities, as tags do for vieram assim "&lt" "&gt", tem um "j" voador servindo de Jquery(document.., se você quer uma alternativa continue lendo.
Gerador e validador de CPF
Para validar basta usar essa linha:
CPF.valida("123.456.789-00");

A lib já filtra pontos e traços.
Veja no Github
Exemplo de utilização

/*!
* Gerador e Validador de CPF v1.0.0
* https://github.com/tiagoporto/gerador-validador-cpf
* Copyright (c) 2014-2015 Tiago Porto (http://www.tiagoporto.com)
* Released under the MIT license
*/
function CPF(){"user_strict";function r(r){for(var t=null,n=0;9>n;++n)t+=r.toString().charAt(n)*(10-n);var i=t%11;return i=2>i?0:11-i}function t(r){for(var t=null,n=0;10>n;++n)t+=r.toString().charAt(n)*(11-n);var i=t%11;return i=2>i?0:11-i}var n="CPF Inválido",i="CPF Válido";this.gera=function(){for(var n="",i=0;9>i;++i)n+=Math.floor(9*Math.random())+"";var o=r(n),a=n+"-"+o+t(n+""+o);return a},this.valida=function(o){for(var a=o.replace(/\D/g,""),u=a.substring(0,9),f=a.substring(9,11),v=0;10>v;v++)if(""+u+f==""+v+v+v+v+v+v+v+v+v+v+v)return n;var c=r(u),e=t(u+""+c);return f.toString()===c.toString()+e.toString()?i:n}}

   var CPF = new CPF();
   document.write(CPF.valida("123.456.789-00"));

   document.write("
 Utilizando o proprio gerador da lib

");
   for(var i =0;i<40;i++) {
      var temp_cpf = CPF.gera();
      document.write(temp_cpf+" = "+CPF.valida(temp_cpf)+"
");
   }

$("#input").keypress(function(){
    $("#resposta").html(CPF.valida($(this).val()));
});

$("#input").blur(function(){
     $("#resposta").html(CPF.valida($(this).val()));
});

<input type="text" id="input" />

Comment: Obrigado, era exatamente isso.
Comment: Eu verifiquei este, porém necessito de uma para validação em tempo real, ou seja, assim que o usuário sair do input.
Comment: execute o script novamente, coloquei um evento monitorando a tecla pressionada e a saída do focus
Answer: Adaptei o script da resposta do @AlbertBitencourt.
Removendo a parte que considera 10 e 11 como 0, pois aparentemente essa validação não existe.

function cpf(cpf){
    cpf = cpf.replace(/\D/g, '');
    if(cpf.toString().length != 11 || /^(\d)\1{10}$/.test(cpf)) return false;
    var result = true;
    [9,10].forEach(function(j){
        var soma = 0, r;
        cpf.split(/(?=)/).splice(0,j).forEach(function(e, i){
            soma += parseInt(e) * ((j+2)-(i+1));
        });
        r = soma % 11;
        r = (r <2)?0:11-r;
        if(r != cpf.substring(j, j+1)) result = false;
    });
    return result;
}

console.log('11111111111', cpf('11111111111'));
console.log('82312321312', cpf('82312321312'));
console.log('825.566.405-02', cpf('825.566.405-02'));
console.log('875.189.681-85', cpf('875.189.681-85'));
console.log('875.189.681-86', cpf('875.189.681-86'));
console.log('640.422.216-70', cpf('640.422.216-70'));

Links Relacionados
Como validar e calcular o dígito de controle de um CPF
Fórmula para gerar CPF's Válidos
Answer: Montei uma pseudo classe em JavaScript para gerar e validar números de CPF, seguindo a regra dos dígitos verificadores. O código fonte pode ser encontrado no GitHub:

https://github.com/tome-vilela/geracpf

Segue um exemplo de uso:
var n = new CPF().generate();

if (new CPF().validate(n)) {
  alert('sucesso!');
}

Caso precise criar números de CPF para teste, deixei disponível o mesmo algoritmo neste site estático:

Gerador de CPF

Vale ressaltar que os números gerados são válidos, mas não são reais, a não ser que ocorra uma colisão de um número aleatório com um número real.
Para saber se um número de CPF é real, só consultando a Receita Federal mesmo, mas será necessário informar também a data de nascimento do portador do CPF:

www.receita.fazenda.gov.br/aplicacoes/atcta/cpf/ConsultaPublica.asp

Finalmente, havendo necessidade de validação automática de um grande número de CPFs recomendo o seguinte Web Service:

www.soawebservices.com.br

Até o momento foi o mais barato que encontrei, suporta HTTPS e tem disponibilidade razoável (de vez em quando ele sofre de problemas de "timeout").
Answer: Eu fiz uma em javascript usando o algoritmo da receita federal.
O método recebe uma string sem pontos e traços e retorna um bool se é valido ou não.
function VerificaCPF(strCpf) {

var soma;
var resto;
soma = 0;
if (strCpf == "00000000000") {
    return false;
}

for (i = 1; i <= 9; i++) {
    soma = soma + parseInt(strCpf.substring(i - 1, i)) * (11 - i);
}

resto = soma % 11;

if (resto == 10 || resto == 11 || resto < 2) {
    resto = 0;
} else {
    resto = 11 - resto;
}

if (resto != parseInt(strCpf.substring(9, 10))) {
    return false;
}

soma = 0;

for (i = 1; i <= 10; i++) {
    soma = soma + parseInt(strCpf.substring(i - 1, i)) * (12 - i);
}
resto = soma % 11;

if (resto == 10 || resto == 11 || resto < 2) {
    resto = 0;
} else {
    resto = 11 - resto;
}

if (resto != parseInt(strCpf.substring(10, 11))) {
    return false;
}

return true;
}

Comment: Diversos valores fornecidos pelo site https://www.geradordecpf.org/ não passam no seu algoritmo :(


How do I pre / post process aggregated css or js files?

Question: I want to declare the character encoding of our aggregated css files - how would I be able to pre or post process the aggregated css files in Drupal 8?
E.g. injecting @charset "UTF-8"; on top of all css files.
Answer: Using dependency injection we are able to inject a modified Asset Dumper, which can contain custom code.
Add to a custom module / or create a new module:
mymodule/mymodule.services.yml
services:
  asset.css.dumper:
    class: Drupal\mymodule\Asset\Utf8CssAssetDumper
  asset.css.collection_optimizer:
      class: Drupal\Core\Asset\CssCollectionOptimizer
      arguments: [ '@asset.css.collection_grouper', '@asset.css.optimizer', '@asset.css.dumper', '@state' ]

mymodule/src/Asset/Utf8CssAssetDumper.php
<?php
namespace Drupal\mymodule\Asset;

/**
 * Dumps a CSS asset and injects a utf-8 encoding string at beginning.
 */
class Utf8CssAssetDumper extends \Drupal\Core\Asset\AssetDumper {

  /**
   * {@inheritdoc}
   *
   * Injects utf-8 encoding statement at start of data string.
   */
  public function dump($data, $file_extension) {
    if ($file_extension == 'css') {
      // Don't override existing charsets.
      if (FALSE === strpos($data,'@charset ')) {
        // Charset string not found prepend.
        $data = "@charset \"UTF-8\";\n" . $data;
      }
    }
    return parent::dump($data, $file_extension);
  }
}

A short note on this: since this kicks in for all aggregated css files you might want to add additional checks to existing encodings etc.. If you have everything encoded the same way (which is very much suggestible) then this shouldn't cause weird side effects.
This approach also works for javascript (js) files:
services:
  asset.js.dumper
  asset.js.collection_optimizer


Este programa não funciona. Porém se eu der o scanf da variável ch antes do scanf das variáveis x e y, ele funciona. Alguem saberia me explicar porque

Question: #include <stdio.h>
#include <stdlib.h>

int main()
{
    char ch;
    int  x, y;

    printf("Digite o valor de x e y:");
    scanf("%d %d", &x, &y);

    printf("Digite o valor de ch:");
    ch = getchar();

    switch (ch)
    {
        case '+':
        {
            int c = x + y;
            printf("Soma: %d\n", c);
            break;
        }
        case '-':
        {
            int c = x - y;
            printf("Subtracao: %d\n", c);
            break;
        }
        case '*':
        {
            int c = x * y;
            printf("Multiplicacao: %d\n", c);
            break;
        }
        case '/':
        {
            int c = x / y;
            printf("Divisao: %d\n", c);
            break;
        }
    }
}

Comment: Leia o manual. `scanf()` retorna um `int`. Teste. É ingênuo seguir sem testar. O problema com o programa é que você precisa consumir o  `\n` que encerrou o primeiro `scanf()` e como não fez isso ele é usado para a segunda chamada a `scanf()`
Comment: Muito Obrigado arfneto, não entendi muito. Só sei que quando se coloca o "\n" depois do scanf, ele funciona, embora o printf que pede o valor de ch so aparece depois. Vou olhar o manual sim. É pq estou começando o C agora e sozinho...kkkkk
Comment: Se não aparecer um '\n` o `scanf()` não retorna. Depois de ler os dois números chame `fgetc(stdin)` para ler esse '\n' ANTES de tentar ler uma letrinha chamando `getchar()`
Comment: Só pra deixar claro (não sei se foi essa a confusão que vc fez), o `\n` que estamos falando é apenas uma notação: **é uma forma de representar um único caractere**, que é a quebra de linha (quando vc digita ENTER, este caractere é enviado juntamente com os dados que vc digitou antes do ENTER - ou seja, se digitar "ab" ENTER, são enviados 3 caracteres: o `a`, o `b` e a quebra de linha - que chamamos simplesmente de `\n`). Isso não quer dizer que vc tem que digitar explicitamente o caractere ``\`` seguido do caractere `n`.
Comment: De qualquer forma, o que acontece é que o `scanf` não consome o `\n`, ele só lê os números. Depois, o `getchar` consome o `\n`, por isso ele nem espera vc digitar nada. Já tem bastante coisa no site sobre isso, por exemplo [aqui](/q/111697/112052) e [aqui](/search?q=%5Bc%5D+limpar+buffer), e tem [esse link também](https://c-faq.com/stdio/scanfprobs.html), pra se aprofundar no assunto.
Answer: Compare com algo assim:
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int x = 0;
    int y = 0;

    printf("Digite os valores de x e y: ");
    int res = scanf("%d %d", &x, &y);
    if (res != 2) return - 1; // nao leu, cancela
    fgetc(stdin);

    printf("Digite o operador (+ - * /): ");
    int ch = getchar();

    switch (ch)
    {
        case '+':
        {
            int c = x + y;
            printf("Soma: %d\n", c);
            break;
        }
        case '-':
        {
            int c = x - y;
            printf("Subtracao: %d\n", c);
            break;
        }
        case '*':
        {
            int c = x * y;
            printf("Multiplicacao: %d\n", c);
            break;
        }
        case '/':
        {
            int c = x / y;
            printf("Divisao: %d\n", c);
            break;
        }
    };  // switch()
    return 0;
}

Você precisa consumir o '\n' que encerrou a chamada a scanf() ou ele vai servir para alimentar o getchar() e nunca vai ler o operador...
Como está aprendendo se acostume a mostrar os valores que imagina ter lido.
Se tivesse mostrado o valor de ch em seu programa depois do getchar() teria visto que o valor era 10, o valor do \n
Comment: Bom dia arfneto. Eu nao entendo o que vc quer dizer quando fala em consumir o '\n'          E no seu programa postado vc não utiizou o '\n' no scanf. Tô mais perdido que cego em tiroteiro...kkk.
Comment: :) Você está lendo ao contrário. O `scanf()` não utiliza um `\n`. O `\n` finaliza a execução de `scanf()` e a função retorna com o total de coisas de conseguiu ler. Leu o programa que te mostrei? E se você não ler esse `\n` de alguma forma ele vai ser enviado pro `getchar()` na linha seguinte. Foi o que eu te mostrei e expliquei.
Comment: Resolvido o problema. O meu programa do jeito que está, basta digitar o comando fflush(stdin);  depois do scanf das variáveis x e y, e não precisa fazer mais nada que ele executa...KKKKKK
Comment: Memso assim, obrigado pela atenççao
Comment: Eu te expliquei o que está errado. Te mostrei o exemplo. Te expliquei para mostrar o valor lido pelo `getchar()`  e ver que é 10. E te expliquei que `fflush()` nem está definida para a entrada, apenas para a saída. Um ou outro compilador pode aceitar, mas não é assim que funciona. continua errado. O `scanf()` só  vai retornar depois de alguém teclar ENTER.  E aí ele pode retornar por exemplo `0` se você teclar apenas `x` na entrada. Rode o exemplo
Comment: Vixe. Vou me ligar nisso aí. Valeu e mais uma vez obrigado..


Decision making based on epistemic uncertainty

Question: You have a yellow button and a blue button. The yellow button saves 10 lives. The blue button saves 1 life. However, both buttons have an independent, unknown probability of working. Your objective is to save as many lives as you can. Which button do you hit?
Is the decision arbitrary as the probability of the buttons working is completely unknown or is it mathematically logical to choose one over the other?
Answer: From a mathematical viewpoint, the decision is arbitrary. However, most people would probably be more comfortable with the yellow button.
The probability of success $X_i$ for each button $i=Y,B$ is unknown. If you assume that $X_i$ is i.i.d., for instance, the yellow button is preferable. OF course, this or other similar assumptions, while consistent with the given information, are arbitrary.
Another approach to argue for the yellow button is to assume that the best criterion is minimise the maximum regret. This is allegedly more compelling, but it offers you no guarantee that you saving as many lives as possible (the criterion says only that, in the worst case, you could not have saved more).
Comment: Great, thanks for the answer!


If $x$ is positive, then why does $\frac{1}{\sqrt{x+1} + \sqrt{x}} = \sqrt{x+1} - \sqrt{x}$?

Question: Given that $x$ is positive, $\frac{1}{\sqrt{x+1} + \sqrt{x}} = \sqrt{x+1} - \sqrt{x}$
I've been trying to convert the left side of the equation to the right side:
$$ \frac{1}{\sqrt{x+1} + \sqrt{x}}$$
But then how can I flip this round to be what I have on the right side?
I know that $\frac{1}{\sqrt{x}} = x^{-\frac{1}{2}}$, so I would think that this would give me
$$(x+1)^{-1/2} + x^{-1/2}$$
Which I thought would then convert to
$$-\sqrt{x+1} + (-\sqrt{x}) $$
so I'm not sure how the first part $\sqrt{x+1}$ got to be positive
Comment: This and the question you asked recently are not "Linear Algebra". That is a much different subject.
Answer: Rationalize the denominator:
\begin{align}
  \frac{1}{\sqrt{x+1} + \sqrt{x}} \cdot \frac{\sqrt{x+1}-\sqrt{x}}{\sqrt{x+1} - \sqrt{x}} &= \frac{\sqrt{x+1}-\sqrt{x}}{\underbrace{\left(\sqrt{x+1} + \sqrt{x}\right) \cdot \left(\sqrt{x+1} - \sqrt{x}\right)}_{\color{red}{\text{FOIL}}}} \\[0.3cm]
  &= \cdots
\end{align}
Some notes:
If you want to show that two things are equal to each other, it's better to manipulate only one of them than it is to start by saying they're equal to each other and then manipulating both sides to verify, etc.
Your idea of converting to $(x+1)^{-1/2} + x^{-1/2}$ won't work because, in general, $\displaystyle \frac{1}{a+b} \ne \frac{1}{a} + \frac{1}{b}$.
Comment: How does multiplying the denominator by sqrt(x+1) - sqrt(x) make the denominator 1?
Comment: @maudulus, by FOILing.  I updated the answer to show a little more without quite giving it away.
Comment: the golden rule: $(a+b)\cdot(a-b)=a^2-b^2$.
Answer: Clear the denominator to get:
$$1 = (\sqrt{x+1} + \sqrt{x})(\sqrt{x+1}-\sqrt{x}) = (x+1)-x.$$
As Tilper points out, this is not a correct proof per se, but once you see this, you can reverse the ordering of your logic and write a proper proof.
In this case it would be more proper to write:
$$1 = (x+1)-x = (\sqrt{x+1} + \sqrt{x})(\sqrt{x+1}-\sqrt{x}). $$
Therefore since $\sqrt{x+1} + \sqrt{x} \neq 0$,
$$\frac{1}{\sqrt{x+1} + \sqrt{x}} = \sqrt{x+1} - \sqrt{x}.$$
Answer: One can basically use
$$
\frac{1}{a+b}=\frac{1}{a+b}\frac{a-b}{a-b}=\frac{a-b}{a^2-b^2}
$$
valid for $a-b\ne0$. If $a=\sqrt{x+1}$ and $b=\sqrt{x}$, you have
$$
a^2-b^2=(x+1)-x=1
$$
so
$$
\frac{1}{\sqrt{x+1}+\sqrt{x}}=
\frac{1}{a+b}=\frac{a-b}{a^2-b^2}=
\frac{\sqrt{x+1}-\sqrt{x}}{1}=
\sqrt{x+1}-\sqrt{x}
$$
With some practice, you'll do the steps automatically:
$$
\frac{1}{\sqrt{x+1}+\sqrt{x}}=
\frac{1}{\sqrt{x+1}+\sqrt{x}}\,
\frac{\sqrt{x+1}-\sqrt{x}}{\sqrt{x+1}-\sqrt{x}}=
\frac{\sqrt{x+1}-\sqrt{x}}{(\sqrt{x+1}\,)^2-(\sqrt{x})^2}
$$
Answer: You need to use a little trick with fractions. Recall that for any number $n$ that is not zero, $\frac{n}n=1$, and 1 times any number is itself.
So start with the left side: $\sqrt{1+x}-\sqrt{x}$. If we choose our $n$ to be $\sqrt{1+x}+\sqrt{x}$, then:
$$\sqrt{1+x}-\sqrt{x}=\frac{\sqrt{1+x}-\sqrt{x}}1\cdot\frac{\sqrt{1+x}+\sqrt{x}}{\sqrt{1+x}+\sqrt{x}}$$
Then "FOIL" the top:
$$\frac{\sqrt{1+x}^2+\sqrt{x}\sqrt{1+x}-\sqrt{x}\sqrt{1+x}-\sqrt{x}^2}{\sqrt{1+x}+\sqrt{x}}=\frac{1+x-x}{\sqrt{1+x}+\sqrt{X}}=\frac1{\sqrt{1+x}+\sqrt{x}}$$


Can't Convert sql connection string to byte[]

Question: I am trying to convert an sqlstring that contains normal characters and '_' , ';', and '='
and when i try to do this:
Byte[] byt = Convert.FromBase64String(value);

I get this error message
An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll

Additional information: The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.

Additonal:
-I am using this to encrypt an sqlstring
-my decrypt which uses this same function works fine but when trying to convert back for encryption it fails
Answer: This is exactly your problem
Byte[] byt = Convert.FromBase64String(value);

The input is not a valid Base-64 string

You are trying to convert from a base64 string which you aren't supplying
byte[] byt = Encoding.ASCII.GetBytes(value);

Convert back to a string
string value = Encoding.ASCII.GetString(byt);


Find all integers $n>1$ with the property that for each positive divisor $d$ of $n$, we also have that: $(d+2) \mid(n+2) $.

Question: Find all integers $n>1$ with the property that for each positive divisor $d$ of $n$, we also have that:
$$
(d+2) \mid(n+2)
$$
So far, I've tried to get as much info about it as possible, but I don't know how to proceed.
My attempt so far:
First, we know that $n$ is of the form of the form $3K+1$. Also, if you take the smallest prime divisor of $n$, call it $p$, we know that:
$$
n=pd \Rightarrow d+2 \mid pd+2 \Rightarrow d+2 \mid 2p-2
$$
Hence $p \leq d \leq 2p-4$.
Comment: If you're writing down your effort, then it'll be better visible if you edit the post and do that rather than do it in the comments. Thanks.
Comment: What have you tried?
Answer: You've made a good start, with this showing how to complete the solution by checking the multiplier. First, with $d = 1$ always being a divisor, we require that $1 + 2 \mid n + 2 \;\to\; n \equiv 1 \pmod{3} \;\to\; n = 3k + 1$, as you've already stated. Since the only other factor of primes is the prime itself, and $d = n$ always satisfies $d + 2 \mid n + 2$, this means that all primes $n$ where
$$n \equiv 1 \pmod{3}\tag{1} \label{eq1A}$$
are solutions. Otherwise, similar to what you did, for any composite $n$, have $p$ be its smallest prime factor. Then $d = \frac{n}{p}$ is also a factor of $n$ so, for some positive integer multiplier $m$, we have
$$\begin{equation}\begin{aligned}
n + 2 & = m\left(\frac{n}{p} + 2\right) \\
n + 2 & = \frac{mn}{p} + 2m \\
pn + 2p & = mn + 2pm \\
(p - m)n & = 2p(m - 1)
\end{aligned}\end{equation}\tag{2}\label{eq2A}$$
Note from the second line above that $m \lt p$ since, otherwise, the RHS is greater than the LHS. Thus, if $p = 2$, then $m \lt 2 \;\to\; m = 1$, but then the last line becomes the incorrect $n = 0$. Otherwise, with $p \gt 2$, then $2 \nmid n$. The last line then shows that $2 \mid p - m$. However, we then get that $n \le p(m - 1) \le p(p - 2)$, but since $n \ge p^2$ (as $n$ is composite and $p$ is the smallest prime factor), this is also not possible.
This proves the only solutions are those given in \eqref{eq1A}, i.e., $n$ which are primes of the form $3k + 1$.


Files.write() is not working properly, while BufferedWriter seems to be fine

Question: I had a simple exercise to do:

read a file
filter out all lines beginning with "//"
remove additional spaces
write it back to a file

And I came up with following code:
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.stream.Collectors;

import static java.nio.file.Files.lines;
import static java.nio.file.Files.newBufferedWriter;
import static java.nio.file.Files.write;
import static java.nio.file.Paths.get;
import static java.util.stream.Collectors.toList;

public class FileParser {
    public static final String PATH = "test.txt";

    public static void main(String... args) {
        try {
            List<String> strings = lines(get(PATH)).filter(line -> !line.startsWith("//")).map(line -> line.trim().replaceAll(" +", " ")).collect(toList());
//            write(get(PATH), strings, StandardOpenOption.WRITE);
            BufferedWriter writer = newBufferedWriter(get(PATH));
            for (String string : strings) {
                writer.write(string);
                writer.newLine();
            }
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Unfortunately that commented piece of code for some reason doesn't work, while the one below it works just fine. That strings list always contains only proper result too. For file:
a
//b
c

The expected result should be:
a
c

While the actual result is:
a
c

c

What is the source of this problem?
It works when writing to a different file that the one we read from it.
Comment: Using static imports the way you did just makes the code harder to read.  Don't do it.
Comment: You may also want to use `StandardOpenOption.TRUNCATE_EXISTING`
Answer: Here's the Javadoc for StandardOpenOptions. This is what it says about WRITE option:

Open for write access.

Although it's not too informative, it opens the file and starts writing from the beginning. It overwrites the existing content and keep remaining text as is. If you want to remove the existing content then you need to use TRUNCATE_EXISTING option:

If the file already exists and it is opened for WRITE access, then its length is truncated to 0. This option is ignored if the file is opened only for READ access.

You need to make sure the file is not open (in any editor or in program) before using this option.
Here is the test program that works fine with your file:
public static void main(String[] args) throws IOException {
    List<String> strings = Files.lines(Paths.get("<somepath>/Test.txt")).filter(line -> !line.startsWith("//")).map(line -> line.trim().replaceAll(" +", " ")).collect(Collectors.toList());
    System.out.println(strings);
    Files.write(Paths.get("<somepath>/Test.txt"), strings, StandardOpenOption.TRUNCATE_EXISTING);
}

Comment: It does, I have added the test program that works with sample file provided in question.


Tail set on $\mathcal{F}$ non-principal a $\kappa$-complete ultrafilter on $\kappa$

Question: I'm reading some contents on set-theory for my own interest, and I stumbled upon some questions I cannot solve yet.

Let $\mathcal{F}$ be a $\kappa$-complete non-principal ultrafilter on $\kappa$. Then for every $\alpha < \kappa$, we define the tail set to be $C_\alpha = \{\beta < \kappa, \ \alpha < \beta\}$. Show that for every $\alpha$, $C_\alpha$ belongs to $\mathcal{F}$.

My intuitions : suppose there exist $\alpha$ such that $C_\alpha \notin \mathcal{F}$. Then because this is an ultrafilter on $\kappa$, we have $\left(\kappa-C_\alpha\right) \in \mathcal{F}$. I could go two directions here :

Using the fact that $\mathcal{F}$ is $\kappa$-complete, I need to to build some less-than-$\kappa$ intersection, contradicting the fact that $\mathcal{F}$ is non-principal. But I don't think that's the way to go.
Or using the fact that $\mathcal{F}$ is non-principal, I should try to build a partition of $\kappa$, $\{X_\lambda, \lambda< \kappa\}$, from this $C_\alpha$, where all $X_\lambda \notin \mathcal{F}$, contradicting the fact that $\mathcal{F}$ is $\kappa$-complete.

Any suggestion?
Thanks
Edit
Let us first consider the case $\kappa = \omega$. $C_\alpha = \{ \beta < \omega : \alpha < \beta\}$. Suppose there exist $\alpha$ such that $C_\alpha \notin \mathcal{F}$. Note that $C_{\alpha+1} \subset C_\alpha$. Therefore $C_\alpha \notin \mathcal{U}$ implies $C_{\alpha+1} \notin \mathcal{F}$. Because $\mathcal{F}$ is an ultrafilter, then $\omega-C_{\alpha+1}, \omega-C_{\alpha} \in \mathcal{F}$.  By $\omega$-completeness of $\mathcal{F}$ (or direct definition of filters) :
$$ \{\alpha+1\} = \left(\omega-C_{\alpha+1}\right)\cap\left(\omega-C_{\alpha}\right) \in \mathcal{F}$$
$\mathcal{F}$ contains a singleton, contradicting the fact that $\mathcal{F}$ is non-principal.
Not sure to see how this extend to any $\kappa$. I can see that if $C_\alpha \notin \mathcal{F}$, then for any $\lambda > \alpha$, $C_\lambda \notin \mathcal{F}$. I'm not comfortable yet working with infinite cardinal, this is my first intrusion in this world!
Comment: Do this for $\kappa=\omega$ and you will see what to do in general. The case $\kappa=\omega$ is simple; and any ultrafilter is $\omega$-complete, so the completeness requirement does not add anything in this case.
Comment: I edited the question with your suggestion. not sure how to follow.
Answer: This is a possible solution:
It is assumed, towards a contradiction, that there is some $\alpha<\kappa$ such that $C_\alpha\not\in\mathcal{F}$. Since $\mathcal{F}$ is an ultrafilter, this means that $\kappa-C_\alpha\in\mathcal{F} $ or, what is the same, $\alpha\in\mathcal{F}$. $\mathcal{F}$ is also non-principal, then, $\bigcap\mathcal{F}\not\in\mathcal{F}$, so, it is properly contained in every element of $\mathcal{F}$ and, in particular, $\bigcap\mathcal{F}\subsetneq\alpha$. This means that there is some $\beta\in\alpha$ such that $\beta\not\in\bigcap\mathcal{F}$. Therefore, there must be at least one $X\in\mathcal{F} $ such that $\beta\not\in X$ (in that way, $\beta$ disappears from $\bigcap\mathcal{F} $). It is clear that $\alpha\cap X\in\mathcal{F}$ but $\beta\not\in \alpha\cap X$. Again, since $\mathcal{F}$ is non-principal, $\bigcap\mathcal{F}\subsetneq \alpha\cap X$. In this way, it is possible to define the following sets:

If $\alpha'=0$, $X_0=\alpha\cap X$.

If $\alpha'=\beta+1$, $X_{\alpha'}=X_\beta\cap Z$, where $Z\in\mathcal{F}$ and such that, for some $\gamma\in X_\beta-\bigcap\mathcal{F}$, $\gamma\not\in Z$ (such $Z$ exists for the same reason as $X$ exists).

If $\alpha'$ is a limit ordinal, define $W_{\alpha'}=\bigcap_{\delta<\alpha'}X_\delta$. Since $\mathcal{F}$ is $\kappa$-complete and $|\alpha'|<\kappa$ (this is because, as will be shown later, values of $\alpha'$ greater than $\alpha$ are not necessary), $W_{\alpha'}\in\mathcal{F} $. And $\mathcal{F}$ is non-principal, so, $\bigcap\mathcal{F}\subsetneq W_{\alpha'}$. Thus, it is possible to do the same as before: for some $\gamma\in W_{\alpha'}-\bigcap\mathcal{F}$, take some $Z\in\mathcal{F}$ such that $\gamma\not\in Z$ and then, define $X_{\alpha'}=W_{\alpha'}\cap Z\in\mathcal{F}$.

It is easy to see that, at each step, the ordinal $\gamma$ is an element of $\alpha$, because $X_{\alpha'}\subset \alpha$. Then, for some $\varepsilon\leq\alpha$, the set $X_{\varepsilon}$ will be empty: $X_{\alpha'}\subset\alpha$ and at each step at least one different element of $\alpha$ has been removed from the previous $X_{\alpha'}$'s. But $|\alpha|<\kappa$ and the filter is $\kappa$-complete, so, $X_{\varepsilon}\in\mathcal{F}$, then, $\varnothing=X_{\varepsilon}\in\mathcal{F}$, which is absurd. And this proves that every tail set belongs to $\mathcal{F} $.
Answer: Some basic properties:
(1). If $C\subset \kappa$  and if $\forall A\in\mathcal F\,(C\cap A\ne\emptyset)$ then $C\in\mathcal F.$ Proof: $C\in \mathcal G=\{(C\cap A)\cup B: A\in \mathcal F\land B\subseteq \kappa\}$ and $\mathcal G$ is a filter on $\kappa$ with $\mathcal G\supseteq\mathcal F,$ so $\mathcal G=\mathcal F$ (by maximality of $\mathcal F)
.$
(2). If $C\subset \kappa$ and $C\not\in\mathcal F$ then $C\cap A=\emptyset$ for some $A\in\mathcal F.$ This is immediate  from (1).
(3). If $C\subset \kappa$ then $(C\in\mathcal F)\lor (\kappa\setminus C\in\mathcal F).$ Proof: By(2), if $C\not\in\mathcal F,$ there exists $A\in\mathcal F$ with $A\subset\kappa\setminus C,$ and we have $(\kappa\setminus C\supseteq A\in\mathcal F\implies \kappa\setminus C\in\mathcal F).$
(4). If $\beta\in\kappa$ then $\{\beta\}\not\in \mathcal F$ because $\mathcal F$ is non-principal.
Suppose $\emptyset\ne\alpha\in\kappa.$ By (4), no member of $D_{\alpha}=\{\{\beta\}:\beta\in\alpha\}$ belongs to $\mathcal F.$ So by this, and (3), $\mathcal F\supset E_{\alpha}=\{\kappa\setminus C: C\in D_{\alpha}\}\ne\emptyset.$
Now $\mathcal F$ is $\kappa$-closed, and therefore $C_{\alpha}=\cap E_{\alpha}\in\mathcal F.$
And for the case $\alpha=\emptyset,$ we have $C_{\alpha}=\kappa\in\mathcal F$ because $\mathcal F$ is a filter on $\kappa.$


python different length for same unicode

Question: I found something really weird about unicode, in my understanding, if I u"" + "string", the type will be unicode, but why are their length different?
print len(u''+'New York\u200b')
14
print type(u''+'New York\u200b')
<type 'unicode'>
print len(u'New York\u200b')
9
print type(u'New York\u200b')
<type 'unicode'>

I also tried to get rid of \u200b, which I think it is unicode
text = u'New York\u200b'
print text.encode('ascii', errors='ignore')
New York
text = u''+'New York\u200b'
print text.encode('ascii', errors='ignore')
New York\u200b

Also got different result, I am really confused!
btw, I am using python 2.7, is it the time to change to 3.3?? Thanks in advance!!
Comment: in `u''+'New York\u200b'`, `'New York\u200b'` is not unicode, therefore, the \u200b is ignored. This is inconsistent with your second result, though.
Answer: >>> (u''+'New York\u200b').encode('utf-8')
'New York\\u200b'

As you can see, since 'New York\u200b' is not a unicode string, the \u escape doesn't have any special meaning and it is interpreted literally, i.e. as the sequence of ASCII characters \ u 2 0 0 b, hence the string has length 14. The u'' only converts the string to unicode, but it does not cause a re-interpretation of the contents. Putting the u before the literal makes python interpret it as an escape, hence as a single character, hence the string is length 9.
In your second example:

text = u''+'New York\u200b'
print text.encode('ascii', errors='ignore')
New York\u200b

Here the .encode does not modify the characters in the string, it only converts from unicode to str.
It's probably clearer if you print the contents of the two strings
>>> print(u'New York\u200b')  # note: \u200b interpreted as unicode character
New York
>>> print(b'New York\u200b'.decode('ascii'))
New York\u200b

Or if you prefer to see an actual unicode representation try with code point 9731:
>>> print(u'New York\u2603')
New York☃
>>> print(b'New York\u2603'.decode('ascii'))
New York\u2603

Comment: Thanks so much! So u'' only convert whatever in the quote from str to unicode, but not the str it is appending to, and make the type to unicode for the whole thing?
Comment: @amstree Yes. When you concatenate two strings, python does *not* interpret the escapes. The escapes are interpreted *only* when creating the string *literals*. Concatenation operations treat all characters the same. If you want to interpret the contents of a string you should use the `unicode-escape` encoding. For example: `b'\u2603'.decode('unicode-escape')` is `u'\u2603'`(or `'☃'`) while `b'\u2603'.decode('ascii')` is the string `u'\\u2603'`. The latter is a one-character string, the former is a 6 character string made of the characters ```\``` `u` `2` `6` `0` `3`.
Answer: 'New York\u200b' is a non-unicode string of length 14.
(You append it to u'' string, but it itself is not unicode yet.)
u'New York\u200b' is a unicode string of length 9.
Comment: This is a restatement of the question, not an answer.


Skype auto link

Question: I know how to add a link field in Drupal for Skype (skype:username?chat), but I dind't find any answer about automatically convert it into a Skype link.
Let's say users fill their profiles and in a link field write "foreigner"; this link should be automatically converted into foreigner when shown.
How can I achieve this task?
I'm using Drupal 7.
Answer: The module I would use is the Skype Status module. Despite the name, it shows a link to allow users to chat or call another user on Skype.

Retrieves Skype status information via Skype's public presence service for users to display in their profile and also provides a block for site-wide usage (available only in D7!).

What you need to do is:

Install and enable the Skype Status module
Add a user profile where users can enter their Skype ID
Go to admin/config/people/skype_status

Select the field used for the Skype ID
Change the action performed when the button is clicked
Select the button style

Once the users enter their Skype ID, their user profile will show a button to chat/call them, which shows also their status on Skype.

For the status to be visible, users need to select "Shows my status on the web" for their Skype account from the Skype application.
Comment: Ok, I'll try that module. Thank you very much! I'll tweak the images that comes with the module, to create what I want to look like.

Skype auto link


Ruby on Rails, Devise: Force user to re-enter password for the specific pages

Question: I'm developing an app using Rails 4 and Devise for user's authentication. It's intended be used on the computers of our clients' storefront by their customers, and a user should always logged-in with each store's user account.
However, since there are some pages that we don't want customers to see, like <code>/admin</code>, we've decided that users have to re-enter password (only password, not both username and password) for the first time when visiting the specific pages even if they have already logged in.
How do you force user to re-enter password for the specific pages?
Comment: Define a re-authentication method in `ApplicationController` and use `before_filter` to run it for specific actions. If `session[:reauthenticated_at]` is recently modified, do nothing, otherwise redirect the user to reauthentication controller that will ask for password, verify with Devise (`current_user.password_digest && current_user.authenticate(params[:password])`) and set `session[:reauthenticated_at]` to `Time.now`
Comment: Thank you for the detailed instructions!!
Answer: {I am doing a similar app which is intended to support group activities.  So the leader logs in on each computer and the participants simply pick their user name.  to protect the leaders configuration pages I did the following
<code>    before_action :re_authenticate,  only: [:admin_functions]
    private
    def re_authenticate
       authenticate_or_request_with_http_basic('Administration') { |username, password|
          username==current_user.username && current_user.valid_password?(password)
        }
   end
</code>
works well.  The user has to re-authenticate to access the admin pages, so the computers that they've login to for the class, don't have access without a second login.


How to set correct Inline SVG Circle coordinates

Question: I can make an inline SVG circle like this:

 <svg height="100" width="100">
      <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
    </svg>

However, I'm struggling to understand the cx and cy and height and width properties.
What I want to achieve is a 15x15px circle that has no free space around it, but I can't seem to get it right.

<svg height="15" width="15"><circle cx="0" cy="0" r="9" stroke="black" stroke-width="1" fill="#c0c0c0" /></svg>
This one only shows the bottom right corner
<svg height="15" width="15"><circle cx="7.5" cy="7.5" r="9" stroke="black" stroke-width="1" fill="#c0c0c0" /></svg> This one cuts the circle to a square

What is the correct way to achieve what I want? You can try for yourself here: https://www.w3schools.com/graphics/tryit.asp?filename=trysvg_circle
Answer: Let's make the SVG canvas borders visible for clarity.
To do this, write a CSS style in the header of the SVG fil
style="border:1px solid"

<svg height="100" width="100" style="border:1px solid">
  <circle id="circ" cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
</svg>

The next step is to define the parameters width, height, x, y for the bounding rectangle of the circle using the JS getBBox() method

<svg height="100" width="100" viewBox="0 0 100 100" style="border:1px solid">
  <circle id="circ" cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
</svg>

You can see that the width of the rectangle is 80px padding from the beginning of the SVG canvas 10px, total size is 10 + 80 + 10 = 100px
If you want there to be no white space around the svg element, you need to remove these margins and add space to fit a 3px circle stroke

<svg height="84" width="84" viewBox="0 0 84 84" style="border:1px solid">
  <circle id="circ" cx="42" cy="42" r="40" stroke="black" stroke-width="3" fill="red" />
</svg>

The border around the SVG canvas can be removed as it was used to visually debug positioning
Answer: In the first case the root element has a height and width of 15 so you can see a portion of the x axis from 0 to 15 and the same for the y axis. A circle centred at the origin will therefore only have the bottom right corner visible as that's the only part of the circle within the root element canvas.
As to the second circle 7.5 - 9 (the radius) - 0.5 (1/2 the stroke width) < 0 and 7.5 + 9 + 0.5 > 15 so the circle is simply bigger than the outer SVG element canvas.


Different regression models in clusters, same variance structure

Question: I have data that can be clustered so that each cluster has its own set of both observations and variables. I want to fit a linear model on each cluster, but i want the clusters to share the same variance structure (and thus estimate parameters of the variance function on all data). Can it be done in standard R package like nlme/lme4?
Answer: As long as you have the same dependent and independent variables measured on all individuals, regardless of cluster membership, then you can use lmer to model your data. However, you state that

each cluster has its own set of both observations and variables.

Does that mean you have a unique set of variables that you measured on cluster A and then another unique but different set of variables you measured on cluster B? If so, then those unique variables cannot be used in the lmer model. For example, imagine that your clusters were schools. If you measured school type as a categorical variable (primary/secondary) for every school in your sample, then it could be included in the model. But if for some schools you measured school type and others you only got the age range of students, then neither of those predictors could be used in your model.
Any cluster-specific variables you wish to include in the model must be measured the same in all clusters.
Edit: The multilevel model allows you to model both the intercept (mean of the dependent variable in a group) and slope (association between a independent and dependent variable) uniquely for each group. Again, as long as you have the same variables measured on all groups (binary, categorical, nominal, etc.).
If using maximum likelihood (e.g., lmer), then there is a limit to how many of the slopes you can model as varying across clusters, but with a Bayesian approach you could potentially model all slopes as varying.
The multilevel model equation, separated by level, makes this obvious. Here $X$ represents a level 1 variable (units within clusters) and $W$ represents a level 2 (cluster-specific) variable:
$y_{ij}$ = $\beta0_j$ + $\beta1_jX_{ij}$ + $\beta2X{ij}...$ + $e_{ij}$
$\beta0_j$ (cluster intercept) =  $\gamma_{00}$ + $\gamma_{01}W_j$ + $u_{0j}$
$\beta1_j$ (cluster slope) = $\gamma_{10}$ + $\gamma_{11}W_j$ + $u_{1j}$
The intercept variance ($\sigma^2_{u0j}$) and slope variance ($\sigma^2_{u1j}$) are shared across clusters, and indicate how much clusters vary around the fixed effect parameter estimates of $\beta0_j$ and $\beta1_j$. These can be estimated using Empirical Bayes prediction if you are interested in working with them further.
Comment: The variables are binary, it's then natural to treat separately groups that have nothing in common (zeros). How to fit a model separately in each cluster in lmer with a common variance function?
Comment: Thanks for the edit. So basically, it has to be done via random effects?
Comment: Yes, in the random effects modeling framework, that is how you do it. If you want to switch to a "fixed effects" framework, also called "no pooling," then move to `lm` in R and enter dummy variables for groups and interact those dummies with each of the variables you want to vary by group. That will give you a ton of coefficients that will be difficult to interpret, but tends to be preferred by econometricians.


Efeito âncora em um componente carregado dinamicamente no Angular

Question: Olá. Utilizo a versão 8.1.3 do Angular no meu projeto e estou tendo uns problemas para criar um efeito de âncora no card de produto que é carregado dinamicamente na tela. Tentei utilizando o velho html com href apontando para o ID do produto, mas sem sucesso. Tentei também uma ou outra biblioteca pronta para fazer utilizar de outras maneiras o scrollTo() mas também sem sucesso. Alguém já fez algo parecido ou  tem ideia de como fazer isso em um SPA?
<app-card-produto *ngFor="let p of e.produtos"[produto]="p"">
</app-card-produto>

Esse é o card que possuo na minha tela de catálogo. O comportamento que preciso é entrar na tela de detalhe do produto, mas que ao voltar, a página role até o card que possua o ID (ou outro identificador que seja necessário) o qual acessei por último. A parte boa disso é que ao voltar da tela de detalhe, já tenho a consulta da API pronta, ou seja, os cards só precisam ser renderizados, já tenho toda a lista de produtos salva no IndexedDB.
Estou fugindo totalmente sobre usar jquery, creio que deve haver uma solução para isso sem precisar dele, mas em um caso extremo posso me render quanto a isso.
Answer: Consegui resolver o problema, necessitando agora apenas de ajustes para deixar 100%.
No ngOnInit da tela de catálogo, adicionei o seguinte:
window.addEventListener("scroll", this.scroll, true);

Isto adiciona a assinatura no evento do scroll, executando a função scroll (this.scroll) a cada alteração no valor do mesmo.
A função ficou assim:
scroll = (event: any): void => {
    this.scrollNumber = event.srcElement.scrollTop;
    // console.log(event);
    // console.log("posição " + this.scrollNumber);
};

Como o meu comportamento de acessar a tela de detalhe do produto era disparado pelo método dentro do card, passei o valor do scrollNumber salvo na função para o card por parâmetro.
<app-card-produto *ngFor="let p of e.produtos" [produto]="p"
    [scrollPosition]="scrollNumber">
</app-card-produto>

No método que redireciona para a tela de detalhe passando todos parâmetros irrelevantes aqui, eu salvo o valor do scroll na SessionStorage da seguinte maneira:
let scroll = this.scrollPosition;
sessionStorage.setItem("scrollPosition", JSON.stringify(scroll));

Feito isso, ao voltar para a tela de catálogo, eu crio um método para fazer a leitura dessa variável na sessão e setar o valor dela ao scroll da página. No ngOnInit eu chamo o método this.recoverScroll();. E no método eu tenho o seguinte:
recoverScroll() {
    let scrollSaved = JSON.parse(sessionStorage.getItem("scrollPosition"));
    setTimeout(() => {
        document.getElementsByClassName(
            "ng-scroll-viewport"
        )[0].scrollTop = scrollSaved;
    }, 10);

    //reset scroll
    sessionStorage.setItem("scrollPosition", JSON.stringify(0));
}

Para garantir que o acesso por nenhuma outra rota diferente da DetalhePage -> CatálogoPage acabe rolando para um produto que não faz sentido no contexto, ao fim do método eu zero a variável da sessão.
Conclusão: talvez não seja uma das melhores práticas setar o valor usando o 'ng-scroll-viewport', mas não consegui utilizando nenhuma outra forma que encontrei pelos fóruns. Só preciso agora adicionar uma animação para deixar o scroll suave. Já vi que nesse caso não será possível através do CSS, mas assim que eu resolver atualizo a resposta.
Comecei há pouco a trabalhar com programação e menos ainda com Angular, então com certeza deve haver uma maneira mais otimizada de fazer isso, mas espero de qualquer forma ter ajudado!