Elimination system where both opponents can lose

Question: Is there any tournament system that deals with the fact that both opponents can lose? Or is there an easy, non-complicated and fair way of modifying an elimination-like system to deal with it?
Context
I'm doing in historical fencing (HEMA). In this type of fencing, we want to strongly discourage so-called double hits, i.e. a situation in which both opponents hit each other at approximately the same time.
When we do tournaments, there are several options of dealing with double hits. The simplest one is that a double hit is a point for both opponents but that does not discourage the double hits, on the contrary, it encourages it in some situations (one of the opponents is one point from victory while the other one is not).
Another system is that double hits are not counted at all. This is a bit better but it can lengthen the matches.
The last system is that double hits are punished by both opponents losing (either right away or after some amount of double hits). This last option is closest to what we would want - it punishes double hits and can be scaled depending on the experience of the contestants (by the amount of double hits allowed). However it has one major drawback: it works only in round-robin-like tournament systems and any elimination-like system is broken by the fact that both opponents should lose. Hence my question.
Comment: I am not able to reply to your question but I can sugget you to generate warnings when the athlete collect too many double hits (eg every 5 double hits). The warning can cause a penalty on the next round (start from -3 hits the next round) or with 3 warning the athlete is eliminated or a mixed solution
Comment: What about using [Double-elimination tournament](https://en.wikipedia.org/wiki/Double-elimination_tournament) with some modification? You can still win the tournament, if you don't have more than 2 defeats.
Comment: @gdrt94 That "some modification" is what I'm asking for. Double-elimination does not solve it at all. The core problem of the double hits is that **both** athletes (should) lose and then there is nobody to fight with the winner of the neighbor match. And they should not have bye, that seems unfair.
Comment: That's why it's just a comment, not an answer. I just gave you a raw idea :)
Answer: You are essentially asking for two contradictory things. You want a single-elimination system where (1) there is a winner of each match, so that there is an opponent for the next round, and (2) there is no winner of the match. You need to decide which factor is more important to you.
Here are the options that I see:

