Second cohomology of a torsion-free hyperbolic group

Question: Does any body know examples of torsion-free hyperbolic group $G$ such that $H^2(G,\mathbb{R})=0$ (trivial G-action on $\mathbb{R}$)?
In fact I am interested in if there are known examples of even-dimensional, closed Riemannian manifolds $(M,g)$ with negative sectional curvature such that $b_2(M)=0$.
I noticed this paper by Epstein-Fujiwara, but I am not sure if the result for bounded group cohomology gives information on my question.
Comment: There are many examples of hyperbolic 3-manifolds which are even integer homology spheres.
Comment: @user188722: Then you should update the question.
Comment: Oh, I forgot, I want even-dimensional manifolds.
Comment: @QiaochuYuan: Such a product will not be hyperbolic.
Comment: Huh, wow, I was being silly. Apparently in fact a compact hyperbolic manifold is never a nontrivial product of two other manifolds: https://mathoverflow.net/questions/324273/can-a-hyperbolic-manifold-be-a-product
Comment: Your best bet would be compact quaternionic-hyperbolic manifolds.
Comment: My suggestion is to write directly to Nicolas Bergeron (he is at ENS, Paris) and ask him what is known about $b_2(\Gamma)$ for torsion-free uniform quaternionic-hyperbolic lattices (quaternionic dimension $>1$). My guess is that it is either known to be always positive or always zero. If it is known to be zero, you get your examples. If it is known to be positive, then your question (about manifolds of negative curvature) is almost surely an open problem.
Comment: @MoisheKohan Thank you for your suggestion!
Answer: Based on my comments:
First of all, the question about hyperbolic groups is very different from the one about fundamental groups of closed connected manifolds of negative curvature: "Most" hyperbolic groups are very much unlike "manifold groups." Second: The mentioned paper by Epstein and Fujiwara is interesting but totally irrelevant for the purpose of your question. Now, your real question is:

Is there an example of a closed connected even-dimensional manifold $M$ of negative curvature  such that $b_2(M)=0$?

Here is what I know: The first interesting case, of course, is of 4-dimensional manifolds. Such a manifold $M$ would have positive Euler characteristic (see the references here), hence, effectively, you are asking about the existence of a negatively curved 4-dimensional rational homology sphere. This is an open problem (stated explicitly for manifolds of constant negative curvature by Bruno Martelli, I think). If there is such a hyperbolic 4-manifold, it would have the smallest possible volume among hyperbolic 4-manifolds.
Among locally-symmetric manifolds of negative curvature, complex-hyperbolic ones always have $b_2>0$ (because of the Kahler class). I do not believe there are any explicitly known examples (say, meaning that somebody computed their Betti numbers) of closed real-hyperbolic manifolds of dimension $\ge 6$. There are also no known vanishing theorems for $b_2$ in the class of manifolds. (All the known results are on the "nonvanishing side", they are of the type: There exists a finite-sheeted covering space with positive Betti numbers $b_i$ so some values of $i$.) This leaves one with quotients of quaternionic-hyperbolic spaces (and of the Cayley-hyperbolic plane). While there are no explicitly known examples (again, meaning that somebody computed Betti numbers), there might be vanishing/nonvanishing theorems for $b_2$ known in this class.
As for negatively curved manifolds  of dimension $\ge 4$ which are not locally-symmetric, there is only a handful of constructions (which mostly use locally-symmetric manifolds as their starting point) and no known construction can ensure vanishing of $b_2$.
Thus, unless there are known vanishing results for $b_2$ in the case of torsion-free cocompact discrete subgroups of isometries of quaternionic-hyperbolic spaces ${\mathbf H}{\mathbb H}^n, n\ge 2$, your question  should be treated as an open problem.


OpenSSL generate certificate with endianess,encoding and charset

Question: I'm having some trouble creating a certificate with the openssl commandline tool.
The specs for the private key are:

"A digital signature using an RSA 1024 bit key with a SHA-1 hash
  function (RSA-SHA1-1024)"

Creating it as follows
openssl genrsa -out rsa.key 1024

Generating the CSR
openssl req -new -key rsa.key -out csr.csr

The certificate has the following spec:

Format = x.509
Charset = UTF-8
Encoding = Base-64
Endianness = Little Endian
OAEP Padding = PKCS1 v1.5 padding
Private key size = 1024 bits
Hash Message Format = SHA-1

I've tried tons of combinations of the following:
openssl x509 -req -utf8 -enc base64 -pkcs -sha1 rsa:1024 -in csr.csr -signkey rsa.key -out server.crt

I can't get a large set of combination of the above command to work at all, always some parameter that breaks it.
According to the spec we're supposed to sign a RSA message digest with the given certificate. I'm a bit confused why and how we are supposed to do this, maybe its an erroneus specification?

Specification documentation
I'm using OpenSSL 1.1.0f  25 May 2017
The endianess i can't even find how to set it with the openssl commandline tool, any help here would be greatly appreciated!
Comment: What is this for? It feels like you might be misinterpreting documentation somewhere. Your first quote for example talks about a signature which you can create without a certificate and just the private key. The algorithm references are also considered fairly old and insecure at this point depending on the context.
Comment: Yes that's whats confusing me to, i'm updating the post with the picture given in the specification. I don't really need a self signed certificate to make an openssl signing but in the documentation it seems like i have to. Bit confused ...
Answer: Unless I'm reading it wrong, that doc seems to contradict itself. It talks about certificate creation and that self-signed certs are ok, but then later says the only thing they want you to send to the NTA is the public key. Signing the data doesn't require a certificate, just the private key. So I'm wondering why they don't just have you create a public/private keypair rather than a whole cert that is only ever going to sit on the box and never get used.
Here's how you'd create a simple RSA 1024 private key and extract the public key into its own file:
openssl genrsa -out rsa.key 1024
openssl rsa -in rsa.key -outform PEM -pubout -out rsa.pub

The rsa.pub file is what you'd send to NTA. I've never heard of anyone needing to deal with endianness explicitly with openssl. So I could be wrong, but you likely don't have to worry about it. The UTF8 charset likely only matters for actual certs with text fields like the Subject. Openssl outputs PEM files with ASCII encoding which is fine (and normal) because PEM is Base64 encoded. PKCS1 v1.5 padding is also standard.
So now that you've got your keys. Let's try signing their example data from section 2.2.5 of their doc. First, throw the data into a file to make it easier to use in examples.
echo -n 'signature_from_previous_receipt;2014-01-24;23:59:59;123456789;1250.00;1000.00' > data.txt

Display the SHA1 hash just to prove we've got data that matches the example
openssl dgst -sha1 data.txt

Hash and sign the data, convert it to base64 with no line breaks and save it to a file.
openssl dgst -sha1 -sign rsa.key data.txt | openssl base64 -A -out data.sig

Hypothetically, the text within data.sig is now what you'd use for "signature_for_this_receipt" from the example.
To verify, we can just do the following which should output "Verified OK".
openssl dgst -sha1 -verify rsa.pub -signature <(openssl base64 -d -A -in data.sig) data.txt

If for some reason you do need an actual certificate file, you can replace the first command that generates the private key with this one liner that will generate both the key and a self-signed cert. You still need the same second command to extract the public key.
openssl req -nodes -x509 -sha1 -utf8 -newkey rsa:1024 -keyout rsa.key -out server.crt -days 365 -subj "/CN=MyCert"


Learning HMM parameters by counting?

Question: In 8.4.3 of the book Speech and Language Processing: An introduction to natural language processing, the two matrices transition probabilities and emission probabilities can be learned by counting as follows:
$$P(t_i|t_{i-1})=\frac{C(t_{i-1}, t_i)}{C(t_{i-1})}$$
$$P(w_i|t_i)=\frac{C(t_i, w_i)}{C(t_i)}$$
where $t_i$ is a state and $w_i$ is a word.
But I remember that it is the EM algorithm that should be applied. Am I missing something?
Comment: This is the fully observed case, for when you have the tag sequence (the latent variables) provided. EM a is used for when your data is "partially observed": you don't have the values of the latent variables. All you have is the text, not the tags.
Comment: If you've never observed the states, then you don't ever know. The best you can do is to try some post-hoc matching. There's a decently famous paper about what happens to the hidden states for text by Merialdo (1994). (But remember that J&M do observe the states! That lets them steer the parameters however they want.)
Comment: @AryaMcCarthy If it's unsupervised, how do we know which state represents which meaning? For instance, we only know there should be five states(A, B, C, D, and E), but we don't know which state stands for A.
Answer: This is not really a HMM. They call it a HMM because it has the same structure.

A base level of states ($t$) which transition from one to the next.
An emitted level of states ($w$) whose observation depends on the base states.

