rails model relationship

Question: Hi I am really new to rails and I am trying to create a products ratings model.
So there's users (name, email, pw)
Users has a list of products that the user has rated. With a rating (1-10) and a comment.
Each product has its description, a list of the users who rated them, the rating and the comment.
How should I create the relationship? Should I have 3 models, user, rating, product, or can I get by with just user and product?
Also what would be the :has_many .etc relationship look like?
Answer: Here's what I would do
class User
  has_many :ratings
  has_many :products, :through => :ratings
end

class Product
  has_many :ratings
  has_many :users, :through => :ratings
end

class Rating
  belongs_to :user
  belongs_to :product
end

This way if you wanted to get all the users that have rated a product, you can say product.users.
Answer: This would a great case for a has_many :through =>
User Model.
User has_many :ratings
User has_many :products, :though => :ratings

Rating Model.
belongs_to :user
belongs_to :product

Product Model.
Product has_many :ratings
Product has_many :users, :through => ratings

n.b. this is now considered superior to has_and_belongs_to_many which many folks consider to be basically deprecated at this point.
Personally I've never liked using has_many_and_belongs_to, both as it works and also because of the frequent re-work to turn it into has_many, :through as soon as an additional attribute is desired on the join model (ratings in this case).
Actually you want a rating 'level' so you already have a case for the has_many, :through !

rails model relationship


Is it possible to import an SQL file?

Question: I have an SQL database created from another application and I would like to add it to my existing Drupal 8 site. I didn't find a way to do so.
I came across the Data module, but I have no idea how to use it and I don't find any documentation.
Does anyone know how to achieve this?
Comment: This question is way too broad. Yes, of course you can have a database from another application on your server. Yes, you can use that database directly from Drupal, yes, you can add the tables from that database to your Drupal database. But in all these cases you're still going to need code to actually USE that data within the Drupal framework.
Comment: You mean into the database as non Drupal tables (no name collisions)? Yes.
Answer: For usage on Data module please check external documentation https://www.drupal.org/node/2180593
There is another drupal 8 stable module that can be helpful to achieve the results.
You can import the custom sql table into the drupal DB directly and can be used in Drupal Views directly.
https://www.drupal.org/project/view_custom_table
Answer: It really depends on what you want to import.
Migrate is the module suite of choice. See Drupal 8 external content migration translation problem for a multilingual setup ..
Comment: Thanks for your answer. I would like to add tables with data on them. I'll check your recommended module

Is it possible to import an SQL file?


Running a spatial model without having a panel dataset

Question: I am trying to run a linear probability model with spatial lagged Xs in R.
The idea is to have the crime_type_1, a binary variable, as the dependent variable, and the faction as the independent variable that is also a binary variable. I have one observation for each crime committed with information on the date, the neighborhood that occurred, and the faction that committed the crime. This means that I don't have a panel because each date and neighborhood is linked to more than one observation. I tried to run a Morans'I test with the command lm.morantest, but I couldn't because the data has more observations than the spatial weighted matrix, which is the number of neighborhoods.
Below we have a small sample of the data that I am using to run the model.
<code>structure(list(neighborhood = c("CORDOVIL", "COSTA BARROS", "INHOAIBA",
"BONSUCESSO", "BANGU", "SANTA TERESA"), Date = structure(c(12784,
12784, 12784, 12784, 12784, 12784), class = "Date"), faction = c("TRAFICO",
"TRAFICO", "TRAFICO", "TRAFICO", "TRAFICO", "TRAFICO"), crime_type_1 = c(FALSE,
FALSE, TRUE, FALSE, FALSE, FALSE)), row.names = c(NA, -6L), class = c("tbl_df",
"tbl", "data.frame"))
</code>
I would like to know if it is possible to run this model without having a panel dataset. Thank you.
Comment: *I don't have a panel because each date and neighborhood is linked to more than one observation*  Where did you come up with this rule? I've never heard of it. Regardless, it is possible to restructure your data to reflect the simultaneity of the crimes. Let your common unit of analysis be the date and have a set of *faction* and *neighborhood* dummy variables where ones are entered in the rows (dates) when the crime is committed and zero otherwise.
Comment: Kelly's paper *Understanding Persistence* discusses using Matern's function for spatial correlations. https://www.researchgate.net/publication/344044108_Understanding_Persistence
Answer: I understand that the type of data you have is a dot pattern, but you are trying to analyze area data.
For that you would have to geocode these coordinates to get the approximate address of each one and the neighborhood information, but this part of the geocode is not very well formatted, it comes as a string so you would have to get the neighborhood information out of that string and make a table to count how many crimes happened in each neighborhood.
Another alternative would be to use point pattern analysis.
There is a package called spatstat that does this type of analysis.
I never dealt with dot pattern modeling, I just know that it is possible to assign characteristics to these events (which they call the marked point pattern)
https://rpubs.com/spring19cp6521/Week11_Wednesday1 here is information about spatstat.
https://rspatial.org/raster/rosu/Chapter5.html here is an example with crimes and different types of crimes.
I hope it helps.


What PERL env vars need to be set for a local install?

Question: I'm running Centos 7.2, which has Perl 5.16 by default.
Some software one of my users has requested requires at least Perl 5.18, with a preference for 5.22. I've installed 5.24 in /opt/perl/5.24 using:
./Configure -des -Dprefix=/opt/perl/5.24 -Dotherlibdirs=/opt/perl/5.24/lib/perl5 -Uuseperlio

We use Environment Modules, and I only want this one piece of software to use this Perl version - it will otherwise be, in the jargon - "unsupported".
What environment variables now need to be set for the use of that software?
Obviously I'll append /opt/perl/5.24/bin to $PATH, but what other variables does perl need/require - for the installation of modules and etc? (using cpanimus)
I can see there is a $PERL5LIB, and a $PERL_PATH on various posts - but are these canonical for Perl or just related to the posts in question?
Comment: The Programming Perl (third edition, http://www.geos.ed.ac.uk/~bmg/software/Perl%20Books/prog/ch19_02.htm ) would suggest that we only need $PERL5LIB but it also looks out of date.
Answer: I don't think you should need any environment variables to be set, as long as your Perl is installed correctly. Simply invoking your perl interpreter should be sufficient. Environment variables relevant to perl are documented on the perlrun page of perldoc, but variables such as $PERL5LIB are only used to override the normal behavior. You should not need to set them in this situation.


Looking for example(s) of infinite abelian group $G$ , other than $\mathbb Q / \mathbb Z$, such that $\mathbb Z^+=\{o(g):g \in G\}$

Question: Give example of an infinite abelian group $G$ (if exists) , other than $\mathbb Q / \mathbb Z$ , such that $\mathbb Z^+=\{o(g):g \in G\}$ . Please help
Comment: Ah ok, so infinite order is excluded explicitly? Then take $A$ to be any finite abelian group.
Comment: You can still take the torsion subgroup of $S^1$.
Comment: Hint: consider a direct sum of cyclic groups of various orders.
Comment: What is ${\mathbb Z}^+$? Does it include infinity? If not, then $S^1$ is not an example, and if so then ${\mathbb Q}/{\mathbb Z}$ is not an example.
Comment: @Derek Holt : I edited
Comment: $\mathbb Q/\mathbb Z \oplus A$ for any abelian group $A$.
Comment: @MooS: But taking $A:=\mathbb Z$ , what is the order of $(\mathbb Z , 1)$ in $\mathbb Q/\mathbb Z \oplus \mathbb Z$ ?
Answer: $\oplus_{n=2}^\infty \mathbb Z / n\mathbb Z$


Basic question about inequality

Question: let $x>1$
Obviously $x^2>x$
Then $x^2>x>1$
Taking $x^2>1$, we can assert that this holds true for all the values for $x>1$ and $x<-1$
But if I take $-5$ such that $x<-1$, then $x^2>x$ holds but $x>1$ doesn't. Why is it so? Doesn't $x^2>x>1$ mean that all of the three must be true?
Comment: Yes, if you say $x^2 > x > 1$ then both inequalities should hold. Also, you're assuming in the very beginning that $x>1$ so this inequality can't be applied to $x < -1$.
Answer: When you deduced that $^2>>1$, you specifically had the constraint that $x > 1$. Of course, this inequality is not then applicable since now you have $x > -5$ which is a larger domain than $x > -1$.
More specifically, $x > 1 \Rightarrow x^2 > x > 1$ is a true statement, but $x^2 > x \iff x> 1$ is clearly not a true statement as you have demonstrated.
Answer: Yes, $x^2>x>1$ is really shorthand for "$x^2>x$ and at the same time $x>1$". So it doesn't hold for $x = -5$.
You start with "let $x>1$". This is not true for $x = -5$. You do get $x^2 > 1$ in this case, but your argument as written won't get you there. You need a different argument.

Basic question about inequality


Modulation via a major chord, then another major chord a half step down

Question: In Nick Cave's "Darker With The Day", there's a modulation at the end of the chorus which sounds very good (to me), but I don't understand why it works.
The verse is more or less in G major:

GM GMb7 CM Cm

The chorus is in Bb major:

BbM FM Gm FM EbM DM

...and then back to GM starting the next verse. The EbM to DM part is the part I'm wondering about. Why does that make so much sense to my ear? It sort of echoes the "liturgical" sound of the V -> v -> I thing from the verse; is that why?
Outside of this context, it doesn't usually sound all that great to follow a major chord with another major chord one half step down.
Answer: The D major chord is the dominant chord (V) of G major with the next chord being G major it makes sense this modulation would work. Typically in Bb major, you would build a D minor chord instead, but it's not unheard of to use different quality of chords especially when you want to change what chords you emphasis(like utilizing secondary dominants) or modulate. If a D minor chord was used before the D major chord then it could be considered a chromatic median modulation as the quality changing from minor to major fits that description perfectly.
Here is how I would look at it:

Bb major: I  V vi  IV (III or V/ii)
G  major:                  V              I

As you can see the progression starts out squarely in Bb major, but on the D major chord which can be looked as a a chord used to pivot back to G major.
Comment: Ahhh! Thank you. That makes sense now. I was even comparing it to the C major/C minor thing, but I still didn't get it.
Comment: And the fact that you have three major chords (FM EbM DM) stepping down the scale of Bb. This is a logical progression in and of itself.
Answer: If you're still wondering about the chord progression of two major chords where the second one is one half-step lower and the second one also functions as the dominant chord of a tonality, you may want to look into augmented sixth chords, which you can read about here. In your case, the Eb Maj chord would be similar to a German sixth chord in G minor. Though the chord is missing the distinctive raised scale degree four (i.e. C# in G minor) the Eb Maj chord still functions like a German augmented sixth in that it moves to the dominant chord. This is an interesting way to modulate from Bb major to G minor because it uses Bb major's IV chord (the Eb chord) in a context that only really makes sense in a G key.
Comment: Two other factors which make this progression "make so much sense": 1) The modulation is to the key the song started in, and so sounds like a resolution; if the song had started in B flat with the chorus's chord sequence, the modulation to G would be to a *new* key 2) The chorus's G minor sort-of anticipates the later G major. It might prime you into thinking of E flat in terms of a G tonic, which works as Alex explained.


AJAX data transfer between angularjs front-end and nodejs back-end

