Syntax errors when right shift operator is used as a template parameter

Question: If I take the address of a right shift operator and pass it as a template parameter, the right shift symbol is being misread as the end of the template parameter list, and the resulting confusion is causing multiple errors.
template <class T, void(T::*)(int)> struct TemplateMagic {};
struct TestStruct { void operator>> (int) {} };

int main() {
//All the errors are on this line:
    TemplateMagic<TestStruct, &TestStruct::operator>> >* ptr;
}

Running this in Microsoft Visual Studio Express 2013 for Windows Desktop
Version 12.0.31101.00 Update 4 gives the following errors:

error C2143 : syntax error : missing ';' before '>'
error C2275 : 'TestStruct' : illegal use of this type as an expression
error C2833 : 'operator >' is not a recognized operator or type

As far as I can tell, the operator>> > symbols are being broken apart so it reads it as operator>, followed by a terminating > to close the template arguments, and ending with a spare > for the lulz. I assume this is a bug.
Is there any way to reword this so it gets recognized as valid?
Comment: Did you try putting it in parenthesis: `TemplateMagic>) >* ptr;`?
Answer: Simply adding parentheses around &TestStruct::operator>> will force MSVC to parse it correctly.
This code compiles with MSVC 19.00.23008.0 :
template <class T, void(T::*)(int)> struct TemplateMagic {};
struct TestStruct { void operator>> (int) {} };

int main() {
    TemplateMagic<TestStruct, (&TestStruct::operator>>) >* ptr;
}

The "trick" of adding parentheses will work in many situations where an expression is ambiguous or misunderstood by the compiler.


Can't get rails search form to work with simple_form and sunspot

Question: I have a simple rails app that uses the simple_form gem for forms and I am trying to set up a search form using sunspot. I have followed the instructions in Ryan Bates' railscast on setting up sunspot and it works fine except for the fact that I know I am not using the simple_form helpers and I would like to. Here is the code for the search form:
From _search.html.erb:
<%= form_tag rules_path, :method => :get do |f| %>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
<% end %>

From rules_controller.rb:
def index
  @search = Rule.search do
    fulltext params[:search]
  end
  @rules = @search.results

  respond_to do |format|
    format.html # index.html.erb
    format.json { render json: @rules }
  end
end

Like I mentioned this works for now but the question is:
How can I alter the _search.html.erb for to use the simple_form format?
Answer: I was able to get it working by giving the form a symbol the same name as the input and specifying the URL. Take a look at the URL your form_tag produces and what simple_form_for produces with just a path. So try this in your form partial:
<%= simple_form_for :search,  url: rules_path , :method => :get do |f| %>
    <%= f.input :query, :autofocus => true %>
    <%= f.submit "Search" %>
<% end %>

if that doesn't work, study what your form_tag produces and try to replicate that with simple_form.
Answer: For to do this I'm using simple_form the next way:
1. Define a form(I use haml)
=simple_form_for :search, url: search_path(:search), :method => :get  do |f|
 =f.input :q
 =f.submit "Search"

2. Define a route in routes.rb
get '/jobs/search/:q', :to => 'jobs#search', :as => :search

3. Define a method inside your controller (in my case jobs_controller.rb)
  def search
   @search = params[:search][:q]
  end

Answer: Have you tried the following:
<%= simple_form_for rules_path, :method => :get do |f| %>
  <%= f.input :search %>
  <%= f.button :submit %>
<% end %>

Comment: I tried that and got the following error: `undefined method `rule_rule_rule_rule_rule_rule_rule_rule_rule_rule_rule_rule_path' for #<#:0x00000103b733e8>`
Comment: Woud you try `<%= simple_form_for rules_path do |f| %>` instead please?
Comment: When I try that the submit button says "Save /rules" and attempts to save a new rule when clicked.
Comment: What is missing is the `:method => :get`, sorry!
Comment: That still has the problem where the submit action links to saving an empty new action link the above comment.
Answer: Use my guide to get simple_form in-place search boxes working with AJAX: http://rexstjohn.com/in-place-ajax-search-box-with-ruby-simple_form-gem/


How to filter 2 values in R?

Question: in my dataset, there are some null values (NA) and "tbd" values. I want to remove this 2 values. I have tried this one and didn't works.
train%>%
  filter(!is.na(User_Score) & User_Score!="tbd")%>%
  summarise(
    Max=max(User_Score),
    Min=min(User_Score),
    Mean=mean(User_Score),
    Median=median(User_Score),
    QUA1=quantile(User_Score,1/4),
    QUA3=quantile(User_Score,3/4),
    IQR=IQR(User_Score)
)

I also tried this one too, but still the same.
train%>%
filter(User_Score != NA & User_Score != "tbd")%>%
summarise(
 Max=max(User_Score),
 Min=min(User_Score),
 Mean=mean(User_Score),
 Median=median(User_Score),
 QUA1=quantile(User_Score,1/4),
 QUA3=quantile(User_Score,3/4),
 IQR=IQR(User_Score)
)

the error said:
argument is not numeric or logical: returning NAargument is not numeric or logical: returning NAError: Problem with `summarise()` input `QUA1`.
x non-numeric argument to binary operator
i Input `QUA1` is `quantile(User_Score, 1/4)`.
Run `rlang::last_error()` to see where the error occurred.

any ideas how to fix it? thanks before
Answer: A column can have data of only one type. Since you have values in the data which are not numeric ('tbd') the type of column is character. After removing the values convert the column to numeric and then perform the calculation.
library(dplyr)

result <- train%>%
  mutate(User_Score = suppressWarnings(readr::parse_number(User_Score))) %>%
  filter(!is.na(User_Score)) %>%
  summarise(
    Max=max(User_Score),
    Min=min(User_Score),
    Mean=mean(User_Score),
    Median=median(User_Score),
    QUA1=quantile(User_Score,1/4),
    QUA3=quantile(User_Score,3/4),
    IQR=IQR(User_Score)
  )

Comment: thankyou for answering my question, i have tried your code, but now the error is

Error: Problem with `summarise()` input `QUA1`. x missing values and NaN's not allowed if 'na.rm' is FALSE i Input `QUA1` is `quantile(User_Score, 1/4)`. Run `rlang::last_error()` to see where the error occurred.

what does this mean?
Comment: Some example data to debug the issue would have been helpful but I think that means there are other values in your data which are not numeric. Try the updated answer.

How to filter 2 values in R?


Is there a way to animate animatedContainer within a fixed width Container?

Question: I'm having trouble simulating a "colour countdown" within my app. Basically, I want the inside container to slowly shrink (from top to bottom) while the outside container (with the border) stays the same in width and height. Right now, my code adjust both of the containers instead of just the innermost one.
Google's documentation and tutorials don't have much to say about this niche case. Is this even possible?
Below is what it looks like without setting a width and height to outside container
Good trial
and here is what it looks like when I do set a width and height.
Bad trial
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:scoped_model/scoped_model.dart';
import 'package:timely_flutter/scoped_models/model.dart';

class Timer extends StatefulWidget {
  State<StatefulWidget> createState() => _Timer();
}

class _Timer extends State<Timer> {
  _Timer();

  MainModel model;
  var width = 600;
  var height = 500;
  var margin = EdgeInsets.only(bottom: 10.0, right: 10.0, left: 10.0);
  var backColor = Colors.black;
  var text = Text("Hello", style: TextStyle(color: Colors.white),);
  bool selected = false;

  Widget build(BuildContext context) {
    return ScopedModelDescendant<MainModel>(
      builder: (BuildContext context, Widget child, model) {
        return GestureDetector(
            onTap: () {
              print("clicked");
              setState(() {
                selected = !selected;
                print(selected);
              });
            },
            child: Container(
              margin: const EdgeInsets.all(5),
              padding: const EdgeInsets.all(5),
//              height: height.toDouble(),
//              width: width.toDouble(),
              decoration: BoxDecoration(
                border: Border.all(color: Colors.black)
              ),
            child: new AnimatedContainer(
              height: selected ? height / 4: height / 1.5 ,
              width: width /1.5, // this will give you flexible width not fixed width
              margin: margin, // variable
              color: backColor,// variable
              duration: Duration(seconds: 4),
              curve: Curves.fastOutSlowIn,
              child: new Column(
                children: <Widget>[
                  new Expanded(
                    flex: 1,
                    child: new Container(
                      alignment: Alignment.topCenter,
                      child: text, //varaible above
                    ),
                  ),
                  new Expanded(
                    flex: 1,
                    child: new Container(
                      alignment: Alignment.bottomCenter,
                      child: text, //variable above
                    ),
                  ),
                ],
              ),
            )
        )
      },
    );
  }
}

Comment: The outer container will resize to fit the child widget unless set dimensions are given. Setting constant height and width to the parent container might help you or you can wrap the child container with a `SizedBox`
Answer: Set a width and a height to the fixed Container, so that it won't resize to fit its child.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:scoped_model/scoped_model.dart';
import 'package:timely_flutter/scoped_models/model.dart';

class Timer extends StatefulWidget {
  State<StatefulWidget> createState() => _Timer();
}

class _Timer extends State<Timer> {
  _Timer();

  MainModel model;
  var width = 600;
  var height = 500;
  var margin = EdgeInsets.only(bottom: 10.0, right: 10.0, left: 10.0);
  var backColor = Colors.black;
  var text = Text("Hello", style: TextStyle(color: Colors.white),);
  bool selected = false;