In a true HMM, the states $t$ are hidden and you have to use EM to get a maximal likelihood estimation of what they might be.
In this case, you actually (if I've understood the text correctly) have both the $t$ and $w$ states as observations so you can compute the conditional probabilities directly by just counting.
Edit:
Actually if you read a bit further in the text, it appears they transition in to considering the taggings as actual hidden states which are to be inferred (Viterbi algorithm etc.).

Learning HMM parameters by counting?


Error parsing IP header

Question: I have a small function that tries to print the fragment offset of an IP header.
<code>ParseIpHeader(unsigned char *packet, int len)
{
    struct ethhdr *ethernet_header;
    struct iphdr *ip_header;

    /* First Check if the packet contains an IP header using
       the Ethernet header                                */

    ethernet_header = (struct ethhdr *)packet;

    if(ntohs(ethernet_header->h_proto) == ETH_P_IP)
    {
            /* The IP header is after the Ethernet header  */

            if(len >= (sizeof(struct ethhdr) + sizeof(struct iphdr)))
            {
                    ip_header = (struct iphdr*)(packet + sizeof(struct ethhdr));

                    /* print the Source and Destination IP address */

                    //printf("Dest IP address: %s\n", inet_ntoa(ip_header->daddr));
                    //printf("Source IP address: %s\n", inet_ntoa(ip_header->saddr));
                    printf("protocol %d\n", ip_header->protocol);
                    printf("Fragment off is %d\n", ntohs(ip_header->frag_off));

            }

}
</code>
My packets are TCP (the ip_header->protocol is always 6. the problem is that the frag_off
is always 16384. I am sending a lot of data, why the frag_off is always constant?
Thanks.
Comment: Also - maybe you would clarify the end goal of what you plan to achieve with the code / use case of it - maybe then I could expand on the answer.
Comment: I am using recvfrom to get data from the wire. the max buffer of recvfrom is 65K.

So some data are being received in the next packets and I want to merge them
Answer: Fragment offset is shared with flags. You have the "DF" (don't fragment) bit set.
Which gives you 16384 for the entire 16-bit field, given the fragment offset of 0.
Take a look at the http://www.ietf.org/rfc/rfc791.txt, starting from page 10.
EDIT:
The DF bit in the TCP segments that you are receiving is set by the remote side, to perform the Path MTU discovery - in a nutshell, to try to avoid the fragmentation.
In this case the sending side learns the biggest MTU that the overall path can handle, and chops the TCP segments such that they did not exceed it after the encapsulation into IP.
EDIT2:
regarding the use of recvfrom() and TCP: TCP is a connection-oriented protocol, and all of the segmentation/fragmentation details are already handled by it (fragmentation is obviously handled by the lower layer, IP) - so you do not need to deal with it. Anything you write() on the sending side will be eventually read() on the other side - possibly not in the same chunks though - i.e. two 4K writes may result in a single 8K read sometimes, and sometimes in two 4K reads - depending on the behaviour of the media inbetween concerning reordering/losses.
IP Fragmentation and reassembly is handled transparently by the operating system, so you do not need to worry about it, same as about packets out of order, etc. (you will just see the decreased performance as the effect on the application).
One good read I could recommend is this one: UNIX network programming. Given Steven's involvement with the TCP, it's a good book no matter which OS you use.
EDIT3:
And if you are doing something to be a "man in the middle" (assuming you have good and legitimate reasons for doing so :-) - then you can assess the upcoming work by looking at the prior art: chaosreader (one-script approach that works on pcap files, but adaptable to something else), or LibNIDS - that does emulate the IP defragmentation and the TCP stream reassembly; and maybe just reuse them for your purposes.
Comment: Thanks for the response. However I am queering the data from a packet. I am not setting the DF flag.
if ((ntohs(ip_header->frag_off) & 0x3fff) == 0)
this means I am reading the first packet.
Comment: Since the flags occupy the three most significant bits, the check above in fact checks that this packet is not fragmented at all (offset is zero and MF (more fragments) is not set).

In any case this mask of 0x3fff would remove the DF, that is set by the remote side (default on most of the systems, to perform Path MTU discovery).
Comment: Thanks Andrew. So what kind of code do I need to see if this is the first fragment or not?
Comment: If you only need to know fragment offset, then you'd mask away the 3 bits of flags by using the 0x1fff as the mask.

Though would be interesting to know what you plan to do with this - merely knowing something is a first fragment might or might not be sufficient. I.e. if you assume that the TCP header always fits into the first fragment - in case of malicious/buggy implementations on the other side it will not be a correct assumption.
Comment: OK. Assume that I have an echo server that sends lines of text. I am sniffing the wire.

The first packet contains the text "Hello ... " and a few moments later comes a new packet with the text " ... world".

How to I know that the second packet that comes after the first packet is the next packet? I want to concatenate them in order to create buf="hello ... world".
Comment: So, the question is whether you are sniffing the wire or you are the client on the other side using the sockets API ?
Comment: I am actually using raw sockets.
len = recvfrom(raw, packet_buffer, 5000, 0, ...);
how do i know that the package is completely received?
Comment: uh. if you are using raw sockets, then there is **a lot** more work besides the full IP reassembly, TCP state machine handling, etc. But take a look at my 3rd edit and see if that is something that might suit you - you can study the source of these to see what you're up for :-)
Comment: @cateof: Sequence number tells you the offset of the data in the TCP stream.  Get a copy of _TCP/IP Illustrated Volume 1_ [Google Books](http://books.google.com/books?id=-btNds68w84C&lpg=PA275&dq=tcp%2Fip%20illustrated%20volume%201&pg=PA275#v=onepage&q=tcp/ip%20illustrated%20volume%201&f=false) to learn about how TCP works.

Error parsing IP header


Discrete mathematics proving or disproving

Question: If $x$ and $y$ are positive integers with $x>y+1$, then $x^2 -y^2$ is not prime.
How do you prove this? I have tried doing it but I couldn't prove it.
Answer: You know that
$$x^2-y^2=(x-y)(x+y).$$
So if $x>y+1$, then $x-y\geqslant 2$, so $x^2-y^2$ can not be prime because it can be written has the product of two integers greater than $2$.
Comment: How would you show that it is greater or equal to 2 ?
Comment: Because you know that $x-y>1$ and $x-y$ is an integer.


Manipulating windows of other applications with .NET?

Question: is it somehow possible to manipulate a window of another running application with code in my own with .NET (Windows 7)?
I often use PuTTY and would find it very helpful if I could write a program which adds key shortcut which does the same as right clicking the taskbar in Windows 7 and choosing "Show windows side by side" but not for all windows. Just for every open instance of PuTTy, so I have an overview of every open shh connection.
I hope this doesn't sound to confusing.
Anyway, to achiev this, I need to be able to manipulate other windows (in this case the PuTTY windows), e.g., resizing, moving, showing/hiding, etc., them.
If at all possible, I'd like to stick with C#, not C/C++
Thanks in advance!
Answer: This definitely should be possible, but will need a whole arsenal of platform invokes. The relevant WINAPI functions to invoke would be EnumWindows to retrieve all top-level windows, GetWindowInfo to retrieve the location, size and title of each window and finally MoveWindow to move and resize the appropriate windows.
Good luck!


move and limit motion of a div inside an other div

Question: I have two simple divs, where one is contained inside an other
div#numero{
    position:absolute;
    background-color:#ff3324;
    border-style: solid;
    border-width: 2px;
    width:30px;
    height:30px;
    font-family: "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Geneva, Verdana, sans-serif;
    font-size:1em;
    line-height: 30px;
    text-align:center;
    margin-left:0;
    margin-right:0;
};

div#cont{
    position:relative;
    border-style: solid;
    border-width: 2px;
    width:500px;
    height:500px;
    margin-left:auto;
    margin-right:auto;
    padding:0;
}

I want to move the first inner div inside the container

            1

where the moveDiv is simply
function moveDiv()
{
    var e = document.all["numero"]
    x = window.event.clientX ;
    y = window.event.clientY ;

    e.style.left = x +"px";
    e.style.top = y +"px";

}

The code does not work as I would like. There's a very big offset between the position where the mouse is and where the inner div (numero) gets moved. I'd also like to limit the movement inside the container div.
Some help would be appreciated.
thanks.
Comment: make a jsfiddle: http://www.jsfiddle.com and people will help you
Comment: see http://stackoverflow.com/questions/11979784/why-is-pagex-and-pagey-relative-to-wrapper-not-document/11979955#11979955
Answer: See http://jsfiddle.net/enHmy/
Add the following code after your html code
document.getElementById('cont').onmousemove=moveDiv;

And then your function should be:
function moveDiv(e){
    if(!e){e=window.event;}
    var el = document.getElementById('numero');
    x = e.clientX-this.offsetLeft-this.clientLeft-el.offsetWidth/2;
    y = e.clientY-this.offsetTop-this.clientTop-el.offsetHeight/2;

    el.style.left = Math.min(Math.max(0,x),this.clientHeight-el.offsetWidth) +"px";
    el.style.top = Math.min(Math.max(0,y),this.clientHeight-el.offsetHeight) +"px";
}

But let's analyse your function:
Why do you use document.all["numero"]? That's very old and doesn't work on compliant browsers, now it's document.getElementById('numero');.
And then you use window.event. That works on IE, but you should pass an argument e (the event) and, if e is not defined (it's old IE), we set it to window.event.
And when you are closing a CSS rule, don't write a semicolon after }.
Edit:
If you scroll the page, numero is not positioned correctly.
Fixed in http://jsfiddle.net/enHmy/1/:
function moveDiv(e){
    if(!e){e=window.event;}
    var el = document.getElementById('numero');
    x = e.clientX-this.offsetLeft-this.clientLeft-el.offsetWidth/2+getScroll('Left');
    y = e.clientY-this.offsetTop-this.clientTop-el.offsetHeight/2+getScroll('Top');

    el.style.left = Math.min(Math.max(0,x),this.clientHeight-el.offsetWidth) +"px";
    el.style.top = Math.min(Math.max(0,y),this.clientHeight-el.offsetHeight) +"px";
}
function getScroll(dir){
    return Math.max(document.body["scroll"+dir]||0,document.documentElement["scroll"+dir]||0);
}


How do I plot a graph or chart on the confirmation message?

Question: How do I plot a graph on the confirmation message, on a webform and Drupal 8?
I searched a lot, but did not find anything useful, but these results.

There are several modules involved in graphing, including the Charts module.

There is a programming solution (Display webform results data in a Google Chart), but I don't think it works, since the site will contain dozens of questionnaires. Drawing charts should be easy, something similar to Twing or only in the confirmation message textBox area.

images files can be displayed if uploaded to the site via the questionnaire in this way (from How to Display Image after submitting webform in the confirmation message page).

There are previous attempts at Drupal 7, such as the Webform Charts module. I don't know how it worked.
Answer: Since there doesn't seem to be a solution for this, I would define a webform handler that would preprocess the confirmation page with the chart that you generate.
There are plenty of D8 module for charting, and in the handler you have access to the webform submission values. You could even use a different method and save the chart image into a hidden image field on the submission. Handlers are sweet like that.
Check out WebformHandlerBase class/interface for the full method list. Checkout this other answer involving webform handlers to get you started. Once you have your handler, check out these examples for your methods.
Acting on presave()
/**
 * The example below demonstrates:
 * - retrieving a submission value
 * - processing it
 * - setting a field value to that result
 *
 * @param WebformSubmissionInterface $webform_submission
 *   A webform submission.
 */
public function preSave(WebformSubmissionInterface $webform_submission)
{
  $age = $webform_submission->getElementData('age');
  $ageChart = $this->someInjectedFooChartingService($age);
  $webform_submission->setElementData('age_chart', $ageChart->BarExportPng());
}

Acting on preprocessConfirmation()
/**
 * The example below demonstrates:
 * - retrieving a submission value
 * - processing it
 * - passing data to the confirmation template
 *
 * @param array $variables
 * @throws Exception
 */
public function preprocessConfirmation(array &$variables)
{
  /** @var WebformSubmissionInterface $webform_submission */
  $webform_submission = $variables['webform_submission'];
  $age = $webform_submission->getElementData('age');
  $ageChart = $this->someInjectedChartingService($age);
  // Add data to the confirmation template
  $variables['agechart'] = $ageChart;
}

Answer: thank you Ryan Hartman for your answer.
There is no solution other than writing a new module to perform this task. I might do this, But I'll collect some resources here for future readers.
This is another approach to plot a chart. (Overriding a Webform Confirmation Message in Drupal 8)
    /**
 * Implements hook_preprocess_HOOK().
 */
function mymodule_preprocess_webform_confirmation(&$vars) {
  if ($vars['webform']->id() == 'rate_workshop') {
    $request = \Drupal::request()->query;
    $display_mode = $request->get('display_mode');
    $rate_type = $request->get('rate_type');
    if ($rate_type === 'complete' && $display_mode === 'overlay') {
      $markup = t('Thank you for your feedback.') . '

';
      $markup .= '<button class="overlay-only">';
      $markup .= t('Explore more of this workshop');
      $markup .= '</button>';
      $vars['message']['#allowed_tags'] = ['br', 'button'];
    }
    else {
      $markup = t('Thank you for your feedback.');
    }

    $vars['message']['#markup'] = $markup;
  }
}

Thank you @kiamlaluno for editing my post.
Comment: If I was able to answer you question, could you accept it?
Answer: After trying several solutions, I found that the best way is an easy forgotten one.
i used

webform-confirmation--[webform_id].html.twig

in the theme.
you can use java script directly, same as provided by source (like google charts), just replace Webform variable like this:
{% set H_Axis =  webform_submission.data.H_Axis  %}


Propositional Logic - Truth tables - with formulas and given truth values

Question: Qu
Morgan Kaufmann.
http://myweb.sabanciuniv.edu/rdehkharghani/files/2016/02/The-Morgan-Kaufmann-Series-in-Data-Management-Systems-Jiawei-Han-Micheline-Kamber-Jian-Pei-Data-Mining.-Concepts-and-Techniques-3rd-Edition-Morgan-Kaufmann-2011.pdf
Morgan Kaufmann.
http://myweb.sabanciuniv.edu/rdehkharghani/files/2016/02/The-Morgan-Kaufmann-Series-in-Data-Management-Systems-Jiawei-Han-Micheline-Kamber-Jian-Pei-Data-Mining.-Concepts-and-Techniques-3rd-Edition-Morgan-Kaufmann-2011.pdf
Answer:
a.v) $(¬((¬(¬ R)) \vee Q)) \wedge (¬ R)$ I am struggling on this last question, I am getting confused on how to contruct the truth table.

Just substitute the truth values then evaluate the connectives one at a time
$\begin{array}{c:c:c:c:c:c:c:c:c|ll}(\lnot & (\lnot & \lnot & R) & \vee & Q)) & \wedge &\lnot & R&(¬((¬(¬ R)) \vee Q)) \wedge (¬ R)
\\ &&&\color{blue}T&&\color{blue}F&&&\color{blue}T &(¬((¬(¬ T)) \vee F)) \wedge (¬ T)
\\ &&\color{blue}F&\color{silver}T&&\color{blue}F&&\color{blue}F&\color{silver}T&(¬((¬(F)) \vee F)) \wedge (F) & \tiny\textsf{Hmm...something and false...}
\\ &\color{blue}T&\color{silver}F&\color{silver}T&&\color{blue}F&&\color{blue}F&\color{silver}T&(¬((T) \vee F)) \wedge (F)
\\ &\color{silver}T&\color{silver}F&\color{silver}T&\color{blue}T&\color{silver}F&&\color{blue}F&\color{silver}T&(¬(T)) \wedge (F)
\\ \color{blue}F&\color{silver}T&\color{silver}F&\color{silver}T&\color{silver}T&\color{silver}F&&\color{blue}F&\color{silver}T&(F) \wedge (F)
\\ \color{silver}F&\color{silver}T&\color{silver}F&\color{silver}T&\color{silver}T&\color{silver}F&\color{blue}F&\color{silver}F&\color{silver}T&(F)
\end{array}$

a.i) $P → Q \land R$ .... I got (False)

$T~\to~T\land F$ is false $\checkmark$

a.ii) P → R / Q .... I got (True)