Question: FYI: There is main question on the bottom if you ever feel like my post is too long ;)
Im trying to build my first angularjs app and now Im stuck with collecting data via ajax from nodejs (express) server.
In front-end Im loading templates with angularjs routers and ng-view. In every route i have template and specific controller (this should be pretty basic thing right?).
OK here comes the wall... I was thinking to put $http.get() to load right stuff for the template from the nodejs server in the controller. With GET I could send variables like this.
<code>$http.get('http://.../API', { params: { twitterData : true,  needed : "data2" } } )
    .success( function(result) {
        // pass result to template.
    });
</code>
And then on the server side get params like this.
<code>router.get('/', function(req, res) {
    this.params = req.query;

    // here run every function and collect it to one object
    // then return it for front-end ajax call.

   res.send(JSON.stringify(collectedDataObj));
}
</code>
collectedDataObj could look something like this:
<code>{ twitterData :
    { thisIs:twitterObject },
    blog : {title: "...", content: "..." }
}
</code>
Collecting data would be by nested callbacks like introduced here http://book.mixu.net/node/ch7.html
So is this "collecting all data in back-end" best way to get data or should I send many ajax calls to collect data for one angular view?
Meaning one $http.get() for getting titter object and one for blog content etc.
And of course if you know some pass me links for good tutos/examples.
Answer: IMO, whenever possible it's best to get everything you can in one request.  Trips back and forth to the server get pretty expensive.


T-SQL Left Outer Join Select Top 1 - MAX

Question: I have data from a table that looks like this:
encounter | prov_id_name
---------------------------
12345678  | 123456ProviderA

I then want to match it up on the provider id from a dimensional table instead of pulling in the substring if there is a match in the dim table.
The dimensional table looks like the following:
orgz_cd | src_pract_no | pract_rpt_name
----------------------------------------
0002    | 123456       | PROVIDER A X
1234    | 123456       | Provider A
4321    | 123456       | Provider A

I used the following SQL worked to get what I needed:
LEFT OUTER JOIN (
    SELECT ZZZ.src_pract_no
    , MAX(ZZZ.pract_rpt_name) PRACT_RPT_NAME
    FROM smsdss.pract_dim_v AS ZZZ
    GROUP BY src_pract_no
) AS MD
ON LEFT(HL7.PRIM_CARE_PROV_NAME_ID, 6) = MD.SRC_PRACT_NO

My question is why did this not work, which is what I originally tried, which would give no results at all:
LEFT OUTER JOIN (
    SELECT TOP 1 ZZZ.src_pract_no
    , MAX(ZZZ.pract_rpt_name) PRACT_RPT_NAME
    FROM smsdss.pract_dim_v AS ZZZ
) AS MD
ON LEFT(HL7.PRIM_CARE_PROV_NAME_ID, 6) = MD.SRC_PRACT_NO

I also tried:
LEFT OUTER JOIN smsdss.pract_dim_v AS MD
ON LEFT(HL7.PRIM_CARE_PROV_NAME_ID, 6) = (
    SELECT TOP 1 SRC_PRACT_NO
    , PRACT_RPT_NAME
    FROM SMSDSS.PRACT_DIM_V
)

I am thinking no results came back or rather it did not work as I expected because the subquery is being evaluated only once for the first result that comes back not finding a match and then that's it, not sure though.
Comment: Yes you are correct, the subquery would only be executed once and there is no guarantee that it would match the ID that you are looking for in your ON condition.
Comment: 1. `TOP(n)` doesn't make much sense without an `ORDER BY`. It just picks an arbitrary record from the matches. 2. `SELECT TOP 1 ZZZ.src_pract_no, MAX(ZZZ.pract_rpt_name)` is invalid without a `GROUP BY ZZZ.src_pract_no`. 3. The original subquery selects one row *per src_pract_no*, your alternative selects one row only.
Comment: Thank you both, so I was on the right track of thinking, just missing a few key points.
Answer: I think you want OUTER APPLY:
OUTER APPLY
(SELECT TOP 1 pd.pract_rpt_name
 FROM smsdss.pract_dim_v pd
 WHERE LEFT(HL7.PRIM_CARE_PROV_NAME_ID, 6) = pd.SRC_PRACT_NO
 -- ORDER BY ?
) MD

Use an ORDER BY if you want a particular name (such as the longest or most recent) when there are multiple matches.


application of FTC to find a function

Question: this is what written in my worksheet:
find a function$"f(t)"$ and a number $"a"$ such that
$$6 + \int_{a}^{x}\frac{f(t)}{t^2} \ dt = 2\sqrt{x}$$
so i change things a bit
$$\int_{a}^{x}\frac{f(t)}{t^2} \ dt = 2\sqrt{x} - 6$$ and differentiating both sides left with respect of $x$ using FTC on LHS and normal differential at RHS and get
$$\frac{f(x)}{x^2}= \frac{1}{\sqrt{x}}$$
then i take
$f(x)=x^\frac{3}{2}$ and $f(t)=t^\frac{3}{2}$ then i take $a=9$ to completing the equation. but i don't know whether this right or not since worksheet doesn't provide answers , so i would thankful if someone could tell me how
Comment: Your answer is correct.
Comment: @KaboMurphy thank you for checking it!
Answer: You have correctly found the function $f(t)$ and the number $a$. You can check your answer by evaluating $f(t)=t^{3/2}$ and $a=9$
$$\int_{a}^{x}\frac{f(t)}{t^2} \ dt=\int_{9}^{x}\frac{t^{3/2}}{t^2}\ dt =\int_{9}^{x}\frac{1}{t^{1/2}}\ dt= \Big[2\sqrt{t}\Big]_9^x=2\sqrt{x}-2\sqrt{9}=2\sqrt{x}-6$$

application of FTC to find a function


How to load multiple html files by using wkhtmltopdf with other options in a batch file

Question: I'm trying to combine multiple html files into one pdf file by using wkhtmltopdf(ver 0.12.6) in a batch file, besides there are some options need to work with.
Since the number of html files that I need may changes before running my batch file, I move all of them in a folder. Therefore my goal is to load all the html files in the folder, add some options I need, and call wkhtmltopdf to generate the pdf file.
Here's what I've done:
<code>@echo off
setlocal
set TARGET=Result

:: go to the folder with lots of html files and one css file
cd .\myfolder

:: convert to a pdf file
wkhtmltopdf ^
--enable-local-file-access ^
--user-style-sheet %TARGET%_Report.css ^
(FOR %%A IN ("*.html") DO %%A) ^
%TARGET%_Report.pdf

cd..
pause
</code>
Sadly it can not work. I think the problem is I can not use FOR loop in this way, but I'm not sure how to fix it.
Here's the error message. Please give me some advise, thank you!
<code>Loading pages (1/6)
Error: Failed to load http:/, with network status code 3 and http status code 0 - Host  not found
Error: Failed loading page http: (sometimes it will work just to ignore this error with --load-error-handling ignore)
Error: Failed to load http:/, with network status code 3 and http status code 0 - Host  not found
Error: Failed loading page http: (sometimes it will work just to ignore this error with --load-error-handling ignore)
Error: Failed to load http:/, with network status code 3 and http status code 0 - Host  not found
Error: Failed loading page http: (sometimes it will work just to ignore this error with --load-error-handling ignore)
Error: Failed to load http:/, with network status code 3 and http status code 0 - Host  not found
Error: Failed loading page http: (sometimes it will work just to ignore this error with --load-error-handling ignore)
Error: Failed to load http://in/, with network status code 3 and http status code 0 - Host in not found
Error: Failed loading page http://in (sometimes it will work just to ignore this error with --load-error-handling ignore)
Error: Failed to load http://do/, with network status code 3 and http status code 0 - Host do not found
Error: Failed loading page http://do (sometimes it will work just to ignore this error with --load-error-handling ignore)
Exit with code 1 due to network error: HostNotFoundError
</code>
Comment: Of course, you cannot use a `for` loop within an argument of another command. So you will have to build the list of HTML files within a variable in advance (using a `for` loop) and use that variable in the `wkhtmltopdf` command line then. Please use the search facility on top of this page to find out how to get such a [list of files](https://stackoverflow.com/search?q=%5Bbatch-file%5D+list+of+files+variable) into a variable…
Comment: thanks a lot, I solved it by using this and use `%files%` while calling wkhtmltopdf:
`set "files="
for %%F in ("*.html") do (call set files=%%files%% %%F)`
Answer: Please try my code
echo on
for /f "delims=" %%a in ('dir /b /s "D:\source folder*.html"') do "directorywkhtmltopdf\bin\wkhtmltopdf.exe" [-s A4] "%%a" "D:\OUTPUT DIRECTORY\pdf%%~na.pdf"
pause
echo off
I try this code and it works
But the result on result.pdf you must go to the last page of your pdf documents to see the result.
I still confused about the result :D
perhaps any helps more
Comment: Use special code formating


Display topic at top of list if has new reply

Question: I have a list of my topics by default it will get the topics where the reply_id is 0 And then arrange them by there date_created.
How every if there is a reply to one of the topics then that topic should go to the top of the list.

Question How can I make sure if there is a new reply to a topic then that topic will go to list.

Currently my var dump as you can see have two items how ever the 2nd array item should be at top because it has a new last post time()
Array
(
    [0] => Array
        (
            [title] => How to
            [author] => demo
            [author_post_time] => Tue Jun 13 , 2017 19:43:01 pm
            [last_post_by] => demo
            [latest_post_time] => Tue Jun 13 , 2017 19:43:01 pm
        )

    [1] => Array
        (
            [title] => How to install codeigniter
            [author] => admin
            [author_post_time] => Sat Jun 10 , 2017 23:26:48 pm
            [last_post_by] => demo
            [latest_post_time] => Tue Jun 13 , 2017 20:48:00 pm
        )

)

Image of database
Model
<?php

class Topic_model extends CI_Model
{
    public function get_active_topics($fid)
    {
        $data = array();

        $this->db->select('t.*, u.username');
        $this->db->from('topics t');
        $this->db->join('user u', 'u.user_id = t.user_id');
        $this->db->where('t.reply_id', '0');
        $this->db->order_by('t.date_created', 'desc');
        $query = $this->db->get();

        foreach ($query->result_array() as $topic_result)
        {
            $reply = $this->get_reply($topic_result['topic_id']);

            // This $date1 just for display only as shown on image
            $date1 = date('D M d', $topic_result['date_created']) . ' , ' . date('Y H:i:s a', $topic_result['date_created']);

            // This $date2 just for display only as shown on image
            $date2 = date('D M d', $reply['date_created']) . ' , ' . date('Y H:i:s a', $reply['date_created']);

            $data[] = array(
                'title' => $topic_result['title'],
                'author' => $topic_result['username'],
                'author_post_time' => $date1,
                'last_post_by' => isset($reply['username']) ? $reply['username'] :  $topic_result['username'],
                'latest_post_time' => ($reply['reply_id'] > 0) ? $date2 : $date1,
            );

        }

        return $data;
    }

    public function get_reply($reply_id)
    {
        $this->db->select('t.*, u.username');
        $this->db->from('topics t');
        $this->db->join('user u', 'u.user_id = t.user_id');
        $this->db->where('t.reply_id', $reply_id);
        $this->db->limit(1);
        $query = $this->db->get();

        if ($query->num_rows() > 0) {
        return $query->row_array();
        }

        return false;
    }
}

Comment: Do you have one or two tables for topics and replies?
Comment: @Tpojka just the one.
Comment: Because this is two tables job. Similar to blog articles and comments with one to many relation between.
Comment: @Tpojka I tried with two tables had no luck so went back to one.
Comment: Study normal forms in DB (tables) design. Especially pay attention on [3rd](https://en.wikipedia.org/wiki/Third_normal_form) one. It should be done logically. If you don't respect some key points of how things need to be done, you are going into issues deeper and deeper and code is becoming hard or impossible to maintain. You need `topics` table with all attributes of topic. Excluding anything that is related to replies. With that, you need `replies` table with all attributes reply needs and with `topic_id` as foreign key. You should go from that point IMHO.
Comment: @Tpojka I went back to the two table way as I tried it first one of the answers suggested to try something like this `$this->db->order_by('r.date_created DESC, t.date_created DESC');` it worked now.
Comment: I didn't understand if you are using one table or two tables design. I don't see that accepted answer include replies table nor replies create date, but if that floats your boat...
Answer: Please try to use below mentioned line, I hope this will fix your issue.
Change From
$this->db->order_by('t.date_created', 'desc');

TO
$this->db->order_by('t.reply_id DESC, t.date_created DESC');

Comment: Vote up from me. I just tried going back to the two table way and tried your way `$this->db->order_by('r.date_created DESC, t.date_created DESC');` this way seem to work now thanks for tip
Comment: @wolfgang1983, Glad to help you out.
Answer: Try ordering your table first by date2 and if that doesnt exist (no reply) then date1. You seem to have it implemented already, you're just ordering by date created on the post.
Comment: $date1 and $date2 are just for the display as you can see in the image at bottom
Comment: sorry, when I said date1 and date2 I meant change this line '$this->db->order_by('t.date_created', 'desc');' to order by most recent reply instead if reply_id is not 0 for any of the topics


Discord.js bot audit logs problems (v12)

Question: I am writing my first bot and I have some problems with audit logs.
I want to create audit logs, which will be sending information, who kicked a member from the server.
I found something on the internet but it is working really weirdly. When I am kicking my test account, it is okay, it shows that I kicked him. But when I want to leave on my own, the log says that I am kicking this test account. What is more, when my friend is kicking this account, it is okay ant it says that he kicked him, but when I am leaving on my own again, it says that this friend kicked him. I don't know how to repair it.
Here's my code:
bot.on('guildMemberRemove', async member => {
    const kanal = bot.channels.cache.get("698649855727501402");
    const fetchedLogs = await member.guild.fetchAuditLogs({
        limit: 1,
        type: 'MEMBER_KICK',
    });
    const kickLog = fetchedLogs.entries.first();
    if (!kickLog)  return kanal.send(`${member.user.tag} left the guild, most likely of their own will.`);

    const { executor, target } = kickLog;

    if (target.id === member.id) {
        kanal.send(`${member.user.tag} left the guild; kicked by ${executor.tag}?`);
    } else {
        kanal.send(`${member.user.tag} left the guild, audit log fetch was inconclusive.`);
    }
});

Comment: It'd be better if you posted your code here and you need to clarify your question more
Comment: I don't know what do you mean with "clarify my question", you mean to add some details or make it more transparent?
Answer: The behavior you are getting is caused because you are always fetching audit logs, and always use latest entry. When you leave on your own, there is no audit log entry generated at all. Additionally, latest entry for your fetch will be the same kick every time you fetch without there being new kick.
To avoid that, you should compare time of when someone left, and when was the log you fetched generated. Note however, that audit logs don't have to be generated immediately, if ever.
Snippet below should allow you to do what you want - it checks if fetched kick log was created over 5s earlier than your fetch. That time window should be long enough to account for delays etc., but you are free to make it smaller.
const logs = await member.guild.fetchAuditLogs({ limit: 1, type: 'MEMBER_KICK' });
const log = logs.entries.first();
if (!log) return;
if (Date.now() - log.createdTimestamp < 5000) {
  kanal.send(`${member.user.tag} was kicked by ${log.executor.tag}.`);
} else {
  kanal.send(`${member.user.tag} left the guild.`);
}

Comment: Okay, I see the problem, but still I can't solve it. How can I get this time?
Comment: Updated answer.
Comment: Thank you very much! I am an idiot, I forget about "Date.now()", which I used 30 lines higher :D Once more, thank you!


Create-react-app with react-router v3 hosted on S3 not working with "fetch as google"

Question: I currently have a React app built with create-react-app using react-router v3 hosted on S3 through CloudFront. The app is the view for a PHP api hosted elsewhere. The react-router is set up to use browserHistory.
Currently we are trying to set up the app so that it can be crawled by google and are testing this with google webmaster tools and "fetch as google".
The homepage fetches no problem but any internal page is unable to even render and returns a "not found".
The site also still has a 404 error show in console when trying to directly navigate to a route in a new tab (but loads the page as expected).
What I've tried so far:
1) importing babel-polyfill at the entry point for the googlebot.
2) set up CloudFront error pages to send 404 responses to /index.html with a 200
3) set the error page for s3 to index.html
From my reading, google shouldn't require server-side-rendering just to crawl the site (SEO is not a concern for us), but none of the other solutions I've found online seem to solve the problem.
Will I need to make the whole app be able to handle SSR, something simple like: https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md#serving-apps-with-client-side-routing, or are there other things I can try that will just make a page crawlable without setting anything up server side?
Any help or direction to further resources would be appreciated!
Comment: Could this be happening because you haven't enabled HTML5 mode?