If it's most important that there be a winner of the match, then you need to decide on a "tiebreaker" that determines who wins, or otherwise award one of the players the win even though you don't really want to.
If it's most important that there be a player for the next round, but you really don't want it to be one of the players that was disqualified in the current round, then you need to decide on some sort of "tiebreaker" to determine somebody who moves forward in that slot despite not being one of the original players. For example, it may be that the highest-scoring non-disqualified loser of that round ends up with a "wild card" of sorts and ends up paired in the next round, despite having lost their "own" match. This of course doesn't really help if your double-loss happens in the final round, and could lead to some weird cases especially if double-losses are common and you run out of "wild cards". (Plus, it's probably just going to be confusing for everybody.)
If it's most important that there be no winner, then you need to just accept that nobody moves on for that round, and the next round opponent gets a bye. (And it will be really unsatisfying for everybody if it happens in the final round, to end a tournament with no winner and two "finalists".) For what it's worth (just because this is the game which I'm most familiar with the tournaments of, or at least I used to be), for competitive tournaments in the Magic: the Gathering card game, if an event is single-elimination, and both players lose due to a match-loss penalty resulting in a double-loss, this is the way it's handled and the next round opponent gets a bye. I'm not aware of this ever having happened in practice, as both match-loss penalties and single-elimination tournaments are rather rare.

Really, for any tournament with matches more complicated than results that are clearly "win" or "loss", you want to look for alternatives to elimination bracket formats. Elimination-format tournaments don't deal well with anything beyond winning and losing, such as ties, double-losses, ranking based on score, or players withdrawing. If you want a format where people can earn (for example) 0 for loss, 1 for tie, or 2 for win, where each player could get any of those values, you want something like Swiss or Round Robin.
And if I could expand for a bit beyond what you're directly asking, it sounds like your actual problem is trying to find the right method of including "penalties" in your matches. This has been handled in many different ways by different games, and it's probably worth looking at a few. For your particular issue, perhaps you want to allow for double-hits to count as a point (or half a point?) for both players, but not allow it to count for a player for which it would then award a win (or within n points of winning). Or perhaps a double-hit gives some kind of "strike" separate from the score, which is used for tiebreaking, seeding, invites to future events, or just plain public shaming but doesn't directly impact the result of that particular match.


Send input value to typescript (without button send)

Question: I have a regular input text:
<form>
    <input type="text" oninput="sendInput()" />
</form>

I want to send what the user typed in the box into the typescript file (without a submit button or something) when the user has finished typing, send the input to the typescript.
I try with this code but it's not working.
Answer: Demo use ngModel two way binding
<input type="text" [(ngModel)]="inputParam"/>

{{inputParam}}

Demo or use ViewChild as a way
component.ts
inputParam=""
  @ViewChild('input') _input: ElementRef;
  sendInput(){
    this.inputParam= this._input.nativeElement.value;
  }

html part
<form >
    <input #input type="text" (input)="sendInput()"/>
</form>
{{inputParam}}


Pushing a string to a private member vector

Question: I have a std::vector<std::string> tileSet_ as a member variable of a class. In the constructor of said class I call the function
void MapWindow::shuffleTiles() const
{
  std::vector<std::pair<std::string, unsigned>> tileAmounts = {
    {"a", 2}, {"b", 4}, {"c", 1}, {"d", 4},
    {"e", 5}, {"f", 2}, {"g", 1}, {"h", 3},
    {"i", 2}, {"j", 3}, {"k", 3}, {"l", 3},
    {"m", 2}, {"n", 3}, {"o", 2}, {"p", 3},
    {"q", 1}, {"r", 3}, {"s", 2}, {"t", 1},
    {"u", 8}, {"v", 9}, {"w", 4}, {"x", 1}
  };

  int tileN = 0;
  for (std::vector<std::pair<std::string, int>>::size_type i = 0;
    i < tileAmounts.size();i++) {
    tileN += tileAmounts.at(i).second;
  }

  // only used once to initialise (seed) engine
  std::random_device rd;
  // random-number engine used (Mersenne-Twister in this case)
  std::mt19937 rng(rd());
  // guaranteed unbiased
  std::uniform_int_distribution<int> uni(0,tileAmounts.size() - 1);

  for (int i = 0; i < tileN; i++) {
    auto random_integer = uni(rng);
    //qDebug() << i << ":" << random_integer;
    std::cout << i
              << ":"
              << tileAmounts.at(random_integer).first
              << ":"
              << tileAmounts.at(random_integer).second
              << std::endl
              << std::endl;

    while (tileAmounts.at(random_integer).second < 1) {
      std::cout << "Reshuffling "
               << tileAmounts.at(random_integer).first
               << ":"
               << tileAmounts.at(random_integer).second
               << std::endl;
      random_integer = uni(rng);
    }

    std::string s = tileAmounts[random_integer].first;
    std::cout << s
              << std::endl;

    tileSet_.push_back(s);
    tileAmounts.at(random_integer).second -= 1;
  }

  for (std::vector<std::string>::size_type i = 0;
    i < tileSet_.size();i++) {
    std::cout << tileSet_.at(i)
              << std::endl;
  }
}

which at the very end attempts to push back a randomly picked string from a pair contained in the vector tileAmounts into the memeber vector. For some reason, this raises the error
no matching member function call to 'push_back'

Why does this happen. I'm taking the vector to be pushed back from a std::pair, but surely that shouldn't be causing any type mismatches? A std::string in a std::pair contained in a std::vector is still a std::string, no?
Comment: We can't reproduce the problem (without making guesses). Please provide enough code so that we can simply cut/paste the code and generate the same result.
Answer: Took me a while to get it all building (with some guesses).
The problem is that the method is marked const. Thus you are not allowed to call any mutating functions on members (ie you can not call none const member functions or none const member functions on any member variables).
 void MapWindow::shuffleTiles() const
                                ^^^^^
 ...
     tileSet_.push_back(s);  // Attempt to mutate the state of the object.

This is explained in greate detail in the error message generated by the compiler:
t2.cpp:61:14: error: no matching member function for call to 'push_back'
    tileSet_.push_back(s);
    ~~~~~~~~~^~~~~~~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/vector:712:36: note: candidate function not viable: 'this' argument has type
      'const std::vector<std::string>' (aka 'const vector<basic_string<char, char_traits<char>, allocator<char> > >'), but method is not marked const
    _LIBCPP_INLINE_VISIBILITY void push_back(const_reference __x);
                                   ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/vector:715:36: note: candidate function not viable: 'this' argument has type
      'const std::vector<std::string>' (aka 'const vector<basic_string<char, char_traits<char>, allocator<char> > >'), but method is not marked const
    _LIBCPP_INLINE_VISIBILITY void push_back(value_type&& __x);

If you go to the end of the line it says: "but method is not marked const"
Deciphering line:

note: candidate function not viable: 'this' argument has type
  'const std::vector', but method is not marked const
  void push_back(const_reference __x);
note: candidate function not viable: 'this' argument has type
  'const std::vector', but method is not marked const
  void push_back(value_type&& __x);
Answer: I figured out the source of the problem: the vectortileSet_ didn't use to be a member variable, but I made it so out of necessity. I had, however, originally defined the function shuffleTiles as a const function, which of course makes it impossible for it to change the state of the class. Removing the const from the definition fixed the issue.
The error messages in C++ can sure be mystical.


Detect when your windows 8 app is uninstalled?

Question: How can I tell using c# or winjs when your app that the user downloaded is being uninstalled?
Can you call home, or try to save the client by giving/redirecting them to a site with an exit poll?
Comment: Sounds like some annoying software.
Comment: @watson - a post uninstall survey is relatively common. Chrome did it (and may still) for example.
Answer: Not supported. A key goal with the Windows Store is to make it seamless and painless for consumers to try apps. One result of this is that Store apps don't have any control over or hooks into install/uninstall processes. Bottom line is that the act of uninstall is not a time to try to exercise user engagement strategies. :)


Why do more levels not show in the logistic regression summary in R

Question: So I have a df with 6 variables and 334 obs, and one of the variables (doctor) consists of 11 levels. Doctor 1,2,3, etc.. till 11. When I do this:
fit <- lm(surgery~ fracture + age + diagnosis + doctor, data=df)
summary(fit)

the result is as follows:
lm(formula surgery~ fracture + time+ diagnosis + doctor +age , data=df)
Residuals:
    Min      1Q  Median      3Q     Max
-0.9580 -0.3892  0.0311  0.3669  0.8584

Coefficients:
              Estimate Std. Error t value Pr(>|t|)
(Intercept)  1.227e-01  1.566e-01   0.783   0.4342
fracture    -2.992e-01  6.811e-02  -4.393 1.59e-05 ***
waittime    -4.420e-05  2.362e-05  -1.872   0.0623 .
diagnosisLO2 1.548e-01  1.576e-01   0.982   0.3267
diagnosisLO3 7.911e-01  1.370e-01   5.776 2.03e-08 ***
diagnosisLO5 3.914e-01  1.261e-01   3.105   0.0021 **
diagnosisLO6 1.345e-01  1.929e-01   0.697   0.4864
doctor       3.077e-02  7.440e-03   4.137 4.67e-05 ***
age         -3.037e-03  1.786e-03  -1.700   0.0902 .
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.4281 on 279 degrees of freedom
  (46 observations deleted due to missingness)
Multiple R-squared:  0.2758,    Adjusted R-squared:  0.255
F-statistic: 13.28 on 8 and 279 DF,  p-value: 2.971e-16

Why are the doctor levels not showing? What am i doing wrong? I also tried coding it with dummy codes as follows:
install.packages("fastDummies")
library(fastDummies)
dfdummy <- dummy_cols(df, select_columns = "doctor")

but to no avail. Any clues?
Comment: The most likely reason is that `doctor` is coded as numeric, not a factor. So try: `lm(surgery~ fracture + age + diagnosis + as.factor(doctor), data=df)`
Comment: It **really** helps to reduce your situation to a minimal reproducible example. For instance, this code produces the same problem: `summary(lm(surgery ~ doctor, data.frame(surgery=rnorm(3), doctor=1:3)))`  Because there are only three observations in this dataset you should have no trouble identifying and fixing the problem.
Comment: @RobertLong Thank you! That helped me a lot!
Answer: TL:DR : Code your variable as a factor.
The long version:
While this question appears to be about software, there is a fundamental statistical issue at the heart of it, which I find is often not well understood bvy students.
It is always good to remember what a regression coefficient for a variable means:

it is the association of a 1 unit change in that variable, with a change in the outcome / response (leaving any other variables in the model unchanged)

So, consider for a moment this very simple dataset, consisting of just one variable doc taking the numeric values 1, 2 and 3:
(dt <- data.frame( doc = rep(1:3, 2)))
##  doc
##   1
##   2
##   3
##   1
##   2
##   3

When we use this in a regression model, R will create a model matrix, typically called $X$ which is used to fit the model:
$$ Y = X\beta + \epsilon$$
where $Y$ is the outcome, $\beta$ is the regression coeffcients and $\epsilon$ is the error. In the above case, $X$ will be:
 (X <- model.matrix(~ doc, dt))
  (Intercept) doc
           1   1
           1   2
           1   3
           1   1
           1   2
           1   3

So we have a column of 1s for the intercept (because it is constant for every observation) and an exact copy of our doc variable. So, the model would estimate two coefficients, an intercept and an estimate for doc. Suppose that these were 5 and 2 respectively, that is $\beta = (5 \: \: \: \: 2)$.  It is then very easy to see that $X\beta$ will be:
$$ \begin{align}
           1\times 5 \: \:+ \: \:  1\times 2  \: \:=& 7 \\
           1\times5 \: \:+ \: \:  2\times2  \: \:=& 9  \\
           1\times5 \: \:+ \: \:  3\times2  \: \:=& 11 \\
           1\times5 \: \: +\: \:   1\times2 \: \: =& 7 \\
           1\times5 \: \:+ \: \:  2\times2 \: \: =& 9 \\
           1\times5 \: \:+ \: \:  3\times2 \: \: =& 11
\end{align}
$$
Note that the interpretation of the regression coefficients is:

the intercept is the expected value of the outcome when doc is zero: that is: $1 \times 5 + 1\times 0  = 5$

the estimate for doc is the change in the outcome that is associated with a 1 unit change in doc - which can be seen from inspection is 2.

Now, when doc is categorical a little more work is needed. This is usuallly accomplished by using dummy variables and some contrast coding framework, which is often treatment constrasts. Let us repeat the above, but this time using treatment contrasts for categorical doc with levels "A", "B" and "C":
(dt.f <- data.frame( doc = LETTERS[rep(1:3, 2)]))
##  doc
##   A
##   B
##   C
##   A
##   B
##   C
 (X <- model.matrix(~ doc, dt.f))
##  (Intercept) docB docC
##           1    0    0
##           1    1    0
##           1    0    1
##           1    0    0
##           1    1    0
##           1    0    1

What is hapenning here ? This indicates that the model will produce 3 estimates, one for the intercept, one for docB and one for docC. Note that the value in the model matrix for the relevant level of doc is 1 when it corresponds to that level, and zero otherwise. Thus, docA is  implicitly included in the intercept and we refer to A as the reference level for doc
So, similar to before, let's suppose that the coefficient estimages are 5, 3 and 2 so that $\beta = (5 \: \: \: \: 3\: \: \: \: 2)$. Then $X\beta$ will be:
$$ \begin{align}
           1\times 5  \: \: +  0\times 3 \; \;+ 0 \times 2 =& 5 \\
           1\times5 \; \;+   1\times 3  \; \;+ 0 \times 2 =& 8 \\
           1\times5 \; \;+   0\times 3  \; \;+ 1 \times 2 =& 7 \\
           1\times5 \; \;+   0\times 3  \; \;+ 0 \times 2 =& 5 \\
           1\times5 \; \;+   1\times 3  \; \;+ 0 \times 2 =& 8 \\
           1\times5 \; \;+   0\times 3  \; \;+ 1 \times 2 =& 7
\end{align}$$
As for interpretation:

the intercept is the expected value of the response when all the variables are zero, which implicitly means when doc is at it's reference level of A

As before, the estimates for docB and docC are the associated change in the outcome for a 1 unit change in the variable, so for docB this is the difference in the outcome between docB and docA, and for docC this is the difference in the outcome between docC and docA. That is docB is associated with reponse that is 3 units greater than docA, and docC is associated with reponse that is 2 units greater than docA. We can then infer that docB is associated with reponse that is 1 unit greater than docC. However note that with more levels

This was a very long way of explaining that to fix your problem, you should encode your doctor variable as categorical.
Answer: Make sure that you doctor variable is a factor by using Class function. There is no need for you to create a dummy variable. R when it see a factor variable it will create a dummy variable on its own. It will choose one of the levels as a reference to give you estimates.


erro na função isempty

Question: Tenho um erro nesta função isempty no matlab, necessito que quando se encontre vazia através de uma matriz faça a condição a seguir ao if isempty:
function bn_hat = my_descodificador_Hamming_v2(rn,N,H_Ham,n_cyc,k_cyc,simb_alfa)

rn      = reshape(rn,n_cyc,N/k_cyc)';

bn_til      = rem(rn*H_Ham',2);

sn_til      = bi2de(bn_til,'right-msb')';
cn_hat      = rn';
pos         = find(sn_til>0);
pos_erro    = nansum(simb_alfa(sn_til(pos)),1);

if isempty(pos_erro,[])

    cn_hat(pos_erro+n_cyc*(pos-1)) =  not( cn_hat(pos_erro+n_cyc) );

end

bn_hat      = cn_hat(k_cyc:end,:)';
bn_hat      = reshape(bn_hat',1,[]);

o erro que me dá é o seguinte:

Eb/No = +0 dB  :: erros = Error using isempty
  Too many input arguments.
Error in my_descodificador_Hamming_v2 (line 11)
  if isempty(pos_erro,[])
Error in sim_FSK_incoerente (line 56)
  bn_hat = my_descodificador_Hamming_v2(cn_hat,N,H_Ham,n_cyc,k_cyc,simb_alfa);
Answer: A funcão isempty aceita apenas um parâmetro, mas no seu código tem dois.
Se você usar
if isempty(pos_erro)

deve resolver.
Comment: Resolveu, obrigado pela ajuda.

erro na função isempty


Is it possible to evaluate this integral?

Question: Is it possible to evaluate this integral: $$\int_{0}^{\frac{\pi }{2}}\ln(\sin 2x){\rm d}x$$
Comment: You might want to take a look at Clausen's Integral (http://mathworld.wolfram.com/ClausensIntegral.html)
Comment: @Alexander Jones : This type of question can be answered by typing something like int(ln(sin(2*x)),x=0..Pi/2) into the box at wolframalpha.com and hitting the equals sign. If it has a closed form, wolframalpha will almost certainly find it.  It may not tell you where it came from, though.
Comment: Voting to close this one down. The same question has been answered in the following links.

http://math.stackexchange.com/questions/354795/

http://math.stackexchange.com/questions/341643/

http://math.stackexchange.com/questions/37829/
Answer: Yes, it is possible. Here is how you advance. Recalling the identity $\sin(2x)=2\sin(x)\cos(x)$, we have
$$ \int_{0}^{\pi/2}\ln(\sin(2x))dx =\int_{0}^{\pi/2}\ln(2)dx + \int_{0}^{\pi/2}\ln(\sin(x))dx + \int_{0}^{\pi/2}\ln(\cos(x))dx. $$
The first integral is easy to evaluate. The second and the third integrals are equal and you can see this by just using the change of variables $x=\frac{\pi}{2}-\theta$. Now, let's evaluate one of them as
$$ \int_{0}^{\pi/2}\ln(\sin(x))dx = \int_{0}^{1}\frac{\ln(u)}{\sqrt{1-u^2}}du=\frac{1}{4}\int_{0}^{1}\ln(t)t^{-1/2}(1-t)^{-1/2}dt=I, $$
where the changes of variables $\sin(x)=u$ and $u^2=t$ were used respectively. To evaluate the last integral, consider the integral
$$ F = \int_{0}^{1}t^{\alpha}(1-t)^{\beta}dt = \beta(\alpha+1,\beta+1), $$
where $\beta(s,t)$ is the $\beta$ function. So, $I$ follows from $F$ as
$$ I= \frac{1}{2}\lim_{\beta \to -1/2}\lim_{\alpha \to -1/2}F_{\alpha}(\alpha,\beta)=-\frac{1}{2}\pi\ln(2). $$
Answer: It is well known that  $\Pi_{1\le k<n}\sin \frac{k\pi}{n}=\frac{n}{2^{n-1}}$.
So $\int_0^\pi \ln \sin x dx =\lim_{n\to \infty}\frac{\pi}{n}\ln \Pi_{1\le k<n} \sin \frac{k\pi}{n}=-\pi\ln 2 $. Therefore $\int_0^{\pi/2} \ln \sin 2x dx=-\pi\frac{\ln 2}{2}$.
Answer: This link contains at least four different ways to compute it (none of them uses Clausen function).


send packet in linux kernel

Question: I wrote a module to send a packet in kernel-space. but after insmod it gives a segmentation fault error. I have tried to change some parts of it but I still get errors.
the code:
//libraries

#define IP_Header_RM 20
#define UDP_Header_RM 8

static int __init init_Module(void){
    unsigned char *Data = "Test_Packet";
    int i = strlen(Data);
    struct sk_buff* skb = alloc_skb(ETH_HLEN + IP_Header_RM + UDP_Header_RM + i, GFP_ATOMIC);
    struct iphdr* iph = (struct iphdr*)skb_push(skb, IP_Header_RM);
    struct ethhdr* eth = (struct ethhdr*)skb_push(skb, sizeof (struct ethhdr));
    struct udphdr* uh = (struct udphdr*)skb_push(skb, UDP_Header_RM);
    struct net_device *Device;
    uint16_t proto;
    uint8_t Mac_Addr[ETH_ALEN] = {0x38, 0xd5, 0x47, 0xa1, 0x07, 0x41};
    Data = skb_put(skb, i);
    skb_reserve(skb, ETH_HLEN);
    Device = dev_get_by_name(&init_net,"enp0s3");
    proto = ETH_P_IP;
    uh->len = htons(i);
    uh->source = htons(2121);
    uh->dest = htons(2121);

    iph->ihl = 5;
    iph->version = 4;
    iph->tos = 0;
    iph->tot_len= htons(IP_Header_RM + i);
    iph->frag_off = 0;
    iph->ttl = 64;
    iph->protocol = IPPROTO_UDP;
    iph->check = 0;
    iph->saddr = 19216805;
    iph->daddr = 19216804;
    skb->protocol = eth->h_proto = htons(proto);
    skb->no_fcs = 1;
    memcpy(eth->h_source, Device->dev_addr, ETH_ALEN);
    memcpy(eth->h_dest, Mac_Addr, ETH_ALEN);

    skb->pkt_type = PACKET_OUTGOING;
    dev_queue_xmit(skb);
    return 1;
    }

static void __exit exit_Module(void){
    printk(KERN_INFO "Done");
    }

module_init(init_Module);
module_exit(exit_Module);

which parts I made mistake?
Thanks in Advance
Comment: `memcpy(eth->h_dest, Mac_Addr, ETH_ALEN);` <<-- looks suspect
Comment: What **exact** line causes a segfault? In other words, until which line the execution proceed without fault? How `skb` variable is defined?
Comment: @Tsyvarev i updated the code skbuff alocate just after ```int i = strlen(data)```. the SF is related to the lines before ```uh->dest = htons(2121);```
Comment: According to the [description](https://elixir.bootlin.com/linux/v5.11.10/source/include/linux/skbuff.h#L2384), `skb_reserve` is allowed only for **empty** buffer. So you need to call it before any `skb_push`.
Answer: You need to do skb_reserve() up front on the allocated buffer, before doing any skb_put() calls for user data or skb_push() for eth/IP headers.  You were segfaulting trying to skb_push() first, on a buffer without proper reservations.  I also had a few other suggestions for you:

Include your complete source next time!
Rearrange the order of your pushed headers to make a legit UDP/IP packet
dev_get_by_name() may fail; should check before trying to memcpy to its buffer
Push the user data before any eth/IP header(s)
Return 0 rather than 1 from a module's init() to indicate success

A tutorial page like this may help to put it all together:  http://vger.kernel.org/~davem/skb_data.html
The code below does not segfault on my Debian 10 system with a 4.19 Linux kernel.
//libraries

#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#include <linux/module.h>
#include <linux/virtio.h>
#include <linux/virtio_net.h>
#include <linux/bpf.h>
#include <linux/bpf_trace.h>
#include <linux/scatterlist.h>
#include <linux/if_vlan.h>
#include <linux/slab.h>
#include <linux/cpu.h>
#include <linux/average.h>
#include <linux/filter.h>
#include <linux/kernel.h>
#include <linux/pci.h>
#include <net/route.h>
#include <net/xdp.h>
#include <net/net_failover.h>

#define IP_Header_RM 20
#define UDP_Header_RM 8

static int __init init_Module(void){
    unsigned char *Data = "Test_Packet";
    int i = strlen(Data);
    struct sk_buff* skb = alloc_skb(ETH_HLEN + IP_Header_RM + UDP_Header_RM + i, GFP_ATOMIC);
    struct net_device *Device;
    uint16_t proto;
    struct iphdr* iph;
    struct ethhdr* eth;
    struct udphdr* uh;
    uint8_t Mac_Addr[ETH_ALEN] = {0x38, 0xd5, 0x47, 0xa1, 0x07, 0x41};

    skb_reserve(skb, ETH_HLEN + IP_Header_RM + UDP_Header_RM + i);
    Data = skb_put(skb, i);
    iph = (struct iphdr*)skb_push(skb, IP_Header_RM);
    uh = (struct udphdr*)skb_push(skb, UDP_Header_RM);
    eth = (struct ethhdr*)skb_push(skb, sizeof (struct ethhdr));

    Device = dev_get_by_name(&init_net,"enp0s3");
    if (Device == NULL) {
        printk(KERN_INFO "init_Module: no such device enp0s3\n");
        return 1;
    }
    proto = ETH_P_IP;
    uh->len = htons(i);
    uh->source = htons(2121);
    uh->dest = htons(2121);

    iph->ihl = 5;
    iph->version = 4;
    iph->tos = 0;
    iph->tot_len= htons(IP_Header_RM + i);
    iph->frag_off = 0;
    iph->ttl = 64;
    iph->protocol = IPPROTO_UDP;
    iph->check = 0;
    iph->saddr = 19216805;
    iph->daddr = 19216804;
    skb->protocol = eth->h_proto = htons(proto);
    skb->no_fcs = 1;
    memcpy(eth->h_source, Device->dev_addr, ETH_ALEN);
    memcpy(eth->h_dest, Mac_Addr, ETH_ALEN);

    skb->pkt_type = PACKET_OUTGOING;
    dev_queue_xmit(skb);
    return 0;
    }

static void __exit exit_Module(void){
    printk(KERN_INFO "Done");
    }

module_init(init_Module);
module_exit(exit_Module);

MODULE_DESCRIPTION("Stack Overflow 66846959");
MODULE_LICENSE("GPL");

Comment: I won't edit the answer now that it's been accepted.  But looking back, it would have been best to both verify that alloc_skb() actually returned something non-NULL, and also to free up the skb in the error path of dev_get_by_name() in the name of good housekeeping.

send packet in linux kernel


How do I generate a unique ID from web/javascript and then generate same unique ID in android App?

Question: Hi I would like to generate a unique ID from web/Javascript and also be able to generate the same unique ID in app without the two communicating. I will not be using PhoneGap just pure javascript or probably a light library.
I was initially planning to use the device ID but its not accessible from JavaScipt without using PhoneGap. There are many ways I know how to generate a unique ID from native Android app but I'd like to be able to generate the same one from the Web/JavaScipt.
Any help is appreciated thanks so much.
Comment: You can generate unique number using Date() like var now = new Date().getTime(); which will return always an unique number. But same number from other place it looks like impossible.
Comment: It won't be unique if two systems can generate the same value
Comment: thanks for the answers. it was good to get a reality check.
Answer: Unique ID Suppose to  be Generated Only Once.
Now come to your question:

How do I generate a unique ID from web/javascript and then generate
  same unique ID in android App?

You can not generate the same ID from two different places i.e. from Android Native and JavaScript/Web. Please keep in mind, not possible.
Note : If you are able to generate the same ID again then that ID is not unique at all.


Como clonar objetos em Python?

Question: Em algumas linguagens, além de podermos instanciar uma classe para construção de um determinado objeto, podemos também clonar uma instância já existente, caso queiramos um objeto com as mesmas caracteristicas da instância atual, porém sem alterar o estado da original.
Por exemplo, se eu quisesse modificar uma cópia de um objeto DateTime em PHP, para usar a mesma informação da data do objeto dessa instância, porém tendo uma instância apenas com o horário modificado, eu poderia fazer assim:
  $date = new Date('2015-01-01 00:00:00');

  $date2 = clone $date;

  // não precisei redefinir a data, mas só a hora

  $date2->setTime(23, 59, 59);

Acima, não foi necessário criar uma nova instância com a informação da data, mas apenas clonei e modifiquei para o horário que precisava.
É claro que acima foi apenas um exemplo, mas existem ainda outros casos que a criação de uma nova instância de um objeto poderia se tornar complicada, devida a dependências de um objeto. Aí podemos clonar para ter as mesmas informações num novo objeto, porém sem modificar o original.
Em Python também percebo que tudo (ou quase tudo até, onde percebi) são objetos. Porém, em se tratando de instâncias de classes, existe alguma forma de clonar objetos como se faz em PHP?
Parar criar uma instância de uma classe em Python não precisamos de um operador new, como em PHP.
Então como seria a forma de se clonar um Objeto em Python? Existe um operador específico para isso?
Outra coisa é que em PHP podemos usar um método mágico dentro da classe chamado __clone para determinar o comportamento daquela classe quando um clone for criado.
E em Python? Existe algum método especial para poder modificar o comportamento da classe em relação a criação de um clone?
Comment: Wallace estará à procura de algo como https://docs.python.org/3.5/library/copy.html, http://www.python-course.eu/deep_copy.php?
Comment: Tipo isso. Interessante é saber que o Python resolveu isso com um módulo...
Answer: Em Python, a forma mais comum de fazer isso é usando o módulo copy da biblioteca padrão.
Se dt é um datetime, você pode criar uma cópia fazendo:
from copy import copy
dt2 = copy(dt)

(* veja última sessão d respostas sobre o datetime especificamente)
O módulo tamem tem o método deepcopy, e a grande diferença é que enquanto o copy só vai copiar a instância - e manter referências internas para os objetos que sejam apontados pelos atributos.
Em particular para estruturas de dados com várias listas e diconários aninhados - o deepcopy vai fazer uma cópia recursiva de cada lista e dicionário na sua estrutura - enquanto que o copy vai criar uma cópia só do objeto passado, mas manter todas as referências internas.
O copy e deepcopy quebram um galhão - mas poderiam ser implementados em uma forma genérica, usando Python puro, com poucas linhas. O interessante da inguagem Python é que os objetos são definidos de forma a permitir introspecção, e em geral não violam essas regras.  Portando, se você, por exemplo, quisesse copiar uma instância de um objeto genérico, e não dispussesse do copy.copy poderia: (1) chamar o método __new__ da classe do objeto explicitamente, (2) atualizar o atributo __dict__ da nova instância para ser igual o __dict__ do objeto copiado:
obj = MinhaClasse()
obj.a = 20
obj.b = 30

obj2 = type(obj).__new__(type(obj))
obj2.__dict__.update(obj.__dict__)
print (obj2.a, obj2.b)

Saída:
20 30

Mas o copy ainda cobre vários corner cases, podendo copiar objetos que tenham atributos que não estão no __dict__, e etc...
(Só para constar - o mecanismo normal para instanciar uma classe chama o método __new__ e logo em seguida o __init__ de uma classe. Por isso quando criamos uma classe, em geral personalizamos só o __init__ - ao chamar só o __new__, o novo objeto não é inicializado com nenhum valor. Ao copiar os atributos, que ficam no __dict__, você tem seu "clone")
datetime: Note que o objeto datetime da biblitoeca parão do Python é imutável, então você não pode alterar o horário dele. Isso é necessário para que os datetimes possam ser usados como chaves de dicionários. Se precisar criar um outro datetime, mantendo a data e mudando o horário como no seu exemplo, precisará fazer uma função auxiliar que faça isso 'manualmente':
def changetime(dt, new_time):
    return  datetime.datetime(dt.year, dt.month, dt.day, new_time.hour, new_time.minute, new_time.second)

Comment: Muito obrigado pela resposta. O DateTime até que não me preocupou muito, pois foi o primeiro exemplo que me veio a mente quando citei sobre PHP. A resposta está bem explicativa, vou marcá-la como útil :p

Como clonar objetos em Python?


SUSE 12.1 Apache startup after oci8 installation

Question: I have got a virtual server running opensuse 11.4 with apache, php, oracle instantclient, and oci installed through pecl.
The steps it took for me to have it up and running on 11.4 were:
# Install instantclient
rpm -Uvh oracle-instantclient11.2-basic-22.214.171.124.0.x86_64.rpm
rpm -Uvh oracle-instantclient11.2-devel-126.96.36.199.0.x86_64.rpm

# Install OCI8 through pecl
pecl install oci8

# add oci8 to modules
vi /etc/php5/conf.d/oci8.ini
extension=oci8.so

# add LD_LIBRARY_PATH to apache
vi /etc/sysconfig/apache2
# add to bottom of script
export LD_LIBRARY_PATH="/usr/lib/oracle/11.2/client64/lib"

# restart Apache
/etc/init.d/apache2 restart

Celebrating the same procedure on a fresh installation of OpenSUSE 12.1 results in apache throwing the following message at startup:
PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib64/php5/extensions/oci8.so' - libnnz11.so: cannot open shared object file: No such file or directory in Unknown on line 0
I can't get any explanation, why it is working for 11.4 and in 12.1 it stops working.
Can someone please point me in the right direction..
Answer: I had the same problem also on openSUSE 12.1 but I did installed oci8 from source. I did a vendor change for php5 from openSUSE to obs (open build service):
openSUSE  -->  obs://build.opensuse.org/server:php

The vendor change also became with an upgrade of php from 5.3.8 to 5.3.17 wich is a nice feature.
Then made a symlink for the libnnz11 (looks like the enviroment variable wasn't working for me):
ln -s /usr/lib/oracle/11.2/client/lib/libnnz11.so /usr/lib/libnnz11.so

and now the extension is recognized and is working fine.
There is a bug reported with this issue if want to try the patch included in the config.m4 file generated by phpize but that didn't worked for me.


Drupal URL encoding breaks redirects/links

Question: I added a link to my Toolbar Shortcuts list and the path is:
admin/content?title=&type=slides&author=&status=All&vid=All
But when you click it, Drupal redirects to:
admin/content%3Ftitle%3D%26type%3Dslides%26author%3D%26status%3DAll%26vid%3DAll

Which breaks the link and redirects to a wrong page.
How do I prevent Drupal from converting symbols and leave it as it is.
Comment: Welcome to Drupal Answers! Notice that you simply stated facts, without asking any explicit question. Stack Exchange doesn't work well with implicit questions.
Answer: This is drupal core functionality that converts special correctors to string when using in toolbar shortcut menu.
Answer: Temporal workaround, create views with friendly URLs for pages you need, e.g. now each exposed filtered result has its own views page.
Can't come up with anything else since Drupal 'works this way'.


Adding Subdomain for my ruby on rails server, how to do?

Question: i've got some problems with my ruby on rails server.
It is running under localhost:3333 in my debian vm under a windows8 host.
I've installed apache2 and passengermodul for apache to get ruby. And then I've installed rails.
Now I need a subdomain wich calls the ruby on rails server.
for example admin.localhost:3333

Is something like that possible? And when how can I configurate it?
Answer: Add custom hosts with subdomains to the hosts file, follow these steps
In your terminal, open hosts file
cd /etc
sudo nano hosts

Add the host as mentioned in the following lines to the hosts file, you can add as many as you want
127.0.0.1       admin.localhost
127.0.0.1       subdomain.localhost

Save the file, CTRL + X then press Y
Done.
To run with a custom port, specify the port number while starting the server,
rails s -p 3333

Now you can run your application with, admin.localhost:3333
Hope this helps!
Comment: yeah thats clear, hats what I have done already ... but whats with the port 3333?

and how can I link it to my ruby on rails application running under localhost:3333
Comment: I have edited the answer, you just need to start the rails server specifying the port number with it, `rails s -p 3333`
Comment: yeah how the rails server could be started is clear thanks but how do I link the subdomain admin.localhost to the localhost:3333
Comment: Its already linked, in the hosts file I have used `127.0.0.1` which is the default address for localhost too, try using `admin.localhost:3333` it will still work
Comment: site isn't available ... dosn't load anyting
Comment: Please check whether it is correctly entered in `hosts` file or not because it should definitely work if everything is done perfectly
Comment: added a picture in my question
Answer: You can use the lvh.me domain. That domain has a DNS entry that will redirect to localhost. This also works for subdomains, so you can visit admin.lvh.me:3000 and it will redirect to localhost:3000 while still having the subdomain available in the Rails request.
The advantage is that you don't have to edit your localhost file.


How you know where to use LCM (Least Common Multiple)

Question: I'm new in number theory and my question might be very simple for you, but I don't understand how you know when to use LCM.
For example in this question: Mike and Sara work together and Sara takes a break every 45 min and Mike takes a break every 20 min. After they finish their break (they are having break together), how long before they take break TOGETHER again? The answer is LCM(45,20) = 180 min.
Maybe I don't get something right, but I don't understand why we use LCM?
Can you explain?
Comment: Assume that Mike's breaks last equally long, and Sara's breaks also last equally long.  If a break lasts at most $5$ mins for both parties, then the answer is as you state.  If each of Mike's breaks lasts more than $5$ mins, then the answer is $90$ mins.  Otherwise, if each of Sarah's breaks lasts more than $5$ mins, then the answer is $140$ mins.  If you notice, $5=\gcd(20,45)$.
Comment: LCM tells you how to combine two divisibility relations into one, as follows  $$  a,b\mid c\iff {\rm lcm}\,(a,b)\mid c$$
Comment: Mike has breaks at $x=n*20$ minutes.  Sarah has breaks at $y=m*45$ minutes.  The have mutual breaks when $x=y=n*20=m*45$.  This time is a multiple of 20.  It is also a multiple of 45.  So it is a common multiple of 20 and 45.  The first such common break will be the lowest such common denominator.
Answer: They take break together again whenever the time elapsed is a multiple of both $45$ and $20$. The first time they take break together is the smallest such common multiple – in other words their lowest common multiple.


How do you run multiple karate feature file in a gatling simulation?

Question: How do you run multiple karate feature file in a gatling simulation?
The following is my code snippet for my gatling simulation:
class TestGatlingScalaSimulation extends Simulation {

  val log: Logger = LoggerFactory.getLogger(classOf[TestGatlingScalaSimulation])

  /*val environmentVars = System.getenv().asScala
  for ((k,v) <- environmentVars) println(s"key: $k, value: $v")*/

  val properties: mutable.Map[String, String] = System.getProperties.asScala
  //for ((k,v) <- properties) println(s"key: $k, value: $v")
  val activeUsers: Int = properties.getOrElse("SIM_ACTIVE_USERS", "10").asInstanceOf[String].toInt
  val rampUpPeriod: Int = properties.getOrElse("SIM_RAMP_UP_PERIOD", "10").asInstanceOf[String].toInt
  val karateFeatureFile: String = properties.getOrElse("SIM_FEATURE", "karate/example.feature")

  val protocol: KarateProtocol = karateProtocol()

  protocol.nameResolver = (req, ctx) => req.getHeader("karate-name")

  val create: ScenarioBuilder = scenario("create").exec(karateFeature(s"classpath:$karateFeatureFile"))
  log.info("Running simulation of feature [{}] with [{}] users ramped up in [{}]", karateFeatureFile, activeUsers.toString, rampUpPeriod.toString)
  setUp(
    create.inject(rampUsers(activeUsers) during (rampUpPeriod seconds)).protocols(protocol)
  )
}

I'm only able to run one feature file each time like this:
./gradlew -Pgatling_simulation=performance.TestGatlingScalaSimulation -DSIM_ACTIVE_USERS=100 -DSIM_RAMP
_UP_PERIOD=10 -DSIM_FEATURE="karate/flight/myfeature.feature" gatlingRun

Answer: This is described clearly in the docs: https://github.com/intuit/karate/tree/master/karate-gatling#usage
val create = scenario("create").exec(karateFeature("classpath:mock/cats-create.feature"))
val delete = scenario("delete").exec(karateFeature("classpath:mock/cats-delete.feature@name=delete"))

setUp(
  create.inject(rampUsers(10) during (5 seconds)).protocols(protocol),
  delete.inject(rampUsers(5) during (5 seconds)).protocols(protocol)
)


Adding references in Visual Studio project template?

Question: I'm creating a multi-project template for VS2015 where one of the created projects references the other. How do I add the reference using the template?
If I add the reference using the VS GUI it will add the following to the .vcxproj file:
<ItemGroup>
<ProjectReference Include="path\xyz.vcxproj">
<Project>{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}</Project>
</ProjectReference>

And the GUID is a valid one, since VS knows the GUID of the referenced project. When I create the new projects from template I don't know what GUID will be chosen for the newly created project, so I can't add a valid GUID by using the template parameters. I can easily add the Include="..." part correctly, but the GUID I don't have.
I couldn't find much info on the <ProjectReference> tag either, but it seems that a valid GUID is required, leaving the <Project> tag out causes the reference to not work, and same happens if I use all zeros GUID.
Answer: In my case I have 2 project references in the main project. It worked for me in Visual Studio 2019, Net Core 3. as @skaddy answer, but not after several Visual Studio restarts and finally machine restart (that sucks).
The difference is that I did not care about the guid I  just let Visual Studio care about that.
Steps

In the solution template, the Root.vstemplate I set CopyParameters="true"

    <ProjectTemplateLink ProjectName="$safeprojectname$.API" CopyParameters="true">
        APITemplate\MyTemplate.vstemplate
    </ProjectTemplateLink>

I ensure that ReplaceParameters="true" was there in the main project template ( it was since the beginning).

    <TemplateContent>
        <Project TargetFileName="APITemplate.csproj" File="APITemplate.csproj" ReplaceParameters="true">
            ...
        <\Project>
        ...
    <\TemplateContent>

In the main .csproj file I look at the references and change them with the parameters

From this
    <ItemGroup>
        <ProjectReference Include="..\Data\Data.csproj"/>
        <ProjectReference Include="..\Service\Service.csproj"/>
    </ItemGroup>

To this
    <ItemGroup>
        <ProjectReference Include="..\$ext_safeprojectname$.Data\$ext_safeprojectname$.Data.csproj"/>
        <ProjectReference Include="..\$ext_safeprojectname$.Service\$ext_safeprojectname$.Service.csproj"/>
    </ItemGroup>

Again, for me the parameters just works after machine restart.
Comment: Just make sure the tag of  and  inside template data does not have an addentilanal prefix or postfix it just should be just $safeprojectname$
Comment: This worked for me. Tip: at least on VisualStudio 2022, you can prevent the reboot by deleting the c:\users\{user_id}\AppData\Local\Microsoft\VisualStudio\17.x_yyyyy\NpdProjectTemplateCache_en-US file as well as the ProjectTemplatesCache_{xxx} directory, located under the same path.
Comment: +1 for the $ext_safeprojectname$ reference. That was exactly what I was missing. I couldn't find docs on that anywhere.
Answer: You can generate the GUIDs in the solution template and pass them to the projects. Therefor you need the parameter CopyParameters in the ProjectTemplateLink in Solution Template.
Example:
<ProjectTemplateLink ProjectName="$safeprojectname$.Data"  CopyParameters="true">

Your project template has to replace parameters
<Project TargetFileName="Data.vbproj" File="Data.vbproj" ReplaceParameters="true">

Now you can access the parameters from solution template inside the project file and set the external guid parameter (note the acces to the external parameter have a "$ext_")
 <ProjectGuid>{$ext_guid1$}</ProjectGuid>

For the project with the reference you use the ProjectReference inside ItemGroup
<ItemGroup>
  <ProjectReference Include="..\$ext_safeprojectname$.Data\$ext_safeprojectname$.Data.vbproj">
    <Project>{$ext_guid1$}</Project>
    <Name>$ext_safeprojectname$.Data</Name>
  </ProjectReference>
</ItemGroup>

It worked for me using Visual Studio 2017 with .NET Framework 4.5.2


Googledrive app for windowsphone?

Question: I am developing a Google Drive application for Windows Phone using URLs provided in the SDK through HTTPWebRequest. Is there an API for WP8 to develop Google Drive applications?
I downloaded all of the content without any problem. While I am uploading the MIMEtype, it is not always uploaded correctly, and is uploaded as an octet stream.
Please can anyone help with how to upload to Google Drive using C# code?
Thanks
Answer: Check the "Upload Files" section of the Google Drive SDK :
https://developers.google.com/drive/manage-uploads
Comment: Hi i take help from this document and develop and i uploaded correctly, till two days back it works good and uploaded correct mimetype,now from two days the same code i am running agian i found that uploaded mimetype is octetstream only...is it depends on client id,secret or key???
Comment: take an example of creating folder in gdrive for this i am doing in two steps first one to create folder using post request and second to update name and mimetype by put request
Comment: first method post  string url = "https://www.googleapis.com/upload/drive/v2/files?uploadType=media&access_token=" + Goolgletoken;                 string[] HeaderKeys = { "X-Upload-Content-Type" };
            string[] HeaderValues = { "application/vnd.google-apps.folder" };
Comment: second put  string url = "https://www.googleapis.com/drive/v2/files/" + id + "?&access_token=" + Goolgletoken;
            String multipartRequestBody = "{\"title\":\"" + FolderName + "\", \"mimeType\": \"application/vnd.google-apps.folder\"}";
Comment: url is Upload url and HeaderKeys is header and HeaderValues is value and multipartRequestBody is body
Comment: what i am wondering is before two days it worked properly from last two days it is not working i.e,mimetype is always as OctetStream not as application/vnd.google-apps.folder,name is updating mime not...
Comment: if u dont understand please provide me an exmaple to create folder in googledrive using webrequest
Comment: hi catalin Manoliu, can u tell how to upload through webrequest
Answer: i got solution, actually i am using  string[] HeaderKeys = { "X-Upload-Content-Type" }; string[] HeaderValues = { "application/vnd.google-apps.folder" } for post method,
here i used request.contentType in the place of X-Upload-Content-Type now i am uploading all files with correct stream.

Googledrive app for windowsphone?


Connectedness problem and countability of compact subsets of the Sorgenfrey line

Question: 1) Stuck with this problem, can you please help? Show that if $X$ is connected and for a connected subspace $A$ of $X$ we have $X \setminus A = U \cup V$ where $U,V$ are open in $X \setminus A$ and disjoint, then the sets $A \cup U$ and $A \cup V$ are connected.
2) The following result appears in Encyclopaedia of mathematics by Hazewinkel page $375$:
Any compact subset of the Sorgenfrey line is countable.
I tried to prove this without any luck. Why is this true?
Comment: Maybe [this link](http://dantopology.wordpress.com/2009/09/27/a-note-on-the-sorgenfrey-line/) will give ideas.
Answer: I will assume sets of the form $[a,b)$ are open.
Let $C$ be a compact subset of the Sorgenfrey line $E$. As the topology on $\mathbb{R}$ is weaker than the one on $E$, $C$ is also compact in the standard topology of $\mathbb{R}$. In particular it is closed and bounded there. Now, if $A$ is any non-empty subset of $C$, its supremum $\sup(A)$ is not only in $C$ but already in $A$: otherwise the sets $\{x: x < a \}$ for $a \in A$ and $\{ x: x \ge \sup(A) \}$ form an open cover of $C$ without a finite subcover, contradicting its compactness. So compact subsets of the Sorgenfrey line are well-ordered under $>$, the reverse standard order on $\mathbb{R}$.
It is well-known such subsets are at most countable, e.g. using that the order topology is second countable.
Answer: (1) Let $U_0$ and $V_0$ be open sets in $X$ such that $U = U_0 \setminus A$ and $V = V_0 \setminus A$, and suppose that $A \cup U$ is not connected; then there are non-empty sets $H,G \subseteq A \cup U$ such that $A \cup U = G \cup H$, $G \cap H = \emptyset$, and $H$ and $G$ are closed and open in the subspace topology on $A \cup U$.
Suppose that $G \cap A \ne \emptyset \ne H \cap A$. Since $G$ and $H$ are open in $A \cup U$, there are open sets $W_G,W_H$ in $X$ such that $G = W_G \cap (A \cup U)$ and $H = W_H \cap (A \cup U)$. Then $G \cap A $ = $W_G \cap (A \cup U) \cap A = W_G \cap A$, since $U \cap A = \emptyset$, and similarly $H \cap A = W_H \cap A$. Thus, $G \cap A$ and $H \cap A$ are relatively open, non-empty subsets of $A$, and since $A \subseteq G \cup H$, their union is $A$; this contradicts the assumption that $A$ is connected. We may therefore assume that $A \subseteq G$, say, so that $H \cap A = \emptyset$, $W_H \cap A = \emptyset$, and hence $H = W_H \cap U$.
Now $W_H \cap U \subseteq W_H \cap U_0 \subseteq W_H \cap (U \cup A) = (W_H \cap U) \cup (W_H \cap A) = W_H \cap U$, so $W_H \cap U = W_H \cap U_0$, and hence $H = W_H \cap U$ is open in $X$. I claim that $H$ is also closed in $X$, contradicting the assumption that $X$ is connected.
Clearly $X \setminus H = G \cup V = \left(W_G \cap (A \cup U) \right) \cup V = \left(W_G \cap (X \setminus V) \right) \cup V = W_G \cup V$. But $A \subseteq G \subseteq W_G$, so $V_0 \setminus V \subseteq A \subseteq W_G$, and $X \setminus H = W_G \cup V = W_G \cup V_0$, an open subset of $X$, as claimed.
(2) Let $K$ be an uncountable subet of the Sorgenfrey line. Suppose that $x \in K$ and there is a sequence $\langle x_n:n \in \omega \rangle$ in $K$ such that $x_n < x_{n+1}$ for all $n \in \omega$ and $x = \sup\{x_n:n \in \omega \}$ (i.e., the sequence converges monotonically up to $x$ in the Euclidean topology). Let $V_L = (\leftarrow,x_0)$, $V_R = [x, \to)$, and for $n \in \omega$ let $V_n = [x_n,x_{n+1})$; then $\mathcal V = \{V_L,V_R\} \cup \{V_n:n \in \omega\}$ is an open cover of $K$ with no finite subcover. Thus, it suffices to show that $K$ must contain such a point $x$ and sequence $\langle x_n:n \in \omega \rangle$.
If not, for each $x \in K$ there must be a rational number $r(x)<x$ such that $(r(x),x) \cap K = \emptyset$. But $\mathbb Q$ is countable, so there must be distinct $x,y \in K$ such that $r(x) = r(y)$. (In fact the function $r$ must be constant on an uncountable subset of $K$, but we need only two points with the same $r$ value.) Without loss of generality $x<y$. But then $r(y) = r(x) < x < y$, and $x \in (r(y),y) \cap K$, contradicting the choice of $r(y)$. Thus, the desired point and sequence must exist, and $K$ cannot be compact (or even countably compact, since $\mathcal V$ is countable).
Answer: I'm not sure how to answer a question with two questions in it, so here's an answer to the first question.  The argument seems more convoluted than it should be, so please let me know if there's some simplification you see.
We'll show $A\cup U$ is connected, the other case is symmetric.  Suppose that $C \subseteq A \cup U$ is clopen.  Since $A$ is connected, by replacing $C$ with $(A \cup U)\setminus C$ if necessary we may assume $C \cap A = \emptyset$.  Since $U$ is open in $X\setminus A$, there is an open set $U_1 \subset X$ disjoint from $V$ such that $U = U_1 \setminus A$.  Since $C$ is open in $A \cup U$, there is an open set $U_2 \subseteq X$ disjoint from $A$ such that $C = U_2 \cap (A \cup U)$.  Thus, $C = U_1 \cap U_2$, so $C$ was actually open in $X$ all along.
It suffices then to show that $C$ is closed in $X$ (since $X$ is connected, this forces $C$ to be empty granting the connectedness of $A \cup U$).  An argument analogous to the one above works to show that $X \setminus C$ is the union of two open subsets of $X$.

I was going to answer the second question in a second answer, but then I realized that made absolutely no sense.  The point to this question is that any uncountable subset of the reals contains a countably infinite, strictly increasing sequence.  If not, then you'd have a reversed copy of $\omega_1$ (the first uncountable ordinal) sitting inside the reals, which contradicts separability (squeeze a rational between two successive points).
Once you have your increasing sequence $(x_n)_n$, you can build a counterexample to compactness by looking the cover $\{(-\infty, x_n) : n \in \mathbb{N}\} \cup \{[\lim_n x_n, +\infty)\}$ (if the limit exists -- if the sequence blows up to infinity you don't need to worry about that last part).


if continuous function $f$ is zero almost everywhere then $f = 0$ everywhere

Question: If the function $f:G \to \mathbb{R}$ with $G$ a domain in $\mathbb{R}^n$,and $f$ is continuous.
Prove if $f = 0$ almost everywhere(In Lebesgue measure) then $f = 0$ everywhere.
My attempt: w.l.o.g assume $f(x)>0$ for some $x$,since $f$ is continuous ,there exist a neighborhood of $x$ with all $f(y)>0$ on the neighborhood,and the neighborhood is not measure zero.So we have the result.
Is my proof correct?
Comment: Yes, it is. Congratulations.
Answer: Yes, your proof is correct.
You can make it even more precise (but maybe cumbersome) using a $\delta$-$\epsilon$ argument. Since $f$ is continuous at $x$, for every $\varepsilon>0$ there exists $\delta>0$ such that $||x-y||<\delta$ implies $|f(x)-f(y)|<\varepsilon$. Since $f(x)>0$, say $f(x)=l$, we can take $\varepsilon=\frac{l}{2}$ and so $f(y)>\varepsilon>0$. This is true for all $y\in B(x,\delta)$ -the open ball of center $x$ and radius $\delta$-, whose measure is positive (you can even look at the volume of the ball if you want to check that). So we have the contradiction.
Comment: Just a nitpick, $G$ is a domain in $n$-dim Euclidean space, but the procedure is the same.
Comment: Yes, I missed that. I'm going to correct it, because the only difference is changing absolute value by norm and the interval by a ball.


Best option for DFS deployment

Question: Initially, we placed the DFS function on the 2 domain controllers but the login times are getting longer/slower and the CPU/memory resources on the 2 domain controllers are almost flatline during peak hours where a lot of users are reading and writing files on the servers. To mitigate this, we plan to deploy 2 new domain controllers, demote the 2 old domain controllers and leave the DFS function on the old servers.
I know that a domain namespace is highly dependent on Active Directory -- is there going to be a performance issue if we split the DFS function from the domain controllers? Is our plan the best approach or is there a better one?
Comment: how many dfs links are in the tree?
Comment: There are 5 DFS links in the tree
Answer: Are the domain controllers hosting the DFS namespace and the shared folders? If they're only hosting the DFS namespace then the user activity should have no bearing on the performance of the domain controllers. My recommendation before you go and build new domain controllers would be to run performance monitor on the domain controllers and see what's really causing the problem. You can do this very easily with PerfWiz and PAL.
http://www.microsoft.com/downloads/en/details.aspx?FamilyID=31fccd98-c3a1-4644-9622-faa046d69214
http://pal.codeplex.com/
Comment: They're hosting the DFS namespace and shared folders. If we move the domain controller function from the server (by deploying 2 new DCs), what sort of traffic can we see between the DFS namespace + shared folder + replication servers and the domain controllers?

Best option for DFS deployment


How to automatically check a checkbox in React if I have the id

Question: I have a set of checkboxes which the user checks to create some filters.  The user submits the form where they activate the filters.  This works fine however if the user goes back to the filterContainer the checkboxes do not keep their state and all checkboxes are unchecked.
How can check the checked checkboxes when the filter page is loaded.
If this was standard JS I would simply grab each dom element (with the correct id and then set the attribute to checked) Although I don't see a way of doing this in React.
Here is the code
Age data is simply an array and the handleClick function just sends the data to the store.
const ageData = [18+,18-35,36-50, 50+]

Age

    {ageData.map((item, index) =>[

      <CheckBox checked={need to send a boolean here somehow}
        handleClick={() =>this.handleClick({
          'id':item.id,
          'name': 'age_group_ids'
        })}
        key={index}
        id={'age:' + item.id} />
      {item.description}
 ])}

Answer: this?
const checkedIds = []

<CheckBox checked={checkedIds.includes(item.id)} ..

Comment: While this code may answer the question, it would be better to explain how it solves the problem without introducing others and why to use it. Code-only answers are not useful in the long run.
Comment: Will this work with an object ( I may have id's which are the same but name is different)
Comment: @marcuspetty the idea is to keep track of selected objects inside a state and then set checked status based on that array


Best practice for handling positions of rows

Question: What is the best practice for moving rows. So that you might want to change order of items. Now if you make a new column called order_id or something, wouldn't that fail if I delete or select rows.
Another method I guess is to just switch values completely with an primary ID, so just values except the ID are changed. however I do not know what people usually use. There are so many websites that give you the ability to change order of things.how so they do that?
Comment: They sort the result sets from the SQL queries (`order by`).
Comment: You use a weight column, give each item a weight when saving a new row and ordering your queries by the weight. When a row is removed, it creates a gap but that has no effect on the sorting. When moving a row to a specific weight, add +1 to all with equal or larger weights.
Answer: Every SQL statement that returns a visible result set should include an ORDER BY clause so that the results are consistent.  The Standard does not guarantee that the order of rows in a particular table will remain constant or consistent, even if obvious changes aren't made to the table.
What you use for your ORDER BY clause depends on the use case.  A date value is the usual choice for a comment thread or blog entry ordering.  However, if you want the user to be able to customize the order that a result set shows in, then you have to provide a column that represents the position of the row, and adjust the value of that column when the user makes changes to the order they see.
For example, if you decide that the column will contain a sequential number, starting with 1 for the first row, 2 for the second, etc.  then you will be ok to delete rows when they need to be deleted without having to do updates.  However, if you insert a row, you will need to give the row you insert the sequential number appropriate for it's position, and update all rows below that with their new position.  Same goes for if you move a row from somewhere else to a new location;  the rows between the new and old locations need to be updated with new postion indexes.


apache configuration for drupal multisite

Question: I have spent over a day trying to get a multisite install to work and I think most of it is in place but I still cannot see the install.php when I visit www.mywebsite.co.uk/install.php?
I have a dedicated server running ubuntu, apache2 and latest mysql and php 5.
I have installed the latest Drupal codebase into
/home/d/r/drupal/web/public_html

I have have setup drupal database (called drupal) to and configured the codebase and all is working great and can view the drupal installation no problem on www.myserver.co.uk/drupal.
I next followed the instructions at: http://gotdrupal.com/videos/multisites-vs-multiple-sites and have setup up my apache conf almost exactly as described:
These are the contents of my various conf files:
/etc/apache2/conf.d/drupal6.conf:
#============================================================
# Toggle APC cache
#php_flag apc.cache_by_default 1
#This is already enabled in php

<Directory "/home/d/r/drupal/web/public_html">
    # Yeah, better performance - no hits to the file system
    # Loading Drupal's .htaccess into memory is much better
    AllowOverride none

    # Define your own file limitations on drupal files
    <FilesMatch "(install.php|cron.php|update.php|\.txt)$">
        Order deny,allow
#        Include conf.d/ip.conf
# including the line above always caused an error when re-starting apache2 so I have hard coded the IPs below (these are not the ones I am usinb obviously!)
Allow from 18.104.22.168
Allow from 18.104.22.168
        Deny from all
    </FilesMatch>

    # Read in Drupal default .htaccess file asif conf - easier CVS management
    Include /home/d/r/drupal/web/public_html/.htaccess

# Offline mode for multisite setup - see file for more info
# Uncomment the line below to set sites offline
    # Include conf.d/offline.conf

</Directory>

# Sorry, no svn peeking
<DirectoryMatch "\.svn">
    # Currently pointing back to drupal
    # High traffic sites might want custom
    # error pages, no need to load drupal
    ErrorDocument 403 /index.php
    Order allow,deny
    Deny from all
    Satisfy All
</DirectoryMatch>

# Allow the .htacces files to be used in the sites folder where /files are stored
<Directory "/home/d/r/drupal/web/public_html/sites">
    AllowOverride
</Directory>

# Block off access to admin and devel - just in case
<LocationMatch "/(admin|devel)">
    Order deny,allow
#    Include conf.d/ip.conf
# including the line above always caused an error when re-starting apache2 so I have hard coded the IPs below (these are not the ones I am usinb obviously!)
Allow from 220.127.116.11
Allow from 22.214.171.124
    Deny from all
</LocationMatch>
#============================================================

/etc/apache2/conf.d/ip.conf:
#============================================================
#This file always caused a problem when repstarting apache so I hard coded the IP addresses
# into the drupal6.conf file.  Would like to undersatand why this wont work! I am using the correct IP addresses, these are just for posting!
Allow from 18.104.22.168
Allow from 22.214.171.124
#============================================================

/etc/apache2/apache2.conf:
#============================================================
# ..
# ..
# All the apache config and at the very bottom is these lines:
# Include the virtual host configurations:
Include /etc/apache2/sites-enabled/[^.#]*
#============================================================

/etc/apache2/sites-available/drupalsites.conf:
#============================================================
# This is called from Apache2.conf
# Each vhost can be read in as its own file
Include vhosts/mywebsite.conf
#============================================================

/etc/apache2/vhosts/mywebsite.conf:
#============================================================
# This is called from /etc/apache2/sites-available/drupalsites.conf
<VirtualHost mywebsite.co.uk:80>
DocumentRoot /home/d/r/drupal/web/public_html
ServerName mywebsiteco.uk
ServerAlias www.mywebsiteco.uk
ErrorLog /var/log/apache2/sites/mywebsite.co.uk_error-log
CustomLog /var/log/apache2/sites/mywebsite.co.uk_access-log "combined"

# Rewrite the www
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.mywebsite\.co.uk/?$ [NC]
RewriteRule ^(.*)$ http://mywebsite.co.uk$1 [L,R=301]

# Read in the drupal configuration
Include conf.d/drupal6.conf

# Block access while developing
#  Include conf.d/beta.conf

</VirtualHost>
#============================================================

/etc/hosts:
127.0.0.1 localhost server0
127.0.0.1 mywebsite.co.uk
18.104.22.168 myservername.co.uk

The website root I have created is at:
/home/m/y/mysite/web/public_html

I have replaced the physical public_html directory with a symlink to
/home/d/r/drupal/web/public_html

I can view the text files such as www.mysite.co.uk/INSTALL.txt but when I try to view any php page (such as install.php or the root) I always get the following error:
"Internal Server Error, this is an error with your script, check your error log for more information."
I am at a loss as to what I need to do next and would appreciate any help or advice.
Thank you
Answer: The config you have posted is vastly more complicated than it needs to be.  I'm not quite sure why it's set up that way, but I did notice a few things that might make a difference.
First and foremost, in drupal6.conf all you should need is the following:
<Directory /home/d/r/drupal/web/public_html/>
    Options +FollowSymLinks
    AllowOverride All
    order allow,deny
    allow from all
</Directory>

The rest of the stuff is secondary and may be complicating (or causing) the problem.  I'd recommend - especially for the initial install - to simplify the configs as much as possible.  I run a lot of Drupal sites and I never mess with anything beyond pointing the mysite.conf to the Drupal directory and creating the (Drupal root)/sites/my.site.com directory and settings files.
I'd recommend ripping all the other stuff out of the drupal6.conf and seeing if it works for the install. Then add back in the access blocks on the /admin, install.php, etc.  I don't recommend messing with the .htaccess files in the config file.  Leave out the line including the .htaccess in the apache configs and just let .htaccess be picked up as it's designed to by apache.
Answer: Just out of curiosity, have you got php enabled and an appropriate AddHandler line somewhere? It looks a bit like it's trying to run the php files as cgi scripts directly rather than using the module. On Ubuntu and Debian you can make sure php is loaded as a module with the following:
a2enmod php5
/etc/init.d/apache2 force-reload

If php works elsewhere in your setup, I'd also be inclined to check the .htaccess file. Specifically, you'll want to make sure it isn't trying to set .php files to be run as cgi scripts explicitly. If you find anything like the following line referring to .php files, comment them out and see if things improve.
AddHandler cgi-script .php

As you've explicitly loaded the .htaccess file, don't forget to reload as appropriate.
Comment: I do however have php based websites also running from this server without a problem (and I have configured the drupal codebase I installed and have it running)
Comment: When I run "a2enmod php5" in shell I get a message saying this module does not exist?
Comment: I performed a atp-get on php5, php5-dev, apache-dev yesterday in order to get the php APC module.
Comment: On further examination, it seems that it may be finding your .htaccess and throwing a 500 Error because you have AllowOverride None set. As a test move .htaccess to htaccess and update your apache config appropriately, then reload and see if things improve. Also if you could post anything relevant from the error log that'd be good too.
Comment: Specifically the fact that drupal includes 'Option' Directives in that file.
Comment: when I move the .htaccess and restart apache I get an error saying .htaccess cannot be found (it is included from drupal6.conf).

I updated apache2.conf to reflect the moved htaccess and got the following error:
Syntax error on line 134 of /etc/apache2/apache2.conf: Syntax error on line 22 of /etc/apache2/conf.d/drupal6.conf: Could not open configuration file /home/d/r/drupal/web/public_html/.htaccess: No such file or directory
Comment: Apologies, I should've been more specific, you should update drupal6.conf to reflect that /home/d/r/drupal/web/public_html/.htaccess has been moved to /home/d/r/drupal/web/public_html/htaccess
Comment: Ok, I did just that and apache restarted ok with no problems.  Checked www.mysite.co.uk and still got server not found.  Checked www.mysite.co.uk/install.php and got "server not found".  Checked www.mysite.co.uk/INSTALL.txt and got the drupal installation instructions.
Comment: Just another quick check, your hosts listed only have 127.0.0.1 mysite.co.uk listed. Is what resolves when you host www.mysite.co.uk what you expect?
Comment: I must admit, I am not sure why I added it to the etc/hosts because I was following instructions from drupal website.  I'm not a linux guru and still finding my way around! I will try removing that line from my hosts and restart apache2.
Comment: my hosts file also has my server name and ip, I omitted that.
Comment: At this point I'm at a loss, at the very least it's not generating a 500 error which is a step in the right direction, ammending my post to reflect what was causing htat.
Comment: I have just removed my website hosting for www.mysite.co.uk from my control panel (webfusion) then re-created it again and now I get server not found?  I also played with symlinks replacing my public_html with a symlink to /drupal codebase.  If I use virtualhost do I also need symlinks?
Comment: I appreciate you help. Thank you.  I will keep bashing at it until something works!


How to send external e-mail from device? (Exchange 2003)

Question: I'd like to get external notifications on my iPhone from service monitors inside the network. The easiest way to do this is to have the devices send e-mails to my ATT SMS email (email@example.com).
However, while internal notifications work fine, it doesn't seem as if Exchange is allowing the relay of these messages to the outside world.
How can I have these devices (APC Matrix, Servers Alive, et al.) alert me anytime?
Thanks.
(Exchange 2003 SP2 on Windows Server 2003)
Answer: What you're trying to get done is referred as allow SMTP relay. Normally exchange SMTP Virtual Server is configured to allow relay only from authenticated senders and quite often the devices sending out e-mails don't authenticate with the server they're relaying through.
There's quite an easy way to achieve this, and that's called allowing IP relay on Exchange.

Open Exchange ESM, navigate down to the SMTP Virtual Server that'll be used to relay
Open the properties of that SMTP Virtual Server, and then on Access Tab locate the section about 'Relay'.
There you'll need to list down IP Addresses of devices and servers that'll need to relay out to external e-mail domains

Once exchange is configured on the devices you can use the exchange server IP/FQDN as a relay host for these outgoing emails.
Comment: Thanks Prayag - and all - for the tips. It turned out I had already added the IP address for the APC in the relay tab (thought this should allow external mailing long ago). It took a power outage and subsequent "warmstart" of the APC... and then the messages were sent out correctly.
Comment: Thank you! Just what I needed to do. Found it in the prompt.
Answer: To do this, the servers sending alerts need to authenticate with the Exchange Server before attempting to send, else they will not be allowed to relay.
You can either setup an account in Exchange for these emails and set your applications to authenticate to this account when they send, or setup Exchange to allow anonymous relaying only from the IP addresses of these services. There is a good article here on how to set that up.
Answer: I've found that if the "From:" address is not an address within the Exchange server's configured email domains, it won't pass it along. Messages like, "powerchute@ahups1" will get bounced, but "email@example.com" will get passed along. In general. It just may be that the Exchange servers need to have that IP address added to the allowed-relay list.
Answer: Sam is correct.  Unauthenticated connections cannot relay by default in Exchange 2000/2003.  What I did is create a second virtual SMTP server on another IP address and check the Anonymous authentication option in the Access tab.  Then I configure any internal notification system to connect to that IP address.  Since this virtual SMTP is not used by your normal mail flow, you are not compromising your normal mail traffic.  If desired, you can set up IP restrictions on the virtual SMTP server for each notification server so that you don't get unauthenticated email coming from unknown sources.
Answer: I've setup what Sam mentioned above and has worked successfully in the past. It seems to be the easiest route.


language in application Android

Question: I have some RSS feed in XML which I am receiving in my Android app. The idea is simple, its just receiving RSS updates and showing them. I managed everything except showing some right words. The problem is that the Data is written in other language, and my app is on English language (I do not know many about those things). Example:
09:05 KAMIONDŽIJE
20:05 Doček naših olimpijaca ispred Skupštine grada
and things like that.. you see those Ž, č, š letters .. they are displayed as some other unknown-to-me languages ..  Does anyone know how to fix this.. I just want it to be as it is written in RSS's XML file, not anyhow changed.
this is my complete parser class:
public class XMLParser {

// constructor
public XMLParser() {

}

/**
 * Getting XML from URL making HTTP request
 * @param url string
 * */
public String getXmlFromUrl(String url) {
    String xml = null;

    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        xml = EntityUtils.toString(httpEntity);

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    // return XML
    return xml;
}
/**
 * Getting XML DOM element
 * @param XML string
 * */

public Document getDomElement(String xml){
    Document doc = null;
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setCoalescing(true);
    dbf.setNamespaceAware(true);
    try {
        DocumentBuilder db = dbf.newDocumentBuilder();

        InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(xml));
            doc = db.parse(is);

        } catch (ParserConfigurationException e) {
            Log.e("Error: ", e.getMessage());
            return null;
        } catch (SAXException e) {
            Log.e("Error: ", e.getMessage());
            return null;
        } catch (IOException e) {
            Log.e("Error: ", e.getMessage());
            return null;
        }

        return doc;
}

/** Getting node value
  * @param elem element
  */
 public final String getElementValue( Node elem ) {
     Node child;
     if( elem != null){
         if (elem.hasChildNodes()){
             for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
                 //if( child.getNodeType() == Node.TEXT_NODE  ){
                 if(child.getNodeType() == Node.TEXT_NODE || child.getNodeType() == Node.CDATA_SECTION_NODE){
                     return child.getNodeValue();
                 }
             }
         }
     }
     return "";
     //return elem.getTextContent();
 }

 /**
  * Getting node value
  * @param Element node
  * @param key string
  * */
 public String getValue(Element item, String str) {
        NodeList n = item.getElementsByTagName(str);
        return this.getElementValue(n.item(0));
    }
 public String getValue2(Element item, String str){
     //NodeList n = item.getElementsByTagNameNS("http://purl.org/rss/1.0/modules/content/", str);
     return item.getTextContent();
 }

}

Answer: You should make sure the text is parsed as utf-8. But when you've done that, you'll still have a bunch of weird chars but this is normal... A lot of languages has weird chars. Denmark (my roots) has æøå.
Edit:
Try this:
EntityUtils.toString(httpEntity,"UTF-8");

Comment: How can I check that it is parsed in utf-8? .. I know what those words mean, they are my homeland's words (Serbia), but I just want them showed right in the app.
Comment: Well then you need to show your code where you read the data.
Comment: Ok, I edited my post.. check it, note getValue2 is for   things and getValue1 is for normal  and  things..

language in application Android


'ambiguous type' error when defining a union of types having type inclusions

Question: I have a record named GenericPet with several fields. Another record named Dog is a type inclusion of the record GenericPet and also has its own field isTrained. The type Pet is a type union of both GenericPet and Dog. When I try to define an instance of Pet in the following code segment, it throws the error: "ambiguous type".
type GenericPet record {
    string name;
    int age;
    string breed;
};

type Dog record {
    *GenericPet;
    boolean isTrained;
};

type Pet GenericPet|Dog;

public function main() {
    Pet myPet = {
        name: "Mickey",
        age: 2,
        breed: "Dane",
        isTrained: false
    };
}

Is this behavior expected, and if so, why? Please clarify.
Answer: Because GenericPet is an open record, the mapping value with the specified four fields is also valid for GenericPet (in addition to Dog). Therefore, the exact inherent type to use cannot be determined, leading to the "ambiguous type" error.
If you want to resolve this ambiguity, you have a couple of options:

Use Closed Records:
If GenericPet was a closed record, you would no longer observe the error. You can make GenericPet a closed record using the closed record syntax:
type GenericPet record {|
    string name;
    int age;
    string breed;
|};

Specify Type Using Type Cast Expression:
Alternatively, you can specify the type to use as the inherent type using a type cast expression with the mapping constructor:
Pet pet = <Dog> {
    name: "Mikey",
    age: 2,
    breed: "Dane",
    isTrained: false
};


Is Dtls available in python3, and how to install it?

Question: From the description of Dtls library, it seems it's not available in python3. And when I want to install with pip install Dtls there's always an

Command "python setup.py egg_info" failed with error code 1 in
  C:\Users\sun\AppData\Local\Temp\pip-build-c_46y9mt\Dtls\

Solution here doesn't help. I am using Python 3.6 on Win7.
Do I have another option for DTLS?
Answer: python3-dtls is the python3 version for dtls package.
Answer: If the library you want to use is not available for the version of your interpreter, then you simply cannot use that library without porting it yourself or waiting for others doing that for you. This is probably not what you want.
This means that Dtls library works only for Python2.7 and version 1.0.0 or higher of the OpenSSL library as mentioned on the website, although it's tested on several plattforms (including yours):

At the time of initial release, PyDTLS 0.1.0 has been tested on Ubuntu 12.04.1 LTS 32-bit and 64-bit, as well as Microsoft Windows 7 32-bit and 64-bit, using CPython 2.7.3. Patches with additional platform ports are welcome.
As of release 1.2.0, PyDTLS is tested on Ubuntu 16.04 LTS as well as Microsoft Windows 10, using CPython 2.7.13.

You can use other libraries if you have to use Python3.x, e.g. standard ssl library or maybe also pyOpenSSL library:

pyOpenSSL remains the only alternative for full-featured TLS code across all noteworthy Python versions from 2.7 through 3.5 and PyPy.

Dtls is a library which simplifies implementation but you are not dependent on it.
Just as a side note: For pyOpenSSL you can also get an idea how to implement it by reading this post.


Subtract "n" days from a list of format [month, day]

Question: I have a this list in the Python.
dates= [6,15],[8,24]

I want to subtract values from this list. For example [6,15] is [month,day] so I want to subtract 15 to 10. I want to get [6,5], well this operation will repeat after that I want to get [5, 26] like this. How can I do this code?
Comment: Please share the code your tried. And what do you mean by *"[6,15] is [month,day] so I want to subtract 15 to 10"*. Why you want to subtract 10 if it is day?
Comment: How do you know the number of days in a month without knowing the year?
Comment: Ohhh... probably you mean you want to subtract any random number which denotes the day, and you want corresponding date in [month, day] format. Is that correct? If yes, then take a look at `datetime` module. Instead of creating a `[month, day]`  list, it will be easier for you to perform this using `datetime` object
Comment: Why don't you use a specialized object for dealing with dates, like `datetime` module provides?
Comment: Look at `datetime`, but `date` and `timedelta` will still only work with a year.
Comment: I want to calculate according to the lunar calendar. I want to determine 2018 .So about after 36 years. The date will be again [6,20]
Comment: Don"t post code in a comment. You can [edit] your question and add it in there. Why do you add tags for 2 versions of Python? Do you need a aingle solution that works under both?
Comment: Welcome to SO. Please finish the tour and you will understand [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) and modify question accordingly to minimal working example. Without posting your code you risk removal of your question. With your stated trail and error code... people are more willing to help you so both can learn. Enjoy SO ;-)
Comment: Complete  usr2564301 request as well by editing your question and remove that particular "code" comment.
Answer: You probably want to use the builtin datetime and 3rd-party dateutil modules for this. Note you will need to specify a year, since some years have months of differing lengths (i.e leap years) -parse will assume the current year:
import datetime.date as dt
from dateutil.parser import parse
from dateutil.relativedelta import relativedelta

print(parse('6/15') - relativedelta(days=10))

Comment: You may mean `print(parse(...`
Answer: You should be using inbuilt datetime.datetime and datetime.timedelta objects to achieve this in simplified way as:
>>> from datetime import datetime, timedelta
>>> my_date_list = [6, 15]  # your current list in "[month, day]" format

# create `datetime` object using above values
# since you don't care about year, using 2018 for demonstration. But you need this.
>>> datetime_obj = datetime(month=my_date_list[0], day=my_date_list[1], year=2018)

# timedelta object for the number of days you want the diff
>>> diff = timedelta(days=20)

# New datetime object
>>> new_datetime_obj = datetime_obj - diff
>>> new_datetime_obj
datetime.datetime(2018, 5, 26, 0, 0)

# You desired format list of [month, day]
>>> [new_datetime_obj.month, new_datetime_obj.day]
[5, 26]

PS: You shouldn't be even storing your initial and final list as "[Month, Day]" format. Simply store the list of datetime objects, and use it where ever you need. new_datetime_obj.month yields the month and new_datetime_obj.day yields the day
Note: You must consider about the year in your code. It is necessary in doing your computation and calculating the days. For example, the calculation for February for leap year and non-leap years yields different results.
Comment: Thanks for your help but How can I do without datetime library?
Comment: @Tommy.pillow unfortunately I don't know any simple way to achieve it without any library. What I believe is it is gonna require a lot of code.
Comment: `datetime` is in the standard library, so you don't need to install anything on top of your base python distribution.


Connecting elements in the set of Natural numbers

Question: Lets say we "connect" two numbers in the set of Natural numbers in a way, that we draw an arrow between them. In each step we draw an arrow from a number to the number which is next to it. If we drew an arrow from a number to another we don't draw another one from the number we arrived in the same step.
Example: 1 2 3 4 5 6 7 8 ...
First step: 1->2 3->4  5->6 7->8 ... (since we connected 1 and 2 from 2 draw a line in this step)
Second step 1->2->3->4 5->6->7->8 ... (since we connected 2 and 3 we dont draw a line from 4 in this step)
Third step 1->2->3->4->5->6->7->8 ... (since we connected 4 and 5 we dont draw a line from 8 in this step)
So my question is: If we keep connecting the numbers in this way infinite amount of times, than will they ever connect into one single line or not?
Personally I don't think they ever will, since after every step there will be a number which isn't connected to another number. However if we repeat this infinite amount of times, than that would mean that at some point we reach every number so this way maybe they will connect to a single line. I would really appriciate any help to clarify this.
Comment: This is not a well-posed question, since you can't really do something an infinite number of times. It is true that, after every step, there will be two numbers that aren't connected. It is also true that, for every number, there is some step after which it will be connected to 1. There is no contradiction.
Comment: At each step, you double the size of the connected segments. The number line remains disconnected after finitely many steps. A reasonable way to define "after infinitely many steps" is the infinite union of the sets of arrows drawn at each step. This set includes all arrows, so we can say that the line is connected after infinitely many steps.
Answer: Yes, all numbers will end up on a single line starting at 1.
We can use induction to prove this.
Inductive Base: It is trivial that $1$ will be on a line starting with $1$
Inductive Step: Suppose $n$ will be on a line starting with $1$. Then if $n+1$ is not already on a line starting with $1$, then an arrow is guaranteed to be drawn between $n$ and $n+1$, since that is the first possible arrow to be drawn given the defined process of drawing arrows. So, if $n$ will be on a line starting with $1$, then $n+1$ will be on a line starting with $1$ as well.
Answer: The short answer to your specific question is: yes, at the end all the numbers are connected in a single line.
You are concerned:

after every step there will be a number which isn't connected to another number

And you are right to be concerned.  This is the paradox of infinity.  This has been one of the central concerns of mathematics for at least 2500 years.
Examples of this appear over and over:

In Zeno's paradox, the speedy warrior Achilles is racing against a tortoise.  The tortoise has a ten-meter head start.  After one second, Achilles has run 10m, but the tortoise has moved on so it is still ahead of him by a meter.  It takes Achilles 0.1 second to catch up, but the tortoise has already moved another 100 cm.  Achilles can catch up to where the tortoise was in another 0.01 second, but by then the tortoise is still  10cm ahead.  The tortoise is always ahead, and Achilles never catches up!  Except, of course, we know that he really does because Achilles is much faster than a tortoise.

Each of the sets $\{1\}, \{1,2\}, \{1,2,3\}, \ldots$ is finite.  But their union is infinite.

Consider the sequence $1,\frac12,\frac13,\frac14\ldots$.  Every element of this sequence is positive.  But when you follow it to infinity, you end at $0$, which is not positive.

Consider the numbers from $1$ through $n$.  If we try to match each number with its square, most of the numbers are unmatched.  For example, in $1\dots 20$ the four numbers $1,2,3,4$ can be matched with their squares $1, 4, 9, 16$, but the numbers $5 \ldots 20$ can't be matched with squares.  $80\%$ of the numbers didn't get matched, and only $20\%$ had matches. As we let $n$ grow larger, the fraction of matched numbers approaches zero. When $n=10000$ only $1\%$ of numbers are matched with their squares.  But somehow when $n$ reaches infinity, every number can be matched with its square.  (This is Galileo's paradox.)

Take a bag; in the bag is a marble with the number $1$.  Every minute, take out the marble with the smallest number $n$, throw it away, and put in marbles with numbers $2n$ and $2n+1$.  So after one second, take out marble $1$ and put in $2$ and $3$; next take out marble $2$ and put in $4$ and $5$, and so on.  The  number of marbles in the bag is always increasing.  But after an infinite number of steps, the bag is empty, because every marble is taken out of the bag and thrown away. (This is the Ross–Littlewood paradox, very similar to your connected-graph example.)

Consider the process which takes a fraction $\frac ab$ and replaces it with $\frac{a+2b}{a+b}$.  Start with $\frac 01$.  This is replaced with $\frac{0+2}{0+1} = \frac 21$, which is replaced with $\frac{2+4}{2+1} = \frac 43$, and so on: $\frac 43\to \frac{10}7 \to\frac{24}{17}\to\frac{58}{41}\to\ldots$.   Every element of this sequence is a rational number.  But the end result is not.  (It is $\sqrt 2$.)  We are used to this now, but when it was first discovered it was considered extremely strange.

Think of a computer program $P_1$ where I put in one number and it computes some function and prints out a result.  And suppose I can be certain that if I wait long enough, the program will always finish and print its result.  Now suppose I have a family or programs $P_1, P_2, \ldots$ and I need answers from all of them.  If the family is finite, there's no problem; I can wait until they all finish.  But if it is infinite, this doesn't work.  Even though every program finishes on its own, there might never be a time when they have all finished.

The Cantor Set is a famous example in topology.  We take the set of numbers $x$ where $0\le x\le 1$.  Then we remove the middle third of the set, leaving $0\le x\le \frac 13$ and $\frac23\le x\le 1$.  Then we remove the middle third of each of those two parts, leaving $0\le x\le \frac19$ and $\frac29\le x\le\frac 13$ on the left and $\frac23\le x \le\frac79$ and $\frac89\le x\le 1$ on the right.  We keep doing that forever.  Every set along the way is a collection of connected intervals.  But the Cantor set itself, the endpoint of this process, does not contain any connected interval.

This kind of "limiting" process is everywhere in mathematics and a large part of mathematics concerns how it works, when it makes sense and when it doesn't, and what the result is.  It's the main idea of calculus, and understanding how it worked just in calculus took 200 years.
Good questions are the ones that are short to ask but long to answer.  This is a great question.


Cor RGB no Visual Studio 2017?

Question: Como consigo ter mais cores para o fundo do meu formulário? Tenho uma cor em RGB e não sei como colocá-la além das cores já oferecidas no Visual Studio 2017. Já tentei pesquisar na internet e não achei nada
Comment: é no Personalizar, lá você cria!
Comment: Como? Por lá só vi mais opções de cores
Answer: No arquivo Form1.cs(nome do seu formulário) dentro de public Form1()(nome do seu formulário) insira o seguinte código:
this.BackColor = Color.FromArgb(255, 232, 232); //os 3 parâmetros são os valores RGB

Com isso você pode alterar a cor do seu formulário de forma programável. Se quiser uma referência via Youtube aqui está.
Comment: Muito obrigado! Para mudar o fundo da ferramenta 'panel' usa-se o mesmo comando?
Comment: Você precisa acessar o objeto Panel(através do seu nome, assim como fiz com só que ao invés de `this` você coloca o nome da variável do objeto), mas sim é a mesma lógica.
Answer: Além da resposta para que possa mudar o valor RGB pelo caminho de programação, naquela caixa que você abriu é só digitar o RGB separado por ; que automaticamente é gerado, exemplo:

Todos os componentes que tiverem configuração de cores também pode ser utilizado a mesma estratégia.
Só por curiosidade o código gerado por baixo é :
this
     .textBox1
     .ForeColor = System
        .Drawing
        .Color
        .FromArgb(((int)(((byte)(100)))), ((int)(((byte)(253)))), ((int)(((byte)(80)))));

Comment: Perfeito Virgilio, Muito obrigado! <3

Cor RGB no Visual Studio 2017?


How do I create a nested model while keeping the inner class private?

Question: I want to encapsulate Filter class within my FilterSelection model so Filter cant be instantiated on its own. However trying to set a property to access the list I get this error:
Inconsistent accessibility: property type is less accessible then property
public class FilterSelection
    {

        public List<Filter> List { get; set; }

        public FilterSelection()
        {
            List = new List<Filter>();
        }

        private class Filter
        {
            public string CustomFilterName { get; set; }
            public string workBook { get; set; }
        }
    }

Comment: Define a public interface and let your class inherit from it and declare your member of List - eg. https://dotnetfiddle.net/1pSjrT
Comment: You can't expose a property to code that might use your class without also exposing the type of that property. In other words, if you are going to let my code create a FilterSelection and as such you are going to give me access to "List" (I would encourage a better name), if "List" is a collection of "Filter" objects, what use would they be to me if I know know what a "Filter" is? So, either class "Filter" needs to be public, or property "List" needs to be private. Alternatively, you could make both "internal" if you just want to use it within your FilterSelection class without exposing it.
Comment: Mark the `List` property `private set;` Remember, adding and removing items from a list is still a `get` operation, even though you are making changes: you "get" the reference to the object, and then use the reference to call the object's "Add()" member function.
Answer: The accessibility of the property and the type must be consistent (or at least, the property must have less than or equal accessibility to the type).
Option 1 - make the property and type available to any code which references your class:
public class FilterSelection
    {

        public List<Filter> List { get; set; }

        public FilterSelection()
        {
            List = new List<Filter>();
        }

        public class Filter
        {
            public string CustomFilterName { get; set; }
            public string workBook { get; set; }
        }
    }

Option 2 - don't allow access to either the property or the class with the exception of in your class's constructor(s).
public class FilterSelection
    {

        private List<Filter> List { get; set; }

        public FilterSelection()
        {
            List = new List<Filter>();
        }

        private class Filter
        {
            public string CustomFilterName { get; set; }
            public string workBook { get; set; }
        }
    }

Option 3 - Make the class and property available to any class within this assembly, but not outside of the assembly
public class FilterSelection
    {

        internal List<Filter> List { get; set; }

        public FilterSelection()
        {
            List = new List<Filter>();
        }

        internal class Filter
        {
            public string CustomFilterName { get; set; }
            public string workBook { get; set; }
        }
    }

Option 4 - make your property and class available to your class and any class which inherits your class
public class FilterSelection
    {

        protected List<Filter> List { get; set; }

        public FilterSelection()
        {
            List = new List<Filter>();
        }

        protected class Filter
        {
            public string CustomFilterName { get; set; }
            public string workBook { get; set; }
        }
    }

Comment: I'm currently working on a Web API and this is a DTO.  Having Filter set to public/internal would mean that Filter can be instantiated without FilterSelection. And setting it to protected/private would mean that I cant access my List property from the controller or service layer. I want my filter class to be coupled with FilterSelection and not to be used anywhere else if that is possible.


Get values from views exposed filter in hook_views_pre_view

Question: I would like to get the current values from an exposed filter in hook_views_pre_view().
For example, if the input filter has some value I would like to change de pager: number of items, the problem is how to get this value from views without using $_GET because I don't think it will work with views ajax.
What is the right way to get current exposed filters values from a view?
Answer: I've found it, there is a views method:
<code>$input = $view->get_exposed_input();
</code>
Comment: I have the same problem, but this solution does not work as `$input` is always empty. Any ideas?