select case getting item from a combo box not working

Question: The expected result is when i click the add button after selecting the homeroom, place and event it wont give me the message box and then when i click the display button it will put it into the selected homeroom and the score into the list box. but when i click add the message box apears and the array doesnt get filled. i think its a problem with the case selects not realising that the things are selected.
Imports System.Xml
Public Class Form1
    Dim Sting As String
    Dim score1 As Integer
    Dim score2 As Integer
    Dim score3 As Integer
    Dim score4 As Integer
    Dim score5 As Integer
    Dim score6 As Integer
    Dim score7 As Integer
    Dim score8 As Integer

    Dim intcounter1 As Integer = 0
    Dim points1(intcounter1) As Integer
    Dim intcounter2 As Integer = 0
    Dim points2(intcounter2) As Integer
    Dim intcounter3 As Integer = 0
    Dim points3(intcounter3) As Integer
    Dim intcounter4 As Integer = 0
    Dim points4(intcounter4) As Integer
    Dim intcounter5 As Integer = 0
    Dim points5(intcounter5) As Integer
    Dim intcounter6 As Integer = 0
    Dim points6(intcounter6) As Integer
    Dim intcounter7 As Integer = 0
    Dim points7(intcounter7) As Integer
    Dim intcounter8 As Integer = 0
    Dim points8(intcounter8) As Integer
    Dim place As Integer
    Dim reader As New XmlTextReader("score.txt")
    Dim writer As New XmlTextWriter("score.txt", System.Text.Encoding.UTF8)

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        cmbHomeroom.Items.Add("7.1")
        cmbHomeroom.Items.Add("7.2")
        cmbHomeroom.Items.Add("7.3")
        cmbHomeroom.Items.Add("7.4")
        cmbHomeroom.Items.Add("7.5")
        cmbHomeroom.Items.Add("7.6")
        cmbHomeroom.Items.Add("7.7")
        cmbHomeroom.Items.Add("7.8")

        cmbPlace.Items.Add("1")
        cmbPlace.Items.Add("2")
        cmbPlace.Items.Add("3")
        cmbPlace.Items.Add("4")
        cmbPlace.Items.Add("5")
        cmbPlace.Items.Add("over 5")

    End Sub

    Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
        If rdbB25.Checked Or rdbF25.Checked Then
            Select Case Sting
                Case cmbPlace.Text = "1"
                    place = 20
                Case cmbPlace.Text = "2"
                    place = 10
                Case cmbPlace.Text = "3"
                    place = 5
                Case cmbPlace.Text = "4"
                    place = 4
                Case cmbPlace.Text = "5"
                    place = 3
                Case cmbPlace.Text = "over 5"
                    place = 1
                Case Else
                    MessageBox.Show("Please select a Place")
            End Select
        End If
        If rdbB50.Checked Or rdbF50.Checked Then
            Select Case Sting
                Case cmbPlace.Text = "1"
                    place = 25
                Case cmbPlace.Text = "2"
                    place = 15
                Case cmbPlace.Text = "3"
                    place = 10
                Case cmbPlace.Text = "4"
                    place = 6
                Case cmbPlace.Text = "5"
                    place = 4
                Case cmbPlace.Text = "over 5"
                    place = 2
                Case Else
                    MessageBox.Show("Please select a Place")
            End Select
        End If

        Select Case Sting
            Case cmbHomeroom.Text = "7.1"
                points1(intcounter1) = place
                intcounter1 = intcounter1 + 1
            Case cmbHomeroom.Text = "7.2"
                points2(intcounter2) = place
                intcounter2 = intcounter1 + 1
            Case cmbHomeroom.Text = "7.3"
                points3(intcounter3) = place
                intcounter3 = intcounter1 + 1
            Case cmbHomeroom.Text = "7.4"
                points4(intcounter4) = place
                intcounter4 = intcounter1 + 1
            Case cmbHomeroom.Text = "7.5"
                points5(intcounter5) = place
                intcounter5 = intcounter1 + 1
            Case cmbHomeroom.Text = "7.6"
                points6(intcounter6) = place
                intcounter6 = intcounter1 + 1
            Case cmbHomeroom.Text = "7.7"
                points7(intcounter7) = place
                intcounter7 = intcounter1 + 1
            Case cmbHomeroom.Text = "7.8"
                points8(intcounter8) = place
                intcounter8 = intcounter1 + 1
            Case Else
                MessageBox.Show("Please select a homeroom")
        End Select

    End Sub

    Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click

        lstDisplay.Items.Add("Homerooms:   Points:")
        lstDisplay.Items.Add("7.1            " & score1)

        lstDisplay.Items.Add(cmbHomeroom.Text)
        lstDisplay.Items.Add(cmbPlace.Text)
    End Sub
End Class