https://stackoverflow.com/questions/25086832/how-to-stop-in-browser-with-react-router
Comment: @BalmySoftware When I look up html5mode it seems to be referencing '#'s in URLs. My URLs look fine on my end and works as expected when accessing something like https:///category/item through a browser but google is unable to find any page like '/category'
Answer: I found out the solution was pretty easy. In the cloudfront distribution, set the custom error pages to have 404 errors go to the target "/" with a http response of 200.
A lot of other people have it posted with the target as "/index.html", if that doesnt work, just try the above.


Locating bandwidth bottleneck

Question: I am using FFMPEG to encode a video stream that is sent to a server at EC2 through ELB. I was only able to get about 2Mbps/15fps throughput to the EC2 instance.
Through process of elimination, I identified ELB as the bottleneck, they provisioned it at a higher throughput and now things are great (getting a solid 4Mbps/30fps)
How could I identify the bottleneck with a tool such as Wireshark? Is that possible? The process I did for finding it was kind of clunky and sometimes the ELB would auto scale up and fix the problem temporarily. I would expect if I looked at traffic with Wireshark I would see some ICMP responses or something from whichever device is the bottlneck, but I'm not really sure.
Answer: I would take a capture on the client and one on a backend server at the same time. If you analyze the client capture and the delays seem to be server side, but you analyze the server side capture and the delays seem to be on the client side, then it's probably something in the middle introducing delay.
To find delays in a pcap, check out a video I made that shows you how

Locating bandwidth bottleneck


Subscription auto canceled after payment paypal

Question: this is my code (form subscription):
<input type="hidden" name="cmd" value="_xclick-subscriptions">
<input type="hidden" name="business" value="email@example.com ">
<input type="hidden" name="custom" value="<? echo $user; ?>">
<input type="hidden" name="lc" value="ES">
<input type="hidden" name="item_name" value="Pago mensual Monetiza.me">
<input type="hidden" name="item_number" value="1">
<input type="hidden" name="amount" value="39">
<input type="hidden" name="currency_code" value="EUR">
<input type="hidden" name="button_subtype" value="Servicios">
<input type="hidden" name="rm" value="2">
<input type="hidden" name="return" value="<?php echo $urlPredeterminada; ?>pago/ok">
<input type="hidden" name="cancel_return" value="<?php echo $urlPredeterminada; ?>pago/ko">
<input type="hidden" name="no_shipping" value="1">
<input type="hidden" name="image_url" value="http://www.monetiza.me/images/logo-monetiza.png">
<input type="hidden" name="notify_url" value="<?php echo $urlPredeterminada; ?>ipn.php">
<input type="hidden" name="suscripcion" value="si">
<input type="hidden" name="a3" value="39">
<input type="hidden" name="p3" value="1">
<input type="hidden" name="t3" value="M">