$T~\to~T\lor F$ is true $\checkmark$

a.iii) (P → Q) → R .... I got (False)

$(T\to F)\to T$ is true. (ex falso (sequitur) quodlibet)

a.iv) ((¬ P) → Q) → (¬ R) .... I got (False)

$((\neg T)\to F)\to(\lnot T)$ is false $\checkmark$
Comment: Off-topic: Upvote for the $\LaTeX-\text{truth table}$!! Can I ask if you did it manually? I'm amazed ^-^
Comment: It's fairly easy to set up manually with the online preview.  @manooooh
Comment: that's true. Thank you for answering, today I can go to sleep in peace...
Comment: Thank you for your reply Graham! Why is a.iii) true I have F-> T ? and for the first question.. is it true? thank you so much
Comment: $T\to F$ is $F$, so $(T\to F)\to T$ is $F\to T$, which is $T$. @nh50  Re: the [principle of explosion](https://en.wikipedia.org/wiki/Principle_of_explosion).


efficient multiple first valid index algorithms in Pandas

Question: One useful function in Pandas is the first_valid_index
One obvious question is that suppose I want to find multiple first_valid_index for my dataframe provided that the particular column in increasing (in this example, it is event_time):
df.where(df.event_time >= 83000000).first_valid_index()
df.where(df.event_time >= 90000000).first_valid_index()
df.where(df.event_time >= 93000000).first_valid_index()
df.where(df.event_time >= 100000000).first_valid_index()
df.where(df.event_time >= 103000000).first_valid_index()

This would take very long time since it will search from the beginning each time I call the function.
But there should be more efficient way to do this.
Any comment or idea are appreciated
I have checked the manual of pandas but I can not find the solution
Answer: Use numpy.searchsorted:
np.random.seed(2022)

#sample data
df = pd.DataFrame({'event_time':np.random.randint(700, size=500000)}).cumsum()
df.loc[20, 'event_time'] = 83000000
df = df.sort_values('event_time', ignore_index=True)
print (df)

#original solution
a = df.where(df.event_time >= 83000000).first_valid_index()
b = df.where(df.event_time >= 90000000).first_valid_index()
c = df.where(df.event_time >= 93000000).first_valid_index()
d = df.where(df.event_time >= 100000000).first_valid_index()
e = df.where(df.event_time >= 103000000).first_valid_index()

print (a,b,c,d,e)
237709 257737 266255 286277 294890

arr = [83000000,90000000,93000000,100000000,103000000]
out = np.searchsorted(df['event_time'].to_numpy(), arr)
print (out)
[237709 257737 266255 286277 294890]

Performance:
#original solution
%%timeit
a = df.where(df.event_time >= 83000000).first_valid_index()
b = df.where(df.event_time >= 90000000).first_valid_index()
c = df.where(df.event_time >= 93000000).first_valid_index()
d = df.where(df.event_time >= 100000000).first_valid_index()
e = df.where(df.event_time >= 103000000).first_valid_index()

86.5 ms ± 4.79 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

#Michael Cao solution
%%timeit
a = df.where(df.event_time >= 83000000).first_valid_index()
b = df.loc[a:].where(df.event_time >= 90000000).first_valid_index()
c = df.loc[b:].where(df.event_time >= 93000000).first_valid_index()
d = df.loc[c:].where(df.event_time >= 100000000).first_valid_index()
e = df.loc[d:].where(df.event_time >= 103000000).first_valid_index()

99.6 ms ± 608 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%%timeit
arr = [83000000,90000000,93000000,100000000,103000000]
np.searchsorted(df['event_time'], arr)

16.9 µs ± 1.77 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

%%timeit
np.searchsorted(df['event_time'].to_numpy(), arr)

8.93 µs ± 104 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Comment: You can call searchsorted directly on the series ... I don't expect a stark perf difference for reasonably large data
Answer: Store the previous result and start looking from there using df.loc
a = df.where(df.event_time >= 83000000).first_valid_index()
b = df.loc[a:].where(df.event_time >= 90000000).first_valid_index()
c = df.loc[b:].where(df.event_time >= 93000000).first_valid_index()
d = df.loc[c:].where(df.event_time >= 100000000).first_valid_index()
e = df.loc[d:].where(df.event_time >= 103000000).first_valid_index()


Why is it impossible to construct private objects through reflection in Java

Question: I clearly set the constructor's setAccessible to true, but why is it still an error! can you tell me how to fix it
public class Person {
    // fields...

    private Person(String name, int age, String address, int num) {
        this.name = name;
        this.age = age;
        this.address = address;
        this.num = num;
        System.out.println("private full-constructor be created");
    }

}

// error happend ?! why?
public static void operatePrivateConstructorFullParameter(Class<? extends Person> clzz) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
    Constructor<? extends Person> constructor = clzz.getConstructor(String.class, int.class, String.class, int.class);
    constructor.setAccessible(true);

    Person person = constructor.newInstance("Miao", 18, "MOON", 88);
}

public static void main(String[] args) throws Exception {
    Class<? extends Person> clzz = Person.class;
    operatePrivateConstructorFullParameter(clzz);
}

Comment: Add error messages as text not as image
Answer: This error isn't about accessibility, it's about finding the constructor.
As specified in its documented contract, the method Class.getConstructor() will only find public constructors.
If you want to find this private constructor, you need to use getDeclaredConstructor() with the correct parameter types
Once you find the constructor, you will still need to make it accessible. Be aware, however, that in a modular application, encapsulation can prevent you from using reflection this way.
Comment: Thank you for your kind answer, because my carelessness got you into trouble. When I saw getDeclaredConstructor(), I had a sudden realization, thank you!
Answer: Try this
Constructor<Person> constructor= (Constructor<Person>) Person.class.getDeclaredConstructors()[0];


How can get a part of a 2D array?

Question: I have a 2d array with shape (100, 64).
I need to obtain a new array like (100, 63), just like deleting one column from a sheet.
So what numpy function should I use to obtain this?
# Let X be my (100, 64) dataset, and i the column I want to delete
np.somefunction(X[:, :i], X[:, i:])

Answer: You can use delete:
np.delete(X, i, axis=1)

or hstack:
np.hstack((X[:, :i-1], X[:, i:])

How can get a part of a 2D array?


tensorflow.python.framework.errors_impl.InvalidArgumentError: Incompatible shapes: [10] vs. [10000]

Question: I am new to Neural Networks and learning to use tensorflow from here, but when I run the code it gives error:
tensorflow.python.framework.errors_impl.InvalidArgumentError: Incompatible shapes: [10] vs. [10000]
 [[Node: Equal = Equal[T=DT_INT64, _device="/job:localhost/replica:0/task:0/cpu:0"](ArgMax, _arg_Placeholder_2_0_2)]]

My code is as follows:
import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data

data = input_data.read_data_sets("data/MNIST/", one_hot=True)
data.test.cls = np.array([label.argmax() for label in data.test.labels])
img_size = 28
img_size_flat = img_size * img_size
img_shape = (img_size, img_size)
num_classes = 10

x = tf.placeholder(tf.float32, [None, img_size_flat])
y_true = tf.placeholder(tf.float32, [None, num_classes])
y_true_cls = tf.placeholder(tf.int64, [None])

weights = tf.Variable(tf.zeros([img_size_flat, num_classes]))
biases = tf.Variable(tf.zeros([num_classes]))

logits = tf.matmul(x, weights) + biases
y_pred = tf.nn.softmax(logits)
y_pred_cls = tf.argmax(y_pred)

cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y_true)
cost = tf.reduce_mean(cross_entropy)
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.5).minimize(cost)

correct_prediction = tf.equal(y_pred_cls, y_true_cls)
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

session = tf.Session()
session.run(tf.global_variables_initializer())
batch_size = 100

feed_dict_test = {x: data.test.images,
                  y_true: data.test.labels,
                  y_true_cls: data.test.cls}

def print_accuracy():
    acc = session.run(accuracy, feed_dict=feed_dict_test)
    print("Accuracy on test-set: {0:.1%}".format(acc))

print_accuracy()

Can someone please explain why I am getting this error and how to resolve this??
Answer: I found the solution, the problem was that I haven't passed the dimension for y_pred_cls so its shape was (10,) but it needed to be (?,10) so I updated y_pred_cls = tf.argmax(y_pred) to y_pred_cls = tf.argmax(y_pred, axis=1)


Linear regression on a sample spanning many orders of magnitude