Comment: For the record, there is far more code there than is necessary and that makes it harder to address the issue. Please read [this](https://stackoverflow.com/help/minimal-reproducible-example) and keep it in mind for future questions. If you need to create a simple test project in order to do that, that's what you do. You should often be doing just that as part of your own efforts to resolve an issue anyway. If you strip away all the noise and look at only what is specifically relevant to the issue, the solution is often staring you in the face but you just couldn't see it through the clutter.
Answer: I managed to fix it by changing the select case
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
If rdbB25.Checked Or rdbF25.Checked Then
    Select Case cmbPlace.Text
        Case "1"
            place = 20
        Case "2"
            place = 10
        Case "3"
            place = 5
        Case "4"
            place = 4
        Case "5"
            place = 3
        Case "over 5"
            place = 1
        Case Else
            MessageBox.Show("Please select a Place")
    End Select
End If
If rdbB50.Checked Or rdbF50.Checked Then
    Select Case cmbPlace.Text
        Case "1"
            place = 25
        Case "2"
            place = 15
        Case "3"
            place = 10
        Case "4"
            place = 6
        Case "5"
            place = 4
        Case "over 5"
            place = 2
        Case Else
            MessageBox.Show("Please select a Place")
    End Select
End If

Select Case cmbHomeroom.Text
    Case "7.1"
        points1(intcounter1) = place
        intcounter1 = intcounter1 + 1
    Case "7.2"
        points2(intcounter2) = place
        intcounter2 = intcounter2 + 1
    Case "7.3"
        points3(intcounter3) = place
        intcounter3 = intcounter3 + 1
    Case "7.4"
        points4(intcounter4) = place
        intcounter4 = intcounter4 + 1
    Case "7.5"
        points5(intcounter5) = place
        intcounter5 = intcounter5 + 1
    Case "7.6"
        points6(intcounter6) = place
        intcounter6 = intcounter6 + 1
    Case "7.7"
        points7(intcounter7) = place
        intcounter7 = intcounter7 + 1
    Case "7.8"
        points8(intcounter8) = place
        intcounter8 = intcounter8 + 1
    Case Else
        MessageBox.Show("Please select a homeroom")
End Select

End Sub
Comment: Unfortunately this answer suffers from the same clutter as the question. It is probably a good solution, but there is no explanation as to what you changed or why it fixed the issue. A short description of the problem you identified and how you solved it would greatly improve this answer.


Are frequency weights and sampling weights, in practice, the same thing?

Question: Frequency weights indicate how many cases in the population a given
observation represents.
Sampling weights indicate the probability (sometimes the inverse of the probability) of an observation being sampled. This example from this document is very clear:

[Assume] the population was divided in two clusters, rural and
  urban areas.  Half of the urban population was interviewed while only one tenth
  of the rural population was interviewed. We can see it as follows: one individual
  interviewed in an urban area represents 2 people while an individual interviewed in a
  rural area represents 10 persons. In order to take this into account, each observation
  will be weighted by the inverse of its probability of being sampled: each rural area
  observation will receive weight 10 and each urban area observation will receive weight.

So, in the example above, the sampling weight will be 2 for the urban individual and 10 for the rural individual. But, if we have a sample of both urban and rural individuals, in order to construct the whole population out of them, we would use frequency weight which are exactly the same as those in the sampling weights, i.e. 2 and 10. Thus, we could simply treat sampling weights are frequency weights. Mathematically, if you were to compute the population average of a given variable, the result would be the same, of course. (The document linked, referring to Stata, says that "Point estimates will be estimated in the exact same way", so Stata treats them identically, for point estimates, of course).
But, is this valid? And can we do the reverse, i.e. treat frequency weights as sampling weights? Following the same logic, you can argue that if one individual represents 2 and other 10 individuals in the population, then this is equivalent as if sampling was clustered/stratified. Or not?
Comment: You are correct, their effect on the estimate is the same. Where they differ is the effect on the standard error of the estimate.
Answer: It is dangerous to think about frequency weights and probability weights as the same... or even similar. In terms of estimation, yes, you would see estimating equations defined as
$$
\sum_{j\in\mbox{ sample}} w_j g(y_j,\theta) = 0 \Rightarrow \hat\theta
$$
but I would never equate probability weights and frequency weights in any text I would write. I very reluctantly explain how to use Stata to produce say histograms with weighted data (because hist does not support [pw]... duh...), but I would put all sorts of red circles around that.
The formula on page 6 for the variance estimator is really obscure, and basically helps nothing; the author is an economist, so he wants to make everything like like an "auxiliary" regression. Instead, I would write things explicitly. First, the "bread" of the sandwich is $X'(\mathop{\rm diag} w_j) X$, the estimate of the population $X'X$ matrix. Second, the "meat" of the sandwich is $\sum_j w_j e_j^2 x_j x_j'$, the estimate of the variance of the estimating equations. Third, the regression degrees of freedom correction may or may not be in place.
To really understand what pweights do (and with all due respect, clustered and stratified samples are very different, so again I would not put these two concepts with a slash in one sentence), you need to go into the foundations of sampling inference. It runs very counter to economists' "the world is a model" viewpoint, and goes with the view that the world is fixed, all $y_i$s and $x_i$s are fixed, and the only randomness is in the sampling inclusion indicators. (Truth be told, when economists talk about "$y_i$ and $x_i$ coming from some undefined population", and then ending up with sandwich formulas, they actually think more like sampling statisticians; more amazing that economists refuse to get familiar with that literature, and invent their own circular propulsion devices instead; the "black" Wooldridge, while an excellent econometrics book, has three wrong definitions in the opening paragraph of the "survey analysis" chapter which is really aggravating as we have to teach economists to unlearn wrong terms and concepts before they can make sense of survey statistics when they start working with surveys and official statistics production.) Sharon Lohr's book and Korn and Graubard are good places to start, and if you want to go (way) deeper into asymptotics and Edgeworth expansions and higher order properties, there's Fuller (same Fuller as Dickey-Fuller test), Mary Thompson and Sarndall et al.
Answer: For reference, Stata treats frequency, sampling and analytic weights identically for point estimates, but not for their variance. Official documentation regarding analytical weights states (where aweights and fweights refer to analytic and frequency weights respectively):

Meanwhile, for sampling weights, the text later on states that (pweights being sampling weights):

The adjustment implied by pweights to the point estimates is the
  same as the adjustment implied by aweights.

The variance are different though, as these sections state.


Change labels text color when input is active

Question: I am trying to accomplish what I have posted below, I have found some things using onChange and onChangeText but no good documentation. Could someone post a good article or an explanation below! Thank you for any insight at all!

  constructor() {
    super();

    this.state = {
      color1: '#FF0000'};}

        {/* Email Input */}
      <Container style = {styles.emailInput}>

        <Form>
          <Item floatingLabel style={{color:this.state.color1}} >
          onFocus={() => this.setState({color1: '#A2A2A2'})}
          onClick={() => this.setState({color1: '##F7018D'})}
          onBlur={() => this.setState({color1: '#A2A2A2'})}

           Email Address
           <Input
          autoCorrect={false}
          autoCapitalize="none"

            />
         </Item>
       </Form>
      </Container>

 emailInput: {
    flex: 1,
    backgroundColor: '#1E2028',
    width: 350,
    position: 'absolute',
    top: 225,
    left: 3

  }

Comment: Here is a similar question which you're looking for.
https://stackoverflow.com/questions/58786281/change-label-color-textinput-react-native-paper-onfocus
Comment: This uses react-native-paper I would rather not have to use that unless I need to
Answer: You may put the following inside the Input
onFocus={() => this.setState({color1: '#0000FF'})}
  onClick={() => this.setState({color1: '#0000FF'})}
  onBlur={() => this.setState({color1: '#FF0000'})}

and then in your style section, use the "this.state.color1" as your text color.
In this way, when the input box is on focus, the textcolor will be changed to blue, and when the user clicks else where, it will become red in color
To give you an example, please try the following
import React, { Component } from 'react';

import {
  StyleSheet,
  View,
  TextInput,
  Text,
} from 'react-native';
//import all the components we are going to use.

export default class App extends Component {

  constructor() {
    super();

    this.state = {
      color1: '#FF0000'};}

  render() {
    return (
      <View style={styles.MainContainer}>
        <TextInput

    style={{color:this.state.color1 , borderWidth: 1,
    borderColor: '#DD0000',}}
placeholder="Type something"
  onFocus={() => this.setState({color1: '#0000FF'})}
  onClick={() => this.setState({color1: '#0000FF'})}
  onBlur={() => this.setState({color1: '#FF0000'})}

        />

<TextInput value="TEST2"/>

      </View>
    );
  }
}

const styles = StyleSheet.create({
  MainContainer: {
    alignItems: 'center',
    flex: 1,
    margin: 10,
    marginTop: 60,
  },

});

you may visit this link to see too:
https://snack.expo.io/71LpKDzvS
Additional information
for your revised codes, please change
 <Item floatingLabel style={{color:this.state.color1}} >
          onFocus={() => this.setState({color1: '#A2A2A2'})}
          onClick={() => this.setState({color1: '##F7018D'})}
          onBlur={() => this.setState({color1: '#A2A2A2'})}

           Email Address
           <Input
          autoCorrect={false}
          autoCapitalize="none"

            />

to
 <Item floatingLabel  >

           Email Address
           <Input
          autoCorrect={false}
          autoCapitalize="none"
          onFocus={() => this.setState({color1: '#A2A2A2'})}
          onClick={() => this.setState({color1: '##F7018D'})}
          onBlur={() => this.setState({color1: '#A2A2A2'})}

            />

to see the effect.
Comment: So I pasted the code you gave me inside the input and in my style section I wrote
```
color: 'this.state.color1'
```

Is that correct? Do I need to import something?
Comment: This gets the job done kinda... I need my label to change color, not the actual input. I have tried playing around with it in my label and my Item, but cant quite get anything going. I feel like you have given be enough information! I am close I can feel it.
Comment: I updated my attempt at the slight change, I cant figure it out though, Mind looking at my updated code and helping?
Comment: please see the "additional information" part and try. Thanks
Comment: Amazing! Thank you so much!! I really appreciate your time.


KeyDown Event Not Firing After Drag Drop Operation

Question: I have a custom editable text box in a template for a TreeViewItem. The items
can be edited when F2 key is pressed. If not in edit mode, when the item is
clicked, a drag and drop operation is triggered.  This is my template for the
editable tree view item:
<code>        <HierarchicalDataTemplate x:Key="editableHierarchyNodeTemplate"
                              ItemsSource="{Binding ContainedParameter}"
                              ItemTemplateSelector="{StaticResource treeItemTemplateSelector}">

        <ut:EditBox Text="{Binding DisplayName, Mode=TwoWay}" PreviewMouseLeftButtonDown="EditBox_PreviewMouseDown" PreviewKeyDown="EditBox_KeyDown"/>
    </HierarchicalDataTemplate>
</code>
The EditBox is custom control which simply switches from a "read only" to editable TextBox. In the "EditBox_KeyDown" method I simply set the IsInEditMode property of the EditBox to true, and it does its magic. However, this event is not fired
after I handle the "PreviewMouseLeftButtonDown" as follows:
<code>  private void EditBox_PreviewMouseDown(object sender, MouseButtonEventArgs e)
    {
        DataObject data = (new DataObject());
        data.SetData("Parameter", (sender as FrameworkElement).DataContext as Parameter);
        DragDrop.DoDragDrop(this, data, DragDropEffects.All);
    }
</code>
I assume that, once the drag drop operation is started, it simply absorbs all key
events. How do I cancel this?
Comment: Probably a focus problem.  You'd normally set the focus on the control when you left-click it and then it gets the key events.  But that no longer happens, you swallow the left click by starting a D+D.  Workaround is to only call DoDragDrop() after the mouse has moved far enough.  Record the MouseDown position and use MouseMove to detect it moving while the left button is down.
Comment: handled = false ? tried ?
Comment: That is a good idea, but won't the focus be swallowed anyway, no matter where do I start the drag and drop operation?
Answer: The problem was, in fact, the lost focus. Important part of solving the issue was that my EditBox was displaying uneditable TextBox when the items is not being edited. TextBox is a focusable control. I chnaged this to TextBlock, which is not focusable.
For drag and drop operations I ended up using the following approach:
http://www.wpftutorial.net/DragAndDrop.html
The combination of these two changes solved the problem.


Why are ROC curves and AUC values not always relevant?

Question: So I have read in posts and in literature (Frank Harrel - Regression Modeling
Strategies fx) that depending on what you do, ROC curves and AUC values are not always relevant, but often written in papers or reports anyways, and sometimes as the "ground truth" to how good a model actually is. My problem is that I'm not entirely sure I understand why it's not always a good thing?
I mean, if I have a model (based on binary outcomes fx) that predicts some value for some input parameters in the model, I would think it made much sense that the highest predicted values should "align" with the outcomes, i.e. a high AUC value if it does indeed predict well. That makes sense to me. But maybe I have misunderstood/overlooked something?
Comment: A relevant thread: https://stats.stackexchange.com/q/414349/121522
Answer: If you look at a contigency table and the various metrics involved you will see that the AUROC curve uses the TPR and FPR metrics, which are often times relevant. However, sometimes you may want to look at it from a different perspective, for ex. the FPR and TNR metrics.


Pytorch does not backpropagate through a iterative tensor construction

Question: I am currently trying to build a tensor iteratively in Pytorch.
Sadly the backprop does not work with the inplace operation in the loop. I already tried equivalent programs with stack for example. Does somebody know how I could build the tensor with a working backprop?
This is a minimal example which produces the error:
import torch

k=2
a =torch.Tensor([10,20])
a.requires_grad_(True)
b = torch.Tensor([10,20])
b.requires_grad_(True)

batch_size = a.size()[0]
uniform_samples = Uniform(torch.tensor([0.0]), torch.tensor([1.0])).rsample(torch.tensor([batch_size,k])).view(-1,k)
exp_a = 1/a
exp_b = 1/b
km = (1- uniform_samples.pow(exp_b)).pow(exp_a)

sticks = torch.zeros(batch_size,k)
remaining_sticks = torch.ones_like(km[:,0])
for i in range(0,k-1):
    sticks[:,i] = remaining_sticks * km[:,i]
    remaining_sticks *= (1-km[:,i])
sticks[:,k-1] = remaining_sticks
latent_variables = sticks

latent_variables.sum().backward()

The stack trace:
/opt/conda/conda-bld/pytorch_1570910687230/work/torch/csrc/autograd/python_anomaly_mode.cpp:57: UserWarning: Traceback of forward call that caused the error:
  File "/opt/conda/lib/python3.6/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/opt/conda/lib/python3.6/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/opt/conda/lib/python3.6/site-packages/ipykernel_launcher.py", line 16, in <module>
    app.launch_new_instance()
  File "/opt/conda/lib/python3.6/site-packages/traitlets/config/application.py", line 664, in launch_instance
    app.start()
  File "/opt/conda/lib/python3.6/site-packages/ipykernel/kernelapp.py", line 563, in start
    self.io_loop.start()
  File "/opt/conda/lib/python3.6/site-packages/tornado/platform/asyncio.py", line 148, in start
    self.asyncio_loop.run_forever()
  File "/opt/conda/lib/python3.6/asyncio/base_events.py", line 438, in run_forever
    self._run_once()
  File "/opt/conda/lib/python3.6/asyncio/base_events.py", line 1451, in _run_once
    handle._run()
  File "/opt/conda/lib/python3.6/asyncio/events.py", line 145, in _run
    self._callback(*self._args)
  File "/opt/conda/lib/python3.6/site-packages/tornado/ioloop.py", line 690, in <lambda>
    lambda f: self._run_callback(functools.partial(callback, future))
  File "/opt/conda/lib/python3.6/site-packages/tornado/ioloop.py", line 743, in _run_callback
    ret = callback()
  File "/opt/conda/lib/python3.6/site-packages/tornado/gen.py", line 787, in inner
    self.run()
  File "/opt/conda/lib/python3.6/site-packages/tornado/gen.py", line 748, in run
    yielded = self.gen.send(value)
  File "/opt/conda/lib/python3.6/site-packages/ipykernel/kernelbase.py", line 361, in process_one
    yield gen.maybe_future(dispatch(*args))
  File "/opt/conda/lib/python3.6/site-packages/tornado/gen.py", line 209, in wrapper
    yielded = next(result)
  File "/opt/conda/lib/python3.6/site-packages/ipykernel/kernelbase.py", line 268, in dispatch_shell
    yield gen.maybe_future(handler(stream, idents, msg))
  File "/opt/conda/lib/python3.6/site-packages/tornado/gen.py", line 209, in wrapper
    yielded = next(result)
  File "/opt/conda/lib/python3.6/site-packages/ipykernel/kernelbase.py", line 541, in execute_request
    user_expressions, allow_stdin,
  File "/opt/conda/lib/python3.6/site-packages/tornado/gen.py", line 209, in wrapper
    yielded = next(result)
  File "/opt/conda/lib/python3.6/site-packages/ipykernel/ipkernel.py", line 300, in do_execute
    res = shell.run_cell(code, store_history=store_history, silent=silent)
  File "/opt/conda/lib/python3.6/site-packages/ipykernel/zmqshell.py", line 536, in run_cell
    return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
  File "/opt/conda/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2855, in run_cell
    raw_cell, store_history, silent, shell_futures)
  File "/opt/conda/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2881, in _run_cell
    return runner(coro)
  File "/opt/conda/lib/python3.6/site-packages/IPython/core/async_helpers.py", line 68, in _pseudo_sync_runner
    coro.send(None)
  File "/opt/conda/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 3058, in run_cell_async
    interactivity=interactivity, compiler=compiler, result=result)
  File "/opt/conda/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 3249, in run_ast_nodes
    if (await self.run_code(code, result,  async_=asy)):
  File "/opt/conda/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 3326, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-124-2bbdbc3af797>", line 16, in <module>
    sticks[:,i] = remaining_sticks * km[:,i]

