Can a finite group act freely (as homeomorphisms) on $\mathbb R^n$

Question: I am asking if whether or not a finite group acts freely (as homeomorphisms) on $\mathbb R^n$.
To answer in the negative, it suffices to show: for any homeomorphism $f$ such that $f^d=\text{id}_{\mathbb R^n}$, then $f$ has a fixed point.
I am looking for a complete self-contained answer.
Answer: Any continuous map, $f: \mathbb R^n \rightarrow \mathbb R^n$, such that $f^n = \text{ id}$ for any natural number $n$ must have a fixed point. The proof is not entirely trivial and there are two ways to do it: either using Smith theory or using algebraic topology (see Bredon, Geometry and Topology, for instance where a scheme for such a proof is laid out). In general, if a group acts freely and properly discontinuously on $\mathbb R^n$, it cannot have torsion. This is also the reason that classifying spaces of finite groups are infinite dimensional. For example, the classifying space of $Z/2$ is $R\mathbb  P^\infty$.
Comment: That "also the reason that classifying spaces of finite groups are infinite dimensional" doesn't seem to hold water. There's no reason that the universal cover of such a group needs to look like $\mathbb{R}^n$.
Comment: Thanks for your answer. I fixed a small font issue in your answer: italicized text can be marked with single asterisks.
Comment: I am actually more interested in the "Smith Theory"(actually the other proof was what I have in mind), but I can't find it anywhere. Could you supply some references?
Answer: This is an elaboration of the answer by user44441. Note that none of these proofs is elementary, meaning both use material going beyond what is typically covered in a graduate topology class, although the proof using cohomological dimension is much simpler, you just need to know sheaf cohomology and some basic material of cohomology of groups.

Via Smith Theory. Let $G$ be a finite nontrivial group of homeomorphisms of $R^n$. Then the action of $G$ extends continuously to its action on $S^n$, the 1-point compactification of $R^n$. Let $C< G$ be a nontrivial cyclic subgroup of $G$, it has order $k>1$. Let $p$ be a prime divisor of $k$. Then $C$ contains a subgroup $H$ of order $p$, isomorphic to ${\mathbb Z}/p$, cyclic group of order $p$. According to the Smith Theory, see Theorem 7.11 in

G.Bredon, "Introduction to Compact Transformation Groups", Elsevier, 1972.
the fixed point set $F$ of $H$ is a Chech cohomology sphere over $p$ of some dimension $r\in [-1, n]$. In other words, the Chech cohomology groups $H^i(F, {\mathbb Z}/p)$ are isomorphic to that of the sphere $S^r$, where $(-1)$-dimensional sphere is the empty set. In order to use this result, you do not need to know what Chech cohomology is (just for the record, it is the sheaf cohomology with respect to the constant sheaf $\underline{{\mathbb Z}/p}$ on $F$), as in our situation, if $H$ acts freely on $R^n$, the set $F$ is the singleton $\{\infty\}$ and its Chech cohomology is the same as any cohomology you are are likely familiar with (singular/cellular/simplicial/cubical). The cohomology of the singleton (with ${\mathbb Z}/p$ coefficients) is zero in all degrees except degree zero, and $H^0(F, {\mathbb Z}/p)\cong  {\mathbb Z}/p$. But no sphere (empty or not) can have such cohomology groups:
Again, you do not need to know what Chech cohomology is since for topological manifolds it is isomorphic to the cellular/singular/... cohomology. Hence, a free nontrivial finite group action on $R^n$ cannot exist.

Via group cohomology. If $G\times R^n\to R^n$ is a free action of a finite group, the projection $R^n\to X=R^n/G$ is a covering map. Hence, the space $X$ is $K(G,1)$. Therefore, $H^*(X, {\mathcal F})\cong H^*(G, M)$ for any $ZG$-module $M$, where ${\mathcal F}$ is the sheaf on $X$ associated with the module $M$. (To construct this sheaf, take the locally trivial fiber bundle $E\to X$ associated with the $ZG$-module $M$ regarded as a set acted upon by $G$, and consider the sheaf of locally constant local sections of $E\to X$.)