  Widget build(BuildContext context) {
    return ScopedModelDescendant<MainModel>(
      builder: (BuildContext context, Widget child, model) {
        return GestureDetector(
            onTap: () {
              print("clicked");
              setState(() {
                selected = !selected;
                print(selected);
              });
            },
            child: Container(
              width: width,
              height: height,
              margin: const EdgeInsets.all(5),
              padding: const EdgeInsets.all(5),
//              height: height.toDouble(),
//              width: width.toDouble(),
              decoration: BoxDecoration(
                border: Border.all(color: Colors.black)
              ),
            child: new AnimatedContainer(
              height: selected ? height / 4: height / 1.5 ,
              width: width /1.5, // this will give you flexible width not fixed width
              margin: margin, // variable
              color: backColor,// variable
              duration: Duration(seconds: 4),
              curve: Curves.fastOutSlowIn,
              child: new Column(
                children: <Widget>[
                  new Expanded(
                    flex: 1,
                    child: new Container(
                      alignment: Alignment.topCenter,
                      child: text, //varaible above
                    ),
                  ),
                  new Expanded(
                    flex: 1,
                    child: new Container(
                      alignment: Alignment.bottomCenter,
                      child: text, //variable above
                    ),
                  ),
                ],
              ),
            )
        )
      },
    );
  }
}


How do I locate the source of an Unmanaged exception?

Question: I have a WinForms application in which I want to be able to provide an HTML editing feature.  So I've translated Lutz Roeder's HTML Writer from C# into VB.NET, and converted it from a windows form into a Custom User Control, which is now hosted in an MDI child form.
It all works fine until I close the parent MDI, in which case it crashes, and I cannot trap the exception.
I've isolated the editor control into a little vanilla WinForms app that doesn't do anything else, and verified that the problem still occurs.
I've also switched on Unmanaged Code Debugging (I'm using VS2010, compiling for x86 and Framework 3.5), and all I get is this:
Windows has triggered a breakpoint in HtmlEditorMdi.exe.
This may be due to a corruption of the heap, which indicates a bug in HtmlEditorMdi.exe or any of the DLLs it has loaded.
This may also be due to the user pressing F12 while HtmlEditorMdi.exe has focus.
The output window may have more diagnostic information.

The only thing other thing I've noticed is that if I leave a long interval after opening the form containing the editor, it doesn't crash.
What I'd really appreciate is some ideas about how to go looking for this problem.  It may be of course that I've made a mistake in the C# to VB conversion, but I'm struggling to know where to look.
Edit:
I've run the app with the debugger attached, and it doesn't give me anything useful.
All I get is the Windows 'Application has stopped working' message, with this in the problem details:
Problem signature:
  Problem Event Name:   APPCRASH
  Application Name: HtmlEditorMdi.exe
  Application Version:  188.8.131.52
  Application Timestamp:    4cfb74c7
  Fault Module Name:    mscorwks.dll
  Fault Module Version: 2.0.50727.4952
  Fault Module Timestamp:   4bebd49a
  Exception Code:   c0000005
  Exception Offset: 000022b5
  OS Version:   6.1.7600.2.0.0.256.1
  Locale ID:    2057
  Additional Information 1: 0a9e
  Additional Information 2: 0a9e372d3b4ad19135b953a78882e789
  Additional Information 3: 0a9e
  Additional Information 4: 0a9e372d3b4ad19135b953a78882e789

I can see that it's an access violation, but even if I go Debug > Exceptions > Win32 Exceptions, and tick c0000005, I don't get anything useful when it breaks - just 'no source available'.
Comment: Can you not attach the debugger using VS and find the exception which is being thrown? Unmanaged exceptions usually have more info in the 'Detail' array inside them.
Comment: To attach (from memory) it's Debug > attach to process, and then load any symbols you need (.pdb file).
Comment: @JD:  Does this give you something different from running the whole thing inside Visual Studio?
Answer: The first message you quoted is produced by the Windows heap manager when it discovers that the internal heap structure is destroyed.  It displays that diagnostic when it sees that a debugger is attached.  The 2nd quoted block is what happens when it bypasses the diagnostic (no debugger attached), it bombs on a hardware exception when it tries to release memory in the corrupted heap anyway.
The trouble with heap corruption is that the real damage is done a long time before the diagnostic is generated.  You can see a stack trace leading up to the diagnostic in the Call Stack window, you'll need to enable the Microsoft symbol server to get meaningful symbols for the Windows functions.  But it won't tell you anything useful about the code that really caused the damage, that requires a time machine.
This kind of heap corruption is invariably caused by unmanaged code.  The AccessViolation exception is a well known scourge to C/C++ programmers and a very large reason why managed code became popular.  While Lutz' source code is all managed, it contains a lot of P/Invoke and COM interface declarations.  There is no good way to debug them, you don't have the source code.
Getting one of those declarations subtly wrong when you converted them to VB.NET is certainly one way this could happen.  It could also well be that the bug was always there but reared its ugly head just now.  Lucky you.  Btw, I don't think the code is 64-bit clean, force it to run in 32-mode for a possible quick fix.  For your main EXE project: Project + Properties, Compile tab, scroll down, Advanced Compile Options, Target CPU = x86.  This is only relevant if you run on a 64-bit version of Windows.
Other than that, I'd recommend you just use the C# project as-is.  Mixing languages in a solution is a very well supported scenario in .NET.
Comment: Thanks for this.  It very much confirms the conclusions I was coming to.  I've now converted the original into a C# Winforms User Control that I've embedded in my VB WinForm.  Sure enough, the problem doesn't recur, so I assume that I made some error in the original translation.  I might look again for it when I have a spare lifetime or two...
Answer: The windbg debugger is the "big gun" for this sort of problem. It can frequently give you clues by telling you about handled exceptions etc. The only problem with it is that it's not easy to use and has a very high learning curve.


Non-oriented Rubiks Cube Group

Question: Consider the (non-oriented, so we do not care about the center of each side) rubiks cube group, $G$, which is a subgroup of $S_{48}$ and is generated by the letters: $\{F,B,U,D,L,R\}$, i.e. I mean that $G = \langle F,B,U,D,R,L\rangle$ (subject to the canonical relations for the non-oriented $3\times 3$ rubiks cube). I am trying to just manually verify if the superflip is in the center (just by verifying if it commutes with each of the generators) using https://rubikscu.be/#cubesolver , but this is exceptionally cumbersome and time consuming. Let $h\in G$ denote the superflip. I have seen other websites, MSE pages, and pdfs describe the center as simply only containing $1_G$ and $h$, but these pages very rarely distinguish if they mean the oriented cube (the subgroup of $S_{54}$) or non-oriented, I am not really sure if it matters either (but furthermore, I am really sure how one would rigorously prove this in any case, the arguments I can find are mostly fairly ambiguous).
Comment: I don't think expressing $h$ in terms of those generators should really be necessary. We know exactly how each group element moves each cubie, so we can just look at the final results of, say, $hR$ and $Rh$ on each cubie to prove they are equal.
Comment: BTW, I've rarely seen people talking about the "oriented" rubik's cube group, which in my mind makes sense since most rubik's cubes don't have centers which allow one to visually recognize a rotation of a center piece.
Comment: By the way, in the oriented cube group any element that only twists centres but leaves the edges/corners alone will be in the centre of the group (as will any of those combined with the superflip).
Answer: As aschepler mentioned in the comments, it's irrelevant how the superflip is realized in terms of the generators. Since the Rubik's Cube group is formally just a subgroup of $S_{48}$, an element like $h$ is literally just a permutation.
But first, let's choose something other than $\{1,\ldots,48\}$ to serve as the set whose permutations we consider.
Let's label the faces as Front, Bottom, Up, Down, Right, Left, and denote the 48 faces

for corners: like "FUR" to denote the Front sticker (hence the first letter) of the front-up-right cubelet
for edges: like "FU" to denote the Front sticker of the front-up cubelet.

To avoid ambiguity, let's further deviate from the standard notation and add commas so that a cycle looks like $(FU,UF)$.
For any term representation of the superflip, we will be able to calculate
\begin{align*}
h = &(FU, UF)(FR,RF)(FD,DF)(FL,LF)\\
    &(UR,RU)(UL,LU)(DR,RD)(DL,LD)\\
    & (BU,UB)(BR,RB)(BD,DB)(BL,LB).
\end{align*}
Note in particular that $h$ is of order two.
To prove that it commutes with every cycle, let's refresh our memories and see how the generators are defined:
\begin{align*}
R &:=(\text{corner cycles})(RU, RB, RD, RF)(UR,BR,DR,FR)\\
U &:=(\text{corner cycles})(UR,UF,UL,UB)(RU,FU,LU,BU)\\
F &:=(\text{corner cycles})(FU,FR,FD,FL)(UF,RF,DF,LF)\\
L &:=(\text{corner cycles})(LU,LF,LD,LB)(UL,FL,DL,BL)\\
D &:=(\text{corner cycles})(DF,DR,DB,DL)(FD,RD,BD,LD)\\
B &:=(\text{corner cycles})(BU,BL,BD,BR)(UB,LB,DB,RB).
\end{align*}
It is now easy to verify that each of the commutators $R^{-1}h^{-1}Rh$ etc. vanish, or, equivalently (and perhaps easier to verify if you know what conjugation does in terms of permutations :-) ), that $h^R := R^{-1}hR = h$ etc.  Notice in particular that since $h$ leaves corner faces invariant, the respective corner cycles in the generators don't contribute to the commutator, explaining why I left them out above.
As you correctly stated, if $h$ commutates with all generators, it has to lie in the center.

Non-oriented Rubiks Cube Group


SNMP packet capture missing in wireshark

Question: I have polled asynchronously a SNMP device in a simulated network using a java file, written with SNMP API. In a 30 seconds of polling time, I have sent around 350000 V1 Get requests.
My SNMP API listener showing that all the request have been sent and got success response for each request. But when I capture the packets using wireshark, it is not showing that all the packets are sent. When I check the request id of the snmp packets in wireshark,I could able to find out that the last request's requst id is same to the total number of packets sent by SNMP API. But request id of some other SNMP packets are missing in the wireshark.
Is there any limitation to wireshark like that it can capture only a particular number of packets per second?
Why this scenario occurred? Please help me to figure out this.
Thanks in advance.
Comment: Are you seeing any SNMP frames at all?
Comment: How many packets are missing in the capture?
35k is a fair few packages to send in only 30s so maybe wireshark cannot handle the load?
Comment: For a 1 second polling, all the packets are captured in wireshark successfully. But when the polling time is increased, packet missing is occurred. For a 30 second polling, 35k requests, wireshark missed around 3k requests. If my API showing that 35k requests was sent, the first request id in wireshark is 1 and the last request id is 35k. But in between 1 and 35k, some requests are missing in wireshark. Is there any maximum load limit in wireshark?
Answer: What do you mean by "simulated network"? If you are running a virtual network on your own PC then the packets will not go through your network and Wireshark will not pick them up. You can find more information and possibly a fix in the Wireshark wiki.
Some other things to look at:

Make sure Wireshark is capturing from the correct interface.
Check if the packets aren't filtered out.
Comment: I captured the packets on local and any interface. Only around 3k requests are missing, other packets are getting captured
Comment: I am using Ubuntu 12.04.5 LTS machine. Wireshark version is 1.6.7 with libcap version is 1.1.1
Comment: I have updated wireshark from 1.6.7 to 1.8.2 using the commands : "sudo add-apt-repository ppa:eugenesan/ppa sudo apt-get update sudo apt-get install wireshark".

In this one also the libcap version is 1.1.1. Packet missing is occuring in this 1.8.2 version also, when I used the SNMP API polling java file.
Comment: When I used a script file using the netsnmp command for polling, out of 300000 requests, 287 were missing. The script file content is given below. "for (( i=1; i<=300000; i++ )) do snmpget -v 1 -c public -t 5 18.104.22.168:8001 .126.96.36.199.220.127.116.11.0 done "

The request per second sent by the netsnmp script file is very much less than the request per second sent by the SNMP API java file. That may be the reason for the missing packet count is reduced for netsnmp request.

From this can I confirm that wireshark will miss packet capture for a large number of request per second?
Comment: I tried to install the wireshark 1.12.7 from www.wireshark.org, in my Ubuntu 12.04. I downloaded the source code for installation. But there was no make file present in that tar file, as said in the "https://www.wireshark.org/docs/wsug_html_chunked/ChBuildInstallUnixBuild.html"

Can you please help me how can I install wireshark 1.12.7 in my machine?

Is that version contain the latest libcap version so that there should not be any missing packets?


Identity theorem for polynomials in several variables