---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-124-2bbdbc3af797> in <module>
     19 latent_variables = sticks
     20
---> 21 latent_variables.sum().backward()

/opt/conda/lib/python3.6/site-packages/torch/tensor.py in backward(self, gradient, retain_graph, create_graph)
    148                 products. Defaults to ``False``.
    149         """
--> 150         torch.autograd.backward(self, gradient, retain_graph, create_graph)
    151
    152     def register_hook(self, hook):

/opt/conda/lib/python3.6/site-packages/torch/autograd/__init__.py in backward(tensors, grad_tensors, retain_graph, create_graph, grad_variables)
     97     Variable._execution_engine.run_backward(
     98         tensors, grad_tensors, retain_graph, create_graph,
---> 99         allow_unreachable=True)  # allow_unreachable flag
    100
    101

RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.FloatTensor [2]] is at version 1; expected version 0 instead. Hint: the backtrace further above shows the operation that failed to compute its gradient. The variable in question was changed in there or anywhere later. Good luck!

Answer: You can not do any inplace operations. So you may not use *= in your algorithm.
k = 2
a = torch.tensor(np.array([10.,20]), requires_grad=True).float()
b = torch.tensor(np.array([10.,20]), requires_grad=True).float()

batch_size = a.size()[0]
uniform_samples = Uniform(torch.tensor([0.]), torch.tensor([1.])).rsample(torch.tensor([batch_size,k])).view(-1,k)
exp_a = 1/a
exp_b = 1/b
km = (1 - uniform_samples**exp_b)**exp_a

sticks = torch.zeros(batch_size,k)
remaining_sticks = torch.ones_like(km[:,0])
for i in range(0,k-1):
    sticks[:,i] = remaining_sticks * km[:,i]
    remaining_sticks = remaining_sticks * (1-km[:,i])
sticks[:,k-1] = remaining_sticks
latent_variables = sticks
latent_variables = torch.sum(latent_variables)

latent_variables.backward()


How can I configure DHCP server to issue the same fixed-address by matching with the client identifier in the discover message

Question: I am able to config fixed ip address with hardware ethernet options, but i am trying to assign fixed ip based on client id(option 61) from DISCOVER message. I tried with below configs , but it doesn't help.
host virtual_1
{
      dhcp-client-identifier = 00:00:00:00:01
      option routers 10.1.1.49;
      option host-name "virtual1";
      #hardware ethernet 00:01:02:03:04:05;
      fixed-address 10.1.1.179;
      option ntp-servers  10.1.1.49;
}

Answer: I think you have the syntax wrong.
Here is how I do it (based on a readable client id)
host aaa {
    option dhcp-client-identifier = "XYZ-aaa";
    fixed-address 220.127.116.11;
}

The "aaa" and "XYZ-aaa" are arbitrary -- you choose;
I use dhclient, so I have:
send dhcp-client-identifier "XYZ-aaa";

in the /etc/dhcp/dhclient.conf file


get the image which is already been downloaded and cached using glide library

Question: I am using glide library to download and cache the images. on click of Imageview I need to pass the downloaded image from this to next activity. In the next activity I have an another Imageview which will display the image that was coming the current activity. So, how to get the cached image.
Thanks in advance.
Answer: You have to pass image url throgh Intent like;
 Intent i = new Intent(getApplicationContext(),SecondActivity.class);
 i.putExtra("image_url", image_url);
 startActivity(i);

SecondActivity
Intent i = getIntent();
id= i.getStringExtra("image_url");

set url to ImageView using Glide;
Glide.with(context)
.load(Uri.parse(id))
.into(imageView);

Comment: @thanks for your kind response. I tried with passing image url. it is not taking the cache image. instead, it download the image from the url.
Answer: Glide doesn't support directly accessing the cache by design. Cache is a transparent storage, meaning you don't need to know about it. Also in Glide the caching is much more fine grained than just the url as key, see EngineKey.
So the solution is to load normally and it will be loaded from the cache if it's there, otherwise downloaded and then loaded. Look into .diskCacheStrategy() for more control as to what gets cached.
Is this offline mode? If so check out the comments in Ensuring That Images Loaded Only Come From Disk Cache on 12 June 2015
For other use cases see the network of related issues Check here .
Answer: You have to pass image url throgh Intent like;
Intent i = new Intent(getApplicationContext(),SecondActivity.class);
 i.putExtra("url", url);
 startActivity(i);

SecondActivity
Intent i = getIntent();
id= i.getStringExtra("image_url");

**When I need to show cached image, I use the same url and**

DiskCacheStrategy.SOURCE:
Glide.with(this)
    .load(url)
    .diskCacheStrategy(DiskCacheStrategy.SOURCE)
    .into(imageView);


onMouseUp and onClick events conflicting

Question: i have a scrollbar and i want to scroll by 40px when clicking on a button , and when holding that same button, it scrolls continuously
So i used onClick event for a single walk of 40px
and i used onMouseDown and onMouseUp for the continuous scrolling effect
The problem is that onMouseUp fires the onClick event too .. so the scroll bar moves for 40px more when we release the mouse button and this gives a bad effect
i used setInterval inside onMouseDown :
clickScroll = () => {
    const slider : HTMLElement = this.state.scrollRef.current;
    slider.scrollBy(40, 0)
}

holdScroll = (type : string) => {
    const slider : HTMLElement = this.state.scrollRef.current;
    this.setState({
        interval : setInterval(() => {
            slider.scrollBy(walk, 0)
        }, 100)
    })
}

stopHoldScroll = () => {
    clearInterval(this.state.interval);
}

And my button :
<Button onClick={this.clickScroll}
  onMouseDown={this.holdScroll}
  onMouseUp={this.stopHoldScroll}>

</Button>

Any idea about how to dissociate these 2 differents effects ?
thanks
Comment: You can actually just use mousedown/up. To get the click functionality, start a timer on mousedown, and then if there is less than say, 100ms, one mouseup, fire the clickScroll code and clear the interval
Comment: thank you it helped me ! see my new answer
Answer: I finally found a way to do it ! thanks to Jacques for the idea
we can combine setTimeout and setInterval to create a small difference between a click and holding button
The boolean can indicate us inside onMouseUp if we were holding or just clicking ! it turns true after 300ms of holding, if not then it's just a click
    const slider : HTMLElement = this.state.refs.current;
    scrollHold = () => {
        this.setState({
            timer: setTimeout(() => {
                this.setState({
                    interval : setInterval(() => {
                        slider.scrollBy(8, 0)
                    }, 20),
                    holded: true
                })
            },300)
        })
    }
    stopScroll = () => {
        if (!this.state.holded){
            this.state.current.scrollBy(40, 0)
        }
        clearTimeout(this.state.timer)
        clearInterval(this.state.interval);
        this.setState({ holded: false })
    }

<Button
  onMouseDown={this.scrollHold}
  onMouseUp={this.stopScroll}>

</Button>


Dynamic view listing nodes in proximity dependent on taxonomy term in url - which is not attached to the node itself

Question: I think what I want is quite complex, but maybe someone can help me with some basics of it.
In d7 I have a content type and each node uses address field and via geocoder creates the geo data for that node. I use taxonomy terms here to categorize the node (eg: shop, restaurant, hotel, etc ..) and some nodes may have multiple categories added as they may be multiple types at the same time(one may be a restaurant as well as hotel).
I have created a taxonomy tree as such:
country -> city, eg:
england -> london
        -> manchester
        -> newcastle

Each city also has geo data attached to it. The country and city will be used in the url to filter the results based on a set proximity.
So, for example I could have this url
www.example.com/england/london/restaurant

which is equal to (for examples sake)
www.example.com/country/$2/$3

The country page is a static page that may list taxonomy terms (cities) for that country.
The next page up - selecting the city from the country page - does not yet display a view, but gives options for which category the node is in (this taxonomy term is attached to the node (Shop, Restaurant, etc ..))
Now I want to create a view that uses term $2 to set the location from which to start the proximity search from (the geo data is already added to the taxonomy field for cities and mustn't first get geocoded from the city name)
Then term $3 is the category which is attached to the node.
It then displays all the nodes from that category at a  previously set distance (radius) away from the cities geo data. I presume I can either create an admin field where the distance can be set or simply hard code it in the module.
So, I am quite new to creating my own custom module and apart from field api I have not had much experience with other drupal api's - especially the views api.
Here is what I need to do - as far as I am aware:
Create a custom module - I don't think I can get around that - that:
1) gets the $2 and the attached geodata
2) creates a view for all nodes with taxonomy term $3 attached to it and filters them using proximity to only show nodes in a XX km radius from the geo point supplied by $2.
  This obviously includes converting lat/long to distances from the set point...
3) I want to be able to display a proximity slider so the radius value can be changed and the view refreshes.
I know this sounds like a massive job, but I thought that maybe I could do some of it directly in views and then maybe use some alter_hooks to add queries (for example to grab the geo data for $2)...
Can anyone help me with this, or give me some tips on how this can be done?
I just need some sort of strating point as I am totally new to this. I would also supply any code written back to the community and document my processes for others to follow.
Many thanks in advance.
Answer: This is a broad question and becomes difficult to answer clearly. There are too many things to do and too many details to resolve. It looks a bit like you are trying to eat an elephant with too many missing teeth. I agree that you will need to create a custom module and by the description you gave, you will need knowledge of php for server side (pre display) and Javascript for client side action (after display). The first thing to do is get do some exploring in the structure of Drupal and how it operates.  From my own experience I know that a couple months of exploration has made a tremendous difference in my ability to solve a problem like this. Do you have any programming experience? If not start with php basics. Then move on to Drupal.
There is an excellent video tutorial series at buildamodule.com.  It charges for some of its content, but it covers a lot of ground.  Building a module will require php/mysql expertise (book:Beginning PHP and SQL by W. Jason Gilmore), an understanding of Drupal operations (book: The Definitive Guide to Drupal 7 publisher:Apress) and a solid knowledge of the key modules (book: Drupal Building Blocks by Earl & Lynette Miles).
You'll know your ready when you find yourself looking forward to writing a custom module.
Comment: Thanks for your input again. I will take a look at that book, although I have seen that it is written for D6, but there shouldn't be too many difference in the code to adapt it to D7. I guess my plan of action is to first write a function to analyse the url and grab the tid from it, then query the tax_geo field for that tid and return the geodata for that tax term. then i'll be a little further and can reevaluate where to go next...
Comment: Hi Joe and thanks for your input! Yes, I have previous experience. I have recently written a field type module (my first ever: http://drupal.org/sandbox/tecjam/1320886) - for the same project -  I have coded php (home taught) for the past 5-6 years on and off. I built my first drupal site with D5, but I didn't require many new functions for this - just a download counter / direct link checker / download script which was easily implemented. My main areas are theming / css3 and xhtml stuff and creating drupal themes from .psd files. I do have drupal books, but none delve into views in detail ...
Comment: I have also watched some talks from past drupal-cons on archive.org over the past few days, which have all been excellent helping me to understand some basics behind hooks and ['#ajax'] calls in D7. I agree that I am a bit stumped when it comes to geolocation and taxonomy / views modules, but plucking existing code apart - eg: openlayers proximity - has also helped a lot... but I just need a starting point for now and I am not sure what this is. But you are right, a bit more reading / learning and understanding is needed.
Comment: However, the reason I posted this here and http://groups.drupal.org/node/191253 is to get some side input as I have no one else I know I could ask about drupal or coding issues. Also, I am on a tight schedule and need to show some progress rather fast, so long nights / weekend lay ahead ... But I am sure it will all pay off eventually. I just wish I had done more research a lot earlier / kept at developing drupal over the years... But it's never too late =)
Comment: Sounds like you've got a good background to solve this! I can't help with location, but I can with views. For views I would recommend viewing "Taming the Beast" video series at Nodeone.se. Views is still likely to through a few curve balls especially with contextual filters and taxonomies. IF you search this site for both tags, you will find what a lot of answers for the suspected 'bugs' (so far the bugs have been me!)  Or ask here.  Great book = "Drupals Building Blocks" written by merlinofchaos.


Cannot set property 'src' of null Angular - Typescript error

Question: I am trying to get the image from computer, and trying to set this image into an image element, but I get the following error.

Cannot set property 'src' of null

Can anybody help?
This is my component file code.
import { Component } from '@angular/core';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})

export class AppComponent {
    title = 'app';
    event: any;
    url: any;
    onSelectFile = (event) => { // called each time file input changes
        if (event.target.files && event.target.files[0]) {
            var reader = new FileReader();
            reader.readAsDataURL(event.target.files[0]); // read file as data url
            reader.onload = (event: any) => {
                this.url = event.result;
                console.log(this.url);
                var image = document.getElementById("#image") as HTMLImageElement;
                image.src = this.url;
            }
        }
    }
}

this is my HTML file code.

<input type='file' (change)="onSelectFile($event)">

Whenever I set the value of my image element I get the error mentioned above.
Comment: Why would you even use document.getElementById here? The whole point of Angular is that it gives you better tools to do it.
Comment: Remove the `#` from your selector. Should just be `document.getElementById("image")`
Comment: this line `onSelectFile = (event) => {` could be just changed to `onSelectFile(event) {`...
Answer: Databind the src attribute of the image to the url property:

Remove all the code after assigning the image link to the url property.
export class AppComponent {
    title = 'app';
    event: any;
    url = '';

    onSelectFile = (event) => { // called each time file input changes
        if (event.target.files && event.target.files[0]) {
            var reader = new FileReader();
            reader.readAsDataURL(event.target.files[0]); // read file as data url
            reader.onload = (event: any) => {
                this.url = event.result;
            }
        }
    }
}

Answer: I think the  id is "image", without "#", because you are using getElementById method.


SQL ALTER TABLE

Question: Preciso fazer algumas alterações no meu banco, porém antes de adicionar uma nova coluna preciso verificar se ela já existe, se não existir criar a nova coluna se não existir a coluna então devera criar
Comando encontrado para verificar existência da coluna
SELECT COUNT(COLUMN_NAME) AS resultado FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'procedimentos_planos_tratamentos' AND  COLUMN_NAME = 'tipo';

se o retorno for 1 não fazer nada e se o retorno for 0 executar seguinte procedimento
ALTER TABLE procedimentos_planos_tratamentos
ADD COLUMN tipo VARCHAR(1);

Comment: Aqui tem algumas formas de fazer isso https://stackoverflow.com/questions/24571611/mysql-alter-table-if-column-not-exists
Answer: consegui resolver o problema da seguinte maneira
    IF (SELECT COUNT(COLUMN_NAME) AS resultado FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_NAME = 'procedimentos_planos_tratamentos' AND  COLUMN_NAME = 'tipo') THEN
    BEGIN
        ALTER TABLE procedimentos_planos_tratamentos
        ADD COLUMN tipo VARCHAR(1);
  END;
  END IF;

SQL ALTER TABLE


Why do classical guitarists recommend putting the left thumb between the index and middle finger?

Question: In most of the literature that I have seen, the recommendation is for the left thumb to be roughly in line with the index finger, running parallel to the frets.  I find that, especially toward the first fret, this causes excessive wrist bend.  If I move my thumb closer toward the floor and angle it so that it is more of a 45 degree angle, I find it helps me keep my wrist straighter.  Are there any problems associated with adopting unorthodox thumb positions?
Edit:
I've realized it's possibly some type of optical illusion.  In the first picture I have my thumb low on the neck and the wrist has a slight bend.

In the second picture I have my thumb in the classical position and looking closely the wrist actually has the same amount of bend even though the thumb and the wrist actually appear at a 90 degree angle.
Comment: The recommended position gives you the greatest flexibility to move up or down frets, and in fact what you may want to be looking at is the position of the guitar. If you are having to bend your thumb that much maybe this is the issue. Can you post a picture of your normal guitar position.
Comment: related: http://music.stackexchange.com/questions/8347/what-are-the-dos-and-donts-of-positioning-your-thumb-on-a-guitar
Answer: I'd say that the location of the thumb is a guideline, not a hard-and-fast law. You can move your thumb laterally a bit in one position compared to other positions if you find it more comfortable.
Classical guitar necks are very wide and fat compared to electric guitar necks, and on a classical neck it is important to keep your thumb near the middle of the back of the neck so that your fingers can reach all over that extra-wide fingerboard.
On an electric guitar neck, or most steel-string acoustic guitar necks, the neck is much narrower and thinner. In that case it's feasible to let your thumb wrap around the whole neck; for some barre chords, it may in fact be easier to grip with your thumb wrapped around the neck. Some electric guitar players even fret notes on the low E string with their thumb wrapped around. But try to do that on a classical guitar, and your hand and fingers will be so constrained by the heft of the neck that it will slow you down tremendously.
Answer: I think your photos exaggerate the vertical placement of the thumb.  The idea is to have your left hand as relaxed as possible, but still do what it needs to do to play the instrument.  If you center your thumb roughly between your middle and ring fingers, that makes it easier for you to jump up a position.
As you say, you should try to keep your wrist as straight (in all axes) as you can.  If you're holding the instrument correctly, with a proper neck angle, following that rule will probably put your thumb in more or less the correct position.  Your photo looks like you're trying too hard.
Relax your left hand, and hold it more or less in your playing location (but just in the open air - no guitar).  Now touch your thumb to the pair of your ring and middle finger-tips.  Now spread your hand open in a natural and relaxed way, so there's room to fit the neck between your thumb and fingers.  This is more or less the playing position you should try for.
Anyway, like the answer above says, this is a guideline.  As you reach for other positions, you will naturally change the thumb/finger relationship.  But you want to try for a central, "home" position when you can.  It should give you the most strength and mobility.
Answer: The main answer to your question, is this: learn three or four classical pieces. You will find that the position recommended by classical guitarists is one that you practically cannot avoid in order to play certain passages with maximum comfort and ease. It's an issue that will take care of itself as you find the most efficient, most comfortable fingerings for that type of musical material.
The thumb has to oppose the forces from the fretting fingers. Classical material often involves stretch fingerings, because there are independent melody lines which sometimes go quite their separate ways.  The thumb has to be somewhere between the extreme points of the stretch in order to balance the forces.
The thumb position in your first picture will work okay some of the time, but it will probably not lead to a strong and confident grip for passages that require stretch
fingerings.
In fact, that thumb position will not only fail to support the classical style but it is a weak one for just about anything. For example, it will not properly support a string bend when you're playing the blues. A strong position for that is on the edge of the neck, pressing down, against the upward bend executed by the fingers.


Como eu garanto números únicos em uma lista de listas?

Question: Boa noite, estou tentando fazer uma cartela de bingo 5x5, usando random para gerar os valores, no entanto não pode haver números iguais. Tentei fazer dessa forma mas ainda surge números iguais:
import random as rd
cart1 = []

for i in range(0, 5):
    cart1.append([])

for l in range(0, 5):
    for c in range(0, 5):
        var = rd.randint(0, 99)

        if var not in cart1:
            cart1[l].append(var)

print("\n")
print("A cartela 1 é:")
for l in range(0, 5):
    for c in range(0, 5):
        print(f"[{cart1[l][c]:^5}]", end="")

    print()

Um dos resultados:
Answer: import random
lista = random.sample(range(100),10)

Esse comando gera uma lista de 10 números variando de 0 a 99. Com isso você pode organizar da forma que achar melhor.
Se você quiser organizar em matriz, eu recomendo usar numpy array.
Por exemplo:
import random
lista = random.sample(range(100),25)
lista = np.array(lista)
lista = np.reshape(lista, (5, 5))

resultado:
array([[29, 85,  6, 40, 14],
       [78,  2, 77, 41, 46],
       [ 9, 52, 68, 19, 97],
       [65, 90, 75, 93, 50],
       [31,  4, 27, 55, 10]])

Comment: Obrigado pela dica!


Why doesn't this limit exist? $\lim_{(x,y)\to(0,0)} \frac{x^2y^3}{(x^2-y^2)^2}$

Question: $$\lim_{(x,y)\to(0,0)} \frac{x^2y^3}{(x^2-y^2)^2}$$
WolframAlpha says it doesn't exist, but I don't know how to prove it. Are there any directionals that give values different from zero?
Thank you all
Comment: Hint: The thing inside the limit is undefined on two whole lines through $0$.
Comment: $x=0$ or $y=0$ or $x=y$ all have $\infty$ as limits For $x=0$, limit could be $\pm \infty$.  It looks like getting $0$ as a limit is harder.
Answer: HINT
We have that

$x=0 \implies \frac{x^2y^3}{(x^2-y^2)^2}=0$
$x=t\quad y=t+t^2 \quad t\to 0^+$ $$\frac{x^2y^3}{(x^2-y^2)^2}=\frac{t^2(t+t^2)^3}{(t^2-(t+t^2)^2)^2}=\frac{t^5+3t^6+3t^7+t^8}{(-2t^3-t^4)^2}\to ?$$


Storyboard segue hides tabBarButton on destination view

Question: Sorry for bad english.
I have MainViewController and TabBarController with two Views in storyboard.
when i push button (using modal segue) in my MainviewController - app switch to firstTabBarView or secondTabBarView depending on conditions. it works fine but after that i lost my TabBarControls at the bottom of any of my tabBarViews.
UPD: action after bar Button pressed
-(IBAction)barButtonPressed:(id)sender
{
    if (condition !=0 ) {
        [self performSegueWithIdentifier:@"segue1" sender:nil];
    } else {
        [self performSegueWithIdentifier:@"segue2" sender:nil];
    }
}

Comment: Showing us the relevant code always helps. ;)
Answer: It's working as advised. A modal segue is a "fullscreen segue" and covers your standard navigation stack.
If you simply want to change the selected viewcontroller, use
[yourTabBarControllerInstance setSelectedIndex:index];

Comment: my noobnes didnt allow me to understand how did i get "yourTabBarControllerInstance" if i created it in storyboard
Comment: I'm writing from iPhone now and not sure about the exact syntax. You have to go through: Application, delegate, main window, root view controller. It should  be UITabBarController *tb = (UITabBarController *)[[[[UIApplication sharedApplication] delegate] window] rootViewController];


3D Convex hull in 3D Convex hull

Question: I have two convex hull, How to check if the smaller one is wholly, partially or not inside the Bigger Convex hull?
Comment: Possibly duplicate?
Comment: Shouldn't it be sufficient to check whether *each corner* of one hull is contained in the other?
Comment: I say possible I have not yet find if it is, have you?
Comment: @Sergio: No, I don't think it's a duplicate.
Comment: @Marco13: can you please explain it in the answer? Please?
Answer: According to the definition of a "convex hull" as the intersection of multiple Half-Spaces, it should be sufficient to check whether all corners of one convex hull are contained in the other.
A point is contained in a convex hull if and only if it is "on the same side" of all planes that make up the faces of the convex hull. So when you want to check whether one point is contained in the convex hull, you can compute the dot products of the point and the normals of the faces of the convex hull. If they are all positive (or negative, depending on the orientation of the faces), then the point is contained in the convex hull.
You can do this for all points (corners) of the smaller convex hull:

If they are all contained in the larger convex hull, then the smaller one is completely contained in the larger one.
If they are all not contained in the larger convex hull, then the smaller one is completely outside in the larger one.
Otherwise, the convex hulls are intersecting
Answer: The answer depends on the available representation for the two sets. So, let us examine how you can check whether $C_1$ is in $C_2$ in each of the following cases:
Case I. $C_1$: extreme points, $C_2$: halfspaces This is the most trivial case. If $C_1=\mathrm{co}\{x_1, x_2, \ldots, x_n\}$ and $C_2=\{x: Hx\leq K\}$ (where $\leq$ is meant element-wise), then just check whether $Hx_i\leq K$. In this case it is also easy to tell whether $C_1$ is outside $C_2$ or it is neither a subset or a superset and they have a nonempty intersection.
Case II. $C_1$ and $C_2$ are given as a linear transformation of a $\mathcal{B}_{\infty}$ with $A,B\in\mathbb{R}^{m\times n}$ and $C_1=A \mathcal{B}_\infty$ and $C_2=B\mathcal{B}_\infty$ (where $\mathcal{B}_\infty=\{x: \|x\|_\infty\leq 1\}$). Then $C_1\subseteq C_2$ if and only if $\|A'x\|_1\leq \|B'x\|_1$ for all $x\in\mathbb{R}^m$. However, this condition cannot always be reduced to something simpler unless, for example, $m=n$, when it can be equivalently written as $\|A B^\dagger\|\leq 1$, where $B^\dagger$ is the Moore-Penrose pseudoinverse of $B$.
Proof. Let us denote by $\delta^*(x\mid C)$ the support function of a set $C$, that is $\delta^*(x\mid C) = \sup_{y\in C}x'y$. Since $A\mathcal{B}_\infty$ and $B\mathcal{B}_\infty$ are both convex and closed, we have
$$
\begin{aligned}
A\mathcal{B}_\infty &\subseteq B\mathcal{B}_\infty\\
\Leftrightarrow \delta^*(x\mid A\mathcal{B}_\infty) &\leq \delta^*(x\mid B\mathcal{B}_\infty)\\
\Leftrightarrow \sup\{x'As\mid x\in \mathcal{B}_\infty\} &\leq \sup\{x'Bp\mid p\in \mathcal{B}_\infty\}\\
\Leftrightarrow \sup_{\|s\|_\infty\leq 1} x'As &\leq \sup_{\|p\|_\infty\leq 1} x'Bp
\end{aligned}
$$
which completes the proof.
Now note that in this particular case, the two sets cannot be disjoint, so it the above condition fails, they will not be nested but they will have a nonempty intersection.
Case III. $C_1$ and $C_2$ are given linear transformations of a ball Similarly as above we may prove that $A\mathcal{B}\subseteq B\mathcal{B}$ if and only if $\|A'x\|_*\leq \|B'x\|_*$ where $\|\cdot\|_*$ is the dual norm of $\|\cdot\|$ which defines $\mathcal{B}=\{x: \|x\|\leq 1\}$.
Case IV. Equal number of extreme points. In that case we may apply the following result (source: Lemma 4.5.1 in L.Q. Thuan, Piecewise affine dynamical systems: well-posedness, controllability and stabilizability, PhD dissertation, Uni. Groningen, 2013): Let $H_P,H_Q\in \mathbb{R}^n$ has full row rank and let $P=\{x: H_P x\leq K_P\}$ and $Q=\{x: H_Q x\leq K_Q\}$. Then $P\subseteq Q$ if and only if one of the following holds true:

There is a lower triangular matrix $M$ with positive diagonal elements so that $H_P = MH_Q$ and $K_P=MK_Q$.
There is an $1\leq l \leq m $ and a matrix $M\in\mathbb{R}^{l\times l}$ so that $H_P^{[l]}=MH_Q^{[l]}$ and $K_P^{[l]}<MK_Q^{[l]}$, where $H_P^{[l]}$ stands for the matrix formed by the first $l$ rows of $H_P$.

Case V If both sets are given in the form of an intersection of subspaces, then it is not always easy - or computationally tractable - to judge whether one is contained in the other. Then, one may have to resort to the enumeration of the vertices of $C_1$ to tell whether $C_1\subseteq C_2$.
Case VI If both sets are represented by a set of extreme points, then again it is very difficult to tell whether one is contained in the other, but it is somewhat easier to tell whether the convex sets these points define are disjoint: simply find a line that separates the points by least squares.

3D Convex hull in 3D Convex hull


no such column: _id SQLite error Android

Question: I'm getting a no such column: _id  error. YES there is a column "_id" in my journals table.
I'm getting the error with this code:

 mDb.execSQL("UPDATE "+DATABASE_PLANTS_TABLE+" SET "+ KEY_PLANT_DAYS+
            " = (SELECT COUNT(*) FROM "+DATABASE_PLANTS_TABLE+" WHERE "
              +DATABASE_JOURNAL_TABLE+"."+KEY_JROWID+" = "+DATABASE_PLANTS_TABLE +"."
                        +KEY_PLANT_HOMEID+")");

The following code DOES work:

mDb.execSQL("UPDATE "+DATABASE_JOURNAL_TABLE+" SET "+KEY_JOURNAL_PLANTS+
                    " = (SELECT COUNT(*) FROM "+DATABASE_PLANTS_TABLE+" WHERE "
                    +DATABASE_JOURNAL_TABLE+"."+KEY_JROWID+" = "+DATABASE_PLANTS_TABLE +"."
                    +KEY_PLANT_HOMEID+")");

LogCat:

08-21 00:07:46.614: ERROR/Database(12943): Failure 1 (no such column: journals._id) on 0x421470 when preparing 'UPDATE plants SET days = (SELECT COUNT(*) FROM plants WHERE journals._id = plants.homeid)'.
08-21 00:07:46.614: DEBUG/AndroidRuntime(12943): Shutting down VM
08-21 00:07:46.614: WARN/dalvikvm(12943): threadid=3: thread exiting with uncaught exception (group=0x4001b390)
08-21 00:07:46.614: ERROR/AndroidRuntime(12943): Uncaught handler: thread main exiting due to uncaught exception
08-21 00:07:46.624: ERROR/AndroidRuntime(12943): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.growjournal.beta/com.grower.beta.plantsList}: android.database.sqlite.SQLiteException: no such column: journals._id: UPDATE plants SET days = (SELECT COUNT(*) FROM plants WHERE journals._id = plants.homeid)
08-21 00:07:46.624: ERROR/AndroidRuntime(12943):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2596)
08-21 00:07:46.624: ERROR/AndroidRuntime(12943):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2621)
08-21 00:07:46.624: ERROR/AndroidRuntime(12943):     at android.app.ActivityThread.access$2200(ActivityThread.java:126)
08-21 00:07:46.624: ERROR/AndroidRuntime(12943):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1932)
08-21 00:07:46.624: ERROR/AndroidRuntime(12943):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-21 00:07:46.624: ERROR/AndroidRuntime(12943):     at android.os.Looper.loop(Looper.java:123)
08-21 00:07:46.624: ERROR/AndroidRuntime(12943):     at android.app.ActivityThread.main(ActivityThread.java:4595)
08-21 00:07:46.624: ERROR/AndroidRuntime(12943):     at java.lang.reflect.Method.invokeNative(Native Method)
08-21 00:07:46.624: ERROR/AndroidRuntime(12943):     at java.lang.reflect.Method.invoke(Method.java:521)
08-21 00:07:46.624: ERROR/AndroidRuntime(12943):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
08-21 00:07:46.624: ERROR/AndroidRuntime(12943):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
08-21 00:07:46.624: ERROR/AndroidRuntime(12943):     at dalvik.system.NativeStart.main(Native Method)
08-21 00:07:46.624: ERROR/AndroidRuntime(12943): Caused by: android.database.sqlite.SQLiteException: no such column: journals._id: UPDATE plants SET days = (SELECT COUNT(*) FROM plants WHERE journals._id = plants.homeid)
08-21 00:07:46.624: ERROR/AndroidRuntime(12943):     at android.database.sqlite.SQLiteDatabase.native_execSQL(Native Method)
Answer: You're not checking the journals table! "FROM" determines what table you're looking into. You probably want to do an inner join?
Comment: Not sure what you mean by this. In the code that does work i reference two separate tables.
Comment: No, you don't. Like I said, FROM determines which table you access. You said "FROM plants", so you will only be able to access data from the table "plants". Anything from "journals" will be completely inaccessible to you. You need to use a JOIN statement, or have two tables in your FROM part.
Comment: while this is the correct anwser could you explain why i am still able to compare to the plants table in the WHERE statment?
Comment: The second approach has the journal table in the outer part of the query (the UPDATE) and the plants table in the inner part (the SELECT), so both tables are being accessed. In UPDATE statements, the table after your UPDATE directive specifies the table being read and modified.


Facebook for Phonegap Java error - missing superclass

Question: Im using PhoneGap version 2.1 and tried to incorporate the facebook-phonegap plugin ( https://github.com/davejohnson/phonegap-plugin-facebook-connect )
I followed the step by step tutorial but i ended up with this 3 errors:
https://i.stack.imgur.com/iJ0gM.png
Any ideas how i can fix them ?
Comment: check this http://stackoverflow.com/questions/1678122/must-override-a-superclass-method-errors-after-importing-a-project-into-eclips
Answer: Okay, so the way to solve tis is either upgrade to higher JDK version or remove the @Override annotations :)
Simple but frustrating if you don't do every-Java dev


Minimum number of points needed to define a circle in 3d space

Question: Firstly I thought that it might be 2.
Having point A as the center. The vector between A and another point B is perpendicular to the plane of the circle and its length determines the radius of the circle.
But then I thought this might define a disk. Thoughts ?
Comment: Any circle with a diameter at least the distance between two points can be made to pass through the two points.
Comment: In a plane, you need either three points *on* the circle, or its center and one additional point on the circle (in this case, only 2). In 3-D you always need 3. Even if you have the center and one point on the circle, the circle it is not uniquely defined since the plane in which the circle lies is not unique.
Comment: @RichardAmbler The OP's second point isn't on the circle. It's used to define both a normal to the plane of the circle and its radius.
Comment: @Florian The OP's proposed second point is not meant to be on the circle. It defines the circle's radius and plane.
Comment: @amd you are right, I misread the description. My apologies. In this case, the OP is right, you could encode all the required information into two points: one being the circle center and thus in the plane, the difference between the two defining the direction of the normal vector (and thus the plane) and its length defining the radius. It's not an intuitive way but it's possible.
Answer: Three points are needed. They define uniquely a plane where a circle lies and the circle as well.
Comment: @user29171 ..and you want one endpoint of this vector to be the center of a circle and the second to define the radius and plane.. In this case you have all parameters to construct the circle.
Comment: Through 2 points in 3-d space it can can be generated infinite number of planes.  (They have common straight line). Through 2 points on the **plane** also it can be generated infinite number of circles. So two points are not sufficient.
Comment: Don't need to define a unique circle. Just at least 1
Comment: @user29171 Three points give you precisely 1 circle ( to be honest they should not be collinear). Two points allow to generate infinite number of circles.
Comment: Doesn't the vector ensure that it makes only 1 circle though, since there is only one plane normal to this vector ?
Comment: This answer doesn't address the proposal in OP's question, which doesn't involve points on the circle.
Answer: A circle is the boundary of a disk, so if you can characterize a disk uniquely, then you can also characterize a circle uniquely. Your considerations are correct.
Answer: It depends how you use the points to define the circle.
If you want the circle to pass through the points, then three points are needed.
But there is another way to define a circle from two given points $P$ and $Q$: you use one point, $P$, as the center of the circle, and you use the other point $Q$ to define the plane containing the circle and its radius. Specifically, the plane normal is in the direction of the vector $Q-P$, and the circle radius is $\|Q - P\|$.
Comment: This is exactly what I was describing in my question. Thank you for the feedback.
Answer: I know this is a necro, but the answer is that you only need a single real number to uniquely define a circle in any finite dimensional space.
First, note that 3 points define a circle. So, all we need is a surjective function $f: \mathbb{R}—>\mathbb{R^n} \times \mathbb{R^n} \times \mathbb{R^n}$ (i.e. $\mathbb{R^{3n}}$)
Cantor shows that such a bijection must always exist. While there are infinitely many such bijections, the easiest way would probably be to use Hilbert's space filling curve. Each point along the curve corresponds to a unique circle in the desired output space, and it's easy to define any point along the curve with a single scalar: how far along the curve is that point? If you continue the Hilbert curve until you've entirely tiled the output space, all possible circles will be accounted for.
It's probably more practical to use 2 or 3 points to define the circle, as discussed in other answers. But you asked for the minimum :)


How to use node title or path alias instead of node id in node reference contextual filter in views?

Question: I have node A with a node reference to node B.
In a view I show all nodes A that have particular node B referenced (nid: 123, title: node-B-title).
Instead of using the nid in the contextual filter I would like to use the node title. For example, instead of:
view-name/123

I would like to use
view-name/node-B-title

How could I do that?
Answer: I had a very similar problem and I not just found the solution to it, but also learned new things about how view works. Let me share what I learned and the solution to your problem too.
When you are creating a view with one or more contextual filters, the view must receive values of those filters from somewhere. This can be done by -

Picking the context filter value(s) from the URL

Typically you would have a page view for such purposes one that has URL of the form foo/%/bar or foo/bar/% for single contextual filter OR of the form foo/%/bar/% or foo/bar/%/% for multiple filters
In case you have multiple filters, the url value that appears first is mapped to the first filter, next to the second filter and so on.

Views allows you to tell what to do if the filter values are not available in the URL. This is typically used for block views.

You can choose from different actions and then configure the choice too.

asdfj kajsdf

Another thing views allows you is to tell what to do with the filter values if they are found in the URL as described in #1 above. Typical use cases are - Making dynamic titles based on filter values, Validating filter values etc.

When validating filter values, you can change the values too! (That is where our solution lies btw). This is very akin to the way we can change $form values in the drupal form validation callbacks.

Solution to your specific problem lies in using a very similar code in the sections pointed to by the arrows in the above image.
This link  proved out to be great help to me. Here is an excerpt from it:
$np = explode('/', drupal_get_normal_path($argument));
if (!empty($np[1])) {
  $handler->argument = $np[1];
  return TRUE;
} else {
  return FALSE;
}

Comment: This did not work for me, but rather caused an ajax error in the view upon saving.
Answer: The view argument must be the field reference of content type, then select the option "Provide default argument" and check the option Id Node (something like that).
1) Add argument "X field reference" 2) Check ID node from url (in add default argument) 3) In validation section, check the content type of node, and on setion "Node type" select "Node Id
And is done. :)
Comment: "content ID from URL" only gives the nid. If I would use a term reference I have a could use "validation criteria" with "term name converted to term ID". For the node reference there is no similar option to translate the title to nid. Probably because titles are not necessarily unique.
Comment: Yes is correct, but is necessary the argument must be the field reference (nid), try that.
Comment: 1) Add argument "X field reference"
2) Check ID node from url (in add default argument)
3) In validation section, check the content type of node, and on setion "Node type" select "Node Id"
Comment: The actual url can have the nid, and path alias could be the node title. This does work isn't it?
Answer: This will not work in all circumstances, but one approach to the problem in the question is to use the actual node display of node B (or node type B) and set its path how you want it with the path or pathauto module.  Then use views block to add the content relationship and the view you want.
Use a contextual filter on NID and then setting Provide default value > Content ID from URL.  Then add the views block to your page or set of pages.
If your context allows you to use a views block on the node itself and not a views page this will make it much easier to get the path you want and the views display you want.
Answer: I edited the accepted answer, but wanted to add the actual code here:
Use PHP validated option under the validation options in the contextual filter.
$np = explode('/', drupal_get_normal_path($argument));
if (!empty($np[1])) {
  $handler->argument = $np[1];
  return TRUE;
} else {
  return FALSE;
}

Answer: Old question, but found it through Google and figured I'd share my solution for anyone else who finds it in future:
There is now a module named safeword  which basically does exactly what Sumeet Pareek suggested: (Automatically) creates a URL friendly field.
Answer: I would recommend the Extended Path Aliases (path_alias_xt) module. It fixes this problem purely by being installed with no configuration, it's basically magic, apparently. :D Not really, but the excerpt from the module page extolls how you just install it and it fixes this and other problems, but doesn't go into how the module does so behind the scenes... O, well, we could always read the code :D It doesn't specifically mention fixing views paths, but I have used it to do so and it works perfectly.
List of problems it solves, from the module page:

Have you ever wondered why, after defining an alias like about-us
  for, say, node/123, your pages are still riddled with those ugly
  machine-generated tabs and links like /node/123/edit,
  node/123/revisions etc.?
Likewise for /taxonomy/term/% and /user/%
  links: did you expect to see /dries/track but got /user/5/track?
Do you find that your browser address bar also shows those ugly numbers
  instead of your aliases?


Custom module menu item declaration leads to error 404

Question: function eventi_menu() {
  $items = array();
  $items['eventi/book/%/'] = array(
    'title' => 'Book',
    'page callback' => 'eventi_book',
    'access arguments' => array('allow booking'),
    'page arguments' => array(2),
    'type' => MENU_CALLBACK
  );
  $items['eventi/book_waits/%/'] = array(
    'title' => 'Book Waits',
    'page callback' => 'eventi_book',
    'access arguments' => array('allow booking'),
    'page arguments' => array(2),
    'type' => MENU_CALLBACK
  );
  $items['eventi/unbook/%/'] = array(
    'title' => 'Unbook',
    'page callback' => 'eventi_unbook',
    'access arguments' => array('allow booking'),
    'page arguments' => array(2),
    'type' => MENU_CALLBACK
  );

  return $items;
}

function eventi_book($nid) {
  echo 'something';
}

All worked OK, but suddenly, when I visit (for example) http://example.com/eventi/book/201, I get an error 404. I cleared the cache, but I keep to get the same error. Do you have any clue why it happens?
Answer: I would guess that trailing slash on the path is throwing you
$items['eventi/book/%'] = array(
  'title' => 'Book',
  'page callback' => 'eventi_book',
  'access arguments' => array('allow booking'),
  'page arguments' => array(2),
  'type' => MENU_CALLBACK
);

Also, if you use %node for the variable in the path, the menu router will call node_load() on the given nid from the path and you'll get the full $node object in your callback function, like so:
$items['eventi/book/%node'] = array(
  'title' => 'Book',
  'page callback' => 'eventi_book',
  'access arguments' => array('allow booking'),
  'page arguments' => array(2),
  'type' => MENU_CALLBACK
);

// ...and so on, until...

function eventi_book($node) {
   return $node->title;
}

Also note that your callback function should return a value, not echo it.
Comment: A menu callback can print a value: see what is done from [node_feed()](http://api.drupal.org/api/drupal/modules--node--node.module/function/node_feed/6), which is the menu callback for the path rss.xml, and which prints its output. The difference between printing the result, and returning a string is that in the latter case [index.php](http://api.drupal.org/api/drupal/index.php/6/source) passes the string, as `$return`, to `theme('page', $return)`. Another difference is that when the menu callback returns a string, that string is cached by Drupal for anonymous users.
Answer: Remove the ending slash in the paths.
function eventi_menu() {
  $items = array();

  $items['eventi/book/%'] = array(
    'title' => 'Book',
    'page callback' => 'eventi_book',
    'access arguments' => array('allow booking'),
    'page arguments' => array(2),
    'type' => MENU_CALLBACK
  );
  $items['eventi/book_waits/%'] = array(
    'title' => 'Book Waits',
    'page callback' => 'eventi_book',
    'access arguments' => array('allow booking'),
    'page arguments' => array(2),
    'type' => MENU_CALLBACK
  );
  $items['eventi/unbook/%'] = array(
    'title' => 'Unbook',
    'page callback' => 'eventi_unbook',
    'access arguments' => array('allow booking'),
    'page arguments' => array(2),
    'type' => MENU_CALLBACK
  );

  return $items;
}


How to let users mark ( like) other users?

Question: In my project I'd like to let users to mark (kinda like) other users.
What solution should I use? Appreciate any feedback.
Answer: You can use Flag module. It does have integration with Views module. So you can configure and customize.

Flag is a flexible flagging system that is completely customizable by
  the administrator. Using this module, the site administrator can
  provide any number of flags for nodes, comments, users, and any other
  type of entity. Some possibilities include bookmarks, marking
  important, friends, or flag as offensive. With extensive views
  integration, you can create custom lists of popular content or keep
  tabs on important content.
Flags may be per-user, meaning that each user can mark an item
  individually, or global, meaning that the item is either marked or it
  is not marked, and any user who changes that changes it for everyone.
In this way, additional flags (similar to published and sticky) can be
  put on nodes, or other items, and dealt with by the system however the
  administration likes.
Answer: Using the Flag module as suggested in the previous answer is indeed the typical solution to answer this question. If you're not familiar with the Flag module, checkout the set of 8 video tutorials about the flag module.
However, often times, depending on your specific case, some of the Flag related modules are usefull also, such as (partial list):

Views, to create lists of flagged content, users, etc, such as in the video about Creating global flags and listing flagged content in Views.
Rules, to trigger rules for anything that is flagged, such as in the video about Triggering rules with Flag, or to set flags with the Rules module, such as in the video about Setting flags with Rules.
Flag Lists, to allow users to create custom lists.
Flag Weights, to add weights to Flags (to be used for sorting).
DraggableViews, to make Views draggable (so that they can be rearranged by Drag'n'Drop.).
Flag Friend, a pre-built flag for marking other users as friends (using the Flag module).
Flag Abuse, a pre-built flag for marking offensive content, with some extra administrative features.
Flag, Hide & Mute, for users to hide individual nodes, such as site-wide announcements or advertisements, and/or to suppress all posts by users they do not want to see.
Flag Files, to flag media files.
Flag Service, to allow Flag to be accessed via a web services interface through the Services module.
DLike, provides a Facebook like "Like" functionality using the Flag and Lightbox2 module.
Conditional Flags, provides an extra API to Flag module, for custom conditions between flags.
Organic Groups Flag Integration, extends the flag module with organic groups support allowing the administrators of each group to override the global flag settings for their group.
Context Flag, allows the use of Flags as conditional triggers for use with the Context module.

Refer to its community documentation for way more details.


Linear probability model, dummy variables and the same standard errors on all estimates

Question: I am fitting the linear probability model,
$$
Y_i=\beta_0 + \sum_{j=1}^J \beta_j G_{ji} +\varepsilon_i
$$
where $Y_i \in \{0,1\}$ and $G_{ji} \in \{0,1\}$, for $j=1,\ldots,J$ and $\sum_{j=1}^J G_{ji}=1$, i.e., the $G_{ij}$ are groups and each individual is placed into one of these groups.
I use OLS to get estimates for $\beta_j$, $j=1,\ldots,J$ (leaving out one group to avoid multi-linearity) and I get my estimates. The weird thing is that the standard errors are the same for all $\beta_j$, $j=1,\ldots,J$, i.e. $se(\widehat \beta_1)=se(\widehat \beta_{2})=\ldots= se(\widehat \beta_J)$.
Is this normal that the standard errors are the same? It's not the first time that this has happened to me and I'm not sure if I'm doing something wrong.
Comment: This requires some matrix algebra, and the Schur complement, to explore. Are you familiar?
Comment: @AlecosPapadopoulos, may I suggest that this is pretty much what my answer does (hating to do self-promotion...)?
Comment: If the groups are equal in size then the principle of insufficient reason is sufficient as i suggested in my answer.
Comment: @ChristophHanck Indeed (+1) Thanks for covering this.
Comment: You did not explain why using a method that allows $Y<0$ and $Y>1$ is a good idea.
Comment: @FrankHarrell This is common practice in many fields. The four main reasons I have seen are: 1) easy to interpret coefficients, 2)  it can be argued that the assumption that errors are normal or logistic is just as strong an assumption as linearity, meaning that there is a mis-specification problem anyway and the coefficient estimates will be biased anyway and 3) coefficient estimates in some specific cases have been shown to be similar and 4) easier to deal with endogeneity (see, for example http://www.mostlyharmlesseconometrics.com/2012/07/probit-better-than-lpm/).
Comment: also as @repmat explains $Y \in \mathbb{R}$ and this could still happen.
Comment: @FrankHarrell I just noticed that you are far more knowledgeable about this than I am so is there any particular reason that you are asking?
Comment: The fact that an incorrect model is commonly used is a poor reason to use it IMHO.  And there is no such thing as "errors are logistic".  The logistic model has no error term and no distributional assumption whatsoever.  "Logistic" here refers to math (link function), not random quantities.  The only reason the linear model coefficients are interpretable is that you omitted all the needed interaction terms that would constrain predictions to $[0,1]$.  Coefficients will not be very similar between the two models.  Odds ratios are interpretable.
Answer: Recall that the standard errors are the diagonal elements of the matrix
$$
\hat\sigma^2(X'X)^{-1}
$$
As pointed out by @repmat, this result requires that each group is of equal size, i.e., that
$$\sum_iG_{ji}=c$$
for $j=1,\ldots,J$.
In that case, you can easily check that
$$
X'X=n
\begin{pmatrix}
1&1/J&\cdots&\cdots&\cdots&1/J\\
1/J&1/J&0&\cdots&\cdots&0\\
1/J&0&1/J&\ddots&\cdots&0\\
\vdots&0&0&\ddots&\ddots&0\\
\vdots&\vdots&\cdots&\ddots&\ddots&0\\
1/J&0&\cdots&\cdots&0&1/J\\
\end{pmatrix},
$$
assuming that the first column contains the constant term. Assuming that one of the redundant dummies has been dropped, so that $X'X$ is of dimension $J\times J$, the inverse is
$$
(X'X)^{-1}=\frac{1}{n}\begin{pmatrix}
J&-J&\cdots&&\cdots&-J\\
-J&2J&J&\cdots&\cdots&J\\
\vdots&J&2J&J&&J\\
&\vdots&J&2J&\ddots&\vdots\\
\vdots&\vdots&&\ddots&2J&J\\
-J&J&\cdots&\cdots&J&2J
 \end{pmatrix}
$$
We see that the diagonal elements are identical (except for the one on the constant), yielding identical standard errors.
The nature of the $y_i$ is irrelevant, as these enter the standard errors only through $\hat\sigma^2$, which however obviously just multiplies each element of $(X'X)^{-1}$ and hence does not affect the result that the diagonal elements are identical.
This result also shows that the squared standard error on the constant is one half that of the dummies.
P.S.: As suggested by Alecos in the comments, we may define the block matrix
$$
X'X=
n\begin{pmatrix}
A&B\\C&D
\end{pmatrix},
$$
with $A=1$, $B=(1/J,\ldots, 1/J)$, $C=B'$ and $D=I/J$ and use a result on partitioned inverses that the lower right block has the inverse
$$
D^{-1}+D^{-1}C(A-BD^{-1}C)^{-1}BD^{-1}
$$
to see that the result is as presented as above.
UPDATE: Regarding the discussion in the comments of @repmat's answer, the numerical equivalence does not exactly hold for robust standard errors.
This is because the "meat" matrix $X'\Sigma_uX$ of the robust variance estimator
$$
(X'X)^{-1}X'\Sigma_uX(X'X)^{-1}
$$
has a diagonal
$$
\begin{pmatrix}
\sum_{i=1}^n\hat{u}_i^2\\
\sum_{i=1,\,i\in j=1}^n\hat{u}_i^2\\
\vdots\\
\sum_{i=1,\,i\in j=J-1}^n\hat{u}_i^2\\
\end{pmatrix}
$$
(assuming that group $J$ has been dropped to avoid multicollinearity), and there is in general no reason to believe that the sums of squared residuals belonging to the different groups are identical.
The differences are minor, though (at least under homoskedasticity). Here is a modification of his illustration:
set.seed(42)
n <- 999
library(sandwich)
library(lmtest)

year1 <- data.frame(rep(1, n/3))
year2 <- data.frame(rep(2, n/3))
year3 <- data.frame(rep(3, n/3))

require(plyr)
years <- rbind.fill(year1, year2, year3)
years[is.na(years)] <- 0
years <- as.factor(rowSums(years))

y <- round(runif(n),0)
reg <- lm(y ~ years)

coeftest(reg, vcov = vcovHC(reg, "HC0"))

>

t test of coefficients:

             Estimate Std. Error t value Pr(>|t|)
(Intercept)  0.486486   0.027390 17.7616   <2e-16 ***
years2      -0.027027   0.038678 -0.6988   0.4849
years3      -0.012012   0.038717 -0.3103   0.7564
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Comment: Thanks for the answer. It looks perfect... I'm wondering if this could be (another) disadvantage of using linear probability models (over say logit or probit). It's not immediate to me why this would be a weakness rather than just a "curiosity."
Comment: As explained in @repmat's answer the issue is not related to whether $y$ is binary!
Answer: This will happen if, and only if, the two (or more variables) have the same variance, or in other words that all groups are equally large (in terms of 1's). The nature of $y$ does not matter.
Here is an example from R:
set.seed(42)
year1 <- data.frame(rep(1, 333))
year2 <- data.frame(rep(2, 333))
year3 <- data.frame(rep(3, 333))

require(plyr)
years <- rbind.fill(year1, year2, year3)
years[is.na(years)] <- 0
years <- as.factor(rowSums(years))

y <- round(runif(999),0)
coef(summary(lm(y ~ years)))

               Estimate Std. Error    t value     Pr(>|t|)
(Intercept)  0.48648649 0.02739570 17.7577679 1.667287e-61
years2      -0.02702703 0.03874337 -0.6975910 4.855958e-01
years3      -0.01201201 0.03874337 -0.3100404 7.565951e-01

If the groups are not equally large (has the same numbers of 1's), the errors will be similar but not identical (as above).
The intuition is that you are just estimating means in different groups. Two dummy variables will always have the same variance if the amount of 1's are the same. Because the formula for the variance is:
$$
p (1-p)
$$
Where $p$ is the (sample) mean of the variable.
Edit: To be clear, you can add other non dummy variables to the regression above. The two dummy variables will still have the same variance.
Comment: The answer appears to be that robust standard errors do not have this property in general, see my update.
Comment: "This will happen if, and only if, the two (or more variables) have the same variance, or in other words that all groups are equally large (in terms of 1's). The nature of yy does not matter."  That assumes the standard errors are calculated under the usual iid assumption, and without clustering by year, right?
Comment: As far as I can see, it requires an homoscedastic assumption on the error term. Without having worked out the finer linear algebraic properties, I can offer no guarantee
Answer: You could ask yourself the question 'Why would I expect one of them to be much larger than the others?'. I do not think you are doing anything wrong as far as specifying your model matrix is concerned. I do wonder though whether using linear regression for an outcome which is binary is a good thing. Most people would use logistic regression here.
Comment: The issue of the OP is not that they are close in value, but _exactly_ equal, implying some unanticipated exact mathematical relationship.
Comment: @AlecosPapadopoulos I was anticipating the OP asking him/herself and realising that the (unstated) equal size of the groups was the issue