Question: Beer's law from chemistry says that the absorbance of a liquid $A$ is proportional to the concentration $C$, so:
$$A = kC$$
The standard thing to do then is to prepare a set of solutions with known concentrations, measure the absorbance to form a 'standard curve' (a calibration curve basically), and do a simple linear regression on that data to get the proportionality (which can then be used to predict the concentrations of unknown solutions).
One easy way to do this is to start with a known concentration and perform a serial dilution, which would get you 2x dilution, 4x, 8x, 16x....etc. I.e. if you start with a solution of $100\mu \mathrm g/\mathrm {mL}$ you'd get solutions with $50\mu \mathrm g/\mathrm {mL}$, $25\mu \mathrm g/\mathrm {mL}$, $12.5\mu \mathrm g/\mathrm {mL}$ etc...
Now when you do the linear regression, you have a data set with lots of data points at low concentrations and very few at higher concentrations. It seems much more natural to represent this problem on a log scale. My question is then, should I be doing a linear regression of $A$ vs. $C$ or $\log A$ vs. $\log C$? When I compare the models, they seem to give answers that are on the same order of magnitude but on the order of 30% different.
Answer: Let the physics (of the experiment and the measuring apparatus) guide you.
Ultimately, absorption is determined by measuring amounts of radiation passing through the medium and those measurements come down to counting photons.  When the medium is macroscopic, thermodynamic fluctuations in concentration are negligible so the principal source of error lies in the counting.  This error (or "shot noise") has a Poisson distribution.  This implies the error is relatively large at high concentrations when little radiation is passing through.
With sufficient care in the laboratory, concentrations typically are measured extremely accurately, so I will not worry about errors in concentrations.
The absorbance itself is directly related to the logarithm of the measured radiation.  Taking the logarithm evens out the amount of error across the entire possible range of concentrations.  For this reason alone, it is best to analyze the absorbance in terms of its usual values rather than re-expressing them.  In particular, we should avoid taking logs of absorbance, even though that would simplify the expression of the Beer-Lambert law.
We should also be alert to possible non-linearities.  The derivation of the Beer-Lambert Law suggests the absorbance vs concentration curve will become nonlinear at high concentrations.  Some way to detect or test this is needed.
These considerations suggest a simple procedure to analyze a series of $(C_i, A_i)$ pairs of concentrations and measured absorbances:

Estimate the coefficient $\kappa$ as the arithmetic mean of $A/C$, $\hat{\kappa} = \sum_i \frac{A_i}{C_i}$.
Predict the absorbance at each concentration in terms of the estimated coefficient: $\hat{A}(C) = \hat{\kappa}C.$
Check the additive residuals $A_i - \hat{A_i}$ for nonlinear trends in $C_i$.

Of course all this is theoretical and somewhat speculative--we haven't any actual data to analyze--but it is a reasonable place to start.  If repeated laboratory experience suggests the data depart from the statistical behaviors described here, then some modifications of these procedures would be called for.

To illustrate these ideas, I have created a simulation that implements the key aspects of the measurement, including the Poisson noise and possibly nonlinear responses.  By running it many times, we can observe the kind of variation that is likely to be encountered in the laboratory.  Here are the results of one simulation run.  (Other simulations can be carried out simply by changing the starting seed in the code below and modifying various parameters as desired.)

This simulated experiment measured absorbance at concentrations of $1$ down to $1/32$. The vertical spreads in values apparent in the scatterplot show the effects of (a) shot noise in the transmission measurements and (b) shot noise in the initial transmission measurement at zero concentration.  (Notice how this actually creates some negative absorbance values.) Although the resulting errors are not going to have exactly the same distributions at each concentration, the roughly equal spreads are empirical evidence that the distributions are close enough to being the same that we needn't worry about that.  In other words, there is no need to weight the absorbances according to the concentrations.
The red diagonal line has been estimated from all 50 simulations.  It has a slope of $\hat{\kappa}=2.13$, which differs slightly from the physically correct slope of $2$ that was used in the simulations.  This deviation is so large because I assumed there was very little radiation to measure; the maximum photon count was only $1000$.  In practice, maximum counts could be many orders of magnitude greater than this, leading to highly precise slope estimates--but then we would not learn much from this figure!
The histogram of residuals does not look good: it is skewed to the right.  This indicates some kind of trouble.  That trouble does not come from asymmetry in the residuals at each concentration; rather, it comes from a lack of fit.  That is evident in the boxplots at the right: although the first five of them line up almost horizontally, the last one--at the highest concentration--clearly differs in location (it is too high) and scale (it is too long).  This results from a nonlinear response I built into the simulation.  Although the nonlinearity is present throughout the full range of concentrations, it has an appreciable effect only at the very highest concentrations.  This is more or less what would happen in the laboratory, too.  However, with only one calibration run available we could not draw such boxplots.  Consider analyzing multiple independent runs if nonlinearity might be a problem.

The simulation was performed in R.  The calculations with actual data, though, are simple to conduct by hand or with a spreadsheet: just make sure to check the residuals for nonlinearity.
#
# Simulate instrument responses:
#   `concentration` is an array of concentrations to use.
#   `kappa` is the Beer-Lambert law coefficient.
#   `n.0`   is the largest  expected photon count (at 0 concentration).
#   `start` is a tiny positive value used to avoid logs of zero.
#   `beta`  is the amount of nonlinearity (it is a quadratic perturbation
#           of the Beer-Lambert law).
# The return value is a parallel array of measured absorbances; it is subject
# to random fluctuations.
#
observe <- function(concentration, kappa=1, n.0=10^3, start=1/6, beta=0.2) {
  transmission <- exp(-kappa * concentration - beta * concentration^2)
  transmission.observed <- start + rpois(length(transmission), transmission * n.0)
  absorbance <- -log(transmission.observed / rpois(1, n.0))
  return(absorbance)
}
#
# Perform a set of simulations.
#
concentration <- 2^(-(0:5)) # Concentrations to use
n.iter <- 50                # Number of iterations
set.seed(17)                # Make the results reproducible
absorbance <- replicate(n.iter, observe(concentration, kappa=2))
#
# Put the results into a data frame for further analysis.
#
a.df <- data.frame(absorbance = as.vector(absorbance))
a.df$concentration <- concentration # ($ interferes with TeX processing on this site)
#
# Create the figures.
#
par(mfrow=c(1,3))
#
# Set up a region for the scatterplot.
#
plot(c(min(concentration), max(concentration)),
     c(min(absorbance), max(absorbance)), type="n",
     xlab="Concentration", ylab="Absorbance",
     main=paste("Scatterplot of", n.iter, "iterations"))
#
# Make the scatterplot.
#
invisible(apply(absorbance, 2,
                function(a) points(concentration, a, col="#40404080")))
slope <- mean(a.df$absorbance / a.df$concentration)
abline(c(0, slope), col="Red")
#
# Show the residuals.
#
a.df$residuals <- a.df$absorbance - slope * a.df$concentration # $
hist(a.df$residuals, main="Histogram of residuals", xlab="Absorbance Difference") # $
#
# Study the residual distribution vs. concentration.
#
boxplot(a.df$residuals ~ a.df$concentration, main="Residual distributions",
        xlab="Concentration")