Question: Let us assume that we are given two polynomials $f,g$ with real coefficients in several variables, say $x_1, \ldots, x_n \in \mathbb{R}$. Further, assume that $f_{|X} \equiv g_{|X}$, with $X$ being the open ball around some $a \in \mathbb{R}^n$, i.e. $X = B_\delta(a)$.
Question: Does this imply $f \equiv g$?
It is clear to me that this holds in the case of polynomials in one variable, i.e. $n = 1$.
According to Wikipedia the identity theorem of complex analysis carries over to several variables only in the case of special sets $X$. Unfortunately, I was not able to find a book which discusses this in detail. And even this applies, it is not clear to me whether this would yield the statement for the real domain.
Any piece of information would be appreciated.
Best wishes,
Max
Answer: Use induction. Fix $(x_1,\dots,x_{n-1})\in B_\delta(a_1,\dots,a_{n-1})$. By the uniqueness theorem for holomorphic functons of one variable,
you obtain $f(x_1,\dots,x_{n-1},z_n)=g(x_1,\dots,x_{n-1},z_n)$ for all $z_n\in\mathbb{C}$ and $(x_1,\dots,x_{n-1})\in B_\delta(a_1,\dots,a_{n-1})$. Then proceed to $x_{n-1}$, etc.
Alternatively: assume without loss in generality that $a=0$. Let $f=\sum a_\alpha x^\alpha$, $\alpha=(\alpha_1,\dots,\alpha_n)$ being a multiindex. Then
$$
  a_\alpha=(\alpha_1!\dots \alpha_n!)^{-1}\frac{\partial^{|\alpha|}f}{\partial x^\alpha}(0),
$$
that is, all coefficients of a polynomial are determined by its values in an arbitrarily small ball.
Comment: Very nice answer.


Ordinal independent variable (IV) and continuous dependent variable (DV)

Question: My independent variable is measured on a likert scale (1–5).
My moderator is dichonomous (yes or no)
I want to use SPSS process macro to measure the moderation relationship. Should I use a dependent variable that can only take values 1,2,3,4,5 (same as IV) or can I use a continuous variable with a range of 10–20?
In case I go with the latter, will my results make sense given that the range of the IV and DV are completely different?
Answer: You should use the DV that you want to analyze.
There is no need for the DV and IV to be on the same scales, or have the same range, or anything else like that.
Questions about how to use SPSS (or any program) to do things are off topic here, but I will say that if SPSS can't handle this, get a new program.  (I'd be amazed if that was the case; SPSS isn't my favorite stats program, but this is pretty elementary. However, I know nothing about the process macro).


How exactly do I use a makefile?

Question: I'm really confused at the moment.
So I have 5 files: main.c, flight.c, flight.h, passenger.c, and passenger.h
flight.h has function prototypes for flight.c, and passenger.h has function prototypes for passenger.c
flight.c and passenger.c have definitions for these functions.
main.c is the program I'll interact with, calling functions from both .c files
I'm not really sure what .o files are for, somebody please care to explain? Here is my Makefile:
flight.o: flight.c flight.h
    gcc -Wall -g -c flight.c
passenger.o: passenger.c passenger.o
    gcc -Wall -g -c passenger.c
main.o: main.c
    gcc -Wall -g -c main.c
reservations.out: main.o flight.o passenger.o
    gcc -Wall -g flight.o passenger.o main.o -o reservations.out

EDIT: I then use the command "make Makefile", and get an error: make: Nothing to be done for `Makefile'.
In my file there is a tab before gcc.
I'd appreciate any help, I'm sure there are lots of things I'm doing wrong. Thanks.
Comment: don't type 'make Makefile', type 'make reservations.out'.
Comment: Is your editor converting tabs into spaces?  It needs to be a tab character.
Comment: looks like it got converted back into spaces after I unticked the use spaces option, I'l check
Comment: consider just calling the program "reservations", the .out extension is uncommon these days.
Comment: Btw, make does have a `-f` option to specify the makefile, so `make -f Makefile` does what you're trying to do with make Makefile. But `Makefile` is one of a number of magic names that GNU make uses by default, so `-f` isn't needed here. The non-option arguments to make are the "targets" that you want to build. The reason you get "nothing to be done" is that you've asked make to build Makefile, and Makefile has no dependencies. Since it exists, make says "nothing to be done". If it didn't exist, make would say "no rule to make target `Makefile'".
Answer: Your problem is that you're using the wrong command.  I would add the following line to the top of your makefile:
all: reservations.out

Then just type make at the command line.  If you don't want to edit the file, just use make reservations.out and you should get the right behaviour.
As to what a .o file is:  it's an 'object' file, meaning it contains compiled (but in this case not linked) code.  Your final makefile rule takes the object files and links them together into a final executable called reservations.out.
Now that I look at it some more, it looks like you have some weird behaviour on your final rule.  I think it should look more like:
reservations.out: main.o flight.o passenger.o
    gcc -Wall -g main.o flight.o passenger.o -o reservations.out