This form records the payment and subscription, but after a few minutes the subscription is canceled and get an email confirming that has been canceled. How do I prevent self unsubscribe?
Sorry for my English, i am a peruvian developer :(
Comment: Hi, welcome to stackoverflow. I am not sure your html has something to do with the problem, maybe you can try to give a better description?
Answer: You need to include src=1 to indicate that the payments will recur on a monthly basis:
<input type="hidden" name="src" value="1">


Set Private NuGet Feed API Key on Mac OS X

Question: I'm using Visual Studio Code on Mac OS X to create a .NET Core application. I'd like to package and push this artifact to our internal, private NuGet feed, which is secured via an API key. According to the NuGet documentation, there's a setapikey sub-command on the NuGet binary to configure an encrypted API key in a local nuget.config file.
However, the NuGet binary isn't available on Mac OS X.
➜  dncore11 nuget
zsh: command not found: nuget

Here's the output from dotnet --info:
➜  dncore11 dotnet --info
.NET Command Line Tools (1.0.1)

Product Information:
Version:            1.0.1
Commit SHA-1 hash:  005db40cd1

Runtime Environment:
OS Name:     Mac OS X
OS Version:  10.12
OS Platform: Darwin
RID:         osx.10.12-x64
Base Path:   /usr/local/share/dotnet/sdk/1.0.1

Question: Given the above, how do I set the NuGet API key for an internal feed on Mac OS X?
Answer: If you only have the .NET Core SDK installed then you can run nuget with:
dotnet nuget

Unfortunately the nuget that is included with the .NET Core SDK does not support the setapikey argument. So I think you are going to be left with downloading nuget.exe and installing Mono so you can run that executable and use the setapikey.


Leftmost outermost Reduction (Haskell)

Question: i got the task to use the leftmost outermost reduction on following expression:
f inc expo 9 (f (*2) expo 3 1)

inc is defined as:
 inc :: Int -> Int
 inc x = x+1

expo is defined as:
expo :: Int -> Int
expo x = expo (x*2)

and f as:
f :: (Int->Int) -> (Int-> Int) -> Int -> Int -> Int
f g h a b = g(a-b)

I have absolutely no clue where to start the reduction with more functions. I read the hint that the redex is not contained in any other redexes, but i dont get it ;(.
I would appreciate every tip/help.
Comment: Actually, it will, since expo (`h` in `f`'s definition) is never used (i.e. never applied to anything).
Comment: look at the equation `f g h a b = g(a-b)` and see what g h a b are in `f inc expo 9 (f (*2) expo 3 1)`. This will produce some expression using `inc`, `expo`, `9` and `(f (*2) expo 3 1)`. The next step is to perform the reduction (substitution, if you will) without which you cannot compute g (a-b). So on, until you get a value of type `Int` (or a function, but in this case you will get a Int)
Comment: from your definition of `expo` it will never terminate
Comment: That means i start the reduction with the f function?  Means inc is the "g", expo the "h", 9 the "a" and the rest "b"?
Comment: @fjh english is an annoying language.  what I meant is 'from your definition of `expo` `expo` will never terminate'
Answer: The first (leftmost, outermost) reduction for
f inc expo 9 (f (*2) expo 3 1)

is to apply the definition of f, once, where f g h a b = g(a-b) so we use g as inc, a as 9 and b as (f (*2) expo 3 1), giving
inc(9 - (f (*2) expo 3 1))

Now we're actually done with the question we were asked. That's the leftmost, outermost reduction made. Notice that we didn't need to use any facts about the other functions, which is probably what the hint was getting at.

Leftmost outermost Reduction (Haskell)


Access global variable from external class

Question: How to structure an application so global variables work ?
I'm looking for the simplest way to do something like :
main.py
from Class_A import Class_A

my_var = 3

c_a = Class_A()
print c_a.get_var()
# ==> NameError: global name 'my_var' is not defined

Class_A.py
class Class_A:
    def get_var():
        global my_var
        return my_var

Answer :
Nagasaki45's answer is good, here is how to implement it :
main.py
from Class_A import Class_A
import Global_Vars

c_a = Class_A()

print Global_Vars.my_var
print c_a.get_var()

Global_Vars.my_var += 12

print c_a.get_var()

Class_A.py
import Global_Vars
class Class_A:
    def get_var(self):
        return Global_Vars.my_var

Global_Vars.py
import random
my_var = random.randint(0,100)

This outputs :
17
17
29

Comment: That only makes it *more* important to try to make `my_var` an explicit input and output rather than a `global`; it will make your code much easier to develop, test and debug as you will reduce the dependency between the various modules.
Comment: Is there a particularly good reason `my_var` can't be an instance attribute or method parameter?
Comment: @jonrsharpe I want to be able to use it in lots of modules and not only read it, but also edit it.
Comment: would you please show me an example?
Comment: ...of method parameters? `def get_var(self, my_var):`.
Comment: Hmm, this would be a terrible spaghetti mess, I have a few variables I want to be globals. Plus to edit the variable in one function I'd need to return it and set it again in main script...
Comment: There will be some up-front work to refactor around this, but [structure is key](http://docs.python-guide.org/en/latest/writing/structure/#structure-is-key).
Comment: Structure is important indeed, that's why I prefer to have a variable which is accessible globally than having to pass it to every function, return it, and re-set it every time it's updated.
Answer: If two modules depends on same variable I would move it outside to a 3rd module and import it from there to both of them. Doing so you will end up with much less problems of circular imports.
In any case, the global keyword is used for setting global variables. Don't use it if you only want to get a variable value.
Answer: If you want some object to be shared by other objects, pass this objects to the others, ie:
shared.py :
import random

class Shared(object):
   def __init__(self):
       self.var = random.randint(0,100)

lib.py :
class MyClass(object):
    def __init__(self, shared):
        self.shared = shared

    def get_var(self):
        return self.shared.var

main.py :
from shared import Shared
import lib

shared = Shared()
obj = lib.MyClass(shared)

print "shared.var : ", shared.var
print "obj.get_var() : ", obj.get_var()
shared.var = 200
print "shared.var : ", shared.var
print "obj.get_var() : ", obj.get_var()

Note that you don't need any "global" variable here.
Answer: Hum ... am I totally wrong, of the real answer does not have anything to do with globals ?
You have to know that Python variables are mostly tags that references values. And integer are immutable. So, after that call:
gv.my_var += 12

gv.my_var references a different value (36). This only change this reference. Other references to 24 are not affected.


Magento: Jquery not working however will work in console

Question: I am trying to get a simple jQuery script to work on my magento product page. However after adding the jQuery script to the XML and thus magento being able to read and add the jQuery script in the header... the script still does not work. I then tried putting the script into the chrome console and it worked fine.
<code>$j(document).ready(function(){
    $j("#ship").show();
    $j("#details").hide();
    $j("#sizing").hide();
    $j(".ship").css("text-decoration","underline");

    $j(".ship").click(function(){
        $j(".ship").css("text-decoration","underline");
        $j(".details").css("text-decoration","none");
        $j(".sizing").css("text-decoration","none");
        $j("#ship").show();
        $j("#details").hide();
        $j("#sizing").hide();
    });

    $j(".details").click(function(){
        $j(".ship").css("text-decoration","none");
        $j(".details").css("text-decoration","underline");
        $j(".sizing").css("text-decoration","none");
        $j("#ship").hide();
        $j("#details").show();
        $j("#sizing").hide();
    });

    $j(".sizing").click(function(){
        $j(".ship").css("text-decoration","none");
        $j(".details").css("text-decoration","none");
        $j(".sizing").css("text-decoration","underline");
        $j("#ship").hide();
        $j("#details").hide();
        $j("#sizing").show();
    });

});
</code>
Comment: Have you set jQuery to noconflict mode?
Answer: Use the Jquery.noConflict() function. it will solve the issue
<code><script type="text/javascript">
  $.noConflict();
  jQuery(document).ready(function($) {
    // Code that uses jQuery's $ can follow here.
  });
  // Code that uses other library's $ can follow here.
</script>
</code>


Where did (the language in) this proof of Godel's incompleteness appear?

Question: Many years ago I ran into the following proof of Godel's first incompleteness theorem
(here $T$ is an "appropriate" theory of arithmetic.):

First, we observe that Tarski's undefinability theorem can be slightly tweaked to say that for all $M\models T$, the theory of $M$ can't be the standard part of an $M$-(parameter-freely-)definable set. Next, by the usual representability arguments we have that every computable set is invariantly definable: if $X\subseteq\mathbb{N}$ is computable and $M\models T$ then $X$ is the standard part of a definable set in $M$. Now if $S$ were a computable satisfiable completion of $T$ we would get a contradiction by looking at $M\models S$. If we want, we can then replace "satisfiable" with "consistent" via the completeness theorem.

My question is:

Where did this argument appear?

I'm not interested in the question of whether this is a "genuinely different" argument; rather, I'm just interested in its presentation in terms of invariant definability. This was a notion first introduced by Kreisel following Godel/Herbrand and subsequently studied by others (see e.g. 1, 2, 3). My vivid recollection is that the argument above appeared as a footnote in the first paper mentioned above, but it turns out it's not there after all.
(A related question is when the variant of Tarski's theorem mentioned above first appeared explicitly. Of course the proof really is a trivial variation of the usual argument, but I'm still interested in when it was observed.)
Comment: FWIW my personal take is that it *is* meaningfully different from the other arguments I'm familiar with, but for a very silly reason - see [here](https://mathoverflow.net/questions/72062/what-are-some-proofs-of-godels-theorem-which-are-essentially-different-from-t/353900#353900). That said, it does also have a minor convenience advantage when we generalize it to higher logics appropriately (e.g. [here](https://mathoverflow.net/questions/350303/robinson-arithmetic-for-some-levels-of-l/350378#350378) by using its generalization I avoid needing to talk about the proof theory of infinitary logic).
Answer: Based on the lack of reference provided here and at MO, as well as my own lack of success in finding a reference, I'm going to tentatively say that this particular approach has not appeared as such in print. I'll delete this answer of course if someone supplies a reference in which it appears, but I think at present it's appropriate to move this off the unanswered queue (I've made my answer CW since the line between answer and non-answer here is a bit blurry, so this doesn't feel quite right as a reputation-producing answer).


Cumulative sum counting at different days

Question: Halo everyone.
I have a table with customer behaviour for different customers at different dates.
I need to make a monthly report of these customers, but and one of the columns should include the number of customers with an account different from zero.
My table looks something like this:
CustomerID      Timestamp   Amount
5               1           100
5               1           150
10              1           20
15              1           200
15              1          -150
5               2          -250
10              2           50
10              2           50

The output from the code should be
Timestamp      #Customers with sum(Amount)<>0
1              3
2              2

Since the account for all 3 are positive in first period but zero for customer 5 in second period.
Until now I have only managed to timestamp the data.
My question is then how can one cumulative sum the accounts for each customer  in any timeperiod and count the number of cases where these account are different from zero?
Comment: This is not a cumulative sum, this is a counting per group.
Comment: You could use the query as in @vkp 's answer
Answer: You can get the running sum with a correlated sub-query and get the count of distinct customers for each timestamp with sum <> 0 thereafter.
SELECT timestamp,
    COUNT(DISTINCT customerid) AS count_customer
FROM(
    SELECT customerid,
        timestamp,
        (
            SELECT SUM(amount)
            FROM tablename t2
            WHERE t2.customerid = t1.customerid
            AND t2.timestamp <= t1.timestamp
        ) AS cum_total
 FROM tablename t1
) t
WHERE cum_total <> 0
GROUP BY timestamp;

Edit: You can try using a variable and see if it performs better.
select timestamp,count(*)
from (select customerid,timestamp
      ,case when @customer=customerid then @cumsum:=@cumsum+amount else @cumsum:=amount end as rsum
      ,@customer:=customerid
     from (select customerid,timestamp,sum(amount) as amount
           from tablename
           group by customerid,timestamp) t
     join (select @cumsum:=0,@customer:='') c
     order by customerid,timestamp
    ) t
where rsum<>0
group by timestamp

Comment: The code runs and I am convinced that it is doing the right thing. Unfortunately it stops after 5 minutes because the maximum of time allowed is exceeded. This must be due to the fact that the table you call ''tablename'' consists of 5.960.000 rows.
So is there another and more efficient method?
Comment: see the edit which uses variables to get the running total. Check to see if it's any faster.
Answer: Another option.
Uses an inner sub query to get the unique time stamps (if you had a table of these it would probably be far more efficient, as it could use indexes effectively). This is joined to the table to get all the rows for that day or before, and SUMs the amount, using HAVING to exclude those where the sum is negative.
Then the outer query counts the number of customers returned for each timestamp in the inner query.
SELECT sub1.Timestamp,
        COUNT(sub1.CustomerID)
FROM
(
    SELECT sub0.Timestamp, a.CustomerID, SUM(a.Amount) AS amount_sum
    FROM
    (
        SELECT DISTINCT Timestamp
        FROM amount_table
    ) sub0
    LEFT OUTER JOIN amount_table a ON sub0.Timestamp >= a.Timestamp
    GROUP BY Timestamp,
            CustomerID
    HAVING amount_sum > 0
) sub1
GROUP BY Timestamp

Where this might struggle is returning a row with a count of 0 for a timestamp where there are no customers with a positive amount up to that date. Might not be an issue for you, but if it is:-
SELECT sub1.Timestamp,
        SUM(IF(amount_sum > 0, 1, 0))
FROM
(
    SELECT sub0.Timestamp, a.CustomerID, SUM(a.Amount) AS amount_sum
    FROM
    (
        SELECT DISTINCT Timestamp
        FROM amount_table
    ) sub0
    LEFT OUTER JOIN amount_table a ON sub0.Timestamp >= a.Timestamp
    GROUP BY Timestamp,
            CustomerID
) sub1
GROUP BY Timestamp

Answer: You should consider using a group by clause
select Timestamp, count(customerID) as CustomersWithNonZeroAmount
from tableName
where Amount<>0 group by timestamp

Let me know if this works.


Extract as Numbers from a String to Calculate

Question: I have a vector as below
data <- c("6X75ML","24X37.5ML(KKK)", "6X2X75ML", "168X5CL (UUU)", "168X5CLKK (BUU)")

The above data is basically pack sizes of bottles in a case. What it means is in case of "6X75ML" there are 6 bottles of 75CL (Centi liters) liquid each. For "6X2X75ML" which is basically a promotion pack has 6X2 = 12 bottles of 75ML (Milli liters) in a case.
I need to find the volume in liters available in each case:
e.g -
"6X75ML" should be (6 * 75 * 0.001) = 0.45 Liters
"24X37.5ML(KKK)" should be (6 * 37.5 * 0.001) = 0.9 Liters
"6X2X75ML" should be (6 * 2 * 75 * 0.001) = 0.9 Liters
[there can only be a maximum of 3 digits between the X]
Conversions:
ML - Milli liters
CL - Centi liters
LTR - Liters
1ML = 0.001LTR
1CL = 0.01LTR

In some cases as in the above there could be values like "168X5CLKK (BUU)" where only CL needs to be taken.
I have the below code helping me to find the quantity of bottles in a case
dataList <- strsplit(data, split="X")
Pack <- sapply(dataList, function(x) prod(as.numeric(head(x, -1))))

eg. "6X2X75ML" ll give 12; "168X5CL (UUU)" ll give 168 etc
Working:
strplit breaks up the vector along "X". The resulting list is fed to sapply which the performs an operation on all but the final element of each vector in the list. The operation is to transform the elements into numeric s and the multiply them. The final element is dropped using head(x, -1).
I am not able to find a way around the an efficient way to split the last element to get the volume.
Comment: Does the (KKK) or (UUU) mean anything? You could use regex to strip out anything in parenthesis. Then you can use the second-to-last character to determine what 10^n you want to multiply by. (M, C, or T)
Comment: You should fix your example. You have `"6X75CL"` in the text but `"6X75ML"` in the data.
Comment: Hi all, can any wone check with a few other examples like : "6X180CL (LMD)" , "6X75CL (JIH) (DELIST)". It does not seems to work here.
Answer: data <- c("6X75ML","24X37.5ML(KKK)", "6X2X75ML", "168X5CL (UUU)", "168X5CLKK (BUU)")

Replace ML with X0.001
data <- gsub("ML", "X0.001", data)

Replace CL with X0.01
data <- gsub("CL", "X0.01", data)

split the string and do the multiplication
unlist(lapply(strsplit(gsub("[A-Z() ]*$", "", data), "X"), function(x){ prod(as.numeric(x))}))

Output:
[1] 0.45 0.90 0.90 8.40 8.40

Comment: The output does not match the example
Comment: Adding a space in the regex will fix it
Comment: In your previous answer, switching `"[A-Z()]*$"` for `"[A-Z() ]*$"` would've produced the desired output.
Comment: It is still incorrect. Just do the math by hand `24*37.5*0.001 [1] 0.9`. It's easy to check your answers
Comment: All we have to go on is the description. They are converting measurements to liters. "ML" is 0.001 Liters, and so on.
Comment: Shouldn't the last two be `8.4`? They have `CL` attached
Comment: Hi all, I believe its working ... the problem was on the conversion factor 0.1 and 0.01... need to put in 0.01 and 0.001
Comment: Thanks all ... it has been a great help.... everyone has basically saved 100's on man hours of effort for n number of people.....
Comment: Hi all, can any wone check with a few other examples like : "6X180CL (LMD)" , "6X75CL (JIH) (DELIST)". It does not seems to work here.
Comment: The question has an inconsistency. The given vector is `data <- c("6X75ML","24X37.5ML(KKK)", "6X2X75ML", "168X5CL (UUU)", "168X5CLKK (BUU)")`, but in the example calculations the OP asks for 6 * `75CL` instead of `75ML (as specified in the given vector).`Just correct the vector and the code gives you the correct answer.
Answer: Sathish solution is straightforward.
If you would require to extract and store the volume and number of bottles, you could also use this code:
# Data
data <- c("6X75ML","24X37.5ML(KKK)", "6X2X75ML", "168X5CL (UUU)", "168X5CLKK (BUU)")

# (1) Calculate volume per unit/bottle
# ------------

# Get volume measurement:
# Extract bottle volume and define conversion factor
bottle.volumes.units <- substr(sub(".*X[0-9,.]+", "", data), 0, 2)
bottle.volumes.in.liter <- gsub("ML", 0.001, bottle.volumes.units)
bottle.volumes.in.liter <- gsub("CL", 0.01, bottle.volumes.in.liter)

# Get volume per bottle
# All numbers in every vector
all.numbers <- regmatches(data, gregexpr('\\(?[0-9,.]+', data))
# The volume information for each bottle
bottle.volumes <- as.numeric(unlist(lapply(all.numbers, last)))

# Harmonize volume measuremet to "liters"
bottle.volumes.in.liters <- as.numeric(bottle.volumes.in.liter) * bottle.volumes

# (2) Get the number of units/bottles
# ------------
number.of.bottles.temp <- lapply(all.numbers, function(x)as.numeric(setdiff(x, as.list(bottle.volumes))))
number.of.bottles <- sapply(number.of.bottles.temp, prod)

# (3) Calculate volume
# ------------
number.of.bottles * bottle.volumes.in.liters

# [1] 0.45 0.90 0.90 8.40 8.40


Proof: Every Cyclic Group is Abelian

Question: Dr. Pinter's "A Book of Abstract Algebra"'s chapter on Cyclic Groups presents the exercise:

Prove that every cyclic group is abelian.

Here's my attempt:
By Theorem 1 (of this chapter):

(i): For every positive integer $n$, every cyclic
      group of order $n$ is isomorphic to $\mathbb{Z}_n$.
      Thus, any two cyclic groups of orders $n$ are isomorphic.

Every cyclic group of order $n$ is isomorphic to $\mathbb{Z}_n$. Since $\mathbb{Z}_n$ is abelian under addition, so too then is the cyclic group.
Please let me know if is this a sound proof.
Answer: Your proof works for finite cyclic groups, although it doesn't really get to the heart of why all cyclic groups, including infinite ones, are cyclic.
Suppose that $G = \langle g \rangle$ is a cyclic group, and that $a,b\in G$. Since $G$ is cyclic, we can write
$$a = g^n\\b=g^m$$
for some positive integers $n,m$. Can you use this to conclude that $ab = ba$?
Comment: I can show that $a^{m}a^{n}=a^{m+n}$, and vice-versa, by Chapter 10's Theorem 1: Law of exponents. Is that right?
Comment: Yes that's correct
Comment: @Mathmo123 the above example works only if the operator (*)  is 'product of and b' Can it be extended to other operators too? Is it a valid proof or am I missing something?
Comment: @AnupKumarGupta I'm not sure what you mean. In a group, we have an operator $*$ which obeys certain axioms. The above proof works in any group.
Answer: For finite cyclic groups this is a very valid proof. The only addenum is the infinite cyclic group $\mathbb{Z}$. Of course, it can be proved directly (below) but, the proof you provide is much more revealing to the structure of abelian groups.
Now, consider $x,y\in G$ where $G$ is cyclic. Since $G$ is cyclic, it is generated by some element, say $a$. Then $xy=(a^m)(a^n)$ for some $m,n\in \mathbb{Z}$. Writing out this product, using the associativty, and then recollecting terms by definition of powers we see $xy=a^{m+n}$. Similarly, $yx=a^{m+n}$ so that $G$ is abelian.
Answer: Your proof is OK. But I think that it would be more interesting if you tried to do it without that theorem.
Hint for this:
Call $x$ the generator of the group. What would the other elements be?
Answer: $$\text{Let $G$ be a cyclic group.}$$
$$\therefore \exists n, m \in \mathbb{Z} \text{ such that}$$
$$a=g^{n} \text{ and } b = g^{m} \quad \forall a, b \in G$$
$$\text{and } G = \langle g \rangle \quad \forall g \in  G$$
$$\text{but $G$ is a group} \quad \therefore XY \in G \quad \forall X, Y \in G$$
$$\therefore ab = g^{n} g^{m} = g^{n+m} = g^{m+n} = g^{m}g^{n} = ba$$
$$\therefore ab = ba \quad \forall a, b \in G \quad \therefore G \text{ is a commutative group.}$$

Proof: Every Cyclic Group is Abelian


How to transit data between Java applet and ASP.NET web page?

Question: Is there a way to pass data from Java applet to aspx page and vice-versa?
Comment: *"Is there a way to pass data from Java applet to aspx page and vice-versa?"*  Yes there is, but since a knowledgeable person could write a complete chapter (or a short book) on the subject, this is 'too broad' for SO.
Answer: You can have a look at websocket.
For the java part, I have a good experience with this library:
http://www.ning.com/code/2010/03/introducing-nings-asynchronous-http-client-library/
On the Windows side, there's a problem that websocket is supported since Windows 8. I don't know if it will suffice or if there's some workaround


Como passar o valor de uma variável através de um botão para outra classe em Swift

Question: Tenho uma tela de login, com os campos e-mail e senha. Preciso utilizar em outra viewController o e-mail que foi utilizado para fazer login no sistema. Mas não consigo passar o e-mail digitado no viewController Login para outra viewController.
Comment: Você está usando storyboard? Se sim: http://stackoverflow.com/questions/11577484/passing-variables-between-view-controllers
Comment: Use o método PrepareForSegue
Answer: Se você está usando Segues, basta sobrescrever o método prepareForSegue na sua ViewController de login.
Por exemplo, supondo que a próxima ViewController se chame NextViewController e o ID da sua Segue seja GoToNextSegue, o código ficaria assim:
<code>override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "GoToNextSegue" {
        let vc = segue.destinationViewController as! NextViewController
        vc.email = "aqui você informa o e-mail"
    }
}
</code>
Obviamente, na sua classe NextViewController você precisa ter um parâmetro chamado email que irá receber a informação.
Answer: Caso você não utilize segue, pode passar da seguinte forma
Primeiro na VC-B declare a variavel que vai receber o valor.
<code>//VC-B
class VC_B: UIViewController{
    var Valor:String!

    override func viewDidLoad() {
        super.viewDidLoad()

        print(Valor)
    }
}

//VC_A
class VC_A: UIViewController{

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func AbrirVC_B(sender:UIButton){
       let story = UIStoryboard(name: "Main", bundle: nil)
        let vc:VC_B = story.instantiateViewControllerWithIdentifier("VC_B") as! VC_B
        vc.Valor = "Novo Valor"
        self.presentViewController(vc, animated: false, completion: nil)
    }
}
</code>


Bijection between $\mathbb{N}$ and $A \subseteq \mathbb{N}$

Question: In Appendix B, Theorem B.3 of Introduction to Real Analysis by Bartle & Sherbert, we have to prove the existence of a function $\phi:\mathbb{N}\rightarrow A$, where $A\subseteq\mathbb{N}$ is a non empty and infinite, such that $\phi(n+1)\gt\phi(n) \geq n \forall n \in \mathbb{N}$ and further prove that $\phi$ is bijective.
In the last portion of the proof, where it is claimed that $\phi$ is surjective, we consider least element $p \in A'=A\setminus \phi(\mathbb{N})$, and we claim that $p \in \{\phi(1),\phi(2),\ldots, \phi(p) \}$.
If the latter claim is false, then $p \in A\setminus\{\phi(1),\phi(2),\ldots, \phi(p) \} = A_{p} $. Till here, it is fine.
I couldn't understand what it is said further, that is $\phi(p+1)$ is the least element of $A_{p}$ and thus, $\phi(p+1)\leq p$ satisfies.
Since we are considering $A'=A\setminus \phi(\mathbb{N})$ to be non-empty, should we not consider the possibility that there might exist a number in $A_{p}$ which is less than $\phi(p+1)$ and doesn't belong to $\phi(\mathbb{N})$ i.e. $\phi(p+1)$ is not the least element of $A_{p}$.
Comment: You have not defined $A$.
Comment: I have defined it when I introduced $\phi$
Comment: No, you have not. You ask to prove there exists $\phi$ that has certain properties, among them that its image is called $A.$ What are the initial assumptions about $A, $ besides $A\subset \Bbb N$?
Comment: I suppose the hypothesis on $A$ is that $A$ is not empty and has no largest member. Is that it?
Comment: Yeah, thanks for pointing that out.
Comment: Although there is nothing wrong with using recursion (in which $\phi (n)$ is defined in terms of $\{\phi (m):m<n\}),$ I could give a longer proof using only induction. For $n\in \Bbb N$ define $[[n]]=\{m\in \Bbb N: m\le n\}.$ For $a\in A$ define $a^*=\{b\in A: b\le a\}.$ Now let $\phi(n)=a$ iff $a$ is the $unique$ $b\in A $ such that $[[n]]$ is bijective with $b^*.$  We must prove that the domain of $\phi$ is all of $\Bbb N,$ and has the other required properties.
Answer: I believe that $\phi$ is recursively defined as $\phi(1) = \min A$, and $\phi(n+1) = \min (A\setminus \{\phi(1), \ldots, \phi(n)\})$ for all $n \in \mathbb{N}$, using the well-ordering of $\mathbb{N}$.
If $p \notin \{\phi(1), \ldots, \phi(p)\}$, then $p \in A\setminus \{\phi(1), \ldots, \phi(p)\}$ so by definition
$$\phi(p+1) = \min (A\setminus \{\phi(1), \ldots, \phi(p)\}) \le p$$
since the minimum of the set is $\le$ than any particular element of the set.
But this is a contradiction with the property that $\phi(n+1) >  n, \forall n \in \mathbb{N}$. Hence $p \in  \{\phi(1), \ldots, \phi(p)\} \subseteq \phi(\mathbb{N})$.


Pythagorean Triples : Show that exactly one of $x$, $y$, and $z$ is divisible by $5$

Question: I was doing some basic number theory problems from Rosen and came across this problem:

Show that if $(x, y,z)$ is a primitive Pythagorean triple, then exactly one of $x$, $y$, and $z$ is divisible by $5$.

Book Solution:

We know that $5$ divides at most one of $x,y$ and $z$
If $5$ does not divide $x$ or $y$, then $x^{2}\equiv\pm 1\pmod5$ and $y^{2}\equiv\pm 1\pmod5$
Then $z^{2}\equiv 0,2\ \text{or}\ -2\pmod 5$
But $\pm 2$ is not a quadratic residue modulo $5$
So $z^{2}\equiv 0\pmod 5$, whence $5$ $\mid z$

My Problem:
Can someone help me out in understanding the first point of the solution? I am all thumbs.
Comment: Probably because the solution is very well explained already. If you need help, point out which specific part you do not understand/know
Comment: Related post: http://math.stackexchange.com/questions/1133612
Comment: Should the second bulled be $5\nmid x$ instead of $5\mid x$? (BTW you could include also the name of the book.)
Comment: @JackYoon , edited :)
Answer: Hint: What does 'primitive' mean?

So the statement we are trying to prove here is if $(x,y,z)$ is a primitive Pytagorian triple, that is to say $hcf(x,y,z)=1$ and $x^2+y^2=z^2$, then $5$ divides at most one of them.
If 5 divides all three of them then 5 divides the highest common factor of $x,y$ and $z$ and this is a contradiction.
So suppose 5 divides two of them. Then by the congruence $x^2+y^2\equiv z^2$ (mod $5$) it is clear that the third one must be divisible by $5$ also which is a contradiction. (for example if we assumed $x$ and $z$ to be divisible by $5$ then we obtain $y^2 \equiv 0$ (mod $5$)
Comment: $(x,y,z)=1$ means 5 divides at most two of them. Suppose 5 divides two of them, then?
Comment: yes. You should easily be able to work the statement out from there. It's 'obvious' to those who has intuition for this but for the first learner it might be useful to write the full proof down. (which should be 2-3 lines anyways)
Comment: First statement says 5 divides at most one of them. Which means for now 5 dividing none of them is fine. I noticed there is a typo in the second statement of the book proof. It should be if 5 does not divide $x$ or $y$
Comment: First of all $(x,y,z)=1$ is not equivalent to $(x,y),(y,z)$ and $(x,z)$ being equal to one. (for instance 4,6,7 satisfy the first condition but not the second)

However even with the stronger first condition 5 can divide at least one of $x,y$ and $z$. I don't know where your confusion comes from so I will write the 'full' proof.
Comment: the 'theorem' is something I have proved in my answer. Ie I assumed there exist prime $p$ which divides two elements out of $x,y,z$ which leads to contradiction.
Comment: Thanks @JackYoon , I got it :) Thanks for bearing with me :)
Comment: Hi , @JackYoon , `primitive` here mean that $(x,y,z)$ = 1 ... am I correct ?
Comment: Hi @JackYoon , a bit more help would go a long way -- can't seem to be able to work it out myself ...
Comment: but is it not possible that 5 does not divide either of them ?
Comment: Hi , @JackYoon , but when we talk about `primitive` here -- that means that $(x,y)$ $=1$ ; $(y,z)$ $=1$ ; $(x,z)$ $=1$ ; so how can $5$ $\mid$ any of $x,y,z$ ?
Comment: Hi @JackYoon , but there is this theorem which says : If $(x, y, z)$ is a primitive Pythagorean triple, then $(x, y)$$=$ $(x, z)$$=$ $(y, z)$$=$ $1$ , so how can $5$ even $\mid$  $two$ of $x,y,z$ ?


MySQL replication using DRBD, distributed lock manager?

Question: I need to implement Linux-HA configuration in two servers. I've decided to use DRBD for block level replication on both hosts, mainly for MySQL data replication.
As I understand, in DRBD configuration there's always a primary server, others are slaves (which can have slave of their own).  Replication is only passed to from masters to slaves, not the other way around.
So what happens, if I have MySQL processes performing writes on both servers at the same time, one of which is master, the other is slave?
The slave can perform writes, but no data is written?
Provided that this configuration will go in conjunction with Heartbeat, it would be Heartbeats' job to ensure that MySQL runs only on the master, but lets assume for the moment, that Heartbeat failed for some reason.
Answer: As far as I know, DRBD does partition level replication. The slave does not mount the partition so it cannot write to it. When there's a problem in the master, the slave will mount the partition and start working.
So you can't have both servers writing over the same data.
Comment: Can the slave mount the block device as read only?
Comment: I have not tried it myself but I guess it could be tricky. Because that partition is being updated constantly with information from the master by drbd, I don't know how well will behave mounted, even read-only.
Comment: Unless the underlying filesystem "knows" that the block device is being updated, the block cache will get out of date and the FS will look massively corrupted.
Answer: The commonly used configuration, and one that I've used myself in the past, is to have two nodes with some resources between them. These resources are a DRBD storage block device, a MySQL daemon and on IP address.
The resources can only ever be "up" on on the primary node. Heartbeat takes care of selecting which node is primary and starting the resources in the correct order - tell DRBD to become primary, mount the BD, start MySQL and bring up the IP. They occur in that order to ensure data consistency. You can failover between the primary and secondary nodes manually at your choosing either by demoting the primary or promoting the secondary.
Whilst the primary is up the only actions that the secondary performs is to replicate DRBD data and participate in Heartbeat communications to say that it's alive. During it's time as a secondary, MySQL is never running and you are unable to use the storage block device. The resources can only be used on one machine at a time.
This setup differs to MySQL's conventional "lazy replication" where a secondary machine runs MySQL and store it's own copy of data. Both have their pros and cons. In my experience, if HB is setup correctly and you have a good backup policy in addition, then the LinuxHA approach can provide much better high availability.
Answer: A better solution for MySQL HA is to use circular MySQL replication. This article explains it further, but the basic premise is to make each server the slave of the other. You will need to set up some sort of load balancer in front.
One thing to worry about is that database connections may be long-lived and you will need to configure applications to reconnect if they die.
Comment: Best to put large scare quotes around "better".  Circular MySQL replication is great in theory, but sucks rocks in practice.  BTGTGTTS.
Comment: womble> That sounds like the haggard voice of experience :)
Comment: Far too long spent fighting MySQL replication.  I'm a DRBD replication booster all the way.
Comment: We use MySQL replication in a master/slave configuration without problems on some very large databases. We have a couple of smaller ones using a circular replication scheme, but they don't have much use right now, so I can't say how well it works.
Answer: "Can't happen".  DRBD will ensure that only one server has the block device active at once.  If you get a "split brain", where both DRBD hosts think the other is dead (so they're both active), they won't reconnect and you need to resolve the inconsistency by hand (usually discard the changes on one master or the other).
Comment: Can DRBD be integrated with Heartbeat to rely on it's mechanism of setting the master/slave combo, instead of using it's own? I don't want multiple mechanisms checking for the same thing. Also, can the slave mount partition as read only and would that be enough to run MySQL in "read only" mode on the slave? Thanks!
Comment: For this reason it's best to use a range of alternative keepalive modes. IP to each other, IP to a common host, serial to each other, etc. Then for completeness a STONITH method over the top which ensures that a node really is dead if it claims that it is.
Comment: Karolis> *1* DRBD doesn't have it's own mechanism to promote or demote. It cares only about the consistency of data between two nodes. Whereas Heartbeat does much more. *2* Generally the answer is no you can't mount from the secondary. Not because of DRBD, but because your filesystem would dislike it.
Comment: @Kariolis: With LVM snapshotting, you can take a snapshot of the DRBD volume on the slave and mount that, but updates won't go through.  Apart from that, listen to Dan C, for he knows of what he speaks.
Answer: If you need DRBD "mainly" for MySQL replication, maybe it is easier to use the replication features built into MySQL?
Comment: The usual method of doing MySQL replication, with a master and a slave, is not a HA solution. You would need to reconfigure all your clients to use the slave in the event of the master failing.
Comment: Mainly, but not only. I'm using MySQL 5.0, and a lot of improvements regarding replication came with 5.1 as far as I know.


UIButton shows/hide content

Question: Is it possible that when user clicks on button it shows or hide content. If yes, it is possible animate the transition?
Comment: Please explain which content exactly you want to hide/show.
Answer: YES.
You can create a custom button, add inside it a UILable or UIimage  and hide, show  and animate it as you wish.
tell if you need more details.
Comment: Thank you for reply, so I have to make a "box" and hidding content by animation which using alfa settings?
Comment: Hi tomas, first off all it is better that you will add comments instead of answering your own question. it will keep the thread cleaner. is changing the label alpha is all you need?
Comment: What is displayed in the "box". I think the easiest way is to add a subview and animate the change of alpha of that subview after touch on that button.
Comment: Sorry guys I did not know that new here. In the "box" there are another labels and icons. And under the box there is another one, separated by another picture with another button to hide the second box, and I want if user hide the first box, down box slide up for more space.
Comment: @Itamar: Yes, you can leave comments with a rep of 1 when you originally asked the question.
Comment: well, I think i understand what you want but not sure. can you post your code here.
Answer: Yes it is possible. You will want to use the tap up inside action of the UIButton in interface builder.
As for animating it, just wrap the code with
[UIView beginAnimations:nil context:nil]
//code to animate the view
[UIView commitAnimations]

As of iOS 4, you can use blocks to animate as well. See this for more reference:
http://developer.apple.com/library/ios/documentation/WindowsViews/Conceptual/ViewPG_iPhoneOS/AnimatingViews/AnimatingViews.html#//apple_ref/doc/uid/TP40009503-CH6-SW3
Comment: The event is actually TouchUpInside.

UIButton shows/hide content


vim replace for a pattern

Question:   <created>
    email@example.com
  </created>

I want to replace the above with but the username may vary i.e,firstname.lastname@example.com ,firstname.lastname@example.com...
      <created>
       firstname.lastname@example.com
     </created>

What is the command to replace this in vim
       %s/<created>\r*\r</created>/new string

Answer: It depends on the formatting that you want, but for the specific example that you quote, you could do one of these:
Really simple, without context: replace email@example.com with email@example.com
:%s/pat@c\.email@example.com/g

With context
:%s:<created>\s*\n\s*\zs.\{-}\ze@c\.com\s*\n\s*</created>:tom

By way of explanation:
:%s:XXX:YYY - Substitute XXX with YYY over the whole file (using colons as delimiters to avoid having to escape slashes or @s with a backslash)

where XXX is:
<created> - literal text to search for
\s*       - soak up any spaces or tabs to the end of the line
\n        - a new line character
\s*       - soak up any spaces or tabs at the start of the line
\zs       - special code that says "the match starts here", so only the bit between this and the \ze are actually replaced
.\{-}     - catch any characters, as few as possible - this will match 'pat' in the example above
\ze       - end of the bit we're changing
@c        - literal text - the @ and the start of the domain name
\.        - '.' means any character, so to match a literal dot, you must escape it
com       - literal text - the end of the email address
\s*       - any spaces/tabs to the end of the line
\n        - a new line character
\s*       - any spaces/tabs
</created> - literal match on the terminator (works because we don't use '/' as the delimiters)

and YYY is just the literal string "tom" to insert

An alternative formation:
:%s:<created>\_s*\zs\S\+\ze\_s*</created>:firstname.lastname@example.com

:%s:XXX:YYY: - as before

where XXX is:

<created>  - literal text to search for
\_s*       - search for zero or more white-space characters, including new-lines (hence the underscore)
\zs        - as before, this is the start of the bit we want to replace (so we're not changing the <created> bit)
\S\+       - one or more non-whitespace characters (\+ is one or more, * is zero or more) - this should catch the whole email address
\ze        - as before, the end of the match
\_s*       - zero or more white-space characters
</created> - the end delimiter

YYY is then the whole email address.

I hope that gives you some helpful information.  There are lots of useful reference guides on regular expressions (which is what these are) on the web (although note that Vim uses a slightly different format to most: \+ instead of + etc).  I'd strongly recommend reading:
:help pattern.txt

But bear in mind there's a lot in there, so read it gradually and experiment.  You can also start by using a simple search (press /) and thinking about doing a substitution later, e.g. type:
/<created>\_s*\zs\S\+\ze\_s*<\/created>

Note that I've prefixed the / with a backslash as the search start is /.  A clever trick with this is that :s by default uses the last search, so you can type the line above (/<created>\_s*\zs\S\+\ze\_s*<\/created>) and tweak it until it's right, then just do :%s::email@example.com and since the bit marked XXX above is absent, it'll use your last search and just work!
If there are any bits above you don't understand, :help is your friend.  For example, to find out about \zs, type:
:help \zs

For information about \_s, type:
:help \_s

For general information about :s type:
:help :s

etc...
Comment: Wow, I was in the middle of typing up my answer, but Al here nailed it. +1. Cheers.

vim replace for a pattern


If $\sum_n \frac{1}{a_n} = 2$ where $a_n$ are positive integers, is there a subset such that $\sum_{n\in S} \frac{1}{a_n} = 1$?

Question: As the title says: I'm wondering, out of curiosity, whether any (weak) Egyptian fraction decomposition of 2 always splits into two Egyptian fraction decompositions of 1.  By a "weak" Egyptian fraction decomposition, I mean one where the denominators are not necessarily required to be distinct.  (The problem with normal Egyptian fraction decompositions, where $a_n$ are required to be distinct, would also be interesting.)
In trying to construct a counterexample -- for example by taking enough prime numbers so that $\sum_{k=1}^n \frac{1}{p_k} > 2$, removing the last one, and inserting enough remainder terms to make up the difference -- I run into a tension between having the denominators grow slowly enough for the sum to diverge, and on the other hand having the sum be close enough to 2 that the remainders can't bring the sums otherwise close to 1.  I haven't yet found a way for such an approach to work.
From the other end, I've written a simple Python script to try to search for decompositions of 2, and see for each whether it's splittable into 2 decompositions of 1.  At the current stage, I've been able to run it for lengths up to 7 and haven't found any counterexamples.  But when I try to allow length of 8, the run time (as the script stands) appears to be prohibitive; and if I trace through the decompositions of length 7 or less that it's testing, it appears that length 7 is not yet enough to get any really interesting decompositions.
Comment: This is a duplicate of [this question](https://math.stackexchange.com/questions/2857872/if-sum-of-reciprocals-of-numbers-is-an-integer-then-there-exists-a-subset-with) where solutions with all denominators distinct were found  The largest denominator could be as small as $30030$
Comment: When you write $\sum_{n}$, you mean $\sum_{n=0}^{+\infty}$ or $\sum_{k=0}^n$ ?
Comment: Are the $a_n$s required to be distinct?
Comment: No, they don't have to be distinct.
Comment: I meant a finite decomposition, $\sum_{n=1}^N \frac{1}{a_n}$.
Comment: @RossMillikan OK, I agree this is a duplicate.  Should I jjust delete it, or should we vote to close?
Comment: @DanielSchepler:  I think just close it as a duplicate.  I started it.
Answer: After making some optimizations to the Python script, I was eventually able to find a counterexample of length 8:
$$\frac{1}{2} + \frac{1}{3} + \frac{1}{3} + \frac{1}{5} + \frac{1}{5} + \frac{1}{5} + \frac{1}{5} + \frac{1}{30} = 2.$$
To see this is a counterexample, suppose we had a splitting, and consider the part of the splitting that includes 30.  Then the sum of the reciprocals of the other elements must be $\frac{29}{30}$.  Therefore, that part of the splitting must also include at least one each of the 2, 3, 5 terms.  However, then already, $\frac{1}{2} + \frac{1}{3} + \frac{1}{5} > 1$, giving a contradiction.
If there are no bugs in the Python script, then it appears this is the unique counterexample of length 8 or less, up to permutation.
Comment: What if the $a_n$ are required to be distinct, as is usually required of Egyptian fractions?   See https://en.wikipedia.org/wiki/Egyptian_fraction and
 https://mathworld.wolfram.com/EgyptianFraction.html#:~:text=An%20Egyptian%20fraction%20is%20a,between%205%20and%20101. That is what I assumed was meant in the original question, which made it more interesting.
Comment: Hmm, if the $a_n$ were required to be distinct, then that would probably push it into the realm again where my Python script would be unworkable.
Comment: If uniqueness was required, one might find: https://www.jstor.org/stable/3597210?refreqid=excelsior%3A345b3a13637016edd76c6ff4779c8343&seq=1, to be relevant.
Comment: One potential way of doing it would be a greedy algorithm — start with some set of (probably relatively prime) numbers $\{p, q, r\}$, say, start with the sum $S= 1/p+1/q+1/r$, and at each stage choose the smallest $t$ such that $S+1/t\leq 2$ but none of the partial sums are equal to 1. This will get a little unmanageable as you get too many terms — since there are $2^n$ partial sums to be checked — but for $n$ in the range of 20-30 that's still very feasible, and several different $\{p,q,r\}$ sets could be tested to try and find examples.
Answer: Here's a counterexample with $19$ terms: $2=\sum_{n\in S}\frac{1}{n}$ where
$$S=\{2, 3, 4, 7, 8, 9, 11, 13, 14, 16, 17, 20, 21, 22, 30, 1547, 17017,
612612, 2450448\}$$
You can manually check that this sum is indeed $2$ but no subset of $S$ leads to a sum of $1$.

ADDENDUM: Since the answer is negative, this begets an interesting generalization: Let $r$ be a given positive rational and let $T$ be a finite set of rational numbers in $(0,r)$. Does there exist a finite set $S\subset \mathbb{N}$ such that
$$\sum_{n\in S}\frac{1}{n}=r$$
but
$$\sum_{n\in R}\frac{1}{n}\not\in T$$
for all $R\in P(S)$ (the powerset of $S$)? For example, in the original question $r=2$ and $T=\{1\}$. I would conjecture such an $S$ must exist for all $r$ and $T\subset (0,r)$ but I have no idea how one would even begin such a proof.


Can you solve this problem with functions?

Question: We are given $f(x)=ax^2+2x+b$, a is not $0$, $Df=R$  and $f\circ g=g\circ f$ where $g(x)=x$ has only solution $x_0$. Then we have to show that $ab\leq 1/4$.
Comment: What is Df, Dg, R...? What have you tried, what have you done?
Comment: You should enclose math expressions in dollar signs for them to render properly. If $g(x)=x$ then of course $g\circ f=f\circ g$. What do you mean by $Dg$?
Comment: It seems to be about the equation $f(x)=x$.
Comment: Ok so maybe in Greece we have other symbolisms..:/ Dg is where the function is defined.. So as it is defined in R it can take all the values for x.. Same with Df.. Sorry for the misunderstanding..
Comment: Domain of the function is $\Bbb R$... What else could it mean? But, @Nick, please check if you have copied the correct function for $g$. And which one has only solution $x_0$?
Comment: I have.. $g(x)=x$ and only $g(x)=x$ has the solution Xo
Comment: For $g(x)=x$ we have $f\circ g=g\circ f$ for all functions $f$, so that's not a condition.
Comment: I thought that as Xo is a solution for g(x) then $g(Xo) =0$ and i tried to replace this in the equation $fog=gof$ but i couldn't prove that $ab<=1/4$
Comment: Ok. So.. we don't have $g(x)=x$ for all $x\in\Bbb R$. And.. $x_0$ is the zero of $g$ and not of $f$. Or what??
Comment: I think he means $g(x)=x$ has unique solution.
Comment: Yes that is what I mean... I will explain it again...  $g(x)=x$ has a unique solution Xo. So for X=Xo then $g(Xo)=0$ right?
Comment: No. For $x=x_0$ we have $g(x_0)=x_0$. $\quad$ I guess, some *continuity* of $g$ or something is also assumed.
Comment: But we are given that Xo is a solution for $g(x)$ ...:/ I really think that it means that $g(Xo)=0$ anyways...
Comment: No. I think I got it: $x_0$ is a solution for the *equation* $g(x)=x$. And $g$ doesn't need to be polynomial, neither continuous, just a function..
Answer: If $x_0$ is a solution for $g(x)=x$, then we also have
$$g(f(x_0))=f(g(x_0))=f(x_0)$$
so $f(x_0)$ is also a solution of $g(x)=x$.
By uniqueness, we have $x_0=f(x_0)$, i.e.,
$$x_0=ax_0^2+2x_0+b\\
0=ax_0^2+x_0+b\,.$$
And, as $x_0$ is already a root of this polynomial $ax^2+x+b$, it must have nonnegative discriminant.
Comment: Yes that's what I also find.. And I cannot figure out what I am doing wrong...:/
Comment: you are not given that $f(x)$ has only one solution. You are given that $g(x)$ has only one solution. Which is Xo
Comment: I could take a picture of the exercise but except of the symbolisms everythin is written in greek..:/
Comment: Updated. I got it.
Comment: Ok yeah this is correct... But how do we prove that $ab<=1/4$?


wxpython: How do I examine dragged data in OnDragOver?

Question: I'm a bit perplexed by drag and drop in wxPython (but perhaps this questions pertains to drag and drop in other GUI frameworks as well). The frameworks provides a couple of callbacks (OnEnter and OnDragOver) that purportedly allow me to inform the system whether the current mouse position is a valid place to drop whatever it is that is being dragged. From these methods I can return wx.DragNone, wx.DragCopy, etc. What baffles me is that from within these methods I am not allowed to call GetData, which means I am not allowed to examine the data that the user is dragging. If I cannot see the data, how am I supposed to know whether it is OK for the user to drop here?
Answer: One solution, which is a hack of limited usefulness, is when a drag is initiated, store the dragged data in a global or static reference somewhere. This way, in the OnEnter and OnDragOver handlers, it is possible to get a reference to the data being dragged. This is of course only useful for drags within the same application (the same instance of the application, actually).
Answer: There is no way to see dragged data in OnEnter and OnDragOver methods.
The only solution I found is to store the dragged item in some instance variable that is then readable inside these methods.
Comment: Can you expand on this a little. I was/am planning on using Wx for a fun project. Dragging with a x/y return, was something I was counting on.
Comment: Oh, you CAN see where the data is dropped into, you just cannot see what is being dragged while dragging (before user lets go of the mouse button), which is sometimes useful (e.g. if you want to change the mouse pointer depending on dragged content).


How to find what Authoritative Name Server provided the answer using dig?

Question: I need to check the differences in records on master and slave when making changes.
Is there some option for dig to show which Authoritative Name Server provided the answer?
for example
dig example.com +short +identify
18.104.22.168 from server 192.168.1.1 in 1 ms.

Shows my IP as the source of information not one of the NS records.
How can I found out, where did it get that information?
EDIT:
Output of the Alfred's suggestion
# dig foo.example.com +all

; <<>> DiG 9.9.3-rl.156.01-P1-RedHat-9.9.3-3.P1.fc17 <<>> foo.example.com +all
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN, id: 1612
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 1, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
;; QUESTION SECTION:
;foo.example.com.       IN  A

;; AUTHORITY SECTION:
example.com.        2924    IN  SOA sns.dns.icann.org. noc.dns.icann.org. 2015082460 7200 3600 1209600 3600

;; Query time: 1 msec
;; SERVER: 192.168.1.1#53(192.168.1.1)
;; WHEN: St dec 02 14:36:24 CET 2015
;; MSG SIZE  rcvd: 101

#

Server 192.168.1.1 is localhost (my cashing name server)
;; SERVER: 192.168.1.1#53(192.168.1.1)
I need to find out which Authoritative Name Server provided the answer.
No output for subdomain +nssearch
# dig foo.example.com +nssearch
# dig www.google.com +nssearch
# dig en.wikipedia.org +nssearch
# dig www.fsf.org +nssearch
#

But when asking for the domain which has it's own zone file, +nssearch gives an answer
# dig example.com +nssearch
SOA sns.dns.icann.org. noc.dns.icann.org. 2018050821 7200 3600 1209600 3600 from server 18.104.22.168 in 108 ms.
SOA sns.dns.icann.org. noc.dns.icann.org. 2018050821 7200 3600 1209600 3600 from server 184.108.40.206 in 160 ms.
;; no response from 2001:500:8d::53
# dig google.com +nssearch
SOA ns1.google.com. dns-admin.google.com. 203084235 900 900 1800 60 from server 188.8.131.52 in 25 ms.
SOA ns1.google.com. dns-admin.google.com. 203084235 900 900 1800 60 from server 184.108.40.206 in 25 ms.
SOA ns1.google.com. dns-admin.google.com. 203084235 900 900 1800 60 from server 220.127.116.11 in 25 ms.
SOA ns1.google.com. dns-admin.google.com. 203084235 900 900 1800 60 from server 22.214.171.124 in 37 ms.
;; no response from 2001:4860:4802:34::a
;; no response from 2001:4860:4802:32::a
;; no response from 2001:4860:4802:36::a
# dig wikipedia.com +nssearch
SOA ns0.wikimedia.org. hostmaster.wikimedia.org. 2018031919 43200 7200 1209600 3600 from server 184.108.40.206 in 23 ms.
SOA ns0.wikimedia.org. hostmaster.wikimedia.org. 2018031919 43200 7200 1209600 3600 from server 220.127.116.11 in 139 ms.
SOA ns0.wikimedia.org. hostmaster.wikimedia.org. 2018031919 43200 7200 1209600 3600 from server 22.214.171.124 in 151 ms.
# dig fsf.org +nssearch
SOA ns1.gnu.org. hostmaster.gnu.org. 2941143849 3600 300 3600000 3600 from server 184.108.40.206 in 35 ms.
SOA ns1.gnu.org. hostmaster.gnu.org. 2941143849 3600 300 3600000 3600 from server 188.8.131.52 in 110 ms.
;; no response from 2001:41c8:20:2d3::a
#

Thank you again Alfred.
Comment: The command shows the server IP. What is the question?
Comment: The server (192.168.1.1) does not have a zone file for the domain. I need to find out which authority server provided the answer.
Comment: Could you issue the command provided in the answer and add the outcome to the question? If you issue this command it should return the server.
Comment: And what returns `dig foo.example.com +nssearch`?
Comment: I assume you have replaced foo.example.com with the real address you would like to check? `foo.example.com` should return nothing indeed.
Comment: You could also add `+recurse`, i.e. `dig foo.example.com +nssearch +recurse`
Comment: `dig google.com +nssearch` without `www.` and `dig wikipedia.org +nssearch` instead of `dig en.wikipedia.org +nssearch`. Otherwise the `ns0.` cannot be found
Comment: Oh now I understand. I can use it only on domain which has its own zone file on name server. Thank you Alfred for your patience with me.
Answer: From the man page:

DESCRIPTION
         dig (domain information groper) is a flexible tool for
         interrogating DNS name servers. It performs DNS lookups and
         displays the answers that are returned from the name server(s)
         that were queried. Most DNS administrators use dig to
         troubleshoot DNS problems...

dig foo.example.com +all

Issuing this command returns the server:
;; Query time: 32 msec
;; SERVER: IP#XY(IP)
;; WHEN: Wed Dec 02 14:34:50 CET 2015
;; MSG SIZE  rcvd: 39

  +[no]nssearch
       When this option is set, dig attempts to find the
       authoritative name servers for the zone containing the name
       being looked up and display the SOA record that each name
       server has for the zone.

dig foo.example.com +nssearch

Also check:

Using dig to query nameservers
How do I find the authoritative name-server for a domain name?
Answer:
Check it in the 192.168.1.1 (the caching nameserver) logs.
Or better, simply don't use a caching nameserver:
dig example.com.   @ns-master.example.com.   +short +identify
dig example.com.   @ns-slave1.example.com.   +short +identify
Answer: Using DiG 9.18.10 I got no output when using +nssearch.  I don't know why.
+trace worked, however.


Question about sufficiency

Question: I learned in my (classical) statistics class that (if we have densities) $T(X)$ is sufficient iff $$f(x)= g(T(x))h(x)$$
I am reading "the Bayesian Choice" and there the factorization-lemma is quoted as $T(X)$ being sufficient if $$f(x|\theta)=g(T(x)|\theta)\cdot h(x|T(x))$$
I am slightly confused, why isn`t it
$$f(x|\theta)=g(T(x)|\theta)\cdot h(x)$$
Answer: Thanks for the question (and reading the Bayesian Choice!). If you consider both equations
$$f(x)= g(T(x))h(x)\qquad\qquad(1)$$
and
$$f(x|\theta)=g(T(x)|\theta)\cdot h(x|T(x))\qquad\qquad(2)$$
they are not that dissimilar, once the dependence on the parameter $\theta$ is taken into account. Actually, (1) is not meaningful for sufficiency if the densities $f$ and $g$ are not indexed by a parameter. Sufficiency then corresponds to $h$ not being indexed by this parameter.
This remark being made, (2) appears as a special case of (2), where
$$h(x)=h(x|T(x))$$
The additional conditioning expresses in an informal manner that the density of $X$ is proportional to the joint density of $(X,T(X)$, which can be written as the marginal density of $T(X)$, $g(t|\theta)$, times the conditional density of $X$ given $T(X)$, $h(x|T(x))$. This is informal as one needs to define proper dominating measures and the like.
Comment: There are rogue solution manuals for the BC available somewhere on the Web, but no official version as a subset of solutions is made available for instructors via Springer...
Comment: I was puzzled why h is conditioned on T. Thanks for the explanation!
Comment: I wonder whether it is possible to get a solution manual for the Bayesian choice?

Question about sufficiency


ASIHTTPRequest DB query/get?

Question: I'm trying to use ASIHTTPRequest for the first time and struggling to find an example to do the following;
Input box (user enters a name) with a 'lookup' button, once the user clicks the button, it looks up the DB for that 'name' and if found, returns with the names email address.
There is 2 columns in the DB- 'name' and 'email'.
How could I do the above or is there an example?
Thanks!
Answer: Im assuming this is a remote server DB.
I would suggest using a PHP or similar script to query your DB rather than directly accessing it remotely. This helps with security and simplifies the interface.
Be sure to protect against unauthorised accesss by using an api key-signature method or similar.
Also I would suggest using the NSURLRequest and NSURLConnection classes over the ASI wrapper, they are quite simple to use and avoid third party code.

ASIHTTPRequest DB query/get?


How many automorphisms

Question:
Hello, I remember that the calculation of the self isomorphism is found by symmetry and rotation and I followed this calculation to calculate the self isomorphism of this diagram but answer is wrong. Am I missing some diagram? Or did I make mistakes in the calculation?
Here are my thoughts on the calculation.
I think this triangle has 6 automorphisms, plus rotations, so this diagram has 6*4=24.
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Comment: I would like to know how many automorphisms there should be in the diagram itself and where I am wrong
Comment: An automorphism is a map from one space into itself. I think than you should edit your question to specify what is this space, what is this set, what is made of...
Answer: The vertices of a triangle in this graph cannot be permuted arbitrarily. This already follows from the fact that two of the vertices have degree $2$ and the other has degree $3$.

The graph has exactly one vertex of degree $4$ in its middle, which means that this vertex is fixed under any automorphism.
Then the four neighbours of the middle vertex can at most be permuted. And as the graph is clearly symmetric in this respect, they actually can be permuted arbitrarily, giving rise to a factor $4!$.
Once you have decided how to permute these four vertices, the two other neighbours of each of these can at most be permuted (and they actually can). This gives rise to a factor $2!$ -- for each of the four triangles.

How many automorphisms