Answer: Neither of your fitted models can be correct for your original equation, and your original equation cannot be a correct model for the random variables you observe.
Let's address some issues one at a time.
1) Your original equation is $A=kC$, but of course data is not observed at population values (otherwise you'd only need one $x$ and $y$ value, since $k=y/x$. Clearly this is not the right model for the data or you wouldn't be trying to fit regressions. We'll see how to rewrite it shortly.
2) If both variables are observed with error, you need more specialized techniques than simple linear regression models.
3) If $C$ is observed with no error (or very low error relative to $A$), you presumably mean a model something like say $E(A|C) = kC$.
The question then is "how to model the variation about the mean" - we need a distribution for $A$ at each $C$, or at least some information relating to the distribution.
a) As you suggested, you could fit a linear model directly to the data on the original scale:
$$\text{E}(A|C)=kC$$
This might suitable if the variability is near constant on this scale ($\text{Var}(A|C)$ near-constant).
Note that this model, based on your population model, has no intercept term; it goes through the origin.
Alternatively, if you have some other model for the variation about the line, such as $\text{Var}(A|C)\propto C^p$, then you could fit a weighted regression.
b) As you mention, another possible model may be fitted on the log-scale:
$$\text{E}(\log_{10}A|\log_{10}C)=\log_{10}k+\log_{10}C$$
This might suitable if the variation is near constant on the log scale ($\text{Var}(\log_{10}A|\log_{10}C)$ near-constant) ... which you'd tend to see if the variance-power in (a) were 2 or close to 2.
Note that this model has an intercept, but has a slope coefficient of 1. A way to fit this model is to fit:
$$\text{E}(\log_{10}A|\log_{10}C)-\log_{10}C=\log_{10}k$$
(That said, you may want to check a more general model that your original one, such as considering a non-unit slope in (b) for example.
The fits in (a) and (b) weight the data differently (though with $p=2$ in (a) the results will be quite close), so they won't give identical answers. On your data they differ by about 26%, which illustrates that for such a sample the choice is quite important.
If you don't have any prior knowledge to guide the choice, residual analysis might be a way to arrive at a model (especially if you have another data set on which you can base that choice); alternatively, you could make $p$ a parameter of a larger model.
(As it happens, a little residual analysis suggests to me there may be potential problems with both (a) with constant variance and with the model in (b); neither model, nor even, perhaps, the more general models (a)-with0intercept and (b)-with-non-unit slope are necessarily suitable (there's a suggestion of curvature about the line). One of the concerns is leverage in (a), which stems from the 'many orders of magnitude')
4) Note that there are numerous other models that might be fitted.
For example, consider $E(A^q|C) = k^qC^q$ for some specified constant $q$ (the log-model corresponds to $q=0$).


How to make nodes to be aware that they were added to menu programatically

Question: I'm adding nodes to menu programatically by custom PHP snippet in Rules. The problem is that nodes aren't aware of this - so the option "Provide a menu link" is unchecked in them, even if their menu-item exists. I cannot find anything relevant in $node object. How to fix this?
My code is:
<code>$node_path = "node/" . $node->nid;
$node_alias = drupal_get_path_alias($node_path);
$menu = menu_load_links('main-menu');

foreach($menu as $key=>$value) {
    if($node_alias == $menu[$key]['link_path'] || $node_path == $menu[$key]['link_path']) {
        return;
    }
    if($menu[$key]['link_title'] == $node->field_rok['und'][0]['value'] && $menu[$key]['link_path'] == "<nolink>") {
        $menu_year = $menu[$key]['mlid'];
    }
    if($menu[$key]['link_path'] == "archiwum") {
        $archiwum_plid = $menu[$key]['mlid'];
    }
}

if(!isset($archiwum_plid)) {
    return;
}

if(!isset($menu_year)) {
    $item = array(
        'link_path' => '<nolink>',
        'link_title' => $node->field_rok['und'][0]['value'],
        'menu_name' => 'main-menu',
        'plid' => $archiwum_plid,
        'hidden' => 0,
    );
    // menu_edit_item_validate(array(), $item); Drupal doesn't recognize this function in this place (Rules), don't know why... :/
    $menu_year = menu_link_save($item);
}

$item = array(
    'link_path' => $node_alias,
    'link_title' => $node->field_numer_w_roku['und'][0]['value'] . '/' . $node->field_rok['und'][0]['value'] .' (' . $node->field_numer['und'][0]['value'] . ')',
    'menu_name' => 'main-menu',
    'plid' => $menu_year,
    'hidden' => 0,
);

// menu_edit_item_validate(array(), $item);
menu_link_save($item);

menu_rebuild();
</code>
Answer: Got it - I had to use drupal_get_normal_path($node_alias) on path added to menu. I hope that will be helpful for someone.


Schmidt group and Permute 2-maximal subgroup with 3-maximal subgroup

Question: $G$ is Schmidt group With abelian Sylow subgroup Then every $2$-maximal subgroup of $G$ permuts with all $3$-maximal subgroup of $G$.
Comment: What is the question?
Comment: Why "hold" ? I neeed prove this sentence.
Comment: Please don't discriminate against foreigners, those who are voting to close.
Answer: Let $G$ is Schmidt group. $G=Q\ltimes P$.($P$ is p-Sylow subgroup and $Q$ is q-Sylow subgroup).
We know Maximal subgroups of Schmidt Group is  $\langle a \rangle \times P$ and $\lbrace P'\times Q^{x} |x\in G\rbrace$(i dont have any proof this).
I just Show  Every maximal and 2-maximal of $Q^{x}$ is normal in $G$. by Schmidt group and sylow subgroup Every maximal and 2-maximal of q-Sylow subgroup of $G$, is normal in $G$. Then every 2-maximal of $G$ permute with evrey 3-maximal of $G$. if 2-maximal and 3-maximal select in $\langle a \rangle \times P$. easy to see permute(because $\langle a \rangle \times P$ is abelian group)


Problems with waiters AWS PHP SDK3

Question: I'm trying to change instance type but since I have updated to SDK3 this script fails. I don't know what I'm doing wrong with waiters.
<code>            $client = new Ec2Client(self::getCredentials());

            $client->stopInstances(array(
                'InstanceIds' => $instanceIds,
            ));

            $client->waitUntil('stopped', [
                'InstanceId' => $instanceId,
            ]);

           $client->ModifyInstanceAttribute(array(
                'InstanceId' => $instanceId,
                'Attribute' => 'instanceType',
                'Value' => $instanceType
            ));

        $client->startInstances(array(
            'InstanceIds' => $instanceIds,
        ));

        $client->waitUntil('running', [
            'InstanceId' => $instanceId,
        ]);
</code>
Answer: I finally found the solution.
The problem was that InstanceId param was wrong... You have to use an array of instaces Ids.
<code>                $client->waitUntil('InstanceStopped', [
                    'InstanceIds' => array($instanceId),
                ]);

                $client->waitUntil('InstanceRunning', [
                'InstanceIds' => array($instanceId),
                ]);

</code>

Problems with waiters AWS PHP SDK3


What is the difference between the 2 ways to remove percentages?

Question: Given the value $690$, I want to remove $10$% from that and then remove another $20$% from the resulting value, so as an example, I am doing:
$690 \over {(1 + 0.1 + 0.2})$ = $690 \over {1.3}$ = $530.76.$  Apparently, I was told this is wrong and it should be:
$690 * 0.9 =$        $621 \over {1.2}$ = $517.50$
In the above, the $10$% is non-compounded and the $20$% is compounded.  Can someone explain what is the difference between the $2$ and is one way better than the other if I do not know certain values like the start or end value (690 in this case)
If I do $690 \over {1 + 0.111111111111 + 0.2}$, I get closer to $517.50.$
Comment: There is only one way to remove 10% which I know of. If you have $a$ and you remove 10% of $a$ you get $a-10$%$\times a = 0.9 a$.
Answer: Rather than comment on the differences between the two approaches, here's the way I would do it. Think in terms of what you want to keep. In the first step, keep 90%, then in the second step keep 80% of that. So just multiply $690(0.9)(0.8) = 690(0.72) = 496.8$.
Answer: If you remove 10 percent of 690 from 690, then you have 90 percent of 690 left; so removing 10 percent of 690 from 690 gives you
$$
690\cdot (.9)=621.
$$
If you remove 20 percent of 621 from 621, you have 80 percent of 621  left; so
 so removing 20 percent of the new value 621 from 621 leaves you with
$$
621\cdot(.8) = 496.8
$$
It would be different to compute $690\cdot (.7)=483$; because here you are removing 10 percent of 690 and 20 percent of $690$.

I'm not sure what you were trying to do with your solution; but it seems you are doing the "backwards problem". An example
A dress is put on a 30 percent off sale. If the sale price was 690 dollars, what was the original price?
Solution: Let $O$ be the original price. We are told that
$$
690=O\cdot .7;
$$
so $O=690/.7=985.71$.
Answer: Neither is correct - you should start with $690\times0.9=621$, to get the $10\%$  reduction, and then do $621\times0.8=496.8$ for the subsequent $20\%$ reduction. Note that this is not the same as just doing a $30\%$ reduction straight off, as the second percentage is of $621$, not $690$, so "each percent" is worth less (this is a common error).
To work backwards, if you're given the $496.8$ and told it was obtained in this way, then you should first undo the $20\%$ reduction. To do this, note that $496.8$ is $80\%$ of the value before the reduction, so you can find $1\%$ by dividing by $80$, and then multiply by $100$ to get the full amount; in one step this amounts to dividing by $0.8$. This gives you back $621$, and then by the same procedure you divide by $0.9$ to get the $690$ back.
As a general rule, you should first work out what $100\%$ is - in the original problem, it's the $690$ you start with, and if you're trying to "undo" a percentage reduction it's the amount you're trying to find (although if you're undoing more than one reduction it's probably easier to do them one at a time, so $100\%$ is the number you want to find in the next step). Then most problems can be reduced to dividing to find out what $1\%$ is, and then multiplying by the percentage you actually want. So when starting with the $690$ and reducing by $10\%$ you start with $100\%$ and want $90\%$, so divide by $100$ and multiply by $90$ (equivalently multiply by $0.9$), and when starting with $621$ and undoing the $10\%$ reduction you start with $90\%$ and want $100\%$, so divide by $90$ and multiply by $100$ (equivalently divide by $0.9$).
Answer: If you remove $10\%$ from $690$, your new value is $690-690\cdot \frac{10}{100}$.
This is $690\left(1-\frac{10}{100}\right)$, or more simply $(690)(0.9)$.
To remove $20\%$ from the new value of $(690)(0.9)$, you go through essentially the same process, and arrive at $(690)(0.9)(0.8)$.
Note that we would have gotten to the same final answer if we removed $20\%$ from $690$, and then removed $10\%$ from the result.
I do not know what you mean by "if I do not know certain values." If we only know the percentages removed, we cannot know the dollar amounts.
But if the initial price is $A$, and you remove $10\%$ and then $20\%$, the same reasoning leads to the final price of $A(0.9)(0.8)$.
So if you know that discounts of $10\%$ and then $20\%$ were applied, and the final price was, say, $576$, then you can determine the original price as follows. Let $A$ be the original price. Then
$$A(0.9)(0.8)=576,$$
and therefore
$$A=\frac{576}{(0.9)(0.8)}.$$
Comment: How does the calculation differ if there are more than 2 percentages 2 remove?  For example, my starting value is 690 and in the following order I need to remove 10% non-compound, 20% compound, and another 5% non-compound.  I have to do it in this order, I can't remove the non-compounds first
Comment: Also, what is wrong with 690 * 0.9 and then 621 / 1.2 = 517.5?
Comment: I am not sure what the $5\%$ non-compound at the end means. If it means you remove $5\%$ of the *original* price at the end, that's easy, just subtract $5\%$ of $690$ from the $(690)(0.9)(0.8)$. About what's wrong with dividing by $1.2$, it is **not** what one gets by removing $20\%$ of $(690)(0.9)$ from $(690)(0.9)$.  So, still difficulties with the same old problem? I thought that was settled long ago.
Comment: Ok, I get your point about the 1.2 and I understand that I can do (690)(0.9)(0.95)(0.8), but wouldn't this remove 5% from 621 and not 690.  I guess what I am trying to get at is how do handle it when I have a mixture of compound and non-compound percentages.
Comment: lol, this was settled a while ago, the problem is when you have live clients telling you the calculation should return a certain result when in fact it should return something else.  I am being told it should return 517.50 and on here the consensus answer is 496.8


Question b show that $a_n$ diverges when $x_n<1/2$

Question: a.  Let $0< x <1/2$ and let $∑a_n$ be a series of positive real numbers.  Assume that the sequence $(a_n)_{n∈\Bbb N}$ is decreasing and that
$$\frac{a_{2n}}{a_n} \leqslant x$$
and converges given this property, but when $x$ is replaced with
$$\frac{a_{2n}}{a_n}<\frac12$$
The series doesn't necessarily diverge. Can someone help me with this?
The answers are here but I don't understand part 2
answers
Comment: I tries to edit your question and get in a form where it's readable, but I had to gess, though.
Comment: What have you tried?  And what is your question? Does "a2n" mean $a_{2n}$ or $a_{2^n}$?  Your linked page uses both.
Comment: Do you not understand the answer or why we're able to construct a counterexample?
Answer: The idea is that we need $\frac{a_{2n}}{a_n}\to 1/2$ from (strictly) below as $n\to\infty$, since otherwise we could use the first part of the exercise to see $\sum a_n$ must converge. An obvious first candidate would be $a'_n=1/n$, since the sum diverges and we have $\frac{a'_{2n}}{a'_n}=1/2$ for all $n$. However, we want the ratio to be strictly less than 1/2, so we'll need to perturb our $a'_n$ a bit so that the inequality is strict but the sum still diverges. A natural guess would be to multiply it by something that approaches 1 as $n\to\infty$, and in order to get the inequality the correct way, we can let this sequence be $1+\frac{1}{n}$.
From now it's just checking whether our guess $a_n=\frac{1}{n}(1+\frac{1}{n})$ (which is positive) works.
First we check that indeed $\frac{a_{2n}}{a_n}<1/2$, but note that $$a_{2n}/a_n=1/2\frac{1+\frac{1}{2n}}{1+\frac{1}{n}}=1/2\frac{2n+1}{2n+2}<1/2,$$ since $2n+1<2n+2$.
So it suffices to see that $\sum a_n$ diverges. But note that $a_n=1/n+1/n^2>1/n$, so by the comparison test and the fact that $\sum 1/n$ diverges we get what we wanted.
Comment: Thanks you legend this has been a huge help thank you


"Tritone" intervals in n-tone equal temperament

Question: In 12-tone equal temperament, the tritone interval is made of three whole tones (six semitones) and is considered, if I am not mistaken totally, as the most dissonant interval.
I have two questions:

Is there an explanation why tritone interval seems so dissonant in 12-tone equal temperament?
Is there a generalization of this "tritone" dissonance in the n-tone equal temperament where n is a natural integer other than 12? How can we construct that? Is it unique?

One possible answer to the latter question is that "tritone" intervals can be defined as an half of an octave. Obviously, this only works when n is even. Is it possible to generalize the "tritone" quality even to scales with an odd number of equal tones?
Comment: I think it would be very hard to back up your statement that the tritone is the single most dissonant interval. Who says so? The minor second and the major seventh are equally dissonant.
Comment: Semantically, "tritone" is three whole tones. Would you have a definition of "tone" in a n-temperament scale? Then take three of these. If you are looking for the most dissonent (it's arguable if the tritone is the most dissonant interval in 12-temperament. There is a tritone in a dominant 7 chord), then find the "weidest" frequency ratio.
Comment: I'm pretty rusty with this area of theory. That being said I think some consider the minor second (a half step) the most dissonant harmonic interval.
Comment: It's pretty dissonant in other temperaments as well - in Medieval times it was avoided in music - especially vocal.
Comment: @MattL. And the augmented octave even more so.
Answer: As some of the other answers have eluded to, there are two basic problems with your question:

The first is the question of how you generalize a "tritone" in a non-12-TET based system. One possibility is to interpret it literally as three whole tones (which then begs the question as to how you define a whole tone in a non 12-tone system). Another possibility would be to define it as a half an octave, which still leaves tritones undefined for odd n. Because tritones are inherently defined around a diatonic system consisting of whole tones and half tones, it is not clear what the proper generalization to other systems should be. For example, perhaps with an odd n, you could define the two intervals on either side of n/2 as a minor tritone and a major tritone (bothe of which would likely be dissonant). But to my knowledge, this isn't standard terminology.
The second issue is with your assertion that the tritone is the most dissonant. This is not necessarily true, as we'll see below, and depends on how you define dissonance.

It's not really worth trying to argue around the semantics of an undefined tritone (besides, what about other dissonant intervals, or intervals in non-ET systems?). As a result, I will generalize your question to the following:

Is there an explanation why any interval seems so dissonant in any tuning system?

When formulated in this manner, the question merges into the following question which already has an excellent answer: Is there a way to measure the consonance or dissonance of a chord? (although the title says "chord", much of the answer is concerned with the consonance/dissonance of intervals).
To summarize the answer from that page, two pure frequencies will produce a "roughness" (caused by the interference of the two sound waves) which gradually increases as the frequencies get closer together, and is maximal somewhere around a minor 2nd. Frequencies much closer than that start to be perceived as out of tune versions of the same frequency, and the perceived roughness rapidly decreases until it reaches zero when they are in unison.
However, most instruments do not produce a single pure frequency, but create a harmonic series of frequencies. In order to compute the dissonance of two notes, you have to sum all the "roughness" between all the pairs of frequencies in the two instruments spectra. In this approach, the tritone is primarily dissonant because it is a m2 away from the second overtone of the fundamental (a P5), and inversely, it's second overtone (a P5) is a m2 away from the fundamental.
When you plot this out for all frequencies, you get what is called a Plomp-Levelt curve which looks like the following, though it will probably differ depending on how you weight the formulas, and what the individual spectra of the instruments look like. You'll notice in this graph that, while the tritone isn't the most dissonant interval (at least according to this mathematical model of dissonance) it is the most dissonant interval between a m3 and a m7. Furthermore, the local maximum is actually pitched slightly higher than a tritone (somewhere between a tritone and a fifth). You'll also note that the axis across the top is equally divided into 12 parts from unison to octave. For any other system, you would merely divide the axis into a different number of subdivisions. Or, for other non-equal tuning systems, you would just find the corresponding subdivisions.

Addendum - Timbres and Tuning
Because the above curve that models the degree of consonance for various intervals is determined, in part, by the location of an instrument's overtones, this suggests that instruments with inharmonic overtones (such as xylophones, bells, or synthesizers) might be able produce curves with consonances at different locations, including locations more suited for alternate tuning systems. Sethares has performed some research in this area, and in the linked article, provides a series of timbres theoretically suitable for 10-TET -- including a consonant tritone! Unfortunately, I don't see an audio sample provided.
Addendum - Defining Dissonance
You ask specifically about a uniquely "most dissonant" note, but such a thing does not exist, either at the tritone, or at any other interval. Such a question assumes the existence of a single, objective, quantitative scale by which dissonance can be measured. There is no such scale. There are many factors that come into play: acoustics/physics, biomechanics, neurophysics, and -- importantly -- ethnocultural experiences. The Plomp-Levelt curve provided above is merely one model that attempts to explain the phenomenon of dissonance, which depends on specific instruments' spectra, and it's inharmonicity, as well as making assumptions about how the ear rounds nearby pitches. As shown above, these parameters can be tweaked to produce different curves. As an example of a different model, here is one based on neural synchronization, which, according to the abstract,

"explore[s] the theory of synchronization properties of ensembles of
  coupled neural oscillators to demonstrate why simple frequency ratios
  may have achieved a special status and why they are important for
  auditory perception."

Since there is no single objective quantitative definition of dissonance, there cannot be an objectively "most dissonant" interval.
Answer:
Two other importantnotes in a given key (which are the basis for main chords) are the 4th and 5th notes of a major scale, being 5 and 7 semitones from the root respectively. Giving the subdominant and the dominant. That puts a tritone right between them, neither one or the other, but too close to sound consonant. Yes, mathematically it could be construed that it ought to sound good, but musically it doesn't - unless one has acquired the taste, so to speak.
Don't know!!
Comment: No, mathematically there is no reason to think it would sound consonant. Assuming equal temperament these are both approximations, but the perfect 4th is a frequency ration of 3:4, and the perfect 5th is 2:3, which are both round fractions. Exactly half an octave is a frequency ratio of 1: root(2), which is a horrible irrational number, so no wonder it sounds nasty. (Check: 4th plus 5th = 4/3 * 3/2 = 2; root(2)*root(2) = 2.)
Comment: @BrianChandler - so, horrible fraction = nasty sound?!
Comment: @Tim: yes, you could indeed say so.
Comment: @Tim it's not that simple. Dominant 7th chords contain tritones. Do they sound "nasty" to you? They don't to me.
Comment: @BrianChandler or maybe the irrational square root of two sounds okay because it approximates the ratio 25:18 or 45:32.  Do you think semitones are dissonant?  Does the answer depend on whether the ratio is 25:24 or 16:15 or the twelfth root of two?
Answer: To answer 2: yes, for any n, if n is even, then half an octave is n/2 divisions. (This is rather boringly obvious, so perhaps I don't understand the question.) I don't understand what you mean by "unique".
Comment: I don't see the point of this question: assuming that "tritone" means "half octave", then obviously in n-equal-temperament where n is odd, n/2 is not an integer, so there is no exact half octave. The closest approximation is (n+1)/2 or (n-1)/2, each of which is an equally bad approximation; and in fact the half octave is maximally difficult to approximate.
Comment: Why half an octave is always the most dissonant interval for all `n`? Your property is asserted without clues.
Comment: By ``uniqueness'', I mean the existence of a single most dissonant interval in the `n` equal temperament for all `n`, like in the case `n = 12`. From what I know, there is no reason for the fact there cannot be two different most dissonant intervals for some values of `n`.
Comment: In most edo-tunings, almost all intervals sound horrible. The tritone usually won't stand out much... For instance in 16-edo, diminished seventh chords are pretty much the only proper chords you have, so they take on an almost consonant role.
Comment: I did not mean to claim that half an octave is "most dissonant"; I do not think there is really a way to determine exact rankings of dissonance. I only point out that half an octave means a frequency ratio of 1: root(2), which is irrational, and therefore dissonant because it cannot be a ratio of integers. The number of divisions makes no difference as long as n is even.
Comment: OK. So, what about a consistent definition of tritone intervals when `n` is odd?
Comment: The cube root of two is also an irrational number, yet many people find the major third to be a consonant interval.
Answer: Whether it is dissonant or not is a matter of cultural practice. However, splitting an octave in half (harmonically) means that the product of the ratio of these intervals is Sqrt(2). It has been known (at least from the time of Pythagoras) that this number is irrational; it cannot be written as a ratio of whole numbers. Thus, any "just" set of intervals cannot include this division (nor can any finite combination thereof). For example, the "large" just whole tone has a ratio of 9/8 (and a "small" whole tone of 10/9; just intonation cannot even create a single whole tone. Combining three of these gives one of the following (9/8)^3=729/512, (9/8)^2*10/9=45/32, 9/8*(10/9)^2=25/18, and (10/9)^3=1000/729. None of these exactly equal the Sqrt(2). From the theory of continued fractions, the best approximations (those which need a bigger denominator to be better) are 1/1, 3/2, 7/5, 17/12, 41/29, 99/70, 239/169... None of these can be made easily from other intervals.
This does reflect musical notation in that F# and Gb are different notes and reflects the normal usage where diminished fifths shrink and augmented fourths expand. B-F resolves to C-E while F-B resolves to E-C.
Generally, one may have to adjust notes on-the-fly (as in which of the two wholetones should be used) to keep close to just intervals.
Comment: The discussion of just ratios isn't relevant.  The question is about equal temperament with an arbitrary number of divisions to the octave.  That F♯ and G♭ are different pitches is irrelevant, and also, for 12-tone equal temperament, it is not correct.

“Tritone” intervals in n-tone equal temperament


Kendo UI Upload Async Error

Question: I downloaded a trial version of Kendo.UI, so logging onto the forums, at this stage is not possible, hoping someone on here can help me solve this problem.
I'm trying to implement the async upload onto a basic MVC 4 application. I've added a reference to the Kendo.UI.MVC wrappers, and added the necessary namespace Kendo.UI.MVC to both web.config files (root and under Views).
If I implement a basic uploader on my landing view (index.cshtml) it works fine:
<form action="/Home/Save" method="post">
   @(Html.Kendo().Upload().Name("files"))
   <input type="submit" value="Submit" />
</form>

However, as soon as I add the Save() method to Async, I get an "index was out of range" exception. I know it's the save method, because if I just add "AutoUpload(true)" without an action reference, it does not throw an exception. If I just add "Remove("Remove", "Home")" it still shows the Select button, without an error, but the "Save("Save", "Home")" method keeps throwing the mentioned exception.
I followed the examples that ship with the trial to the letter and it should web working, yet it does not.
View (index.cshtml):
@(Html.Kendo()
      .Upload()
      .Name("files")
      .Async(async => async
                      .Save("Save", "Home")))

-- Error is being thrown on the above statement
@(Html.Kendo()
      .Upload()
      .Name("files")
      .Async(async => async
                      .AutoUpload(true)))

-- this line works
Controller (HomeController):
public class HomeController : Controller
{
   public ActionResult Index()
   {
      return View();
   }

   [HttpPost]
   public ActionResult Save(IEnumerable<HttpPostedFile> files)
   {
      // I just want the break-point to be hit
      // does not due to IndexOutOfRange exception being thrown

      return Content("");
   }
}

Answer: The only thing that seems wrong is the Razor syntax:
(@Html.Kendo()

should be
@(Html.Kendo()

I was able to run your code with this small change.
Comment: Hi, thanks, but even with that change I still get the IndexOutOfRange exception.
Answer: Updated the MVC templates for Visual Studio and it works. Thanks.

Kendo UI Upload Async Error


Equivalence between "mathematical induction" and "transfinite induction" for natural numbers?

Question: The "principle of mathematical induction" says that for a subset $S$ of $\omega$ (where $\omega$ is the set of all natural numbers), if $0 \in S$ and $n \in S \implies n^+ \in S$, then $S = \omega$.
The "principle of transfinite induction" says that if $X$ is a well-ordered set, $S \subset X$, and $s(x) \subset S \implies x \in S$ (where $s(x)$ is the set of all predecessors of $x$ in $X$), then $S = X$.
Page 67 of Naive Set Theory (Halmos) says that "[the principle of transfinite induction] when applied to $\omega$ is easily proved to be equivalent to the principle of mathematical induction".
However, I had trouble proving this (possibly because I had trouble formulating this "equivalence" precisely).

How can I formulate and prove the statement that "the principle of transfinite induction, when applied to the natural numbers, is equivalent to the principle of mathematical induction"?
Comment: That's not how transfinite induction is supposed to go.
Comment: No, induction would only prove that $\omega\subseteq S$. You didn't state that $S\subseteq \omega$.
Comment: And similarly for transfinite induction, you can only deduce $X\subseteq S$, since $S$ might contain more elements.
Comment: Thanks Thomas, those were oversights on my part when I typed the question.
Comment: Apply mathematical induction to the statement $P(k):s(k)\subset S$ to get the transfinite induction applied to the natural numbers (I thought it was called strong induction). By the way, why are you working on such topics? I thought unless you are a working mathematician, these questions don't concern you.
Comment: Does the equivalence not follow from the simple fact that $\omega$ is a well-ordered set.
Answer: First, state the principle of transfinite induction in the case that $X = \mathbb{N}$.

If $\mathbb{N}$ is a well-ordered set, $S \subset \mathbb{N}$, and $s(x) \subset S \implies x \in S$ (where $s(x)$ is the set of natural numbers less than $x$), then $S = \mathbb{N}$.

To show this is equivalent to standard induction, you need to show the conditions are the same.   I.e., you need to show that the following are equivalent:

For all $x \in \mathbb{N}$, if $x \in S$, then $x^+ \in S$.
For all $x \in \mathbb{N}$, if $s(x) \subset S$, then $x \in S$.

$1 \implies 2$ is straightforward.  For $2 \implies 1$, prove the contrapositive, and use the fact that $\mathbb{N}$ is well-ordered to find a minimum counterexample.
I am a little skeptical of this, however, because to prove two forms of induction are the same you would want to be working in a world where neither of them need be true.  That is, you can't use any form of induction in your proof.  I do not know how one proves the natural numbers are well-ordered but I would certainly think it uses induction.  And I wonder if one can even construct the natural numbers without some sort of induction.  I am no expert in set theory, so I don't know how to resolve this issue, but there is certainly something fishy going on.
Comment: I think there's a typo in your first line. It is true that $\Bbb N$ and $\Bbb Z$ are the same letter, modulo a unitary rotation matrix, but they denote different sets. :-)
Comment: @AsafKaragila True, thanks!
Comment: There was definitely induction involved in the proof that $\mathbb{N}$ is well-ordered--I'm not sure how to resolve this issue either.  However, I'm okay with leaving the issue alone, and I'm happy with your answer--my main goal here was to get help with formulating the equivalence sensibly.


Maximum size of cards inside a canvas

Question: I am now working with a Web Application, which needs to draw some cards on a fixed rectangle canvas.  Below is the criteria:

The canvas size is fixed with width "w" and height "h" when the Web Application starts.
There are "n" no. of cards which won't be changed after started.
All cards must in the same size, which has a fixed ratio with width "cw" and height "ch", the cards are able to re-size within the canvas.

I would like to calculate the maximum width and height of each card in such cases.  Can anybody help?
Comment: The maximum size? Do you mean the maximum area?
Comment: Yes, I would like to find maximum width and height allowed of each card
Answer: Your question is lacking a lot of information. please read the comments in the code. I hope my answer may help you.

// initiate the canvas
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
let cw = canvas.width = 300,
  cx = cw / 2;
let ch = canvas.height = 300,
  cy = ch / 2;

// number of cards
let n = 12;
// the horizontal and vertical ratio
let ratio = {x:.2,y:.3}
// the width and the height of a card
let w = cw*ratio.x;
let h = ch*ratio.y;
// a counter
let i = 0;
//a double for loop to draw the cards
for(let y = 0; y<ch; y+=h){
for(let x = 0; x<cw; x+=w){
  if(i < n)
  {drawCard(x,y);
  i++}
}
}

function drawCard(x,y){
  ctx.beginPath();
  ctx.strokeRect(x,y,w,h);
}
canvas {
  border:1px solid #d9d9d9;
}
<canvas id="canvas"></canvas>
Answer: Finally, I found the solution myself.
This performance may not is the optimal one, but the solution gives me the new card width, new card height, cards per rows and cards per column.  So that the cards can almost cover the canvas.

function crwh(col, row, n, cw, ch, w, h, exactN) {
  // Methods
  this.fn_init = function(col, row) {
   this.col = col;
   this.row = row;

   if (this.col > 0 && this.row > 0) {
    // Calculate new card width & card height base on col
    this.cw_new = (this.w / this.col);
    this.ch_new = (this.cw_new / this.cw * this.ch);

    if (this.fn_valid() == false) {
     // Calculate new card height & card width base on row
     this.ch_new = (this.h / this.row);
     this.cw_new = (this.ch_new / this.ch * cw);
    }
   }
  }

  this.fn_area = function() {
   // Get the size the rectangle
   return this.cw_new * this.ch_new;
  }

  this.fn_valid = function() {
   var valid = true;

   // True if col * row must equal to no. of cards, False allow col * row greater than no. of cards
   valid = valid && ((this.exactN == true && (this.col * this.row) == this.n) || (this.exactN == false && (this.col * this.row) >= this.n));
   // col * card width (new) must be shorter than canvas width

   valid = valid && ((this.col * this.cw_new) <= this.w);

   // row * card height (new) must be shorter than canvas height
   valid = valid && ((this.row * this.ch_new) <= this.h);

   return valid;
  }

  // Properties
  this.n = n;
  this.cw = cw;
  this.ch = ch;
  this.w = w;
  this.h = h;
  this.exactN = exactN;

  this.col = 0;
  this.row = 0;

  this.cw_new = 0;
  this.ch_new = 0;

  this.fn_init(col, row);
 }

 function fn_getCardDimensions(n, cw, ch, w, h, exactN) {
  var crwh_max = new crwh(0, 0);

  // Loop thru 1 to n for col & row to see which combination allow a maximum card size
  for (var col = 1; col <= n; col++) {
   for (var row = 1; row <= n; row++) {
    if ((col * row) >= n) {
     var crwh_cur = new crwh(col, row, n, cw, ch, w, h, exactN);

     if (crwh_cur.fn_valid()) {

      if (crwh_cur.fn_area() > crwh_max.fn_area()) {
       crwh_max = crwh_cur;
      }
     }
    }
   }
  }

  return [crwh_max.col, crwh_max.row, crwh_max.cw_new, crwh_max.ch_new];
 }

 var n = 80;    // No. of Cards
 var cw = 344;   // Card Width (orig)
 var ch = 512;   // Card Height (orig)
 var w = 0;    // Canvas Width
 var h = 0;    // Canvas Height
 var exactN = true;  // True if col * row must equal to no. of cards

 function fn_drawCards() {
  var canvas = document.getElementById("canvas");
  var ctx = canvas.getContext("2d");

  w = canvas.width;
  h = canvas.height;

  [col, row, cw_new, ch_new] = fn_getCardDimensions(n, cw, ch, w, h, exactN);

  for (var i = 0; i < col; i++) {
   for (var j = 0; j < row; j++) {
    ctx.beginPath();
    ctx.strokeRect(i * cw_new, j * ch_new, cw_new, ch_new);
   }
  }
 }

  fn_drawCards();
canvas {
  border:1px solid #00FF00;
 }
<canvas id="canvas"></canvas>

Maximum size of cards inside a canvas


Lower bound on universe size for set system with pairwise intersections of 1?

Question: Given a finite universe $U$, consider a collection of subsets $S_1, ..., S_n \subset U$, where each subset has exactly $k$ elements. Suppose that each pair of sets has exactly one element in common: that is, give any distinct pair $i, j \in [n]$, we have $\left\vert S_i \cap S_j \right\vert = 1$.
My question: Given a fixed pair of integers $(n, k)$, what is the minimum size of a universe $U$ for which such a set system can exist? I am interested in all ranges of parameters but especially when $n >> k$.
(Actually, I am also interested in an upper bound, but I believe this will be given by requiring that the sets $C_1, ..., C_n$ form a sunflower, so $\left\vert U \right\vert = n(k-1) + 1$. Please correct me if this upper bound is wrong).
I think I have made partial progress on this question: in the case where $n = k + 1$, I claim that we need $\left\vert U \right\vert \geq {k + 1 \choose 2} = (1 + 2 + ... + k)$. This comes from an arrangement where each pair of sets shares a unique element of $U$, which intuitively should be the most "efficient" arrangement but I cannot prove this.
Answer: Each set $S_i$ contains $\binom{k}2$ pairs of elements of $U$. Furthermore, for any two sets $S_i$ and $S_j$, the set of pairs of $S_i$ is disjoint from the set of pairs of $S_j$, because $|S_i\cap S_j|=1$. Therefore, the number of pairs of elements appearing in any of the $S_i$ is at least $n\cdot \binom{k}2$. The number of pairs of elements in $U$ must be at least this, which implies
$$
\binom{|U|}2\ge n\binom{k}2
$$
Using the approximation $\binom{m}2\approx m^2/2$, this means that roughly $|U|\ge k\sqrt{n}$.
Furthermore, this bound is attained whenever $k=q+1$ and $n=q^2+q+1$, for any prime power $q$, by the set of lines in the finite projective plane of order $q$.
Comment: Thanks! Do you know if projective space also attains the generalized lower bound? That is, if instead of interections of size $1$ we require that $\forall i, j \left\vert S_i \cap S_j \right\vert = \ell$ then ${\left\vert U \right\vert \choose \ell + 1} \geq n {k \choose \ell + 1}$ by the same reasoning. Do the $\ell$-dimensional subspaces of some projective space over a finite field attain this bound?


convert git dump into local repo

Question: I got a git dump which was originally exported from GitHub.
I can't know how they made the export but I have extracted the zip file and the structure of the files are as below.
git status from that folder returns with:
On branch main nothing to commit, working tree clean
Tried and didn't help:
git clone exported_dir/ dst_dir/
I do expect to see in that repo some C# code files

How can I convert them to the actual resources keeping all branches, history, logs, etc?
Comment: Then you are already set to go. A Git repository is just a directory hierarchy with a set of files. If you zip it up and unpack it elsewhere, that's usually all you need to do. It's as simple as that.
Comment: that's all you got? That sounds like you got close to nothing in that repo. `git ls-tree -r main`. That should get you the list of files that makes up the tip of `main`.... also `git show --name-status main` should show you if there was something put in that first (and only) commit.
Comment: If you cd into that directory, and run `git status`, what does it show?
Comment: @NickODell ```On branch main
nothing to commit, working tree clean```
Comment: Can't understand. Where do I see the code files? I don't see them in this hierarchy. I do expect to see some C# files there
Comment: Perhaps your files are not in the `main` branch. Or perhaps they aren't there at all (if they were careless enough to not provide any instructions, perhaps they didn't even export it right).
Comment: If I change the remote to my local repo on github and push that there it worked and I was able to see the files. But locally I can't view them
Comment: The files that make up the project _won't_ be in there... you will be able to see them when you checkout a branch (or do a reset). Check the current state of stuff (current branch, what is going on) with `git status`. Given you have only _the repo_ (I would assume), git should say that you are working on some branch and _everything_ is missing.... if that is the case you can do a `git reset --hard` and you are setup to continue with all files in the working tree.
Comment: @eftshift0 the description is saying I have tried that approach already and shared the result of ```git status```
Comment: If the working tree is clean _and_ you have no files, then _perhaps_ you are on a commit that has... _nothing_. (unlikely but still possible)... or you are on an orphan branch? Check `git branch -a` and `git log --all --oneline --graph` if you have something there.
Comment: @eftshift0 running ```git branch``` retuned with branch "main" only. ```git log``` returned with ```(HEAD -> main) Initial commit```
Comment: @eftshift0 probably they did provide a bad export. thx
Answer: It seems you received a mixture of a bare and non-bare repository. Normally if you have files like HEAD, config, packed-refs it's already a repository (without a working tree).
You can try git clone locally from this directory to "un-bare" the repo:
git clone unzipped-dir/ somewhere-else/

Comment: It didn't help remain the same stracture and files

convert git dump into local repo


PreviewKeyDown of checkbox in Multi Select ComboBox in WPF

Question: I use this article to create multi-select ComboBox.
I want to select/unselect the CheckBox inside each item when pressing the Space button.
I tried to add PreviewKeyDown for the CheckBox but the event doesn't get raised.
I also tried adding PreviewKeyDown in the StackPanel but then I can't get the selected item that it's CheckBox is currently checked.
Comment: Add PreviewKeyDown event to main window instead of CheckBox .
Comment: How to get selected item for checked checkbox?
Comment: if (sender is ComboBox  && ((ComboBox )sender ).IsDropDownOpen && (((ComboBox )sender ).Items[0] as CheckBox).IsChecked = true){....}
Answer: You need to handle KeyUp of the combobox and make sure that the dropdown is open.
Update:
<Grid>
    <ComboBox x:Name="cbo" KeyUp="ComboBox_KeyUp" Height="30" Width="200">
        <CheckBox Content="checkbox1"/>
        <CheckBox Content="checkbox2"/>
        <CheckBox Content="checkbox3"/>
        <CheckBox Content="checkbox4"/>
        <CheckBox Content="checkbox5"/>
    </ComboBox>
</Grid>
///////////////////////////
private void ComboBox_KeyUp(object sender, KeyEventArgs e)
    {
        if (cbo.IsDropDownOpen)
        {
          // select first and second
         (cbo.Items[0] as CheckBox).IsChecked = true;
         (cbo.Items[1] as CheckBox).IsChecked = true;

        }
    }

Comment: combobox in open, i want to checked checkbox that in selected item in press space.
Comment: @ar.gorgin I have added some code to give you an idea.
Comment: I use Multi select combobox, I want to add event for items .
Answer: I use EventSetter.
<ComboBox.Resources>

</ComboBox.Resources>

and in code behind.
private void EventSetter_OnHandler(object sender,KeyEventArgs e)
 {
 var item=((ComboBoxItem)sender).DataContext as Node;
 item.IsSelected=!item.IsSelected;
 }


Nginx reverse proxy to private aws s3 bucket bad gateaway

Question: I have created a private bucket on aws and I want to reverse proxy it using nginx.
I have used the same server for all the different proxies.
this is the configuration file for nginx:
user nginx;
worker_processes 1;

error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;

events {
    worker_connections 1024;
}

http {
    server_names_hash_bucket_size  64;
    server {
        listen 80;
        server_name ec2-...-...-....eu-central-1.compute.amazonaws.com;

        rewrite ^(.*) https://$host$1 permanent;
}
server {

    listen 443;
    server_name ec2-...-...-....eu-central-1.compute.amazonaws.com;

    ssl_certificate /etc/nginx/ssl/server.crt;
    ssl_certificate_key /etc/nginx/ssl/server.key;

    ssl on;
    ssl_session_cache builtin:1000 shared:SSL:10m;
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers HIGH:!aNULL:!eNULL:!EXPORT:!CAMELLIA:!DES:!MD5:!PSK:!RC4;
    ssl_prefer_server_ciphers on;

    access_log            /var/log/nginx/ssl_access.log;

    location ^~ / {
        #proxy_set_header x-real-IP $remote_addr;
        #proxy_set_header x-forwarded-for $proxy_add_x_forwarded_for;
        #proxy_set_header host $host;
        #proxy_pass https://url.com;

        #proxy_set_header        Host $host;
            #proxy_set_header        X-Real-IP $remote_addr;
            #proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
            #proxy_set_header        X-Forwarded-Proto $scheme;

            # Fix the "It appears that your reverse proxy set up is broken" error.
            proxy_pass          https://url.com;
            proxy_read_timeout  30;

        proxy_ssl_session_reuse off;
        proxy_ssl_verify off;
    }

        location /one/service {

        # proxy_set_header X-Real-IP $remote_addr;
        # proxy_set_header Host $host;
        # proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
         proxy_pass http://beanstalk-4.212314.eu-central-1.elasticbeanstalk.com/;
         proxy_read_timeout  30;
         proxy_ssl_session_reuse off;
         proxy_ssl_verify off;

        }
        location   /privateproxy  {
              set $s3_bucket        'bucketname.s3.eu-central-1.amazonaws.com';
              set $aws_access_key   'AWSAccessKeyId=mykey';
              set $url_expires      'Expires=$arg_e';
              set $url_signature    'Signature=$arg_st';
              set $url_full         '$1?$aws_access_key&$url_expires&$url_signature';

              proxy_http_version     1.1;
              proxy_set_header       Host $s3_bucket;
              proxy_set_header       Authorization '';
              proxy_hide_header      x-amz-id-2;
              proxy_hide_header      x-amz-request-id;
              proxy_hide_header      Set-Cookie;
              proxy_ignore_headers   "Set-Cookie";
              proxy_buffering        off;
              proxy_intercept_errors on;

              resolver               172.16.0.23 valid=300s;
              resolver_timeout       10s;

              proxy_pass             http://$s3_bucket/$url_full;
        }
}

  }

But I am getting 502 Bad Gateway
Have I done something wrong in the config?
The log file:
2016/03/21 09:13:42 [error] 16695#0: *8 bucket.s3.eu-central-1.amazonaws.com could not be resolved (110: Operation timed out)
Comment: Thank you @Anatoly. I edited my question.
Comment: Show the full Nginx config in order to find another (longer) matched location because AWS returns 2xx or 4xx responses, 5xx looks like your custom application, not AWS. Nginx logs are also require for further analysis.
Answer: If bucket name is correct the problem is with resolver. Described IP address: 172.16.0.23 works as DNS server for non-VPC EC2 only. If you use VPC, resolver should be equal to want you get from:
cat /etc/resolv.conf

For example 10.0.1.0/16 VPC subnet may have 10.0.1.2 allocated as internal resolver. If you don't know which one is used (VPC/non-VPC) then open DNS should help:
resolver 184.108.40.206;

Make also sure you specified plausible S3 bucket name:
set $s3_bucket        '-->>bucketname.s3.eu-central-1.amazonaws.com';

Comment: Yes! That was the issue with the 502 Bad Gateway. Thank you! It has another problem now though.:Code>AccessDenied

Query-string authentication requires the Signature, Expires and AWSAccessKeyId parameters
Comment: @Yianna sure! Please share your S3 URL example first. We also need to know ACL/permissions for particular file.
Comment: The bucket is supposed to be unaccessible from the outside word. I have checked that the url is correct and I found out that my problem is now the signature version 4, since mz instance runs in Franfurt and I am getting "The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256."
Comment: @Yianna how did you generate pre signed URL for S3 content? Do you use up to dated SDK for your platform?
Comment: I tried using aws java sdk to generate the pre-singed url, but I figured out that this needs to be done for every requested item in the bucket seperately, therefore I just used the bucket policy to allow access to a specific ip and keep it private for everyone else. This way no signature is needed. I would still prefer to find a solution for the nginx configuration and signature calculation but this is my workaround to the problem.
Comment: @Yianna to avoid signing each private S3 URL you need to have such Nginx module, which I don't have anything to recommend, we just sign every URL before use, AWS SDK does it job pretty good and fast without making any external calls.
Answer: If the EC2 server where you run nginx is in the same VPC as your private S3 bucket
then you can set up an S3 VPC endpoint and update your bucket
policy to use that endpoint (details here), then just add this to your
nginx.conf:
    location   /privateproxy/  {
          proxy_pass https://bucketname.s3.eu-central-1.amazonaws.com/;
    }

Answer: Consider referencing this project from NGINX. It contains all of the configuration needed to proxy a private S3 bucket.


Is LSI rebuilding as background task

Question: I'm investigating the state of an LSI raid array that might have recently suffered a drive failure.  The array had a spare configured, so the array is not degraded.  However, the storcli command ( /opt/lsi/storcli/storcli /c0/e252 show ) shows that 2 of the drives have a background task (BT:Y) running.
Does that mean it is rebuilding?  What would a background task be?
-----------------------------------------------------------------------------
DG Arr Row EID:Slot DID Type   State BT      Size PDC  PI SED DS3  FSpace TR
-----------------------------------------------------------------------------
 0 -   -   -        -   RAID10 Optl  N  10.915 TB dflt N  N   dflt N      N
 0 0   -   -        -   RAID1  Optl  N   5.457 TB dflt N  N   dflt N      N
 0 0   0   252:0    3   DRIVE  Onln  N   5.457 TB dflt N  N   dflt -      N
 0 0   1   252:1    5   DRIVE  Onln  N   5.457 TB dflt N  N   dflt -      N
 0 1   -   -        -   RAID1  Optl  N   5.457 TB dflt N  N   dflt N      N
 0 1   0   252:2    6   DRIVE  Onln  Y   5.457 TB dflt N  N   dflt -      N
 0 1   1   252:3    7   DRIVE  Onln  Y   5.457 TB dflt N  N   dflt -      N
-----------------------------------------------------------------------------

Is there a way to find out what those 2 drives are doing in the background?
Answer: A background task is one you can issue without impacting array availability - ie: during normal operation.
Array rebuild is such a task, as you can continue using the array during the reconstruction. storcli even has the rebuildrate command to select the rate, in percentage, of the background rebuild task.
However, when a disk rebuilds, its state should be Rbld, while you have Onln. Maybe the rebuild already finished (or never happened) and now the two disks are being checked by a patrol read, which is another background task.
Anyway, you should be able to use the show rebuild command to get the current rebuild state.  As always, be sure to triple check your commands to avoid any unexpected issues.
Answer: Usual background tasks that involve Onln drives are consitency check and partrol read. They are used to detect silent bad blocks that aren't referenced often and so to detect failing drives early, or when information was damaged for some reason (e.g. a bit error) and the RAID redundancy syndrome needs recalculation.
To see if it's ongoing, use:
storcli /cx show patrolRead
storcli /cx show cc

Is LSI rebuilding as background task