In addition, you have passenger.o as a prerequisite of passenger.o, which is for sure going to cause you problems.  What I would do is something like this (it could be even tighter, but I'm trying to make this straightforward):
.PHONY: all clean

all: reservations.out

flight.o: flight.c flight.h
    gcc -Wall -g -c flight.c

passenger.o: passenger.c passenger.h
    gcc -Wall -g -c passenger.c

main.o: main.c
    gcc -Wall -g -c main.c

reservations.out: main.o flight.o passenger.o
    gcc -Wall -g main.o flight.o passenger.o -o reservations.out

clean:
    rm -f *.o reservations.out

But what I would really do, if you want to get a bit more into the details, is below.  It might be a bit overkill for such a small project, but it's also easier to tweak and fiddle with as necessary.
.PHONY: all clean

BIN = reservations
OBJ = flight.o passenger.o main.o

all: $(BIN)

%.o: %.c %.h
    gcc -Wall -g -c $<

main.o: main.c
    gcc -Wall -g -c $<

$(BIN): $(OBJ)
    gcc -Wall -g -o $@ $^

clean:
    rm -f $(OBJ) $(BIN)

I recommend checking out the GNU make manual to learn more about all of the fancy stuff you can do.
Comment: Also, I get this message: "make: Circular passenger.o <- passenger.o dependency dropped."

Is that significant? It is just a rule that I'm not supposed to have any warnings so I'm wondering what that message is about.
Comment: That message is because you have passenger.o as a prerequisite (right hand side of a rule) for itself.
Answer:
I'm not really sure what .o files are
  for, somebody please care to explain?

.o are object files, the temporary files which are created by the compiler, which contains the object code for the class. The object codes will be linked by the linker to create an executable binary file.
Comment: I guess there is one for every .cpp file
Comment: anybody please correct me, If I am wrong, I am Windows guy and don't write makefiles.
Comment: Windows has them also, but uses the .obj extension. If you're writing a library, you can distribute the .o and .h file to give people code they can use without giving away your source code. Dynamic libraries (.dll on Windows, .so on Unix) are usually distributed now instead - both ways work, and a comparison is too long for this (already long) comment.
Comment: .o is a pretty standard extension for files that contain compiled but not linked code.  You would then pass these .o files to the linker to end up with an executable file.  In the OP's post, he appears to be calling the linker through the gcc interface, rather than calling it directly; that's fine for such a simple example.  @Priyank has the fundamentals about right (though I think C programmers might take an issue with the use of the word 'class' in his answer).
Answer: make has implicit rules for making binaries out of C source, you don't need to specify explicit rules for this.
So your minimalistic Makefile would look like
CFLAGS = -Wall -g
.PHONY all clean

all: myprogram

myprogram: source1.c source2.c

clean:
    rm -f myprogram

It has one useful side effect - all intermediary files (*.o files in your case) will be deleted automatically after the compilation.
Options from CFLAGS will be added to gcc command line - make implicit rule does it.

How exactly do I use a makefile?


Can one write to a wrapped Stream in java?

Question: I'm writing a java server for an assignment, and I have observed some strange behaviour when I write both into a wrapped stream and a wrapper stream, can this cause any problems ? As far as I see, it can, but how ? Pls enlighten me.
as an example:
OutputStream os = new OutputStream(...);
PrintWriter pw = new PrintWriter(os);

And I want to write both in the PrintWriter, and the OutputStream.
Comment: Do you mean you're using both the `PrintWriter` and the `OutputStream` directly to write?
Comment: Exactly, is that a bad idea  ?
Answer:
To transfer from byte-based stream to character-based stream, you need to use OutputStreamWriter:

An OutputStreamWriter is a bridge from character streams to byte streams.

So that would be:
OutputStream os = ...
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
PrintWriter pw = new PrintWriter(osw);

I think the problem is that you need to specify the encoding, since the constructor PrintWriter(OutputStream out) uses the default encoding which might not be correct for your data input:
OutputStream os = ...
PrintWriter pw = new PrintWriter(os, "UTF-8");


How to add spacing between checkboxlist items?

Question: I have checkboxlist within a table I am using. The checklist I need to line up with checkboxes in the second column. The spacing of each row of the textboxes(second row) is 26px. I can not find how to do spacing between items on checkbox list. Setting margins only does the outside of the list not items within.

I tried cellspacing but I cant get it quite lined up.
Update 2

                <asp:CheckBoxList ID="cbtasklist" runat="server" CssClass="radiobutton">
                    <asp:ListItem Value="Task 1">Task 1</asp:ListItem>
                    <asp:ListItem Value="Task 2">Task 2</asp:ListItem>
                    <asp:ListItem Value="Task 3">Task 3</asp:ListItem>
                    <asp:ListItem>Task 4</asp:ListItem>
                    <asp:ListItem Value="Task 5">Task 5</asp:ListItem>
                    <asp:ListItem Value="Other1">Other</asp:ListItem>
                    <asp:ListItem Value="Other2">Other</asp:ListItem>
                </asp:CheckBoxList>

.auto-style187 {
        height: 26px;
        width: 357px;
    }

Update 3:
  Would it be easier to do a checkbox for each line so I can use the same CSS as the other column?
The reason for the checkbox list is for validation that 1 must be selected.
Comment: Have you tried the CheckBoxList.CellSpacing property? https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.checkboxlist.cellspacing(v=vs.110).aspx
Answer: I hope you are looking for this
   <form id="form1" runat="server">

                <asp:CheckBoxList ID="CheckBoxList1" runat="server" Height="163px">
                    <asp:ListItem>a</asp:ListItem>
                    <asp:ListItem>b</asp:ListItem>
                    <asp:ListItem>c</asp:ListItem>
                    <asp:ListItem>d</asp:ListItem>
                    <asp:ListItem>e</asp:ListItem>
                    <asp:ListItem>f</asp:ListItem>
                </asp:CheckBoxList>

                            <asp:TextBox ID="TextBox1" runat="server" OnTextChanged="TextBox1_TextChanged"></asp:TextBox>

                        aaaa

                            <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>

                        aaaa

                            <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>

                        aaaa

                            <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>

                        aaaa

                            <asp:TextBox ID="TextBox5" runat="server"></asp:TextBox>

                        aaaa

                            <asp:TextBox ID="TextBox6" runat="server" OnTextChanged="TextBox6_TextChanged"></asp:TextBox>

                        aaaa

    </form>

see the image

I just took table inside a table .You can just remove the unwanted column as your desire
don't forget to edit the text box lineup its up to you
Comment: The text is slightly off to the text boxes which they want perfect lined up.
Comment: hey now look this updated one i hope this is appropiate
Answer: why don't you try with this on your CSS:
checkbox { padding-bottom: 10px; }


Como simular um input do tipo radio para o leitor de tela?

Question: Estou fazendo uma pesquisa de satisfação que deve ser acessível aos usuários com leitor de tela.
Para cada pergunta são mostradas opções de respostas contendo um texto "Ótimo, Péssimo, ..." e uma imagem correspondente ao texto. Por fins estéticos não quero utilizar inputs do tipo radio (ou pelo menos não quero que sejam visíveis). Abaixo o código que gera uma das opções para que o usuário escolha:

    <input type="image" src="img/nota4.png" width="48" alt="Bom" onclick="return false;">

Bom

Esse link mostra a solução que já fiz até o momento (incluindo css e javascript): https://jsfiddle.net/moneisa123/o2gxgz9r/13333/
Quando o usuário clica ou da enter em uma das imagens eu altero a cor de fundo da div que contém a imagem para mostrar que o elemento foi selecionado.
Problema 1: No caso do usuário com leitor de tela, como fazer para que, quando ele pressionar enter, o leitor de tela o avise que aquele elemento foi selecionado?
Problema 2: O leitor de tela lê os inputs do tipo image como "botões", o que não é o ideal. Alguma outra sugestão de como apresentar esses elementos de forma acessível?
Obs: Estou testando com o leitor de tela NVDA.
Comment: Será que fazendo uns radio ocultos não resolveria? Por exemplo, um radio oculto para cada botão, e quando o botão for selecionado, o radio oculto referente ao botão seja selecionado.
Answer: Você pode fazer apenas com CSS, nem precisa de JS, e pode manter os inputs do tipo radio usando uma label para cada input, assim não afeta a acessibilidade.
Tenta isso aqui:
HTML

<input type="radio" name="radio" value="1" id="radio01" />Option 1

<input type="radio" name="radio" value="2" id="radio02" />Option 2

<input type="radio" name="radio" value="3" id="radio03" />Option 3

CSS
.custom-radio {
  font-family: sans-serif;
  font-size: 1.8em;
  margin: 0;
  padding: 1em;
  list-style-type: none;
}
.custom-radio li {
  float: left;
  margin-right: 0.5em;
}
.custom-radio label {
  padding: .5em;
  color: #ccc;
  border: solid 3px #ccc;
  border-radius: 8px;
  cursor: pointer;
  -webkit-user-select: none;
  user-select: none;
  -webkit-transition: all .2s linear;
  transition: all .2s linear;
}
.custom-radio input[type="radio"] {
  display: none;
}
.custom-radio input[type="radio"]:checked + label {
  border-color: #33cc33;
  color: #33cc33;
}

Comment: Funcionou muito bem, obrigada!


summing terms to the cardinality all possible subsets of a given set

Question: I am  facing the problem of computing the sum
$$\sum_{L\subset S}(-1)^{|S|-|L|},$$
where $|S|$ denotes the cardinality of a set $S$ is finite and $L$ is a proper subset of $S$.
Thank you!
Comment: Hint: add different steps to your sum. First sum over all possible cardinal of k=|S| then sum over all sets of cardinal $k$. Do the same for $L$ of course and then binomial coefficients will appear and you will be able to apply the binomial formula after this.
Answer: Given that the cardinallity of $\{L\subset S: |L| = j\}$ is $\binom{|S|}{j}$,
we have: $$\sum_{L\subsetneq S}(-1)^{|S|-|L|} = \sum_{j=0}^{|S|-1}\sum_{L\subset S,\\|L|=j}(-1)^{|S|-|L|} = \\ = \sum_{j=0}^{|S| - 1}\binom{|S|}{j}(-1)^{|S|-j} $$
Does this look familiar?
Comment: Yes, binomial formula! What about the final exponent of (-1)? It should be |S|+1 right? Because it would be $(-1)^{|S|} -1=(-1)^{|S|+1}$
Comment: @Jo R I'd actuall go by $\sum_{L\subsetneq S}(-1)^{|S|-|L|} = \sum_{L\subseteq S}(-1)^{|S|-|L|} - S\cdot (-1)^{|S|}$
Comment: I mean, if I had $j=|S|$, I would add $\binom{|S|}{|S|}(-1)^{|S|-|S|}=+1$, so I take away this term from binomial formula with total exponent |S|.
Comment: @Jo R You are correct, and my last comment is a mistake.
Answer: Finding a subset of $|S|$ of cardinality $|L|$ is the same as finding a subset of cardinality $|S|-|L|$ so let us rewrite the sum as
$$\sum_{L\subset S}(-1)^{|L|}.$$
Now, there is exactly ${|S|}\choose{|L|}$ subset of size $|L|$ in $S$. So the sum becomes
$$\sum_{|L|=0}^{|S|-1}{{|S|}\choose{|L|}}(-1)^{|L|} = (-1)^{|S|}$$
using Newton's binomial formula.


Compile error "No global operator found" for templated overloaded operator

Question: I've defined a template class and overloaded operators. When compiling, I get the following error message:

error C2677: binary '+=' : no global operator found which takes type 'Class' (or there is no acceptable conversion)

Here is the relevant code of the class:
template<int foo>
class Class
{
private:
    int value;
public:
    template<int other_foo>
    friend class Class;

    // Constructors and copy constructors for several data type
    // including other possibilities of "foo"; all tested.

    Class& operator+=(const Class& x)
    {
        value += x.value;
        return *this;
    }
    template<class T>
    Class& operator+=(const T& x)
    {
        this += Class(x);
        return *this;
    }
};

If I create two objects of, e.g., Class<3>; the operator += works fine and does the right thing.
However, if I have an object of Class<3> and one of Class<2>, I get the above error which points at the line where "+=" is defined for T [the constructor for different value of foo works fine and is also tested].
What am I doing wrong? How can I resolve this error? The operator is defined, just a few lines above.
Answer: Assuming that the necessary constructor does indeed exist and work correctly, the error in the code you've posted is
this += Class(x);

which tries to modify the value of the immutable pointer this. It should be
*this += Class(x);

Comment: Thanks a lot! That was the problem.
Answer: I think that there are two problems, both in this line:
this += Class(x);

One: the object added to should be *this instead of this, because the latter is a pointer, not the object itself.
Two: There is no conversion constructor from T to Class. That is, you cannot convert from Class<3> to Class<2> so the Class(x) will not compile. The solution would be to add it:
template<int other> Class(const Class<other> &o)
{}

Comment: Thanks! It now works. Thanks for the comment with the constructor from T to Class; this was already done but not included in my code snippet to not have a long code above.


flood fill algorithm initialization c++

Question: EDIT: Okay, after a few answers I will make a few corrections:
byte r, g, b;
    scr->GetRGB(mid.x, mid.y, (byte)& r, (byte)& g, (byte)& b);
    while (r != (byte)0 && g != (byte)0 && b != (byte)0)
    {
        scr->SetRGB(mid.x, mid.y, (byte)255, (byte)0, (byte)0);
        mid.x++;
        FloodFill(scr, mid);
        mid.x--;
        mid.x--;
        FloodFill(scr, mid);
        mid.y++;
        FloodFill(scr, mid);
        mid.y--;
        mid.y--;
        FloodFill(scr, mid);
    }

Plus, before I do anything with the parameters, this is the GetRGB function:
void CDIB32::GetRGB(int x, int y, BYTE& r, BYTE& g, BYTE& b)
{
    if (x >= Width() || y >= Height())
        IERROR;

    int off = y * ByteWid() + x * 4;
    b = m_pBits[off];
    g = m_pBits[off+1];
    r = m_pBits[off+2];
}

And this is the SetRGB Function:
void CDIB32::SetRGB(int x, int y, BYTE r, BYTE g, BYTE b)
{
    //ASSERT(x < Width() && y < Height());

    int off = y * ByteWid() + x * 4;
    m_pBits[off] = b;
    m_pBits[off+1] = g;
    m_pBits[off+2] = r;
}

The assumption of user OzMiz is correct, that the line causing the error. Apologies for the lack of clarity. And this algorithm is indeed a snippet from this exact algorithm you thought about. Any idea on how to do that better is appreciated.
Comment: Code looks very broken to me (e.g. that `while` loop condition !). I suggest looking for a better example to work with.
Comment: What's the signature of the `GetRGB()` and `SetRGB()`  functions?   And on which exact line does the error occur?
Comment: That code slightly looks like snippet from badly broken naive flood-fill algorithm but it is too few to tell for sure.
Comment: @LogicStuff it's answerable - not easily, granted, but I've seen worse
Answer: The error messages suggests that the GetRGB function is expecting the RGB parameters to be BYTE&, i.e. references to bytes.
You should therefore declare your local r, g and b variables accordingly, and just pass them straight to the function:
BYTE r, g, b;
scr->GetRGB(mid.x, mid.y, r, g, b);

Your while loop is also broken - you need to use && or || to join the three conditions, not the , operator.
Comment: When I do that, the code compiler and the program runs, but activating this function causes an unhandled exception.
Comment: @Erthain when you do what exactly, and what exception, at what line?
Comment: @Erthain but at a guess, you're exceeding the bounds of the image...
Comment: @Erthain it's also possible you should be using `||` rather than `&&` if the intent is to detect any non-black pixel
Comment: Unless I am more retarded than I assume I am, I cannot specify that exception: its a runtime thing and it just gives me the memory location. Look over the two other functions, I think they give the security measure for the image size.
Comment: @Erthain right, but you've got no logic in the fill function to check that `x` and `y` stay within those bounds, and if they exceed it there's that call to `IERROR`.  Your debugger _should_ be giving you a traceback.
Comment: Debugger does give me a traceback to the line: scr->GetRGB(mid.x, mid.y, r, g, b);, but not to the IERROR. You think its that, or should it trace to the IERROR directly in the function? By the way, thank you for your patience ^^
Answer: I assume you are getting the error for this line:
scr->GetRGB(mid.x, mid.y, (byte)& r, (byte)& g, (byte)& b);

The last three arguments are addresses and you try to cast them into values.
I think this will resolve your error:
scr->GetRGB(mid.x, mid.y, (byte*)& r, (byte*)& g, (byte*)& b);

Comment: Hmm.. I am not sure... maybe the compiler refers to the &r as BYTE& expression? We need to see the GetRGB signature to be sure.
Comment: ITYM just `&r` - if `GetRGB` expects a `byte*` then there's no need for the cast.
Comment: and in fact it appears to be expecting a `BYTE&`
Comment: I added the function you asked about. Please refer to the edited text and thank you for your assistance.

flood fill algorithm initialization c++


Instant App screen orientation

Question: How can I disable screen orientation in Android Instant app???
I used
android:screenOrientation="portrait"
in every Manifest file (in 3 files) but it doens`t help!
Comment: share your code snippet.
Comment: do you want to fix the orientation in portrait or leave it upon the device's orientation?
Comment: Possible duplicate of [Android - disable landscape mode?](https://stackoverflow.com/questions/582185/android-disable-landscape-mode)
Comment: FIXED!)
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

Thanks!)
Answer: Thanks for reporting the bug Igor. The fix for setting screenOrientation through Manifest in instant apps is coming soon.
Answer: You can do it something like
   From Fragment
 getActivity().setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);  // programmatically

 From Activity
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

Instant App screen orientation


How easy is Drupal for E-Commerce?

Question: I'm looking for the right tool to develop a peer to peer trading website that would include E-Commerce. The site would need to allow registered sellers to enter details about their products this information would then need to be stored in a database that would allow buyers to search based on a set of parameters.
Would all this be achievable with current Drupal modules and how much additional coding would be required to knit it all together?
Answer: You don't need any coding to achieve this functionality, you can just go with Commerce and using Drupal's built-in roles, manage who has the permission to create content (items to sell) and who has the permission to buy it.
for the search aspect of it, I suggest trying Search API, which gives you facet like filtering feature (Like ebay), also you might wanna check Apache Solr for faster indexing
Comment: Thanks guys. Really useful I'll check out the suggested links and give it a go. When is D8 due for release?
Answer:
Would all this be achievable with current Drupal modules

Yes your requirements/specs seem to be perfectly doable with "current" Drupal, if you're talking about Drupal version 7 and starting from Drupal Commerce with specific add-on modules.
For Drupal version 8, things will get even better ... provided you can be a bit patient. Refer to Commerce 2.x for Drupal 8 for lots of details about what's coming up in D8 ...

How much additional coding would be required to knit it all together?

Since Drupal Commerce is pretty much entity based, you'll get a lot of things done without additional coding, only using modules such as Rules, Group, etc.

How easy is Drupal for E-Commerce?


Disconnecting from a wifi network in bash

Question: I am trying to figure out how to disconnect from wifi network without actually taking down the entire interface like in the command below.
ifconfig wifi0 down

Is there any way to disconnect from wifi in vanilla bash without having to use any external package ?
Comment: I can't say **no** definitively, but I'll be real surprised if what you ask for is possible. The main purpose of a shell is to make it easy to control external programs. The unix/linux philosophy is that a program should perform one task well (and if appropriate be able to communicate thru (to and from) via `|` pipes). Will be interested to see if someone has a way of doing this without calling some external program. Also, can you point to something in the GUI interface that distinguishes between "disconnecting" vs "taking down the entire interface" (I don't seen the diff). Good luck!
Answer: It depends completely on what program is managing your wifi connection.
The default for debian, NetworkManager, has a cli tool, called nmcli.
You can list all configured connections with:
nmcli con list

Then you can deactivate a connection with:
nmcli con down <id>

Comment: This is nice, because it does not require root privilege (just like the GUI method does not)
Comment: "Vanilla bash" does not have builtins to connect to a wifi network.
Answer: To remove all connections do:
nmcli --fields UUID,TIMESTAMP-REAL con show | grep never |  awk '{print $1}' | while read line; do nmcli con delete uuid  $line;    done


Como abrir um link com o texto de uma div

Question: Quero criar um botão e o link que abrir nele seja de uma div que esteja no meu site por exemplo em JavaCcript
var elemento = document.getElementById('teste').innerHTML;

button2.onclick = function() {
 window.open(elemento)
}

o var elemento recebe a URL e quando clico no botão abre a url do elemento ('teste').innerHTML;
Como faço isso? Esse não funciona.
Comment: Não funciona? O que acontece? Como definiu `button2`? E qual é o valor na `div`? Aliás, qual é a estrutura do HTML?
Comment: estou perguntando como faço isso só dei um exemplo bobo
Comment: o link que o botão for abrir quando clicar nele ser de um elemento que coloquei na pagina,por exemplo crio uma div com uma url e quero que o link do botão seja a texto da mesma.
Comment: Pelo o que descreveu, seu exemplo chega bem próximo de fazer o que quer. Tente implementar baseado no seu exemplo e, se não funcionar, edite sua pergunta com algo mais concreto.
Answer: Você pode pegar o texto do elemento e colocar no primeiro parâmetro do window.open que se refere à URL que será aberta na janela:
HTML

    http://url_foo.com

<button>Abrir</button>

JS
button2 = document.querySelector("button");
button2.onclick = function() {
   var elemento = document.querySelector("#teste").innerText.trim();
   var popup = window.open(elemento,'_blank','width=500, height=300');
}

Teste no JSFiddle
Comment: quase isso amigo,quero que o link que seja aberta ao invés de conter o texto a url dele seja o texto
Comment:
   www.google.com

Olá!

Abrir
Comment: @MinelopsMl Resposta atualizada. Veja se era isso?
Comment: funcionou sim,muito obrigado!  ;)


How to specify VAR dynamics of factors in Dynamic Factor Model in R

Question: I'm working on a forecasting model. The standard form for it is:
$y_t=\Lambda^*f_t+u_t\\f_t=A_1f_{t-1}+...+A_pf_{t-p}+e_t$
where $f_t$ is a vector of factors obtained from Principal Component Analysis that follows some VAR(p) dynamics. I have no problem with the PCA or the VAR estimation in my dataset, but I struggle with getting the Kalman filter right. I am trying to use R's dlm function, but the standard model specification there is:
$y_t=F^*f_t+u_t\\f_t=Gf_{t-1}+e_t$
I am aware that the dlm function should allow me to specify any dynamic I want for the factors to follow, as already mentioned in an answer on CV here, but I can't work out how to do that - do I create a block matrix with $A_1, ..., A_p$ blocks on the diagonal? If so, how do I then estimate the variance-covariance matrix (call it $E$) using the residuals from my VAR? How can I make the dimensions work? It seems to me that $E$ can only be a $k\times k$, where $k\times1$ is the dimension of $f_t$...
Answer: Package dlm provides the function dlmModARMA, which creates a state space representation of a specific univariate or multivariate ARMA model. What you get using this function is a model in which your observations are exactly the f_t. If you want a factor model, then you have to redefine the observation matrix F and the observation variance V.
Best,
Giovanni


Replace ones in binary columns with values from another column

Question: I have a data frame that looks like this:
df = pd.DataFrame({"value": [4, 5, 3], "item1": [0, 1, 0], "item2": [1, 0, 0], "item3": [0, 0, 1]})
df

  value item1   item2   item3
0   4   0      1         0
1   5   1      0         0
2   3   0      0         1

Basically what I want to do is replace the value of the one hot encoded elements with the value from the "value" column and then delete the "value" column. The resulting data frame should be like this:
df_out = pd.DataFrame({"item1": [0, 5, 0], "item2": [4, 0, 0], "item3": [0, 0, 3]})

   item1    item2   item3
0   0        4      0
1   5        0      0
2   0        0      3

Comment: i think this can be solved if you just use df["columNameToReplace"] = df["value"] and then delete the value from the dataframe ?
Answer: Why not just multiply?
df.pop('value').values * df

   item1  item2  item3
0      0      5      0
1      4      0      0
2      0      0      3

DataFrame.pop has the nice effect of in-place removing and returning a column, so you can do this in a single step.

if the "item_*" columns have anything besides 1 in them, then you can multiply with bools:
df.pop('value').values * df.astype(bool)

   item1  item2  item3
0      0      5      0
1      4      0      0
2      0      0      3

If your DataFrame has other columns, then do this:
df
   value  name  item1  item2  item3
0      4  John      0      1      0
1      5  Mike      1      0      0
2      3  Stan      0      0      1

# cols = df.columns[df.columns.str.startswith('item')]
cols = df.filter(like='item').columns
df[cols] = df.pop('value').values * df[cols]

df
  name  item1  item2  item3
0  John      0      5      0
1  Mike      4      0      0
2  Stan      0      0      3

Comment: Most elegant answer so far
Comment: That works! I have no idea why on the sample data frame it worked without the addition. Thank you!
Comment: I like it but I should have been more specific with my question. Here is how my data frame actually looks like:

    `df_in = pd.DataFrame({"value": [4, 5, 3], "name": ["John", "Mike", "Stan"], "item1": [0, 1, 0], "item2": [1, 0, 0], "item3": [0, 0, 1]})`

And the output df should be:

    `df_out = pd.DataFrame({"name": ["John", "Mike", "Stan"], "item1": [0, 4, 0], "item2": [5, 0, 0], "item3": [0, 0, 3]})`
Comment: @GorjanRadevski Let me know if the edit does it for you.
Comment: @coldspeed I get a really strange Value error now:

`ValueError: operands could not be broadcast together with shapes (2918590,) (2918590,26)`

Even though in the sample data frame the shapes similar: (3,) (3, 3)

Do you know what might be causing the issue? Besides, yes, the edit definitely should do it for me.
Comment: @GorjanRadevski that's super weird. Broadcasting should happen by default. Does `df[cols] = df.pop('value').values[:,None] * df[cols]` work? If not, I'm out of ideas, unless I see some more data.
Comment: Could be version differences doing something funky under the hood. Anyway, that's good to know.
Comment: `df.drop('value',1).mul(df.value,axis=0)`
Answer: You could do something like:
df = pd.DataFrame([df['value']*df['item1'],df['value']*df['item2'],df['value']*df['item3']])
df.columns = ['item1','item2','item3']

EDIT:
As this answer will not scale well to many columns as @coldspeed comments, it should be done iterating a loop:
 cols = ['item1','item2','item3']
 for c in cols:
     df[c] *= df['value']
 df.drop('value',axis=1,inplace=True)

Answer: You need:
col = ['item1','item2','item3']

for c in col:
    df[c] = df[c] * df['value']

df.drop(['value'],1,inplace=True)

Answer: pd.DataFrame.mul
You can use mul, or eqivalently multiply, either using labels or integer positional indexing:
# label-based indexing
res = df.filter(regex='^item').mul(df['value'], axis='index')

# integer positional indexing
res = df.iloc[:, 1:].mul(df.iloc[:, 0], axis='index')

print(res)

#    item1  item2  item3
# 0      0      4      0
# 1      5      0      0
# 2      0      0      3


Can two topological spaces surject onto each other but not be homeomorphic?

Question: Let $X$ and $Y$ be topological spaces and $f:X\rightarrow Y$ and $g:Y\rightarrow X$ be surjective continuous maps.  Is it necessarily true that $X$ and $Y$ are homeomorphic?  I feel like the answer to this question is no, but I haven't been able to come up with any counter example, so I decided to ask here.
Comment: Thanks for the answers everyone!
Comment: Seth, any ideas what happens if we assume $Y$ is equipped with the final topology with respect to $f$ and $X$ is equipped with the final topology with respect to $g$?
Comment: $\text{Identity} : \Bbb{R}_{\text{Discrete}} \to \Bbb{R}_{\text{Usual}}$ is a bijective continuous map but not a homeomorphism.
Answer: The circle $S^1$ surjects onto the interval $I = [-1,1]$ by projection in (say) the $x$-coordinate, while the interval $I$ surjects onto the circle by wrapping around, say $f(x) = (\cos \pi x, \sin \pi x)$.
Added: Why is the circle $S^1$ not homeomorphic to the interval $I = [-1,1]$ ? The usual proof looks at cut points, i.e. a point $x$ whose removal from a topological space $X$ results in a disconnected space $X\backslash\{x\}$.  Since this is a purely topological property, two homeomorphic spaces will have an equal number of cut points.
Note that $S^1$ has no cut points; removal of any single point from the circle leaves a connected open arc.  However a closed interval $I$ has infinitely many cut points because removing any point except one of the two endpoints disconnects it into two disjoint subintervals.
The same observation serves to show the spaces in Karolis Juodelė's answer are not homeomorphic: $[0,1]$ has cut points and $[0,1]^2$ does not.
See Seth Baldwin's comment below for an alternative idea, something that will not disconnect the interval $I$ that does disconnect the circle!
Comment: You can find two points on the closed interval to remove such that it stays connected, while this is impossible for the circle.
Comment: I like this one - no need for exotic Peano curves.
Comment: Thanks, I should have perhaps have also pointed out why the circle is not homeomorphic to the interval (hint: no homology groups needed!).  It seems to be a fairly common exercise...
Comment: @SethBaldwin:  That's neat, in that I was thinking about roughly the reverse, being able to *disconnect* the interval by removing one point (which we cannot do for the circle).
Comment: @Theorem:  I'll be happy to add a note explaining that, but see the above comment by Seth Baldwin and my reply.
Comment: @hardmath : If you don't mind, i would like to know how to prove it actually ?
Comment: great answer. Just to get it right the 2 point mentioned by seth are at the edge, right?
Comment: @draks, right.  Seth is pointing out that we can remove the two endpoints of a closed interval, leaving a connected open interval.
Answer: There is a continuous surjective map from $[0, 1]$ to $[0, 1]^2$ - the Peano curve. There is also a map from $[0, 1]^2$ to $[0, 1]$ - $f(x, y) = x$. However the two spaces are not homoemorphic.
Answer: More generally: any two connected, locally connected, compact, second-countable spaces have your property.  (Hahn-Mazurkiewicz Theorem)
Comment: Strictly speaking, I must add that they have at least two points.
Answer: Others have answered, but maybe these comments will also be useful for this thread. A stronger equivalence (replace "surjective" with "bijective" in both places), which is still strictly weaker than being homeomorphic, was studied by several people in the early days of topology (Banach,  Kuratowski, Hausdorff, Sierpinski, etc. in the 1920's). I believe this stronger equivalence originates from Frechet (1910), who called it type de dimensions. There is a lot about this relation in Sierpinski's General Topology (where it's called dimensional type; see pp. 130-133, 137, 141, 142, 144, 145, 163, 165) and in Kuratowski's Topology (where it's called topological rank).
Answer: Just to be different, here's an example that isn't related to the Hahn-Mazurkiewicz theorem. The example is originally due (with a different purpose) to K. Sundaresan, Banach spaces with Banach-Stone property, Studies in Topology (N.M. Stavrakas & K.R. Allen, eds.), Academic Press, New York, 1975, pp. 573-580; the argumentation is mine, On an example of Sundaresan, Top. Procs. 5 (1980), pp. 185-6. The surjections are $1$-$1$ save at a single point each, where they are $2$-$1$.
Let $X=\omega^*\cup(\omega\times 2)$, where $\omega^*=\beta\omega\setminus\omega$, and $2$ is the discrete two-point space, let $\pi:X\to\beta\omega$ be the obvious projection, and endow $X$ with the coarsest topology making $\pi$ continuous and each point of $\omega\times 2$ isolated. Let $N=\omega\times 2$, for $n\in\omega$ let $P_n=\{n\}\times 2$, and let $\mathscr{P}=\{P_n:n\in\omega\}$. A function $f:X\to X$ preserves pairs if $f[P_n]\in\mathscr{P}$ for all but finitely many $n\in\omega$.

Lemma. Let $f:X\to X$ be an embedding; then $f$ preserves pairs.

Proof. Suppose that $f$ does not preserve pairs. Since $f$ is injective, an easy recursion suffices to produce an infinite $M\subseteq\omega$ such that $(\pi\circ f)\upharpoonright\bigcup\{P_n:n\in M\}$ is injective. Let $M_i=M\times\{i\}$ for $i\in 2$. Then $$\left(\operatorname{cl}_XM_i\right)\setminus N=\left(\operatorname{cl}_{\beta\omega}M\right)\setminus\omega\ne\varnothing$$ for $i\in 2$, so $$\left(\operatorname{cl}_Xf[M_0]\right)\setminus N=\left(\operatorname{cl}_Xf[M_1]\right)\setminus N\ne\varnothing\;.$$ But $$\left(\operatorname{cl}_Xf[M_i]\right)\setminus N=\left(\operatorname{cl}_{\beta\omega}f[M_i]\right)\setminus\omega$$ for $i\in 2$, $\pi\big[f[M_0]\big]\cap\pi\big[f[M_1]\big]=\varnothing$, and disjoint subsets of $\omega$ have disjoint closures in $\beta\omega$, so $\operatorname{cl}_Xf[M_0]\cap\operatorname{cl}_Xf[M_1]=\varnothing$; this is the desired contradiction. $\dashv$

Now let $p$ be any point not in $X$, and let $Y=X\cup\{p\}$, adding $p$ to $X$ as an isolated point.

Proposition. $Y$ is not homeormorphic to $X$.

Proof. Suppose that $h:Y\to X$ is a homeomorphism; it follows from the lemma that $h\upharpoonright X$ preserves pairs. Let $$A=\bigcup\Big\{P_n\in\mathscr{P}:h[P_n]\in\mathscr{P}\Big\}\cup\omega^*\;.$$ Then $\big|X\setminus h[A]\big|$ is finite and even, $|Y\setminus A|$ is finite and odd, and $h\upharpoonright(Y\setminus A)$ is a bijection between these two sets, which is absurd. $\dashv$

Finally, the maps
$$f:Y\to X:y\mapsto\begin{cases}
y,&\text{if }y\in X\\
\langle 0,0\rangle,&\text{if }y=p
\end{cases}$$
and
$$g:X\to Y:x\mapsto\begin{cases}
x,&\text{if }x\in\omega^*\\
p,&\text{if }\pi(x)=0\\
\langle n-1,i\rangle,&\text{if }x=\langle n,i\rangle\text{ and }n>0
\end{cases}$$
are continuous surjections.
By the way, each of $X$ and $Y$ embeds in the other, so these spaces witness the lack of a Schröder-Bernstein-like theorem for compact Hausdorff spaces and embeddings.


Performance tipos de EventBus em Vuejs

Question: Em alguns projetos que estou realizando uma manutenção, há o uso de EventBus globais.
No caso, geralmente havia visto da seguinte forma:
event-bus.js
import Vue from 'vue';

const EventBus = new Vue();
export default EventBus;

Porém, me deparei com outra implementação do EventBus:
event-bus.js
import Vue from 'Vue'
const bus = new Vue()

export default function install (Vue) {
  Object.defineProperties(Vue.prototype, {
    $bus: {
      get() {
        return bus
      }
    }
  })
}

main.js
import EventBus from './event-bus'
Vue.use(EventBus)

Geralmente utilizo EventBus, e entendo a maneira como devo utilizá-lo, porém não entendo de fato a maneira em que ele opera, como funciona.
Gostaria por favor de uma explicação clara sobre a maneira em que o EventBus opera (as duas formas se fosse possível), e qual das duas implementações seria a mais "correta" e/ou perfomática.
Answer:
Como o EventBus opera?

Comunicação entre componentes
Toda e qualquer comunicação entre componentes está disponível na instância do Vue e você pode encontra-los dando um console.log(this) dentro do componente, é aí que Props e EventBus operam, eles simplesmente executam métodos na instância que você mesmo poderia fazer, porém de uma forma muito mais organizada e arrisco dizer que muitas vezes até desnecessárias...
EventBus
Antes de entender como funciona é necessário saber se você realmente precisa usar, quando é necessário executar métodos em outros componentes a partir de uma ação no componente central, podemos usar o EventBus, ele opera automaticamente em qualquer componente que esteja associado ao componente, seja $parent ou $children, é como uma propagação global, quem quer ouvir ouve quem não quer fica quieto kk...
Na prática
pensemos e uma entrutura como essa
src

App.vue
Propag.vue
event-bus.js
main.js

Main renderizara o App.vue
event.bus.js
import Vue from "vue";
export const EventBus = new Vue();

App.vue
<template>

Click para emitir

  <Propag ref="prop"></Propag>

</template>

Propag.vue
<template>

    Atualizado pelo EventBus: {{clicks}}

    Atualizado pelo componente : {{compClick}}

</template>

Nas partes em que uso o EventBus e o método simples está demarcado com um comentário identificando, repare que o EventBus é mais verboso e complicado, a longo prazo irá te ajudar? na minha opinião ajuda somente na centralização dos eventos, ou seja, você não precisaria se preocupar em ficar apontando o componente que receberá o evento, basta importa-lo, eu particularmente não uso, pois me ajuda muito a praticidade e a organização da comunicação simples.
Em relação a segunda forma de fazer, não tenho conhecimento para falar...
Código rodando: https://codesandbox.io/s/mm58vw8px8
Answer: Quanto ao mecanismo do EventBus, em ambos os casos eles são iguais, o que muda é a forma de que como se acessa o mesmo.
O segundo caso, o que é definido um plugin que irá injetar à $bus ao prototype do Vue, ou seja, a variável $bus ficará disponível em toda instancia do Vue.
Porem esta forma de injetar o EventBus, me parece uma reinvenção da roda, uma vez que não vejo uma vantagem grande em se fazer isto, ao invés de simplesmente fazer o seguinte no plugin.
import Vue from 'Vue'

const bus = new Vue()
const plugin = {
  install (Vue) {
    Vue.prototype.$bus = bus
  }
}

export default plugin

Quanto a injetar o $bus, o ideal seria faze-lo utilizando um Mixin.
mixins/event-bus.js
import Vue from 'Vue'
const bus = new Vue()
const mixin = {
  beforeCreate () {
    this.$bus = bus
  }
}

export default mixin

plugins/event-bus.js
import Vue from 'Vue'
import EventBus from '../mixins/event-bus.js'

const plugin = {
  install (Vue) {
    Vue.mixin(EventBus)
  }
}

export default plugin

App.vue
import Vue from 'Vue'
import EventBus from './plugins/event-bus.js'

Vue.use(EventBus)

Outro ponto, um Plugin é interessante caso você queria reutilizar algum componente, então a menos que este EventBus seja utilizado por varios projetos, não há porque utilizar ele como um Plugin. Então  o seguinte trecho de código já deve ser suficiente para injetar o seu EventBus
mixins/event-bus.js
import Vue from 'Vue'
const bus = new Vue()
const mixin = {
  beforeCreate () {
    this.$bus = bus
  }
}

export default mixin

App.vue
import Vue from 'Vue'
import EventBus from '../mixins/event-bus.js'

Vue.mixin(EventBus)

Comment: @guastallaigor como o próprio nome (mixed in) sugere, irá realizar uma mesclamento das propriedades (seja os hooks, metodos, eventos, data, etc) com as propriedades da instancia do Vue. então digamos que tenhamos um Mixin com o hook mounted e este mixin é adicionado a um determinado componente, então sempre que este componente for montado, o hook mounted do Mixin será executado, assim como o próprio hook mounted do componente. No exemplo acima o Mixin foi registrado globalmente, mas ele pode ser registrado de forma individual, assim como ocorre com os componentes.
Comment: Vou testar depois estas diferentes implementações. Mesmo com o mixin eu acesso ele com o this.$bus?

Performance tipos de EventBus em Vuejs


Função para criar botões a partir de um Objeto

Question: Preciso criar uma função semelhante a esta:
criarBotoes({
  "Abrir": function(dados){
    alert("Abrindo...");
    console.log(dados);
  },
  "Fechar": function(dados){
    alert("Fechar...");
    console.log(dados);
  },
});

Tentei da seguinte forma:

function criarBotoes(botoes){
  for(var texto in botoes){
    $("<button>",{
        text: texto,
        click: botoes[texto],
        appendTo:$('body')
      });
  }
}

criarBotoes({
  "Abrir": function(dados){
    alert("Abrindo...");
    //console.log(dados);
  },
  "Fechar": function(dados){
    alert("Fechando...");
    //console.log(dados);
  }
});

Mas não consigo passar valores para a função botoes[texto]().
Answer: Boa noite!
Modifiquei o seu objeto de botões para ser um array, assim fica mais fácil iterar sobre ele, e cada botão vira um objeto, sendo mais simples para acessar suas propriedades, inclui também duas versões do código uma usando ES5(Seu caso) e outra usando ES6(Caso você esteja interessado) no final ficou assim:
// Versão ES5
var botoes = [
  {
    texto: "Abrir",
    metodo: function(dados){
      alert("Abrindo...");
      console.log(dados);
    }
  },
  {
    texto: "Fechar",
    metodo: function(dados){
      alert("Fechar...");
      console.log(dados);
    },
  }
];

botoes.forEach(function(botao) {
  $('<button>', {
    text: botao.texto,
    click: botao.metodo,
    appendTo: $('body')
  });
});

//Versão ES6
const botoes = [
  {
    texto: "Abrir",
    metodo: (dados) => {
      alert("Abrindo...");
      console.log(dados);
    }
  },
  {
    texto: "Fechar",
    metodo: (dados) => {
      alert("Fechar...");
      console.log(dados);
    },
  }
];

botoes.forEach((botao) => {
  $('<button>', {
    text: botao.texto,
    click: botao.metodo,
    appendTo: $('body')
  });
});

Comment: Boa sujestão, não resolveu meu problema, mas me ajudou a achar a solução. Só precisei mudar isso:
[...]
click: function(){
      botao.metodo("Olá Mundo!")
    }
[...]


SECURITY: Should containers run TLS or can they rely on its sidecar?

Question: I wonder how security experts think about making container traffic secure. Let's take a simple K8S cluster as an example.
I guess we all agree that running HTTPS instead of HTTP within each container is more secure. I would normally configure a TLS on Ingress and then route to an internal container will TLS configured as well.
Modern mashing solutions usually install proxy sidecar - let's take Linkerd2 for a concrete example. Ingress will upgrade all incoming traffic to TLS, it will then use Linkerd's TLS to forward traffic to the sidecar proxy. Everything transmitted until here is TLS and secured. I wonder, now that a secured traffic "already reached" the pod, should a container use TLS as well, or is it safe enough to communicate with the sidecar without TLS? I'd like to hear the security aspect between the container and its sidecar. Should a sidecar be treated as a stand-alone container and thus the communication with a container should also be TLS secured?
Answer: In environments where you want a high level of security for Kubernetes clusters it is now common to apply principles from Zero Trust Networking. For the networking in a Kubernetes cluster this typically means:

Encrypt all network traffic
Use authentication for all network traffic
Granular firewall rules - applied for micro segmentation around each app
Least Privileges access control using RBAC, Service Accounts, JWT and OpenPolicyAgent

The two first points is now usually solved with a Service Mesh product, like Linkerd, Istio and the cloud providers offer managed solutions like AWS App Mesh. These products apply encryption between each Pod in the form of TLS, but also authentication using client certificates and mutual TLS, mTLS in an automated fashion. The Service Mesh usually has a control plane part that is responsible for e.g. rotation of certificates with automation.
The third point is usually done using Kubernetes Network Policies to get dynamic, but granular firewall rules applied to each app instance (Pod) even if it can dynamically be scheduled to different nodes in the cluster. These policies is usually declared in a higher level using e.g. Pod labels instead of hard coded IP addresses.

I wonder, now that a secured traffic "already reached" the pod, should a container use TLS as well, or is it safe enough to communicate with the sidecar without TLS? I'd like to hear the security aspect between the container and its sidecar. Should a sidecar be treated as a stand-alone container and thus the communication with a container should also be TLS secured?

Pods are the units of scheduling in Kubernetes, they are tightly coupled containers - always scheduled together. The containers within a Pod share some resources like linux namespaces, filesystem volumes and cgroups:

The shared context of a Pod is a set of Linux namespaces, cgroups, and potentially other facets of isolation.

In addition the containers in a Pod share the network identity, the IP address, and use localhost to communicate within the Pod. I would consider trust within the Pod, but you should apply granular Kubernetes Network Policies to lock down e.g. what ports the Pod can receive traffic on, and from what Pods.


Survey Analysis: Weighted Randomization to fill Missing Values

Question: I am developing a Survey Analysis Application that works with Categorical Data and looking for a way to treat missing data fairly without losing the original data variance.
Thus, I came up with a way to deal with these values, that is, for every missing value, we make a list of non-missing values in the same column, randomly select a value from that list by using np.random.choice, and use it to fill in the missing value. The randomization by itself is weighted. If a value has a greater frequency, it would have a higher chance of being filled.
The problem is, I have not seen anyone done it this way before so I am not sure whether it would maintain the data variance and the fairness of the survey. Any feedback, suggestions, or flaws that you find in this approach would be greatly appreciated.
Answer: This seems like a simple form of single imputation. You could improve it by:

First considering whether these values are missing (completely) at random or not. If they are not, imputation alone will bias the results and you should look into ways to model missing not at random.
Instead of filling the missing values once, making many copies of your original data, where the missing data are filled in randomly. This is known as multiple imputation.
Taking into account not only the relative frequencies of categories, but also the relationships with other variables. One way to do this is with multiple imputation by chained equations (MICE). In R, the package mice can do this,$^{[1]}$ perhaps there is an implementation in Python as well.

$[1]$: Buuren, Stef. Flexible imputation of missing data. Boca Raton, FL: CRC Press, 2018. Print.
Comment: I really like the idea of doing multiple imputations, as well as the chained equations that we can use to link variables together. Thank you very much for your suggestion.


Show: $\lim\limits_{y \to +\infty}\left [\frac{1}{\sqrt{\pi}e^{y^2}(1-\text{erf}(y))}-y\right]=0.$

Question: I would like to show the following:

$$\lim_{y \to +\infty} \left[\frac{1}{\sqrt{\pi}e^{y^2}(1-\text{erf}(y))}-y\right]=0.$$

Here $$\text{erf}(y)= \frac{2}{\sqrt{\pi}} \int_{0}^{y}e^{-x^2}dx$$ denotes the error-function. In fact I would like to have that $\lim\limits_{y \to +\infty} [\mathbb{E}(X\mid X \geq y)- y]=0$ provided that $X \sim \mathcal{N} (0,\frac{1}{\sqrt{2}})$. Since $$\mathbb{E}(X\mid X \geq y)= \frac{\int_{y}^\infty xe^{-x^2} dx}{\int_{y}^\infty e^{-x^2} dx}=\frac{\frac{1}{2}e^{-y^2}}{\frac{2}{\sqrt{\pi}}(1-\text{erf}(y))}=\frac{1}{\sqrt{\pi}e^{y^2}(1-\text{erf}(y))}$$ the second limit should then reduce to the first one in the yellow box.
Since $\text{erf}(y)$ cannot be stated explicitely with elementary functions I tried to use approximizations of it but it seems that it is not enough to allow errors up to a constant (although the constant is tiny) to show that the limit is zero. I tried the ones given here: https://en.wikipedia.org./wiki/Error_function#Approximation_with_elementary_functions.
I think that intuitively the statments should be correct because of the strong descent of the Gaussian function $e^{-x^2}$ when approaching infinity: The bigger $y$ is the more I expect $\mathbb{E}(X\mid X \geq y)$ to be close to $y$.
Comment: By L'Hospital's rule, as $y \to \infty$, $$\frac{\frac{e^{-y^2}}{\sqrt{\pi}}}{(1-\text{erf}(y))}=y+\varepsilon(y)$$ with $\lim_{y \to \infty}\varepsilon(y)=0$, see my answer below.
Answer: Hint. One may observe that, as $y \to \infty$,
$$
\frac{1}{\sqrt{\pi}e^{y^2}(1-\text{erf}(y))} =\frac{\frac{e^{-y^2}}{\sqrt{\pi}}}{(1-\text{erf}(y))}\to \frac00
$$ then one is allowed to apply L'Hôpital's rule getting, as $y \to \infty$,
$$
\frac{\frac{e^{-y^2}}{\sqrt{\pi}}}{(1-\text{erf}(y))}\sim\frac{\frac{-2ye^{-y^2}}{\sqrt{\pi}}}{-\frac{2}{\sqrt{\pi}}e^{-y^2}}=y.
$$
Comment: $∼$ means that the ratio is $y+o(y)$ which is not enough to conclude. Also by L'Hôpital's rule you just show that the ratio tends to $+\infty$. I do not see how it would even tell you that the rate of divergence is $y$.
Answer: It is known that
$$
{\mathop{\rm erfc}\nolimits} (y) = \frac{{\mathrm{e}^{ - y^2 } }}{{y\sqrt \pi  }}\left( {1 + \mathcal{O}\!\left( {\frac{1}{{y^2 }}} \right)} \right)
$$
as $y\to +\infty$, whence
$$
\frac{1}{{\sqrt \pi \, \mathrm{e}^{y^2 } (1 - {\mathop{\rm erf}\nolimits} (y))}} = \frac{y}{{y\sqrt \pi \, \mathrm{e}^{y^2 } {\mathop{\rm erfc}\nolimits} (y)}} = \frac{y}{{1 +\mathcal{O}(y^{ - 2} )}} = y + \mathcal{O}(y^{ - 1} )
$$
as $y\to +\infty$. This is enough to conclude.


Is it possible to declare multiple micrometer binders in a single bean declaration

Question:
By default, metrics from all MeterBinder beans will be automatically bound to the Spring-managed MeterRegistry

This works great when it's possible to configure the binders individually. What I'm looking, however, it to be able to bulk declare multiple binders. My use case is based on programmatically declaring and creating multiple rabbit queues. The spring-amqp project comes handy with a concept of Declarables class which is:

A collection of Declarable objects; used to declare multiple objects on the broker using a single bean declaration for the collection.

Is there a simlar concept present in spring-boot, I'd call it MeterBinders which allows me to declate multiple meter objects, using a single bean declaration.
I'd like to avoid simultanious declatarion of my queues and meters (with new QueueSizeMeterBinder(queueInformation).bindTo(meterRegistry) - keep these separate).
Currently, to keep these concepts separated, I'm using additional configuration class, which doesn't look to me as an idiomatic spring-way
@Configuration
@RequiredArgsConstructor
class QueueMetricsConfiguration {

    private final Declarables queues;
    private final AmqpAdmin amqpAdmin;
    private final MeterRegistry meterRegistry;

    @PostConstruct
    public void bindMetrics() {
        queues.getDeclarablesByType(Queue.class)
                .forEach(queue -> new QueueSizeMeterBinder(amqpAdmin.getQueueInfo(queue.getName()))
                        .bindTo(meterRegistry));
    }

}

Can I do it any better?
Answer: I am not sure I get your explanation right, but registering multiple bindings in one MeterBinder would be something I have called a composite-binder in my projects:
@Bean
MeterBinder compositeBinder() {
    return (registry) -> {
        // register Meters via a binder
        new FooBinder().bindTo(registry);
        new BarBinder().bindTo(registry);
        // register without indirection
        registry.gauge("mygauge", BigDecimal.TEN);
    };
}


my whole computer is now linked with git trying to link an existing R project MAC

Question: Hi I ran into a problem when I tried to link a regular R Project with Git. Here's the break down:

In terminal I managed to find the directory ~cd...
git init worked
"git add ." worked but here's where I ran into the problem. Terminal started asking for permissions to access documents, downloads, pictures (Seriously? but why?) and I kept pressing "dont allow". Terminal stopped working and I quit Terminal.
Then on one of the discussion threads I came across with this link https://happygitwithr.com/existing-github-last.html
In short I logged-in to my Git Hub account, went to Repo, and uploaded the R Project that was not under version control. Upload was successful but nothing changed in R Studio. So I restarted R Studio and viola, there is "Git" Tab in environment window. Now the bigger problem!
When I clicked the Git tab I could see my directory for pictures, downloads, movies basically every major directory on my MAC. Luckily my repo is private so hopefully no one will be able access pictures and what not. No sure how much of it has been put on the repo. On Git Hub I could only see my newly uploaded RProj and R Scripts from the past

Why did it happen? and what do I do next? Any thoughts, comments?
Screenshot of RStudio;
Answer: It all depends where you did git init .
If you did it in ~ ($HOME, that is /home/<you>), meaning if you see a /home/<you>/.git/ folder, that would explain why Git had to access all those directories (Pictures, Music, ...)
Simply remove that folder, and do a git init . in the actual folder where you have your R project.


Mutual Information for unordered variables

Question: Like many others I am seeking for a method to create a "correlation" like matrix for an unpredictable mix of variables which can contain unordered categorical ones as well.
While there are ideas of defaulting to different options depending on variable types for each pair of variables this seemed complicated (plus Spearman bears the risk for beeing computationally too expensive and I can't use Pearson given non-normality) and using e.g. polycor relies on ordered categorical variables I felt going down the mutual information route would be more straight forward as suggested here.
So I made a little example to check whether it gives me what I want. Some categorical variables, some numerical ones and you can see that both cat1 vs. cat2 as well as num1 vs. num2 are "perfectly correlated" whereas cat1 vs. cat3 as well as num1 vs. num3 are "perfectly anti-correlated", at least when you read an order into the categorical variables based on their alphabetical sort order of values (which is not what I want, see title!):
library(infotheo)

cat1 <- c('a','b','c','a','b','c','a','b','c')
cat2 <- c('x','y','z','x','y','z','x','y','z')
cat3 <- c('z','y','x','z','y','x','z','y','x')
cat4 <- c('d','e','f','d','e','e','d','d','f')
cat5 <- c('c','e','y','b','f','x',NA,NA,NA)
num1 <- c(1,2,3,1,2,3,1,2,3)
num2 <- c(10,20,30,10,20,30,10,20,30)
num3 <- c(30,20,10,30,20,10,30,20,10)
num4 <- c(12,21,3,0,5,7,22,3,100)
num5 <- c(NA,NA,NA,NA,NA,NA,1,2,3)

df <- cbind.data.frame(cat1,cat2,cat3,cat4,cat5,num1,num2,num3,num4,num5)
df.num <- cbind.data.frame(num1,num2,num3,num4,num5)

cor.matrix.nats <- (mutinformation(discretize(df, disc="equalwidth")))
cor.matrix.nats <- cbind.data.frame(row.names(cor.matrix.nats),cor.matrix.nats)

cor.matrix.num.Spearman <- cor(df.num, method="spearman", use="pairwise.complete.obs")
cor.matrix.num.Spearman <- cbind.data.frame(row.names(cor.matrix.num.Spearman), cor.matrix.num.Spearman)

To my surprise the mutual information cat1 vs. cat2 is a lot higher than cat1 vs. cat3 and in fact I observe the exact same difference for num1 vs. num2 compared to num1 vs. num3 (where Spearman produces the expected result). This leads me to believe that for some reason infotheo somehow uses alphabetical ordering to give unordered categorical variables a non-existing order.

While I checked the documentation and another great explanation on the interpretation of mutual information I still can't get my head around why order seems to play a role...
If anyone's got an explanation or a suggestion how to work around this, it would be highly appreciated!
Comment: Playing around I just realized that if I increase the number of bins produced by `discretize` the problem seems to disappear. So maybe it is not a sort order thing but it is still very irritating since the number of samples is the same for cat1, cat2 and cat3...
Answer: Ok, I now understand what's happening. The defaults produce only 2 bins which turns

cat1 and cat2 into 1 2 2 1 2 2 1 2 2
cat3 into 2 2 1 2 2 1 2 2 1

which explains the lower mutual information value (it is indeed not related to sort order!).
Allowing 3 bins by modifying one line of code like so
cor.matrix.nats <- (mutinformation(discretize(df, disc="equalwidth", nbins=NROW(df)^(1/2))))

bins

cat1 and cat2 into 1 2 3 1 2 3 1 2 3
cat3 into 3 2 1 3 2 1 3 2 1

and now mutual information cat1 vs. cat2 = cat1 vs. cat3 = 1.0986123.
Guess I need to think about how to get a robust value for  nbins in  discretize not knowing in advance how many real bins across how many samples are coming in...


Double Sharps And Double Flats

Question:
A double-sharp (x) raises a natural (♮) note by two semitones.
A double-sharp (x) raises a sharp (#) by one semitone.

What does a double-sharp raise a flat by?

A double-flat (♭♭) lowers a natural note by two semitones.
A double-flat (♭♭) lowers a flat by one semitone.

What does a double-flat lower a sharp by?
Answer: A double-sharp would raise a flat note by a tone and a half (three semitones).
A double-flat would lower a sharp note by a tone and a half (three semitones).
Having said both these things, if you have a piece that is changing a flat note to a double-sharp, or changing a sharp note to a double flat, it is likely that you could use a much better enharmonic spelling. For example, it seems far more likely that you would move from G# to E# (or F, depending upon context), than G# to Gbb, even if you wanted to use, for instance, Fb, Eb and D close to these notes too. In fact, if music is very chromatic, it often makes sense to use fewer double-sharps and double-flats, even if this requires using a few more accidentals (naturals, for instance). This is because very chromatic music can start to lose its connection with major or minor scale degrees, this chromatic "alteration" of scale degrees being a good reason to use double-sharps and double-flats in the first place (either as chromatic alteration within a particular key, or chromatic alteration which produces a modulation to another key). In the example above, it would make sense to use the "simplest" accidentals (Ab F E Eb D, G# F E Eb D, Ab F E D# D or G# F E D# D), to make it easy to read. Which of these would be used, would depend upon whether these are heard within a diatonic context or not, and if so within which key. (If, of course, these are used during a passage in F# Minor, it's likely that an E# would be used - context is everything.)
I suppose you could also adjust a double-sharp note to a double-flat (and vice versa), in theory, which would be a a movement down of two tones (four semitones). I can't think of a reason why you would want to do this, apart from as a theoretical exercise, though! If these two notes were next to each other, I guess this would be the interval of a quadruply augmented unison!! (Thanks for correction, @PatMuchmore.)
EDIT: as @Guidot points out in his answer, this situation is basically theoretical; it is very unlikely to actually appear in practice. Double-sharps are nearly always used to extend a sharp by a further semitone (usually where the sharp already appears in the key signature); double-flats are nearly always used to extend a flat by a further semitone (usually where the flat already appears in the key signature). For this reason, in practice it is very unlikely that there would be a need to move from flat to double-sharp, or sharp to double-flat. (As I point out above, if one ever finds the need to do either of these things in a piece of music, the enharmonic spelling is almost certainly incorrect.)
Also, @CarlWitthoft has asked me to be clear: any accidental (sharp, flat, natural, double-sharp, double-flat) "cancels" the associated key-signature sharp or flat for the same note. So, in theory, this could be a way that a note gets "changed" by three semitones by using a double-sharp or double-flat. An example would be using an A double-sharp where the key-signature has an Ab (Eb Major for example). But, again, this is extremely unlikely to be necessary, for three reasons:

an A double-sharp is only really needed if you were also using B# and C# in a passage, too; this is very unlikely in a key that has an Ab in the key-signature (C and Db would be used).
as per @Guidot's answer, an A double-sharp is most likely to be used to "extend" an A# (from the key signature of C# Major, for instance, where there is also a B#).
if the music is very chromatic or atonal, it would be better not to use a key-signature, in which case it is usually appropriate to use accidentals which are easiest to read, so any Ab used in a bar would move to a B natural, rather than an A double-sharp.
Comment: For the theoretical exercise part, what if you were harmonizing a chromatic passing tone? That could move a major 7th to a doubly-diminished. maybe.
Comment: Absolutely, anything is possible. But it still seems more likely that using a single "level" of enharmonic change (eg. G# to F or E# to D) would be sufficient for most diatonic or chromatic purposes (rather than G# to Gbb or E# to Ebb).
Comment: It might need clarification actually, as that's a modern convention. Early 18th century French notation viewed accidentals as adjustments relative to the note indicated by the key signature, not absolute resets of sharpness or flatness. So flat signs just meant "a semitone lower than if this sign wasn't here". So I tend to need that clarifying when I'm not sure what period people are talking about.
Answer: As you mentioned double accidentals start working from the natural tone and shift by two semitones, therefore if the natural tone was shifted towards the other direction before, this has to be neutralized first. Actually this is a quite academic issue, since more than 99% of the double accidentals I encountered in classical music, occured in pieces, where the key signature had already shifted the tone by a semitone in the same direction. I would expect, that contemporary pieces requiring such wild shifts have no key signature at all.
Comment: @BobBroadley No problem with me. I guess part of the difficulty is, that accidentals are context-insensitive (they work irrespective from previous accidentals and actually it is mostly recommended to resolve them first before applying new ones), but the question is posed in a context-sensitive way.
Comment: +1 @Guidot, I tried to point out that this situation is extremely unlikely to occur, and is basically only theoretical. I'm going to amend my answer to make this point more clearly, but will acknowledge your answer, if that's okay with you.

Double Sharps And Double Flats


Random Number generated from Normal Distribution N(0,1)

Question: If we generated random number from Normal Distribution N(0,1) that is always positive by using Uniform Dist from 0.5 to 1, Is it still follow normal distribution the data that we are generated?
Comment: Are you asking that if you use the Probability Integral Transform to generate data from a normal distribution and only take values from .5. to 1 from the Uniform Distribution if the resulting data would also follow A Normal Distribution?
Comment: Your question is unclear. If you generated random values following normal distribution then they follow normal distribution, if not, they do not. It is also unclear what is "always positive by using Uniform Dist from 0.5 to 1".
Comment: @StatsStudent yup that is it. if we generated the data from .5 to 1, is the data still follow the a normal distribution?
Comment: @srimaster, then Glen_b's answer below is correct.
Answer: No, if $V\sim U(\frac12,1)$, the values you get by $\Phi^{-1}(V)$ will indeed be positive, but they will not have a normal distribution.
Just as you cut the standard uniform in half, you have also cut the normal in half:

The right half of a normal distribution isn't a normal distribution.
No normal distribution is entirely positive. If that's what you're trying for, you have to give up something -- either it's not exactly normal or there's some chance it's negative.