Now the proof hinges upon two facts:
a. For every nontrivial finite group $G$ there is a $ZG$-module $M$ and an infinite sequence $k_i\to \infty$ such that
$$
H^{k_i}(G, M)\ne 0.
$$
You can find this in Ken Brown's book "Cohomology of Groups".
In our setting, you only need to know this for finite cyclic groups $G$. In this situation, instead of reading Brown's book you can read his freely available lecture notes here, Exercise 1.5: You take $M=ZG$.
b. If $X$ is a, say, metrizable, topological space of covering dimension $\le n$, then for any sheaf ${\mathcal F}$ on $X$, the cohomology groups $H^k(X, {\mathcal F})=0$ for all $k>n$. Once you get through the definitions, this is actually a "soft" fact, since the covering dimension assumption gives you a cofinal sequence of coverings of $X$ whose nerves are of dimension $\le n$ and, hence, the cochain groups defined using these covering vanish (in degrees $>n$), which implies vanishing of cohomology groups. Assuming that you are familiar with simplicial cohomology, this proof is the same as of the fact that for an $n$-dimensional simplicial complex $X$, its simplicial cohomology vanish in degrees $>n$. Since $R^n$ has covering dimension $\le n$ (you only need to know that the covering dimension is $\le n$, which is proven by constructing an explicit cofinal sequence of covers ${\mathcal U}$), the space $X$ covered by $R^n$ also has dimension $\le n$, simply by projecting ${\mathcal U}$'s from $R^n$ to $X$.
Now, adding (a) and (b), you conclude that $H^k(R^n/G, {\mathcal F})=0$ for all $k>n$ and all sheaves ${\mathcal F}$ (from (b)) while
$H^{k_i}(R^n/G, {\mathcal F})\ne 0$ for some sequence $k_i\to \infty$ (from (a)) and for some sheaf ${\mathcal F}$. This is a contradiction.
Comment: @Anupam: This is simply false, but examples are very nontrivial.
Comment: Does either of your ideas solve the more general problem as to any homeomorphism f of R^n of finite order has a fixed point? If the action of  is free, then we are done. But it need always be free (unless the order is prime....)
Answer: If $G$ acts freely and continuously on $\mathbb{R}^n$ then the quotient map $\mathbb{R}^n \to \mathbb{R}^n/G=X$ is a covering map of degree $n=|G|$. Hence we have for the Euler characteristic (see https://en.wikipedia.org/wiki/Euler_characteristic#Covering_spaces),
$$  \chi(X) \cdot  n=\chi(\mathbb{R}^n)=1.$$
 Since the Euler characterstic is an integer, this implies that $G$ is trivial.
Comment: You have to be careful with this argument: In order to apply the product formula $n\cdot \chi(X)=\chi(Y)$, where $Y\to X$ is a degree $n$ covering map, one usually assumes that $\chi(Y)$ is defined (see e.g. Spanier, p. 481), but it is unclear why this is the case in your setting since your $X$ is noncompact.
Comment: @MoisheKohan: Please correct me, but I think we can salvage this proof, by compactifying $\mathbb{R}^n$ with a single point $\infty$. By extending the action on $\widehat{\mathbb{R}^n}:=\mathbb{R}^n\cup\{\infty\}$ with $g \bullet \infty := \infty$ we get a ramified covering and the argument basically still goes through (we would get $n \chi(X)=n-1$).
Comment: @ctst: Feel free to post a new answer, but make sure you justify the analogue of the Riemann-Hurwitz formula that you use in this setting. (It is easy in the case of simplicial group actions but seems a bit of a pain in general: In particular, I think you will have to resort to sheaf cohomology arguments.)


Filtering List in React

Question: I am creating a basic blog in react using Flux + React Router + Firebase. I am having trouble trying to get a single blog post to render. When I click on the link to a single post, I try to filter out all of the other posts from a list of all posts and display only a single post from my firebase database.
I attempt to do this by matching the key of the firebase entry with the url params like so if (this.props.routeParams.key===key) . I really do not know what I have to do to make this happen. Any suggestions are welcome.
Below is Blogger.jsx, the page where I allow a user to create a blog post and then beneath the blog post, I display a list of the titles all blog posts.
import AltContainer from 'alt-container';
import React from 'react';
import { Link } from 'react-router';
import List from './List.jsx'
import Firebase from 'firebase'
import BlogStore from '../stores/BlogStore'
import BlogActions from '../actions/BlogActions';

const rootURL = 'https://incandescent-fire-6143.firebaseio.com/';

export default class Blogger extends React.Component {
  constructor(props) {
    super(props);
    BlogStore.getState();
    BlogStore.mountFirebase();
    {console.log(this.props.location.query)}

    };

  componentDidMount() {
    BlogStore.listen((state) => {
      this.setState(state)
    })
    this.firebaseRef = new Firebase(rootURL + 'items/');
  }

  componentWillMount() {
    BlogStore.unlisten((state) => {
      this.setState(state)
    })
  }

  renderList = (key) => {
      return (
      <Link to={`blogshow/${key}`}> <List key={key} blog={this.state.blog[key]} /> </Link>
      )
    }

  handleInputChange = () => {

    BlogStore.setState({
      title: this.refs.title.value,
      text: this.refs.text.value});
  }

  handleClick = () => {

    BlogStore.handleClick();
  }

  render() {
    return (

                Create a New Blog Post

Blog Title

          <input
          ref="title"
          value={BlogStore.state.title}
          onChange = {this.handleInputChange}
          type="text"
          className="form-control"/>

Blog Entry

          <textarea
          ref="text"
          value={BlogStore.state.text}
          onChange = {this.handleInputChange}
          type="text"
          className="form-control"/>

          <button onClick={this.handleClick}
          className="btn btn-default" type="button">
            Publish Blog Post
          </button>

        {/*<List blog={this.state.blog} />*/}

        {Object.keys(BlogStore.state.blog)
       .map(this.renderList)}

    );
  }

}

When a user clicks on a link to a single blog post, they should be transported to a page which shows only that single blog post. I have called this component BlogShow. I can't get BlogShow to render because I keep on getting the error

invariant.js?4599:45 Uncaught Invariant Violation: BlogShow.render(): A
  valid React element (or null) must be returned. You may have returned
  undefined, an array or some other invalid object.

This is BlogShow.jsx:
import AltContainer from 'alt-container';
import React from 'react';
import { Link } from 'react-router';
import Blogger from './Blogger'
import List from './List'
const rootURL = 'https://incandescent-fire-6143.firebaseio.com/';

import BlogStore from '../stores/BlogStore'
import BlogActions from '../actions/BlogActions';

export default class BlogShow extends React.Component {
  constructor(props) {
    super(props);
    {console.log(this.props.routeParams.key)}
    this.filterList = this.filterList.bind(this);

}

filterList(key) {
  if (this.props.routeParams.key===key) {
    return (<List key={key} blog={BlogStore.state.blog[key]} />)
  }
}

  render() {

 {Object.keys(BlogStore.state.blog).map(this.filterList)}

  }

}

Comment: You should use [`.filter()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) and not `.map()`. Otherwise they will be set to `undefined` instead of being removed from the array.
Comment: How would I do this? Can you please provide an example of what this would look like?
Comment: I changed it to this and still now luck:

              {Object.keys(BlogStore.state.blog).filter(this.filterList)}
Answer: You are getting that error because your Component BlogShow is not returning anything.
render() {

 {Object.keys(BlogStore.state.blog).map(this.filterList)}

}

Should be:
render() {
    return
 {Object.keys(BlogStore.state.blog).map(this.filterList)}

}

Comment: Thanks @4castle. Your answer is also integrated into my solution.
Answer: I'm not familiar with React.js at all, but I am familiar with pure JS arrays. To remove elements from an array, you should use .filter(), and then afterwards you can map the items.
Something like this:
filterList(key) {
  return this.props.routeParams.key === key; // true if the item should stay in the list
}

mapList(key) {
  return <List key={key} blog={BlogStore.state.blog[key]} />;
}

render() {
  return
 {Object.keys(BlogStore.state.blog).filter(this.filterList).map(this.mapList)}
;
}

Comment: I don't know if React.js precompiles JS, but I think it's incorrect syntax to have `filterList` sitting there on its own. I think it should be `function filterList(key)` and then it should be called like `filterList` instead of `this.filterList`. I could be wrong. Someone edit if I'm not.
Comment: Thank you @4castle. This gets me one step closer. I still recieve the same error but at least I understand the pure JavsScript behind what I am trying to do a little bit better.
Comment: @4castle the error was caused by the return state, you don't even need the filters there.
Comment: @QoP Yes, it was. But if they want to filter, this is how it's done.
Comment: @4castle that's not, if you return a null React is not going to render anything, so it's totally fine.

Filtering List in React


Anomlay Detection using Clustering (K-Means)

Question: I have a big data (100k + records) set that I have divided into two clusters using KMeans.
I also have an array with the cluster centers and I can easily compute the squared distance of each data point to the cluster center.
How can I use this distance to identify the possible outliers? What should I use as a threshold so I can compare that to the distance and properly identify possible outliers?
Answer: Firstly note, that the result of Kmeans with random initialization is not robust (Different resulting cluster centers for each run).
Further the choice of the parameter k further influences your outlier detection and potentially deserves a discussion.
Relevant further material to read on the subject would be:
How to understand the drawbacks of K-means
How to decide on the correct number of clusters?
Assuming that you already informed yourself about both problems and that your current two clusters are exactly what you want, we can now arbitrarily define outliers.
After computing the distance of each datapoint to its cluster center, you can use the x - percentile distance as a threshold. The choice of x depends on the problem you are working on such as the importance of outlier detection. If false negatives are problematic, you better choose a lower value such as x = 90%. Yet if false positives are problematic, you will choose a higher value such as x = 99%.
That beeing said, you might want to have a look into the DBSCAN algorithm which combines outlier detection and clustering nicely and does not require you to predefine the number of clusters:
https://en.wikipedia.org/wiki/DBSCAN


Twig template breaks when adding blocks

Question: Here's the issue:
I have a custom content type for the contact page. Twig template: page--node--9.html.twig. When I add blocks to this template, e.g. {{ page.contact-first }}, it breaks. How can I display blocks on it?
Answer: The solution was simple: the naming of the regions need to use underscores, not dashes.
In theme.info.yml
regions:
  contact_first: 'Contact (First column)'

In the twig template:
{{ page.contact_first }}

Twig template breaks when adding blocks


Scale custom UIView size w/o AutoLayout effects

Question: Question
How can a UIView be created with a user-defined size and then scaled up/down to fit as a subview of a UIViewController?
Use-case
I am developing an application with a primary focus on showing a custom UIView on an external monitor attached to the iOS device. The custom view should be created to natively fit the external monitor. Let's say the external display has a resolution of 1920x1080. The UIView would be created to fit that size and then auto layout would do it's thing. - great!
Typically, the application user cannot actually see the external monitor, so another important part of the application is to provide a representation of the external monitor on the iOS device. Of course, these small window is not going to be the same resolution as the external display and simply creating another view and sticking it on the internal display is not going produce the same results because of AutoLayout.
Goal
I'd like to know how to create another custom view instance programmatically at the same dimensions as the external display (so the layout is identical) and then scale that view up/down to fill a subview on the internal display. Again, it is important that the preview window on the internal display is identical to what is being shown on the external display. I understand there may be some scaling artifacts - that is totally OK.
Application Example
The application in question can be viewed at liveevent.software. My question is in reference to the the external display and the preview of the external display as viewed on the iPad screen. Of course, we have this working already, but we are adding more features and need the local preview to be exactly the same as the external to the operator knows if a message is too long etc...
Important Notes
The UIView being scaled does not contain any gesture recognizers or other items requiring user interaction. Just a few UILabels.
The Issue
The current "working" solution is to create create two instances of the custom view and have them adapt according to auto-layout. While this produces a rough estimation of what is being displayed externally, it is not exact. For example, text may break a line on the iOS preview window but not on the actually external display (because it is larger dimensions).
Comment: Please, show us a *specific* issue, preferably with code. Not some "proof-of-concept" document discussing how an iOS app should look on an external monitor. Can it be done? Maybe. But you've shown no code! I actually decided to click on the link provided - how is your question different than "show me how to do this"? Of course, you have this working already.... then please, what's the issue? And yes, be SPECIFIC.
Comment: Are you able to get the size of the external monitor. If so I can give you a way to start calculating the size of everything to scale proportionally
Comment: @agibson007 Yes, the dimensions of the external monitor (window) are known and I'd like to use a default of 1280x720 if no external monitor is connected.
Comment: @dfd I have updated to explain the iissue in detail. Any code examples I show are going to be too far off course and definitely incorrect. They would distract from the question.
Answer: Depending on how "real time" you need this to be, maybe you could take snapshots of the external UIView? This would result in an UIImage, which you can assign to an UIImageView on the internal display. The image dimensions can be set to whatever you want, and the UIImageView would take care of the scaling.
There are many good answers on how to take a snapshot of a view, for example : this one.
Answer: Instead of creating another instance of the view and using resources to update both accordingly to user actions I would create a snapshot of the view at any change, by using snapshotView method. In terms of performances the snapshotView is very efficient and returns a view object whose content is not editable. This means that you can scale it as you wish to have an exact mirror of your currentView on the second screen.
SnapshotView method probably uses gpu resources, leaving your CPU free to have an high frame rate and performances on your second screen.
Answer: You could maybe create an exact duplicate UIView with same size, and then use CGAffineTransform to scale it to the new size (given that you know the dimensions it needs to fit)
CGAffineTransform is a GPU accelerated operation so performance should be rather optimal.
Only thing to note (as Documentation warns) is that it might not play nicely with Autolayout because frame property will be considered invalid. You will only have bounds and center to manipulate the view.


Where should I put VBA.DoEvents and Application.OnKey if I use an infinite loop?

Question: I'm creating a game in VBA and I don't know how to make Application.OnKey work. Why do I need it? As you can guess, I want an object in my game move when a player presses a key.
A game is basically an infinite loop in a subroutine RunGame(). If I put Application.OnKey as a workbook event without running RunGame(), then it works, so my keyboard and Application.OnKey can understand each other. However, when I run RunGame(), then the key listener doesn't work. I'm sure it's because I put it in a wrong place. The point is I tried it everywhere and have run out of ideas! Could you help me with it? I'm pasting a reproducible example here.
Module "main":
Option Explicit

Sub RunGame()

Call Application.OnKey("{Down}", "OnDownKey")

  Do While True
    '
    '
    'Some game's stuff here
    '
    '

    Call WasteTime(1)
  Loop

End Sub

Module "utils":
Option Explicit

Sub WasteTime(TimeToWaste As Single)

  Dim i As Long

  For i = 1 To TimeToWaste * 1000
    VBA.DoEvents
    i = i
  Next
End Sub

Sub OnDownKey()
  MsgBox "You pressed down key"
End Sub

By the way, if there's anything to change in this little example's logic, I'll appreciate your tips.
Answer: I've got to get to a solution, so I'll respond to my own question. Tips from @Peyter helped me find the way.
First of all, an infinite loop seems absolutely OK to me, I feel that it works more stably than Application.OnTime. There's also Chip Pearson's method, but I didn't find the reason of using it instead of the infinite loop (the result seemed the same).
Second of all, I left Aplication.OnKey be too. I used a solution from this site. This is some Windows function and works very well. There is one issue, though. From now on, a pressed key will mean to Excel both an extra activity and a normal activity. For example, when I press down arrow, I choose a cell below a cell I'm in. I wanted to turn off the regular behaviour for arrows and letters, but I didn't find any pretty way to do it. So I used an ugly one ;) All in all my functions are as shown below.
Module main:
Option Explicit

Sub RunGame()

  Do While True
    '
    '
    'Some game's stuff here
    '
    '

    Call WasteTime(1)
    IsKeyPressed
  Loop

End Sub

Module utils:
Option Explicit

Declare Function GetAsyncKeyState Lib "User32.dll" (ByVal vKey As Long) As Long

Private Const VK_DOWN = &H28 'DOWN ARROW key

Sub WasteTime(TimeToWaste As Single)

  Dim i As Long

  For i = 1 To TimeToWaste * 1000
    VBA.DoEvents
  Next
End Sub

Sub IsKeyPressed()

  If GetAsyncKeyState(VK_DOWN) <> 0 Then
    OnDownKey
  End If
End Sub

Sub OnDownKey()
  MsgBox "You pressed down key"
End Sub

It works. I still don't know where to put VBA.DoEvents, but in the loop it works well. The line Declare Function GetAsyncKeyState Lib "User32.dll" (ByVal vKey As Long) As Long says hello to a Windows function which now will work for us. Private Const VK_DOWN = &H28 'DOWN ARROW key is a definition of down arrow key which now will be called VK_DOWN. IsKeyPressed() checks if the user pressed some key. If GetAsyncKeyState(VK_DOWN) <> 0 checks if it's VK_DOWN which was pressed. Surprisingly for me, this Windows functions works very well with VBA, there are no lags!
Now, what did I do to block the regular behaviour of pressing arrows or letters? I chose one cell in which I wanted to stay - in my example it's AG1. Then I used worksheet events (double click on a sheet on the left in VBA editor and you'll open it). I used two functionalities there:
Option Explicit

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  [AG1].Select
End Sub

Private Sub Worksheet_Change(ByVal Target As Range)
  If Target.Address = "$AG$1" Then
    Application.EnableEvents = False
    [AG1].Clear
    [AG1].Select
    Application.EnableEvents = True
    RunGame
  End If
End Sub

The first one makes it impossible to escape from AG1, because each time you change the selection, VBA selects AG1 for you.
The second one fires when you try to change value of a cell. The subroutine will clear the cell, select it and then start RunGame(). Why is the last thing needed? Because when the user starts typing something, the infinite loop pauses and when the user hits Enter, the infinite loop doesn't continue. I don't really know if it's paused or finished. But hopefully I will make do without using letter keys, so I don't have to worry.
Answer: Why are you using an infinite loop? Gah.
Instead use VBA's WithEvents model to wait for input.
And use Application.Ontime to call a macro, which calls itself again at a set interval. If you Infinite loop, you never destroy objects in that sub, and VBA will run out of memory, crashing the game. When you have even like a side scroller, that moves the frame or something, and you use AOT, then instead of one fluid big sub, you get 1 frame, then 2 frame, and you can change the trajectory of the AOT calls, by using WithEvents to change logic in your AOT calls so that it branches to a different AOT macro.
Comment: But you're stating in your question, that when you press a button, it's not working. This is because VBA is single threaded. So while your sub is infinitely looping, the application isn't able to process the key press. So my solution here is that you replicate your infinite loop (lol) by making an application event which is self-sustainable, but also leaves a gap between events of like <1 second. To the user, the sub will seem like its just looping, but to the computer, there's a <1 second gap for a button press using WithEvents. Thats going to let Application hear that button press event
Comment: Yeah you're going to have to get really crafty to try and get the withevents to handle. Off the top of my head, I'm thinking the sub should check for input somehow. Of course there are some fun weird little work arounds to try and get Excel to behave multi-threaded, if you want to deep dive into this, https://codereview.stackexchange.com/questions/185212/a-new-approach-to-multithreading-in-excel <- this thread is interesting. But you could also spawn workers using VBS scripts / Wscripts that run on the OS, and report back a value to excel after they're done running. It all going to b a waround
Comment: The purpose of infinite loop is not only to catch events. Actually, not at all. The purpose is to keep images going. Why am I using it? A book about creating games which I read told me to do so (however, the language used in that textbook wasn't VBA). I saw a game example in VBA on YT and there the author used: InfLoop: \n 'Everything \n GoTo: InfLoop '''''''''''''''''''''' Effectively, to me it seems the same solution. In my subroutine there are no local objects, so I don't need to destroy them. Do you still think that using a loop here is wrong?
Comment: I'm sorry, but it seems to not be working as it should on my computer (let's leave reaction to events for now). Instead of the loop, I put `Application.OnTime Now + (ms * 0.00000001), "RunGame" ` at the end of the subroutine. I found on StackOverflow that `Now + (ms * 0.00000001)` should give delay of ms miliseconds. But this function behaves crazily. If ms >= 580, then the game is as slow as a snail. If ms <= 570, then the game is way too fast and is unstoppable, that is I can't click "stop macro", I can't do anything, I must close Excel via task manager. This is mathematically impossible.
Comment: It probably means it doesn't work with values less than a second, perhaps?
Comment: You're right on that, Its the Chip Pearson method that works less than a second I was confusing. Here take a look at this one: https://stackoverflow.com/questions/25116231/ontime-for-less-than-1-second-without-becoming-unresponsive
Comment: OK... But now, when I stop the subroutine, Excel crashes. When I click on the sheet during the run, it crashes too! This solution is far from perfect (apart from not working): it uses some external Windows functions, it requires a lot of more code and it's ugly :D I'm sorry :D But I really hope there's something which would work. Anyway, is it really that it's impossible to listen to events when looping in VBA?
Comment: OK, I've got it. It crashes when I stop because this timer must be stopped by the provided by Pearson subroutine, which I didn't use. Now I did and it works. However, if I accidentally click on some cell, Excel crashes. Even if I didn't set any event on cell change. So... it's quite a huge downside. Now I'll check if events started to work ;)
Comment: Yay, it's working! Thank you. Now I'd be very grateful for a solution to the crashing when changing cell problem...
Comment: I must say it's very crashable. It even crashes when I click "start" and then "stop", and then "start", and then "stop", and then "start"... There must be some other way to handle it!
Comment: By the way, I used what is called "Windows timers" on that website. Now I tried also the method described before it and it works like my infinite loop - it works, it doesn't crash, but it doesn't understand events.


Profit maximization problem using optimization

Question: An apartment complex on Ferenginar with $250$ units currently has $193$ occupants. The current rent for a unit is $965$ slips of Gold-Pressed Latinum. The owner of the complex knows from experience that he loses one occupant every time he raises the rent by $2.5$ slips of Latinum. What should be our recommendation for the optimal rent?
The equation I got was $(193-x)\cdot(965+2.5x)$. I tried to maximize it and got $x=-96.5$. The optimal rent is $965+2.5(-96.5)=723.75$.
This answer is not correct? Where did I make a mistake
Thanks
Answer: You did nothing wrong!
Notice that the equation of the total rent with respect to $x$ is a parabola. That means as $x$ goes from $0$ to $-96.5$, the total rent is increasing. However, our maximum occupancy is $250$ residents, so the rent is maximized at $x=-57$.
Comment: we can't actually have x=-96.5 because that corresponds to 289.5 residents and we don't have that much space


Improvements in Drupal Gardens way: How do I place an input filter selector in CKEditor?

Question: I would like to know how to achieve two improvements in WYSIWYG in the same way Drupal Gardens does.

The first one is to place Input filters selector as a dropdown selector within the WYSIWYG toolbar, which saves a lot of space and looks cleaner.
The second one is to place two tabs in order to switch from HTML code and WYSIWG Editor.
I created a site and exported the file as to see which modules Drupal Gardens uses, but I didn't find the correct one.
Answer: This is the code responsible for those modifications.
(function ($) {

Drupal.gardens_misc = Drupal.gardens_misc || {};

Drupal.behaviors.gardens_misc = {
  attach: function(context, settings) {
    if (typeof CKEDITOR != 'undefined') {
      // Bind events to handle enabling and disabling of the WYSIWYG.
      CKEDITOR.on('instanceReady', Drupal.behaviors.gardens_misc.instanceLoaded);
    }

    $('.wysiwyg', context).closest('.text-format-wrapper').once('wysiwyg-tabs', function() {
      var $tabs = $('

').insertBefore($(this).find('.form-textarea-wrapper'));
      $('
' + Drupal.t('WYSIWYG') + '
')
        .bind('click', this, Drupal.behaviors.gardens_misc.tabToggle)
        .appendTo($tabs);
      $('
' + Drupal.t('HTML') + '
')
        .bind('click', this, Drupal.behaviors.gardens_misc.tabToggle)
        .appendTo($tabs);
    });
  },
  instanceLoaded: function(event) {
    var $wrapper = $(event.editor.container.$).closest('.text-format-wrapper');
    var $original = $wrapper.find('.wysiwyg');
    var $clone = $original.clone().val($original.val());
    $clone.bind('change', function(event) {
      $original.val($clone.val()).change();
    });
    $wrapper.find('.cke_toolbox').removeAttr('onmousedown').prepend($clone);
    $wrapper.find('.wysiwyg-tab.enable').addClass('wysiwyg-active');
    $wrapper.find('.wysiwyg-tab.disable').removeClass('wysiwyg-active');
  },
  tabToggle: function (event) {
    if (!$(this).hasClass('wysiwyg-active')) {
      $(this).closest('.text-format-wrapper').find('.wysiwyg-toggle-wrapper a').click();
    }
  }
};

/**
 * Overides the default attach behavior for text formats without an editor
 */
Drupal.wysiwyg.editor.attach.none = function(context, params, settings) {
  var $field = $('#' + params.field);
  var $original = $('#' + params.trigger);
  var $clone = $original.clone().val($original.val());
  var $container = $('

');
  $container.append($clone).insertBefore($field);
  $clone.bind('change', function(event) {
    $original.val($clone.val()).change();
  });

  // @todo: Need to display the allowed tags here
  var tags = Drupal.settings.wysiwyg_formats[$original.val()];
  $('' + Drupal.t('Allowed tags: ') + '' + tags + '').appendTo($container);

  // Original behavior
  if (params.resizable) {
    var $wrapper = $field.closest('.form-textarea-wrapper');
    $wrapper.addClass('resizable');
    if (Drupal.behaviors.textarea.attach) {
      Drupal.behaviors.textarea.attach();
    }
  }

  $field.closest('.text-format-wrapper').find('.wysiwyg-tab.enable').removeClass('wysiwyg-active');
  $field.closest('.text-format-wrapper').find('.wysiwyg-tab.disable').addClass('wysiwyg-active');
};

/**
 * Overides the default detach behavior for text formats without an editor
 */
Drupal.wysiwyg.editor.detach.none = function(context, params) {
  $('#' + params.field).siblings('.wysiwyg-none-header').remove();

  // Original behavior
  if (typeof params != 'undefined') {
    var $wrapper = $('#' + params.field).parents('.form-textarea-wrapper:first');
    $wrapper.removeOnce('textarea').removeClass('.resizable-textarea')
      .find('.grippie').remove();
  }
};

})(jQuery);;

Save the above in its own file e.g. drupalgardens_wysiwyg.js, then either add the script to the .info file of your theme/module or add the file on the relevant page(s) using drupal_add_js or via the #attached property of a form/render array.
To get this to work on a non-DrupalGardens site, I had to comment out the two lines below the @todo comment around line 53. You may need to further tweak the code depending on how you have your wysiwyg profiles configured.


A simpler way to create a dictionary with counts from a 43 million row text file?

Question: Context:  I have a file with ~44 million rows.  Each is an individual with US address, so there's  a "ZIP Code" field.  File is txt, pipe-delimited.
Due to size, I cannot (at least on my machine) use Pandas to analyze. So a basic question I have is:  How many records (rows) are there for each distinct ZIP code?  I took the following steps, but I wonder if there's a faster, more Pythonic way to do this (seems like there is, I just don't know).
Step 1:  Create a set for ZIP values from file:
output = set()

with open(filename) as f:
  for line in f:
    output.add(line.split('|')[8]  # 9th item in the split string is "ZIP" value

zip_list = list(output)  # List is length of 45,292

Step 2: Created a "0" list, same length as first list:
zero_zip = [0]*len(zip_list)

Step 3: Created a dictionary (with all zeroes) from those two lists:
zip_dict = dict(zip(zip_list, zero_zip))

Step 4: Lastly I ran through the file again, this time updating the dict I just created:
with open(filename) as f:
    next(f)  # skip first line, which contains headers
    for line in f:
        zip_dict[line.split('|')[8]] +=1

I got the end result but wondering if there's a simpler way.  Thanks all.
Comment: I always think that when the datasize is large enough, you should look into a database solution, it makes for memory efficient retrievals
Comment: Agree, though this time it was a quick 'sanity check' on the output file (*.txt) coming from the DB team, so a 'one off' type of situation.
Answer: Creating the zip_dict can be replaced with a defaultdict. If you can run through every line in the file, you don't need to do it twice, you can just keep a running count.
from collections import defaultdict

d = defaultdict(int)

with open(filename) as f:
    for line in f:
        parts = line.split('|')
        d[parts[8]] += 1

Comment: Thank you!!! I'm not very familiar with collections module yet, though I did watch a video talk by the creator of "collections". I'll explore those.  And yes, it's 9th item, index 8.
Answer: This is simple using the built-in Counter class.
from collections import Counter

with open(filename) as f:
    c = Counter(line.split('|')[8] for line in f)
print(c)


Access-Control-Allow-Origin erro com XMLHttpRequest()

Question: Olá, estou tendo o seguindo erro:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Já pesquisei e a solução que encontro é de adicionar:
        request.setRequestHeader('Access-Control-Allow-Origin', '*');

Porém, mesmo assim o erro persiste. Se eu executar a aplicação com o Cors desligado, funciona normalmente. Alguém pode me ajudar?
var request = new XMLHttpRequest();

    request.open('GET', 'https://www.URLAPI.com/api/v3/PARAMETRO);

    request.setRequestHeader('Access-Control-Allow-Origin', '*');
    request.setRequestHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    request.setRequestHeader('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers');

    request.setRequestHeader('Content-Type', 'application/json'); //Obrigatorio API
    request.setRequestHeader('access_token', 'MEUTOKEN'); //Obrigatorio API

    request.onreadystatechange = function () {
        if (this.readyState === 4) {
            if(request.status === 200){
            console.log('Status:', this.status);
            console.log('Headers:', this.getAllResponseHeaders());
            console.log('Body:', this.responseText);

                                console.log(request);

            }else{
                console.log("Erro");
                console.log(request);
            }
        }
    };

    request.send();

Projeto Angular 7 (WEB).
Só consigo acessar o dado que preciso quando executo o chrome com o CORS desativado.
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --disable-gpu --user-data-dir=~/chromeTemp

Comment: Tem que liberar o CORS no servidor, foi lá que você alterou?
Answer: Solução:

Como o servidor da API que eu estava trabalhando não estava retornando o protocolo CORS e o navegador estava realizando o bloqueio da comunicação, após muita procura encontrei a solução no link: Utilizando servidor Proxy para realizar a comucação.

Link do servidor que trata o CORS
Este intermediário trata o protocolo CORS e consegue comunicar com a API que preciso. O código fica:
var request = new XMLHttpRequest();

request.open('GET', 'https://cors-anywhere.herokuapp.com/https://www.URLAPI.com/api/v3/PARAMETRO);

request.setRequestHeader('Content-Type', 'application/json'); //Obrigatorio API
request.setRequestHeader('access_token', 'MEUTOKEN'); //Obrigatorio API

request.onreadystatechange = function () {
    if (this.readyState === 4) {
        if(request.status === 200){
        console.log('Status:', this.status);
        console.log('Headers:', this.getAllResponseHeaders());
        console.log('Body:', this.responseText);

                            console.log(request);

        }else{
            console.log("Erro");
            console.log(request);
        }
    }
};

request.send();

Comment: Testei o mesmo código com outra API e sem o intermediador, e funcionou corretamente. Ou seja, a API não trabalha com o protocolo de SEGURANÇA CORS.
Answer:
"Com a implementação do CORS um domínio permite comunicação com outro
  de forma livre, independente do método da chamada (GET, POST, PUT ou
  DELETE) contanto que o domínio de destino tenha especificado esse tipo
  de comunicação.
Geralmente essa configuração é feita no lado da API e cada framework
  tem sua forma de configuração. A parte importante é a inclusão do
  Access-Control-Allow-Origin no header da reposta da API.
Então, em um cenário bem simples, sua aplicação JS cliente em
  dev.meudominio.com.br faz um request para a API (normalmente numa
  chamada AJAX) para o servidor api.meudominio.com.br. A resposta da API
  deve incluir no header da resposta o Access-Control-Allow-Origin:
  http://dev.meudominio.com.br deixando claro para o navegador que ele
  aceita requests originados somente desse domínio."

https://medium.com/@alexandremjacques/entendendo-o-cors-parte-8331d0a777e1
Veja o exemplo de solicitação:
GET /recurso.php HTTP/1.1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5) AppleWebKit/536.30.1 (KHTML, like Gecko) Version/6.0.5 Safari/536.30.1
Accept: application/json, text/plain, */*
Referer: http://dev.meudominio.com.br/
Origin: http://dev.meudominio.com.br/

E a modelo de resposta da API:
HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Date: Wed, 20 Nov 2013 19:36:00 GMT
Server: Apache-Coyote/1.1
Content-Length: 35
Connection: keep-alive
Access-Control-Allow-Origin: http://dev.meudominio.com.br

Se o conteúdo de Origin for idêntico ao de Access-Control-Allow-Origin a comunicação é permitida pelo navegador.
Answer: Eu estava fazendo um GET e o jQuery funcionava e o meu XMLHttpRequest não. Fiquei com raiva, mas descobri o que acontecia entrando no código do jQuery. Então, pra quem tiver esse problema eu consegui resolver adicionando no headers
request.setRequestHeader('Accept', '*/*');

Foi só ISSO! E eu tive que remover os seguintes códigos (não sei o motivo)
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.setRequestHeader('Access-Control-Allow-Origin', '*');


Give an example of a function $f:\mathbb{R}^2 \mapsto \mathbb{R}$

Question: Give an example of a function $f:\mathbb{R}^2 \mapsto \mathbb{R}$ having the property that for $a \in \mathbb R$ and $v \in \mathbb R^2$
$f(av) = af(v)$,
and $f$ is not a linear map.
Comment: Please, show what you have tried and where you are stuck.
Answer: What needs to break is additivity. Every polynomial is homogenous of degree equal to its degree. So let's take
$$ f(x,y) = \sqrt[3]{x^3 + y^3} $$
which is obviously not additive
Comment: "Every polynomial is homogenous of degree equal to its degree" -> but we need odd degree, to preserve the sign.


rfc2307bis and posix groups

Question: I've needed to configure LDAP authentication for Joomla! and the only way to get it to work together (with LDAP group based  was by using groupOfUniqueNames, not the posixGroup. In other words, Joomla expects LDAP to follow the RFC2307bis schema.
This beg the question: do other LDAP using applications understand the RFC2307bis schema?
From what I could find, the 4 most important applications do:

pam_ldap and nss_ldap
Samba
Gosa
phpLDAPAdmin

Besides that, what is the state of general support for this schema (Apache auth, squid, groupware suites, freeradius)?
Any problems with such configuration (rfc2307bis, pam_ldap, nss_ldap and samba)?
Comment: And there are several revisions of the RFC2307bis schema — [draft 02](http://tools.ietf.org/html/draft-howard-rfc2307bis-02) was changed to use `groupOfMembers` class with the optional `member` attribute for groups, while the older [draft 01](http://tools.ietf.org/html/draft-howard-rfc2307bis-01) used `groupOfUniqueNames`, where the `uniqueMember` attribute is mandatory (therefore creating an empty group is not possible without hacks; draft 02 finally fixes this problem).
Answer: From what GOsa² developers said, they are using modified RFC2307 schema that not only uses groupOfUniqueNames as @SergeyVlasov noted is standard in second draft, but also duplicate the regular NIS schema giving full backwards compatibility (as long as one doesn't use other administrative tools for changing group membership or user creation).
I haven't tried it yet, but it looks like one can use this modified schema without problems.

rfc2307bis and posix groups


Performance benchmarks for MCMC

Question: Have there been large scale studies of MCMC methods that compare the performance of several different algorithms on a suite of test densities? I am thinking of something equivalent to Rios and Sahinidis' paper (2013), which is a thorough comparison of a large number of derivative-free black-box optimizers on several classes of test functions.
For MCMC, performance can be estimated in, e.g., effective number of samples (ESS) per density evaluation, or some other appropriate metric.
A few comments:

I appreciate that performance will strongly depend on details of the target pdf, but a similar (possibly not identical) argument holds for optimization, and nonetheless there is a plethora of benchmark functions, suites, competitions, papers, etc. that deals with benchmarking optimization algorithms.
Also, it is true that MCMC differs from optimization in that comparatevely much more care and tuning is needed from the user. Nonetheless, there are now several MCMC methods that require little or no tuning: methods that adapt in the burn-in phase, during sampling, or multi-state (also called ensemble) methods (such as Emcee) that evolve multiple interacting chains and use information from other chains to guide the sampling.
I am particularly interested in the comparison between standard and multi-state (aka ensemble) methods. For the definition of multi-state, see Section 30.6 of MacKay's book:

In a multi-state method, multiple parameter vectors $\textbf{x}$ are maintained;
  they evolve individually under moves such as Metropolis and Gibbs;
  there are also interactions among the vectors.

This question originated from here.

Update

For an interesting take on multi-state aka ensemble methods, see this blog post by Bob Carpenter on Gelman's blog, and my comment referring to this CV post.
Answer: After some online searching, I have come under the impression that a comprehensive benchmark of established MCMC methods, analogous to what one can find in the optimization literature, does not exist. (I'd be happy to be wrong here.)
It is easy to find comparisons of a few MCMC methods on specific problems within an applied domain. This would be okay if we could pool this information -- however, the quality of such benchmarks is often insufficient (e.g., due to lack in the reported metrics or poor design choices).
In the following I will post what I believe are valuable contributions as I find them:

Nishihara, Murray and Adams, Parallel MCMC with Generalized Elliptical Slice Sampling, JMLR (2014). The authors propose a novel multi-state method, GESS, and perform a comparison with 6 other single-state and multi-state methods on 7 test functions. They evaluate performance as ESS (Effective Sample Size) per second and per function evaluation.
SamplerCompare is a R package with the goal of benchmarking MCMC algorithms -- exactly what was I was asking about in my original question. Unfortunately, the package contains only a few test functions; the accompanying paper reports no actual benchmarks (just a small example); and it seems there have been no follow-ups.

Thompson, Madeleine B. "Introduction to SamplerCompare." Journal of Statistical Software 43.12 (2011): 1-10 (link).

For an interesting take on multi-state aka ensemble methods, see this blog post by Bob Carpenter on Gelman's blog, and my comment referring to this CV post.
Comment: You might want to have a look at this December 2017 paper: [Ryan Turner & Brady Neal, How well does your sampler really work?](https://arxiv.org/pdf/1712.06006.pdf) It seems to provide a neat solution to exactly this problem of coming up with a good benchmark for MCMC algorithms.
Comment: Your second link is dead -- could you change it to a working one?
Answer: I would agree with your assessment that there are no comprehensive benchmarks established for MCMC methods. This is because every MCMC sampler has pros and cons, and are extremely problem specific.
In a typical Bayesian modeling setting, you can run the same sampler with diverse mixing rates when the data is different. I would go to the extent of saying that if in the future there comes out a comprehensive benchmark study of various MCMC samplers, I would not trust the results to be applicable outside of the examples shown.
Regarding the usage of ESS to assess sampling quality, it is worth mentioning that ESS depends on the quantity that is to be estimated from the sample. If you want to find the mean of the sample, the ESS obtained will be different from if you want to estimate the 25th quantile. Having said that, if the quantity of interest is fixed, ESS is a reasonable way of comparing samplers. Maybe a better idea is ESS per unit time.
One flaw with ESS is that for multivariate estimation problems, ESS returns an effective sample size for each component separately, ignoring all cross-correlations in the estimation process. In this paper recently, a multivariate ESS has been proposed, and implemented in R package mcmcsevia the function multiESS. It is unclear how this method compares to the ESS of the coda package, but at the very outset seems more reasonable than univariate ESS methods.
Comment: (+1) Thanks for the answer. I agree with some of your points, but I still think that some information could be gained from such a benchmark. How one uses the results of such benchmarks to guide future choices it's up to them -- but *some* evidence is better than no evidence. Good points about ESS.  By multi-state I mean multi-state (or multi-chain, if you prefer), not simply multivariate -- see the quote from MacKay's book in my original question.
Comment: In general, some samplers are known to perform poorly for multimodal distributions(MH, Gibbs), and some are bad for non-convex support (Hamiltonian MC). On the other hand, for high dimensional problems Hamiltonian MC works well and for multimodal distributions simulated tempering etc are good. To do *any* benchmarking, one might need to define different broad classes of target distributions (sub-exponential, log concave etc) for the results to be interpretable generally.
Comment: Well, yes, that's the whole point of building a benchmark for a class of algorithms. See for example [this](http://coco.gforge.inria.fr/) for global optimization. Clearly a benchmark for MCMC cannot just borrow the ones existing for optimization; there is a need to focus on features of the target densities that are specific, common and of interest to MCMC problems, as those you mentioned.

Performance benchmarks for MCMC


How many ways to seat n people at a round table of size k when k is significantly larger than n?

Question: According to a math website I'm looking at (http://web.eecs.utk.edu/~booth/311-04/notes/combinatorics.html), if you have a circular permutation situation (such as a round table), and there are e empty spaces, then the formula is...
(n-1)! / e!
However this doesn't make complete sense to me. Say for instance, I want to seat 3 people at a table with 30 seats. That means there will be 27 empty seats. So total number of ways to seat them is...
(3-1)! / 27! = (extremely below 0)
Can someone explain how my thinking on this is wrong? It would be greatly appreciated!
Comment: Nitpick.  2!/27! is not below zero.  But it is "extremely" fractional and clearly not a non-negative integer which "the number of ways" has to be.
Comment: By the way, I did not particularly like that page you linked to.  I thought the explanations were poorly worded and confusing.
Answer: n is the number of seats; not the number of people.
Thus number of ways to seat 3 people in 30 seats is (30 -1)!/27! = 29*28.
(I'm assuming that the point of the table being circular is that seatings are equivalent up to rotation.  Thus when the first person sits all choices are considered equivalent.)


Features workflow issue with deleting a field

Question: Suppose I have a content type Person with fields: Name, Age, Email
This content type is controlled by a Feature called test so I can source control it and push it to the live site.
My workflow goes like this:

I add a new field on Person called Phone
locally I do: drush fu test -y
I edit the test.info to increase the version number
I commit the changes to my repository
I push the feature to the live site (copy the feature files)
on the live site I do: drush fr test -y
on the live site I do: drush cc all

Then the new field appears on the live site's Person.
If on the first step I remove a field of Person the field will not be deleted from the live site. How do I solve this? I don't want to have to manually delete it from the UI on the live site.
Is this workflow correct?
Comment: Use drush fu test -y --version-increment to automatically increment the version number
Answer: The correct way to remove Features-created content is via hook_update_N (which should be implemented in the file your_module.install).

The main idea with Features is to manage configuration with code. Using hook_update_N is consistent with that, since the field deletion is in code (which can be managed with version control) — whereas the equivalent command drush field-delete field is not being called from managed code; it's a separate command-line step you need to perform (and to remember to perform).
Comment: Sure, that would work, and may be a simpler solution.  But the main idea with Features is to manage configuration with code.  Using `hook_update()` is consistent with that, since the field deletion is in code (which can be managed with version control) — whereas the drush command is not being called from managed code; it's a separate command-line step you need to perform (and to remember to perform).
Comment: Why? Won't `drush field-delete field` work well?
Comment: In which file of a feature will I use hook_update()? hook_update() takes a node object as parameter, so it is not possible to provide it a node object while enabling the feature.
Comment: @subhojit777: Oops, I linked to the wrong hook documentation page.  I just fixed the link; please see the docs for `hook_update_N`.
Comment: @smokris :) I mentioned that hook in my answer
Comment: How would hook_update_N work with multiple enable/disable of the feature? Would that be applied every time?
Answer: This is a double edged sword, it's like this to prevent data deletion which is always a good thing. There's nothing really to solve, this is expected behaviour.
It's the same workflow we use and have been doing for over a year and it works really well. I'd say it's correct but that's a very subjective answer.
Comment: Update hooks would be ideal, or manually remove it.
Comment: OK, I could also do `drush field-delete field`
Comment: And if I really wanted to delete the field? Should I look into update hooks? (I'm a D7 newbie).
Comment: @cherouvim So you'd have to do that every time you recreate a feature?
Comment: A hook_update_N() in the feature's .install file would work.
Answer: Create a new file called "your_feature_name.install"
Inside the file declare hook_update_N, there you can use field_delete_field() and specify the name of field that you want to delete as parameter.
Run update.php and the fields will be deleted.
Answer: If you are using field_phone in other areas, you might just want to remove it from your Person content type, but not delete it entirely from your site. Manually create a YOUR_FEATURE_NAME.install file in your feature's folder like so:

/**
 * Implements hook_update_N().
 *
 * Removes field_phone from Person content type.
 */
function YOUR_FEATURE_NAME_update_7001() {
  if ($instance = field_info_instance('node', 'field_phone', 'person')) {
    field_delete_instance($instance);
  }
  field_purge_batch(500);
  features_revert_module('YOUR_FEATURE_NAME');
}

If you were deleting this from a Person Paragraph instead of a Person Content Type, you could change the first conditional statement to something like this:
if ($instance = field_info_instance('paragraphs_item', 'field_phone', 'person')) {
  ...
}


Angular: If / else statement in view's Form

Question: I'm a total newbie with this "thing". I'm dealing with not mine code…
I have a view that has:
<form (ngSubmit)="submitCreateForm()">

I also have a variable I can use, called type that has either value add or edit.
How have 2 method defined submitCreateForm and submitUpdateForm
How can I modify the ngSubmit in the <form> to call submitCreateForm if type is add or submitUpdateForm when type is edit?
I know it sounds trivial, but the syntax is quite convoluted for me. Ideally I'm looking for a single line conditional.
Comment: Why don't you have `(ngSubmit)="submit()"` and in the component typescript have to logic call the respective method based on the `type` variable?
Comment: This makes sense. Please make your comment an aswer, I will upvote.
Comment: I would normally do this logic in a service based on if the object has a id or not.
Answer: Use ternary operator (?..:) for conditional rendering.
<form (ngSubmit)="type === 'add' ? submitCreateForm() : submitUpdateForm">

Answer: In back end you can handle this you can call always submitForm()
<form (ngSubmit)="submitForm()">

let submitForm() function will decide which submit will call based  on type
 submitForm()
 {
      if(this.type==="add"){
       this.submitCreateForm();
      }
      else{
       this.submitUpdateForm();
     }
 }

Comment: Yes, that's what I did. Ramesh (first comment under my question) was first with this solution. I will upvote both of you.
Comment: You get upvote as your solution is the same as Ramesh, but he was first for accepting answer. Thanks anyway.
Answer: Why don't you have (ngSubmit)="submit()" and in the component typescript have to logic call the respective method based on the type variable?
Comment: You comment was first and that makes sense to me as I don't want to pollute views. I defined generic submit and I pass type. This calls final method based on `type` value.
Answer: 1) This is not the very good practice but this will do the trick. Try keeping two forms based on that Boolean.
<form ng-if="type == true" (ngSubmit)="submitCreateForm()">
<form ng-if="type != true" (ngSubmit)="submitUpdateForm()">

2) My second suggestion is use common submit action and separate logic based on the boolean 'type'


Navegação interna com JQuery

Question: Tenho a seguinte estrutura no meu header:

...

   Reserve aqui!

...

O iframe está com display none, pois só quero que ele apareça quando o link for clicado. Para isso fiz um código em JQuery:
$("#header-reserva a").click(function()
{
    $("#header-reserva-iframe").css('display', 'inherit');
});

O iframe é apresentado quando o link é clicado, mas o link não é direcionado para o iframe no primeiro clique, sendo necessário um segundo click para isso, ou seja, preciso que o link no primeiro click tanto mostre o iframe quanto navegue para o topo dele. Como posso fazer isso?
Answer: Pode usar isso para animar o scroll até o iframe
$('html, body').animate({
    scrollTop: $("#header-reserva-iframe").offset().top
}, 2000);

Comment: Funcionou perfeitamente! Obrigado!
Answer: O link aponta para o frame de fora (window). Para apontar para o iframe, use um target:
Reserve aqui!

Para o target funcionar, acredito que você precisa de um name no iframe:

Comment: Tentei mas não obtive resultado.
Comment: Tente colocar um name no iframe, igual ao id
Answer: Tente forçar a página a ir pra div assim:
$("#header-reserva a").click(function()
{
    $("#header-reserva-iframe").css('display', 'inherit');
    window.location.hash = '#header-reserva-iframe';
});

Answer: Lembre-se que o código jQuery deve rodar só depois que a página terminar de carregar o DOM, que é a árvore de elementos do documento. Com isso você não precisa forçar o navegador a fazer o scroll até o elemento.
$(function(){ // Aguarda o DOM ser carregado
    $("#header-reserva a").click(function() {
        $("#header-reserva-iframe").show(); // Troquei o .css() por .show() só pra ficar mais legível
    });
});

Navegação interna com JQuery


How do I prove the uniqueness of additive identity?

Question: First, suppose $i_1$ and $i_2$ are additive identity in ring R. From the definition of "additive identity" $a+i_1=a$ such that there is $a$ $\in$ $R$, including for $a=i_2$, so $i_2+i_1=i_2$. But $i_2$ is also an additive identity, so there $a \in R$ making $a+i_2=a$. Then $a=i_1$. Then $i_1+i_2=i_1$. Since this is a ring, addition is commutative, so $i_1+i_2=i_2+i_1$. Thus, $i_2+i_1=i_1$. Since $i_2+i_1=i_2$ and $i_2+i_1=i_1$, $i_2+i_1$ is the same element of $i_2$ and is the same as $i_1$, making $i_2=i_1$. Is this how you show it's unique? If not, can someone show me how to prove it's unique.
Comment: Your proof is correct; although it could be made a lot less verbose by just saying $ i_1 = i_1 + i_2 = i_2 + i_1 = i_2 $.
Comment: Yes: this is how you show it is unique.
Comment: That's a little verbose, but essentially it.
Answer: Yes, although you can trim it down a bit; for clarity's sake.

If $i_n$ is an additive identity, then for any $a$ in the ring: $~a+i_n=a~$ and $i_n+a=a$, by definition and the commutative property of addition in abelian groups.
If any $i_1, i_2$ are both additive identities, then we have: $i_1+i_2=i_1$ and $i_1+i_2=i_2$.
Thus for any additive identities $i_1,i_2$, then $i_1=i_2$.
That is: The additive identity for a ring is unique.
$\Box$


Proof for an integral inequality

Question: For a function $f:\mathbb{R}\to\mathbb{R}$, $|f|\leq M$, $f(s)\equiv 0$ for $s<0$, define
\begin{equation}
I^n(t)= n \int_{t-1/n}^{t} f(s)ds.
\end{equation}
In my book they conclude that
\begin{equation}\label{eq}
|I^n(t')-I^n(t)|\leq 2n|t'-t|M.
\end{equation}
How can I proof this inequality? I only see that
\begin{equation}
|I^n(t')-I^n(t)|\leq |n[(t'-t'+1/n)M-(t-t+1/n)M]|=0.
\end{equation}
Comment: It should be $2M|t'-t|$ I think.
Comment: Do we have any conditions on $t$ and $t'$?  Are they just *any* real numbers?
Comment: Also, what you've shown is wrong, because you've bounded $f$ by $M$ but actually we have $|f| \leq M$.  So you don't have $0$ as a bound.  Do you see why?
Comment: If the ranges of integration overlap, the difference between the integrals is bounded by stuff that depends on the 2 non-overlapping parts of the ranges.  This is what happens when $|t-t'|< 1/n$. The two parts are of length  $|t-t'|$ each, and the integrand is bounded by $M$.  (By the way, you left of a factor of $n$ in your formula for $I^n$.)
Comment: I am sorry, you are right. I forgot the factor of n before the integral. t and t' are just any two real numbers. How do you get this result, zhw?
Answer: Suppose $I^n(t)=\int_{t-1/n}^{t} f(s) \,ds$ and $I^n(t')=\int_{t'-1/n}^{t'} f(s)\,ds$.
Then
\begin{split}|I^n(t) - I^n(t')| &= n|\int_{t-\frac{1}{n}}^{t} f(s) \,ds - \int_{t'-\frac{1}{n}}^{t'} f(s)\,ds| \\ &\leq n\left(|\int_{t-\frac{1}{n}}^{t} f(s) \,ds| + |\int_{t'-\frac{1}{n}}^{t'} f(s)\,ds| \right) \\ &= n\left( |\int_{t-\frac{1}{n}}^{t} f(s) \,ds| + |\int_{t'}^{t'-\frac{1}{n}} f(s)\,ds| \right) \\&\leq nM(t - (t - \frac{1}{n}) + nM(t'  - \frac{1}{n} - t') \\ &=nM(t - t') + nM(t' - t) \\&\leq 2Mn|t-t'|  \end{split}
Comment: @Spike I figured it out and modified my answer above.  The key is that since $\int \limits_{a}^{b} f(s)\,ds = -\int \limits_{b}^{a} f(s)\,ds$, we have $\left |\int \limits_{t' - \frac{1}{n}}^{t'} f(s) \,ds \right | =  \left |\int \limits_{t'}^{t' - \frac{1}{n}} f(s) \,ds \right |$.  This allows the term with $\frac{1}{n}$ to cancel with the other $\frac{1}{n}$ term since they will have opposite signs, as above.  I hope that helps!
Comment: I forgot the factor of n before the integral, sorry for this. But that does not change much for your calcluations. Unfortunately I don´t see how I can get the correct estimate from this as $2M(n|t-t'|+1)$ is greater than $2Mn|t-t'|$.
Comment: @Spike Which book is it?  And what page is it on?  I'd like to take a look.
Comment: Page 4 (Step two): https://ocw.mit.edu/courses/sloan-school-of-management/15-070j-advanced-stochastic-processes-fall-2013/lecture-notes/MIT15_070JF13_Lec15.pdf
Comment: That's it, many thanks!
Answer: hint
Put $u=t-s $.
then
$$I^n (t)=\int_0^\frac 1nf (t-u)du $$
and
$$I^n (t)-I^n (t')=\int_0^\frac 1n (f (t-u)-f (t'-u))du $$
Comment: Doing some estimates I get $|n\int_{0}^{1/n}f(t-u)-f(t'-u)du|\leq n\int_{0}^{1/n}|f(t-u)|+|f(t'-u)|du\leq 2M$. But not the result I want to show. How would you continue your estimate?

Proof for an integral inequality


Making tacit assumptions in solve for x problems explicit

Question: When proving an identity such as
$$\frac{a}{c} + \frac{b}{c} = \frac{a + b}{c}\text{,}$$
the full statement being proven is actually the more pedantic
$$\frac{a}{c} + \frac{b}{c} = \frac{a + b}{c} \text{ if } c \neq 0\text{.}$$
Since I am permitted to assume the condition $c \neq 0$, I can multiply every term by $c$ and prove the identity.
I can also check this more pedantic version at $c = 0$. The condition becomes false, which makes the identity true without having to evaluate division by zero in the consequent.
I'm looking for an analog for solve for $x$ style problems. That is, the pedantic version of solve for $x$ style problems which makes explicit what to do with division by zero. Take the equation
$$\frac{6}{x} = 3$$
who's only solution is understood to be $x=2$.
I can't multiply by $x$ to solve it because I don't know $x \neq 0$. Using the idea,  "when solving for $x$, values which make a denominator zero are not solutions", I can write the problem as the more pedantic system of equations
$$\cases{\frac{6}{x} = 3 \\ x \neq 0\text{.}}$$
Now while working on $\frac{6}{x} = 3$ I can assume $x \neq 0$ and multiply both sides by $x$ to solve.
This version can also be checked at $x = 0$. One of the equations in the system of equations becomes false, which makes the entire statement false without having to evaluate division by zero.
Can I set up problems this way? I'm not suggesting $x \neq 0$ can be added based on some rule of algebra. I'm suggesting it can be added as a way to formally set up a solve for $x$ problem in a pedantic style which can then be solved using algebra.
The reason I am asking this is I've seen the concept of tacit conditions for identities in math books, but I've never seen the analogous idea of tacit requirements for solve for $x$ problems. Using it helps me understand what's going on, but I want to make sure it's right.
Answer: Assuming you are talking about real numbers, the statement $\frac{a}{c}+\frac{b}{c}=\frac{a+b}{c}$ is meaningless for $c=0$. It is not that when you prove it you say "if $c\ne0$" but that the statement per se includes such condition. If you want to prove such identity from the first principle, you need to define first what fraction and addition mean.
Exercises in algebra-precalculus usually assume functions with natural domains. So equations such as
$$
\frac{6}{x}=3
$$
are implicitly assuming that both sides are meaningful and thus the equation is actually
$$
\frac{6}{x}=3,\quad (x\ne 0).
$$
To see one more example, it is implicitly assumed in the following equation that $x>2$:

Solve the equation $\frac{1}{\sqrt{x-2}}=4$
Comment: I think what I said at the beginning is not clear. Essentially, I'm trying to say mathematicians often leave out writing down the conditions for identities when those conditions are obvious. Writing every condition down makes it clear both how to prove the identity algebraicly and also evaluate the identity at 0. I want to do the same thing for solve for x problems. That said, your discussion of natural domains answers my question. Thank you.


Finding the conditional distribution of 2 dependent normal random variables

Question: Here's the situation
$X \sim N(\mu, \sigma^2)$ and given $X=x$, $Y \sim N(x, \tau^2)$
I need to find the distribution of $X$ given $Y=y$
From what's given, I know the pdf's of $X$ as well as $Y|X=x$. By multiplying those pdf's together, I can find the joint distribution of $X$ and $Y$ ($f_{X,Y}=f_Xf_{Y|X=x}$).
This seems useful, but I have no clue how to go about finding $f_Y$ to finish it off (since $f_{X|Y=y} = f_{X,Y}/f_Y$). The integral from $-\infty$ to $y$ of $f_{X,Y}$ with respect to $X$ doesn't have a closed form solution to my knowledge.
Is this possible? Am I on the right track? Any help would be tremendously appreciated!
Comment: After finding the joint distribution, rename "$X$" as "$Y$" and "$Y$" as "$X$", then reverse your steps.
Comment: I'm sorry, but I don't follow you. Do you mean divide the joint pdf by the conditional distribution of X|Y to find the pdf of Y? That defeats the purpose as the conditional distribution of X|Y is ultimately what I'm looking for.
Comment: Why do you think you have to take the integral from $0$ to $y$ to get the marginal distribution? The normal distribution is defined over the real line.
Comment: Oops. Typo. My bad. Fixed it in the edit. I don't think it makes the integral any more "computable" though...
Comment: [Also asked on math.SE](http://math.stackexchange.com/q/1631511/15941). Please don't crosspost
Answer: Adapted from this previous answer of mine.
Suppose that $X \sim \mathcal N(\mu,\sigma^2)$ is the value of
a signal that we wish to observe, but what we can observe is
$X+N$ where $N \sim \mathcal N(0,\tau^2)$ is noise that is
independent of $X$. Let $Y$ denote $X+N$. Since $X$ and $N$
are independent, it is straightforward
to determine that $Y \sim \mathcal N(\mu, \sigma^2+\tau^2)$.
Now, the conditional
density of $Y$ given that $X$ has taken on value $x$ is
the density of $x+N$ which is clearly $\mathcal N(x,\tau^2)$.
What we are asked for, however, is the conditional density of
$X$ given that $Y = y$, that is, the a posteriori
distribution of $X$ given that we have observed that $Y = y$.
We choke down the gorge that is rising in our throats
at this blatant Bayesian heresy
and note that $X$ and $Y = X+N$ are jointly normal random
variables, $X \sim \mathcal N(\mu,\sigma^2)$ and
$Y \sim \mathcal N(\mu, \sigma^2+\tau^2)$, and that their
covariance is
$$\operatorname{cov}(X,Y) = \operatorname{cov}(X,X+N)
= \operatorname{cov}(X,X)+ \operatorname{cov}(X,N) = \sigma^2.$$
Now, it is a standard result that when $X$ and $Y$ are
jointly normal random variables, the conditional density
of $X$ given that $Y = y$ is a normal density
with mean
\begin{align}E[X\mid Y = y] &=
\mu_X + \left.\left.
\frac{\operatorname{cov}(X,Y)}{\operatorname{var}(Y)}\right(y-\mu_Y\right)\\
&= \mu+\left.\left.\frac{\sigma^2}{\sigma^2+\tau^2}\right(y-\mu
\right)\\
&= \frac{\sigma^2}{\sigma^2+\tau^2}y +\frac{\tau^2}{\sigma^2+\tau^2}\mu,\end{align}
that is, a weighted blend of the observation $y$ and the
a priori mean of $X$.  Note that if $\sigma^2 \gg \tau^2$,
we give large weight to the observation $y$ and very little to
the known mean $\mu$, while if $\sigma^2 \ll \tau^2$, we tend
to ignore the observation and give heavy weight to the mean $\mu$.
Also, the variance of this conditional density is
$$\operatorname{var}(X)\left(1-\frac{(\operatorname{cov}(X,Y))^2}{\operatorname{var}(X)\operatorname{var}(Y)}\right)
= \sigma^2\left(1-\frac{\sigma^4}{\sigma^2(\sigma^2+\tau^2)}\right)= \frac{\sigma^2\tau^2}{\sigma^2+\tau^2}.$$
This allows us to write down the conditional density
$f_{X\mid Y}(x\mid y)$ directly without messing up the ranges
of integrations etc. as in the OP's approach.
Comment: You helped me even though I'm a cross posting scum... for this, I am eternally grateful, and I vow to put an end to my cross posting ways.
Answer: Once you know the joint distribution, just use the property of the multivariate normal that the conditional distributions are also normal with parameters as defined here: https://en.wikipedia.org/wiki/Multivariate_normal_distribution#Conditional_distributions. Just fix Y to some value rather than fixing X.
Comment: But $f_{X,Y}$ isn't the pdf of a multivariate normal distribution. Or am I wrong about that?
Comment: The normal prior on x is the conjugate prior for the mean of a normally distributed random variable. This means that the posterior (which is proportional to the prior distribution on x times the likelihood of y) will also be normal. If you work it out, you should get this.


Clear up saved name

Question:
Hi, I have first project on React, and I wanna to clear up entry field after submit

                <PresetModalInputWrapper>
                    <PresetModalInput
                        placeholder={'Preset Name'}
                        value={presetName}
                        onChange={(event) => setPresetName(event.target.value)}
                    />
                    {doesContainError ? (
                        <PresetErrorMessage>{messagePresetWithSuchNameExists}</PresetErrorMessage>
                    ) : null}
                </PresetModalInputWrapper>

Comment: It's not clear to me what you're asking.  Are you just asking how to set a blank value to the `presetName` state value?
Answer: you can do this by calling setPresetName('') on the button click event
Answer: You can make a button that executes the setPresetName function, like this:
<button onClick={() => setPresetName('')} />

or on a handleSubmit function
const handleSubmit = (e) => {
    e.preventDefault();

    // ... your submit logic here

    setPresetName('')
}

Clear up saved name


what is difference between useBlockLayout vs useAbsoluteLayout in react table?

Question: I am using react-table. I'd like to know the difference between useBlockLayout, useAbsoluteLayout and useFlexLayout. And what case can use these hooks in?
Answer: check this documentation again.
https://react-table.tanstack.com/docs/api/useAbsoluteLayout
results of these 3 layout hooks will different on style.


How to generate the time series from a given model?

Question: We consider a sparse autoregressive time series of length 1000 obeying the model
$$X(t)=0.2X(t-1)+0.1X(t-3)+0.2X(t-5)+0.3X(t-10)+0.1X(t-15)+Z(t)$$
with nonzero coefficients at lags 1,3,5,10 and 15,where the innovations Z(t) are i.i.d. Gaussians with mean zero and standard deviation 0.1.
The question is how to simulate 1000 time series from the model with R or SAS?
Comment: So how would you define $X(0)$ and $X(1)$?  In your case, you either need the fifteen initial values, and then the rest can be built, or you need to specify the distribution that $X(i)$ are drawn from, for $i<15$ *and* whether the model allows the lags to be brought in as and when they are available, i.e. is $X(t-15) = 0$ if $t<15$?
Answer: In R, fill a vector with Gaussian white noise of zero mean and sd 0.1, then use the filter function. Notice that since the first 15 observations are white noise (and thence not generated by your model), you have to discard a section of your generated observations (say 10 times the maximum lag).
Answer: This is another way of simulating the result using arima.sim. It includes the code and some simple checks.
# Test it on a more well behaved model:
n <- 10000
n.sub <- 9000
maxlag <- 15
x <- arima.sim(n=n,list(ar=c(0,0,0,0,.5)),rand.gen=rnorm,sd=0.1)
x <- x[n-n.sub:1]
acf(x,lag.max=maxlag,type="partial")            # check!
armod <- ar(x,order.max=maxlag,method="mle")
armod       # check!
resi <- armod$resid[(1+maxlag):length(armod$resid)]
qqplot(y=resi,x=rnorm(n.sub-maxlag))          # normal residuals
qqline(resi,probs=c(.3,.7))
mean(resi)
sd(resi)                                      # distributionally proper

# For your example:
n <- 2000
n.sub <- 1000
x <- arima.sim(n=n,list(ar=c(.2,0,.1,0,.2,0,0,0,0,.3,0,0,0,0,.1)),rand.gen=rnorm,sd=0.1)
x <- x[n-n.sub:1]


Page not getting redirected properly

Question: I'm only using i18n and not Entity Translation.
I've an English version of page set as front page( node/page1).
I've restarted working on my multilingual site after 2 months and previously it was working fine.
Earlier I had added French, German, etc translated version of this page.
So if I go to mysite.com/de or mysite.com/fr those translated pages are shown automatically(in short existing translated pages are getting redirected correctly).
But now (after 2 months) when I add translation for untranslated languages like "it" then mysite.com/it does not redirect to the Italian version of the home page.
I've Global Redirect, Translation Redirect enabled. I've also tried clearing all cache several times.
What could be the problem?
Comment: I know it is stupid question, but in a case of "usually worked for me" I just have to ask it. Have you thoroughly cleared chaches after adding new language? And considered regenerating aliases, and so on?
Comment: Looks like a bugreport to me... Have you tried to play with disabling one of your modules and seeing if others work then? Also be advised that [if you set 404](http://drupal.stackexchange.com/q/110651/16495), you may be deleting redirection headers, as you can have only one status header.
Comment: not using anything like 404 to this site.
Comment: I tried clearing all cache several times. I had already downloaded and enabled some 18 languages. So Italian was already there. Adding a new Vietnamese or Italian or so page(I mean a new node) will not redirect the site.com/it or site.com/vi to their node versions. I've restarted work in my site after 2 months and it was working fine earlier.
Answer: Your problem might be because of the "language detection" configuration.
So check this configuration via Configuration -> Languages -> detection and selection: the order should be 'URL, Default, User', and not something like 'Default, URL, User'.

Page not getting redirected properly


Get individual features importance with XGBoost

Question: I have trained an XGBoost binary classifier and I would like to extract features importance for each observation I give to the model (I already have global features importance).
More specifically, I am looking for a way to determine, for each instance given to the model, which features have the most impact and make the input belong to one class or another. I would like to know something like the top 5 features which make the observation belong to some class and indications on how I should modify these 5 features so that the probability of belonging to this class decreases or increases.
For example, let's say my model predicts whether a house costs more than 100,000 dollars (this is the positive class) based on its location, surface and number of bedrooms. I give it the following input: London, 400 square foots, 4 bedrooms and my model predicts a probability of 56% for the house to be in the positive class. I am looking for a Python module or a function that would show the most influential features for each observation.
Answer: There are several different methods for that. You can use native importance measures from xgboost library. Check this answer: https://stackoverflow.com/a/51645066/3733974
You can also look for alternative methods. Here are two of them I can recommend:

Permutation importance. Basically, you permute the values of each of your predictor and check the loss of accuracy for each of them. Here is an article explaining it:
SHAP (SHapley Additive exPlanation) values  A nice article that explains SHAP values, as well as the native importance measures of XGBoost:


Expressing "a subobject is a union of other subobjects" in a topos

Question: Let $(\mathsf C,J)$ be a site. Let $U\rightarrowtail X$. Suppose there's a family of subobjects $(U_i\rightarrowtail X)$ which factors through $U\rightarrowtail X$ such that the factorized family $$(U_i\rightarrowtail U)$$ is a $J$-covering family.
If the site is superextensive, is it true $\coprod U_i\to U$ is an isomorphism?
Answer: The map $\coprod U_i \rightarrow U$ will in general be a cover, that is an epimorphism in the topos. But it has no reasons to be a monomorphism, basically the $U_i$ can overlap.
A trivial example of this you can have only two $U_i$ with $U_1=U_2=U$.
$U_1,U_2 \rightarrow U$ is obviously a cover, but $U_1 \coprod U_2 \rightarrow U$ is not going to be an isomorphism unless $U$ is the initial object.
What is true (without any assumption on the site), is that in the topos, the object represented by $U$ can be written as a colimit of the diagram with all the $U_i$ and all the $U_i \times_{U} U_j$ with maps the projections from $U_i \times_{U} U_j$ to $U_i$ and $U_j$. This corresponds to gluing the $U_i$ together but identifying their intersections/overlap ($U_i \times_U U_j$ is basically the intersection of $U_i$ and $U_j$)
The proof of this is almost trivial: if you wrote down the universal property of this colimit for morphism into an object $X$ of the topos you get exactly the sheaf condition for $X$ and the covering of $U$ by the $U_i$.
If the site is subcanonical and the those fiber products exists in the site then this colimit also holds in the site.
If the site is subcanonical and the fiber product are not necessarily present in the site you still get a colimit of this kind by replacing $U_i \times_U U_j$ by some class of object that have map to the $U_i \times_U U_j$ exactly as when forulating the sheaf condition on a site where there is no fiber product.
If the site is not subcanonical you can basically never deduce anythings on its underlying category from properties of the topos, so there is nothing you can do here.
Comment: Ah, silly me. Accidentally looked at the coproduct as a union. Thanks!!


Como ordenar uma lista pelo options select vuejs

Question: Boa noite, ja fiz essa pergunta, mas vou tentar melhora-la, estou desenvolvendo em laravel vue e preciso apenas jogar a função de ordenar para o option dentro do select, é algo simples, mas que eu não estou encontrando o problema, se alguém puder me ajudar agradeço muito

estou chamando o método da função dentro do th  com v-on:click

só que eu quero altera-la para o usuário setar pelo option no select, assim:

E o código do mesmo se encontra assim

e a lógica se encontra assim
Comment: Se deseja melhorar a pergunta, basta editar a pergunta original (em vez de duplicá-la). Além disso, se quer melhorar, coloque o código como texto e não como imagens (leia o [FAQ](https://pt.meta.stackoverflow.com/a/5485/112052) para entender melhor)
Comment: Resolvi da seguinte maneita

{{titulo}}
Answer: O v-for tem que estar dentro de uma tag option e esta tem que está dentro de um select. E o select tem que ser colocado dentro da tag th para que você consiga concretizar um formato de seleção de opção para ordenação da coluna.
E o v-on:click tem que fazer referência a cada option desencadeando uma ação a cada click em cada option.
Pelo menos, foi isso que entendi do seu código.
Até mais e bom trabalho colega.


Correlation between a percentage and a real number

Question: I have two datasets, one containing the percentage of people with flu and one which has the number of searches for Tea-recipes in google.
Problem is, I get different results when i choose to include the percentage number instead of the real number of people with flu.
Im using Excel function Correl(peoplwithflupercentage, teasearches)
My question is, can I somehow use percentages to look for correlation with real numbers.
Like correlation between a dataset (percentage numbers) and another dataset (real numbers)?
I know this probably is a simple question, but  can't seem to find a good example in the forum or google.
Answer: Yes - you can certainly compare the correlation between %'s and whole numbers. The Excel Correl function uses Pearson's $r$ to calculate correlation. The formula for $r$ (found in the link above or here) is invariant to changes in scale and location of your $X$ or $Y$ variables. That is, you can multiply the $X$'s or $Y$'s by a constant and it won't change their correlation.
Here is an example in R:
## random X's and Y's
x <- c(1,2,3,4,5)
y <- c(10,8,6,4,2)
cor(x,y,method='pearson')
## output
[1] -1
## now multiply your whole numbers by a constant to make them proportions
x <- x*0.01
cor(x,y,method='pearson')
## output
[1] -1

Answer: Adding to the answer of @ilanman, yes, you can certainly use correlation between a percentage and a numerical variable.
If (some of) the percentages are close to zero% or 100%, though, there could be an "saturation effect". Lets say the variables are perc and x, and there is really some (causal) connection between x and perc, say, which we could have modelled via a logistic regression model.  Then the linear relationship is really between x and the log odds corresponding to perc.  But however, the log odds function is close to linear except near the limits of zero and one, so except in some very extreme cases, the correlations calculated between x and perc, and between x and (logodds of perc), will be numerically very close.
And, adding to the answer of @Yash, what he shows is a very different phenomenon (and maybe more important). Such a huge difference as 0.1 and 0.9 cannot come from my explanation above, it comes from a large variation in the denominators. If his unemployment data compares countries (or maybe states in the USA), then the denominators will be population size.  So his correlation of 0.1 measures correlation between GDP and % unemplyment, his correlation of 0.9 is in reality more of correlation between GDP and population! If his GDP is total (and not per capita, he did'nt specify) that is not surprising.  So in that case, the two correlations of 0.1 and 0.9 really measures totally different things.
Comment: This was very helpful! Would this example of accidentally measuring the correlation between GDP and population (and thus getting a very high result) be the same theory if you were measuring vote totals against attempts to those voters in different-sized precincts? I'm seeing very high correlations there but nervous that it's because larger precincts have more people and thus there are more of them to reach out to. Cause when I look at % turnout vs % attempted those numbers drop. Hope this was an appropriate use of a clarifying comment on this thread, thanks!
Answer: There is a difference, when I took % for employment growth and GDP in Millions, the result came up as (0.1) but when I changed employment to no of persons in thousands, it worked and got a positive correlation coefficient of (0.9).
Comment: This is no surprise; the variables are different if the denominator of the growth rate was different, as is true in practice. It doesn't bear on the question.


Constrained optimization : constrain1 OR constraint2

Question: I want to solve a constrained optimisation problem of form:
minimize objective function subject to
constraint1 OR constraint2 or Constraint3
My present methodology is to solve the objective function by consdiering the first constraint only and obtain the optimal function values (say v1). And then solve the objective function considering only the second constraint and obtain optimal function value v2 and then similarly v3.
Then find the $\min\{v1,v2,v3\}$.
Or is there is a better way to solve it.
A random example:
$$
\mbox{minimize}\; x + y+ z
$$
s.t
$$2x + y \le  4  \\
OR -3x + -67y \ge  56
$$
Answer: You can do this by using an extra binary variable $\delta$ that equals $1$ if and only if the first constraint is met. Use the following constraints:
$$
2x+y\le 4 +M(1-\delta) \\
-3x -67 y \ge 56 -M \delta \\
\delta \in \{0,1\}
$$
$M$ is a large constant. You can see that if $\delta$ is set to $1$ the problem is equivalent to
$$
2x+y\le 4 \\
-3x -67 y \ge 56 -M  \\
$$
in other words the first constraint is required, but the second one is switched off as $56-M$ is very small.
If $\delta = 0$, the problem becomes
$$
2x+y\le 4 +M \\
-3x -67 y \ge 56
$$
and in this case the second constraint is required, and the first one is switched off, as $4+M$ is very large.
The solver will set the best value for $\delta$ and thus automatically consider the best scenario possible.


Add VBO checkbox to send Bulk emails in Admin

Question: We are using Enterprise Event module in Drupal 7.  I checked the Views and module files but not able to locate the file as from where Manage Registration Page is formed. Please guide me how I can add VBO checkbox to send Bulk emails in Admin > Content > Event > Edit > Manage Registration Tab.
I am using enterprise event module in which people register for upcoming events. Registration module is used for registration. Admin can view registrants for  specific event.  I need to add a checkbox so that admin can send bulk emails to those registrants.

Please help still hoping for some solution.
Comment: question is not clear for those that have not used enterprise event module before. So you just want to know how to use the vbo module?
Answer: This is how you do it:

Go to Structure > Views and locate the Test Event view.
Click the Edit button.
Find the Fields display and click the Add button.

Filter the available fields by Bulk Operations and select a field you need, e.g. Bulk Operations: User.

Now the settings for this field show up. Scroll down to Selected Bulk Operations and select Send Email.

Click Apply.
Don't forget to save your view.
Now you should have a checkbox and you can select Send Email from a drop down menu.

I'd personaly would not use the VBO field but the Views Send module which is a bit easier to use. If you have the Views Send module, add the field Global: Send Email instead of the VBO field and proceed as described above.


Fibonacci Sequence Visual Basic

Question: I have a quick question about another Visual Basic assignment I'm working on. I have all the code and everything has gone smoothly so far. The app is meant to display the first 100 Fibonacci numbers in a list box, adding the two previously displayed numbers to get the next in a loop. The only problem is that when I hit the button to display the code, the loop continues, and doesn't just stop at 100 numbers. Where did I go wrong?
Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click
    Dim dblA As Double = 0
    Dim dblB As Double = 1
    Dim dblC As Double
    Dim intCounter As Integer

    lstSequence.Items.Add(dblA.ToString)
    lstSequence.Items.Add(dblB.ToString)

    For intCounter = 1 To 100
        dblC = dblA + dblB
        dblA = dblB
        dblB = dblC
        lstSequence.Items.Add(dblC.ToString)
    Next
End Sub

Comment: By the way, why are you using type `Double`? You're only using whole numbers and Fibonacci Numbers are specifically whole numbers so why would you choose `Double` to represent them?
Comment: Debug your code.  You don't work out what is wrong with code simply by reading it.  That is a first step but, if the issue isn't obvious, the next step is to execute the code and watch it in action, i.e. debug it. If you don't know how to debug properly, i.e. using breakpoints, stepping through the code an examining state using tool windows like Autos, Watch and Immediate, then now is the time to learn.  Debugging is an essential tool for a developer.  Without it, you're just a code-writer.
Comment: Yes, it does. See [BigInteger](https://learn.microsoft.com/en-us/dotnet/api/system.numerics.biginteger?view=netframework-4.7.2)
Comment: I just ran you code and nothing is wrong. It works. I would suggest debugging this problem.
Answer: I just tried this.  It works fine.
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim a As Integer = 0
        Dim b As Integer = 1
        Dim fib As Integer
        Dim userinput, i As Integer
        userinput = InputBox("how many interations?")
        i = userinput
        ListView1.Items.Add(1)
        Do
            fib = a + b
            a = b
            b = fib
            ListView1.Items.Add(fib)
            i = i + 1
        Loop While fib < i

    End Sub
End Class

Fibonacci Sequence Visual Basic


Family of sets, intersection of disks

Question: I am working with the following family of sets
$$A_t = \{(x, y) \in \mathbb{R^2}: \exists \ s \in\mathbb{R} \ [(x-s)^2 + (y-t)^2 \le t^2]\}, t \in \mathbb{R}$$
I am trying to find ${\bigcap_{t>0}{A_t}}$. I have noticed this is basically an equation of a disk with the center in $(s,t)$ and a radius $t$. My intuition is that:

For a specific $t$, the family is actually $\{(x,y): 0 \le y \le 2t\}$, so a part of the $\mathbb{R^2}$ plane limited by the x axis and $y = 2t$.
Letting $t$ vary we have a family of sets with the common element being $y = 0$ - the x-axis.

I would appreciate any comments or hints.
Answer: Note that $A_t = \mathbb{R} \times [0,2t]$. Then the intersection is just
$\cap_t A_t = \mathbb{R} \times \{0\}$.
Comment: It is the same whether you have $t>0$ or $t \ge 0$. Just as $\cap_{t >0} [0,t] = \cap_{t \ge0} [0,t] = \{0\}$.

Family of sets, intersection of disks