get last node given the full path of all ancestor's node attributes using cte

Question: Given the following PostgreSQL table:
items
  integer id
  integer parent_id
  string name

unique key on [parent_id, name]

parent_id is null for all root nodes

Currently I build the sql query manually, doing a join for every path element. But is seems quite ugly to me and of course it limits the possible depth.
Example:
path: holiday,images,spain
SELECT i3.*
FROM items AS i1
   , items AS i2
   , items AS i3
WHERE i1.parent_id IS NULL AND i1.name = 'holiday'
  AND i2.parent_id=i1.id AND i2.name = 'images'
  AND i3.parent_id=i2.id AND i3.name = 'spain'

I wonder if there's a better way, probably using CTE?
You can see how my current code works and what the expected output is here:
http://sqlfiddle.com/#!1/4537c/2
Comment: The question is not very clear. What is "last node" ? What do you need to search if you already have the "full path" to it ? Your table definition is not very helpful either. Maybe add some sample data to the question?
Comment: Extra questions:  1) can there be any other _unmatched_ nodes above i1 ? Between i1 and i2, between i2 and i3 ? below i3 ? If so: do you want these to be retrieved, too? 2) is the _order_ of {holiday,images,spain} in the path important , or could these occur in any order ? BTW: unique index on `parent_id` is impossible (and wrong)
Comment: I just added an sqlfiddle. Last node is the last item of the path (a,b,c,d -> d). I only have the names, not any ids. The name of the node is not globally unique, that's why I have to check all parents. I'm doing this using joins right now, but the number of joins is equal to the number of path elements. Which is bad.
Comment: In my query, i1 is always a root node as the parent_id is null. The patch is complete, so no missing elements. I only need the last node (id would be enough). The order of the path elements is important. Think of it as a filesystem's directory structure.
Answer: update2 here's a function, it peforms well, because search goes only within the path, starting from parent:
create or replace function get_item(path text[])
returns items
as
$$
    with recursive cte as (
        select i.id, i.name, i.parent_id, 1 as level
        from items as i
        where i.parent_id is null and i.name = $1[1]

        union all

        select i.id, i.name, i.parent_id, c.level + 1
        from items as i
            inner join cte as c on c.id = i.parent_id
        where i.name = $1[level + 1]
    )
    select c.id, c.parent_id, c.name
    from cte as c
    where c.level = array_length($1, 1)
$$
language sql;

sql fiddle demo
update I think you can do recursive traversal. I've written sql version of this, so it's a bit messy because of cte, but it's possible to write a function:
with recursive cte_path as (
    select array['holiday', 'spain', '2013'] as arr
), cte as (
    select i.id, i.name, i.parent_id, 1 as level
    from items as i
        cross join cte_path as p
    where i.parent_id is null and name = p.arr[1]

    union all

    select i.id, i.name, i.parent_id, c.level + 1
    from items as i
        inner join cte as c on c.id = i.parent_id
        cross join cte_path as p
    where i.name = p.arr[level + 1]
)
select c.*
from cte as c
    cross join cte_path as p
where level = array_length(p.arr, 1)

sql fiddle demo
or you can build path for all of the elements using recursive cte for that and accumuate your path into array or string:
with recursive cte as (
    select i.id, i.name, i.parent_id, i.name::text as path
    from items as i
    where i.parent_id is null

    union all

    select i.id, i.name, i.parent_id, c.path || '->' || i.name::text as path
    from items as i
        inner join cte as c on c.id = i.parent_id
)
select *
from cte
where path = 'holiday->spain->2013';

or
with recursive cte as (
    select i.id, i.name, i.parent_id, array[i.name::text] as path
    from items as i
    where i.parent_id is null

    union all

    select i.id, i.name, i.parent_id, c.path || array[i.name::text] as path
    from items as i
        inner join cte as c on c.id = i.parent_id
)
select *
from cte
where path = array['holiday', 'spain', '2013']

sql fiddle demo
Comment: I assume that'd have very bad performance as it builds a huge temporary table containing all paths?
Comment: Yes, working on more perfomance-wise version. This one is good if you need to show path for all elements
Comment: Thank you very much for your effort! Too bad I cannot accept two answers, because your final version seems equal to Erwin's.
Comment: It's not exactly equal, but idea is the same
Answer: This should perform very well, as it eliminates impossible paths immediately:
WITH RECURSIVE cte AS (
   SELECT id, parent_id, name
         ,'{holiday,spain,2013}'::text[] AS path  -- provide path as array here
         ,2 AS lvl                                -- next level
   FROM   items
   WHERE  parent_id IS NULL
   AND    name = 'holiday'                        -- being path[1]

   UNION ALL
   SELECT i.id, i.parent_id, i.name
         ,cte.path, cte.lvl + 1
   FROM   cte
   JOIN   items i ON i.parent_id = cte.id AND i.name = path[lvl]
)
SELECT id, parent_id, name
FROM   cte
ORDER  BY lvl DESC
LIMIT  1;

Assuming you provide a unique path (only 1 result).
->SQLfiddle demo
Comment: `where path = array...` is redundant here
Comment: Nice work! BTW: I don't like the `ORDER BY ... LIMIT 1` ; I'd prefer `lvl >=3` (I think the OP wants the offspring of the path. not sure)
Comment: @wildplasser: It depends on the exact requirements. if we know there are always three levels, it would have to be `lvl > 3` or `lvl = 4` in my example, since each row carries the *next* level (one less computation).
Comment: Ah! my bad (off-by-one is my middle name) The problem gets more complex if intermediate (unmatched) nodes were allowed, or the ordering were not imposed; see my comment on the OQ.
Comment: Great! Thank you very much for your effort!
Answer: Too late to post my answer (very equivalent to Roman's and Erwin's) But an improvement on the table definition instead:
CREATE TABLE items
        ( id integer NOT NULL PRIMARY KEY
        , parent_id integer REFERENCES items(id)
        , name varchar
        , UNIQUE (parent_id,name) -- I don't actually like this one
        );                        -- ; UNIQUE on a NULLable column ...

INSERT INTO items (id, parent_id, name) values
        (1, null, 'holiday')
        , (2, 1, 'spain'), (3, 2, '2013')
        , (4, 1, 'usa'), (5, 4, '2013')
        ;


Inference problem, having issues translating problem from words into probabilistic terms

Question: This is the question:
There are particular readers for swipe cards, Under normal operating conditions, there is a small probability of 0.02 that swiping a card fails to open
the entrance - some of these readers have a particular
fault. If this fault occurs, then the probability of swipe failure rises to 0.1.
an estimate says that 22% of all the readers it has sold
so far have this fault. It decides to send technicians around to test all the readers it has sold,
and replace the faulty ones. You are tasked with designing a rule to help the technicians decide
whether or not a card reader is faulty. They are to test each reader by swiping a card through it
repeatedly in successive independent trials, until a failure occurs on the N-th trial. Based on N,
the technician must decide whether or not the tested reader is faulty.
My question and answer:
Translating problems like this from words to math has always been a problem for me; I'm trying to work out the two main random variables as per a question, my answer so far has been that it is two Bernoulli random variables where one describes the probablility of a faulty card reader and the other one describes the probability of swipe failure, where you can use the law of total probability to determine the values.
P(Fail|Fault) = 0.1, P(Fail|Fault') = 0.02, P(Pass|Fault) = 0.9, P(Pass|Fault') = 0.98.
The bit that confuses me is when they ask for the two main random variables, as far as I know N is a random variable too correct? So am I interpreting the conditional variables incorrectly in the above paragraph?
Answer: Welcome to CV. Nice question. Here's my attempt:
Let $X$ be random variable such that $X=k$ denotes, first swipe failure occurs in $k^{th}$ swipe. Let the probability of swipe failure in any random swipe be $p_x$. So we have:
$$X \sim Geometric(p_x)$$
Now define another random variable $Y$ that takes value $1$ if machine is faulty and $0$ otherwise. So  we have:
$$Y \sim Bern(p_y)$$
Also,
$$Pr(X=x)=\sum_y Pr(X=x|Y=y)Pr(Y=y)$$
Now, $$Pr(X=N|Y=1)Pr(Y=1) = (1-p_{x|y=1})^{N-1}p_{x|y=1}p_y = (1-0.1)^{N-1}*0.1*0.22$$
Similarly, $$Pr(X=N|Y=0)Pr(Y=0) = (1-p_{x|y=0})^{N-1}p_{x|y=0}(1-p_y) = (1-0.02)^{N-1}*0.02*0.78$$
Therefore, $$Pr(X=N)=0.1*0.22*0.9^{N-1}+0.02*0.78*0.98^{N-1}$$
Now the technician only observes $N$ and must decide whether machine is faulty. So we are interested in:
$$Pr(Y=1|X=N)$$
Using Bayes:
$$Pr(Y=1|X=N)=\frac{Pr(X=N|Y=1)Pr(Y=1)}{Pr(X=N)}$$
Let us assume that technician decides that the machine is faulty if $Pr(Y=1|X=N)\geq0.95$
So, we finally have:
$$\frac{0.1*0.22*0.9^{N-1}}{0.1*0.22*0.9^{N-1}+0.02*0.78*0.98^{N-1}}\geq0.95$$
From here you can calculate an upper bound on $N$. Hope there aren't any mistakes.
Comment: Thanks for your insight. I didn't think of adopting the probability of a failure into the geometric random variable, and thought my original solution was a bit odd using 2 bernoulli random variables.
Comment: Do you have any reccomendations to get better at translating worded problems into mathematics, or how did you learn this concept?
Comment: @Jeygopi I think as you solve more problems, you get a hang of it. If you are new to statistics, see examples from any standard textbook and solve some problems from its exercise. Also, if you think the above answer is correct please do close the question by accepting/voting the answer, otherwise it remains doubtful whether you found the answer to be correct or not.


Cross platform Membership Provider ASP.NET

Question: I'm trying to work a way to allow for ASP.NET membership to be configured once in the web.config, but be able to be configured against both SQL Azure and also Postgres.
I know there are the Microsoft.AspNet.Providers and also the NauckIT providers, but I really want to just use a single provider that will allow both.
Firstly, is there a membership provider that would allow both Postgres and SQL/SQLAzure?
Alternatively, is there a way to extend the Microsoft.AspNet.Providers to allow it use Postgres for storage? and for the matter SQLite?
Basically, I want to continue to use Membership Class as it's riddled through the codebase.
Any links would be helpful.
Comment: Basically, you want to read [my answer](http://stackoverflow.com/questions/5701673/custom-membershipprovider-in-net-4-0/5702000#5702000) :) Then create your database interface and load the correct source to read and update the membership. Can't be easier ;)
Answer: For asp.net 4.5, there is the new "Identity 2.0", and an extension that allows you to use NHibernate (or various other dbs) as the backing store for it.
Check out:
https://github.com/milesibastos/NHibernate.AspNet.Identity
There is also a nuget package.


Regressive function on singular cardinal with bounded preimage for each point

Question: The claim below is considered obvious in Levy's Basic Set Theory:

If $\kappa$ is a singular cardinal, then there is a regressive function $f:\kappa\to \text{cf}(\kappa)$, such that for all $\gamma<\text{cf}(\kappa)$, the preimage $f^{-1}"\{\gamma\}$ is bounded below $\kappa$.

I don't see why this claim holds. The intuitive thing to try first is to take a cofinal sequence $(\alpha_i\mid i<\text{cf}(\kappa))$ in $\kappa$ with ordertype $\text{cf}(\kappa)$, and think of this sequence as breaking $\kappa$ into intervals. So we would map each $x$ in the interval $(\alpha_i, \alpha_{i+1}]$ to $\alpha_i$. But this doesn't work, because it is unclear where $\alpha_\lambda$ themselves will be mapped to, for any limit ordinal $\lambda$. Enumerating the limit points in $(\alpha_i\mid i<\text{cf}(\kappa))$ and trying a similar map doesn't seem to help either, because we'll need to worry about limits of limits, and so on.
(Edit: as you can see, I was completely confusing myself above. I was trying to map things to the elements on the cofinal sequence, instead of their indices. As a result the map I was trying to define has range way above $\text{cf}(\kappa)$!)
So I am a little bit lost now. Do we need to use Fodor's lemma somehow?
Comment: Fun fact, Azriel wrote the whole book in Plain $\rm\TeX$.
Answer: The regressive condition is trivial to satisfy since $\operatorname{cf}(\kappa)<\kappa$: just let $f(\alpha)=0$ for all $\alpha\leq\operatorname{cf}(\kappa)$.  Then, you can pick a sequence $(\alpha_i)_{i<\operatorname{cf}(\kappa)}$ with limit $\kappa$ and define $f(\alpha)$ to be the least $i$ such that $\alpha<\alpha_i$ if $\alpha>\operatorname{cf}(\kappa)$.
Comment: Wow, I was so occupied with mapping things to elements on that cofinal sequence, without thinking of mapping things to the indices on that cofinal sequence (and my map in the question has range way beyond $\text{cf}(\kappa)$). Thanks very much!


Entity Framework 4 - using DateTime2

Question: I want Entity Framework to store all my dates as DateTime2 data type.
I have ProviderManifestToken="2008" in my SSDL and still all the generated dates are DateTime instead of DateTime2. What am I missing?
Answer: You are not missing anything. Entity framework never uses DataTime2 unless you manually modify its database generation process (only in model first approach). You need to update SSDLToSQL10.tt file to use DateTime2 instead of DateTime. Check the end of this answer for more details about modifying the template and configuring VS to use the new template.

Entity Framework 4 - using DateTime2


superfish menu indent issue

Question: I'm having a css issue where my menus with sub menus are indented differently that my menus without sub-menus. I've tried a number of solutions from google with no success.
For instance if you visit our site and hover over "drinkware" you'll see "liquor flasks" is more indented than the others. And under "home + bar" "man cave ideas" is not as indented as the others. http://www.homewetbar.com/
Can anyone suggest a fix?
Answer: in .sf-menu a.sf-with-ul delete the padding-left line (currently padding-left: 1em;) and leave it like this:
.sf-menu a.sf-with-ul {
    padding-right: 1em;
    min-width: 1px;
}

Comment: That doesn't work the padding-right and padding-left here keep the top navigation from collapsing onto itself (adds the spaces between the dividers) When I remove the padding-left the left side of the main nav runs into the divider and the spacing goes crazy.
Comment: I tried it and it worked perfect, are you sure? Basically that padding left is the indent you want to remove, because the indent for all other li elements is already defined
Comment: Hey Devin that worked. The issue was the aligned on the left was then different. So following your code change + adding padding-left 0.2em in the .sf-menu li { } class above that fixed it. Thanks!

superfish menu indent issue


Remove forum comment title

Question: I'm having problems with removing the title of comments on my forum.
I'm using the advanced forum module and the 'comment title' option is disabled. Anyone knows how to remove it? Thanks!
Answer: First install the devel module and then check the theme registry to see if the forum form is in the theme registry or not. for more information about registering a form visit this page. as an example to register the comment form you must use this code:
function YOUR-THEME-NAME_theme($existing, $type, $theme, $path) {
    return array(
           'comment_form' => array(
               'render element' => 'form',
            ),
       );
};

When checking the existence the form theme in theme registry make sure that you use the YOUR-THEME-NAME as administrator theme.
Now use the hook_form_id_alter to customize the form.to see the form elements write:
kpr($form);

now you can hide or change the order of form elements.
Here is the video tutorial

Remove forum comment title


Regular data gaps in a time series

Question: I've been looking at attendance data for a college library taken during finals week when the library was open for 24 hours. However the staff only took head counts during the hours of 12am to 6am (7 data points per night, for about 11-12 nights, 3 semesters worth of similar counts). I was wondering if, because the data isn't "continuous" I can really make anything analysis on it, since it seems to create a cyclical pattern different from what I would see over a true 24 hour period.
Do you think the data is still usable?
Also if anyone knows of any special tool applicable to time series analysis using attendance data, where we want to know how many are using the library and how to get more people to attend, I would be extremely grateful, as I'm new to statistical analysis in general. Thanks!
Comment: Is 12am midnight? If so you are probably missing most of the use of the library, and can only draw conclusions about night studying.
Comment: I am a little confused by your question. Do you have data for attendance for 18 hours per day over a few years and data for only 7 hours during finals week ? Perhaps if you actually posted the observed data I might be able to help. I have been involved with passenger data on an hourly basis for the Paris subway system. We have found that the intra-day distribution is quite different for different days of the week (weekdays vs weekends) and also very dependent on holidays/events.
Answer: We have seen similar problems where there is mixed frequency. For example certain beers are only made 4 months of the year. One can string out the data 7 values for day1 followed by 7 values for day2 ,etc . What we have done is to create 6 dummies for hour of the day reflecting the "fixed effects due to hour" and in this case 6 dummies reflecting day of the week. Additionally you might include interaction effects reflecting the hour-day interaction. There may also be a semester effect that might be significant . Again a set of dummy variables for the semester contrast might be a good idea. One can also include the "free coffee indicator" . Care should be taken to ensure that any outliers get neutralized by incorporating special 0/1 variables for any identifiable anomalies. In this way the "unusual values" won't bias the result. Now additionally there may have been a number of students effect and heretofore unknown deterministic policy changes that might be important to detect. I can suggest Intervention Detection procedures to fish these unknown variables out of the residuals , so to speak.
Answer: It makes no sense to slap the 7 points/day together in a contiguous fashion as your answer suggests, unless you're continuing to track the $\delta t$ between the points and treating the time series as irregularly sampled. You can compute things like (where evening = 12-6am):

Mean head count per 'evening'
Max head count per 'evening'
Min head count per 'evening'

and then analyze the time series consisting of one of  the daily statistics. These would be spaced evenly in time and you might be able to come to some conclusions about them.
Do you have a specific objective in mind for this data, i.e. are you trying to demonstrate decreased usage of these 'all-night' time slots at the end of the exam period?
Comment: I can't give out the data, sorry. 12am is midnight. There is a head count of all students in the building taken at 12am, 1am, 2am, 3am, 4am, 5am, & 6am. This was done each night for the week before and during finals, 11-12 days depending on the semester. Each semester is comprised of these 11-12 day sets. My question is really whether it is ok to put together the 12am-6am data points in one long graph. Its obviously cyclical because there is an 18 hour gap. How do I get rid of or account for that? Is it ok to just ignore the gaps and look at it as any other time series?
Comment: As I mentioned, I am very very new to statistical analysis; could you please explain delta t or at least give me a term to google?

My objective is to identify trends that can be manipulated to drive more people into the library. For example, does giving out free coffee in semester 3 drive more people to study at the library?

Thank you setting me straight on using these as contiguous data.
Comment: $\delta t$ refers to the delta (or relative) time between points. So in your case, between the sample at midnight and 1am, there is a $\delta 1 = 1$ hour.

From your description, it sounds as if what you're mostly interested in is total library usage, which can be represented (in a daily sense) as either the **sum** of all head counts or the **mean** of all head counts. If you convert your data from 7 pts/day into 1 pt/day and plot each Semester individually, you *may* then be able to draw some conclusions about your samples.

Regular data gaps in a time series


Best filesystem for VM storage?

Question: What is the best file system for storing VM images?
I am looking for features that can save some disk space like compression, deduplication, etc. ZFS is known...but any other alternatives in Linux world?
How good is the new EXT4 filesystem for workloads like VM?
Comment: apologize for not realizing my open-ended question. My primary intent was to see if there are any ZFS alternatives in Linux/Unix world that offer facilities like dedupe/compression..
Answer: Let's clear this up, for ESX/ESXi vmdk's can ONLY be stored on VMFS and NFS file systems - presumably what you're talking about is the underlying filesystems of the storage behind this. If this is the case what you'd basically saying is 'what sort of storage should I use' - and that's an extremely open question that you haven't provided enough information to help you with - so it'll be impossible to answer properly without extra constraints.
As far as I'm aware the 'best' mechanism for VM storage in terms of performance right now is by using FusionIO's PCIe-based flash storage set to emulate local DAS. The 'best' in terms of cheapest varies enormously based on volume from cheapo DAS to building your own NFS/iSCSI NAS/SAN box up to good value but still expensive FCoE SANs.
Basically we can't answer your question.
Comment: apologize for not realizing my open-ended question. My primary intent was to see if there are any ZFS alternatives in Linux/Unix world that offer facilities like dedupe/compression..thanks for your reply
Comment: PCIe-based flash to emulate local DAS? Can this be used for caching like ZFS ZIL, L2ARC?
Answer: "Best" is very subjective based on budget, requirements etc.  I would recommend that unless you realy want a cheap test type environment you should go for a SAN based storage array e.g. iSCSI.  If you have 2 ESX hosts this then gives you the option to do vMotion which allows you to upgrade one host at a time whilst keeping all the servers running - i.e. no down time.
If you use thin provisioning then disk case can be saved as it is used as and when it is needed rather than in advance.
Comment: "iSCSI" is a way to share the disk space...not really a SAN. I was looking for a DIY solution...

Best filesystem for VM storage?


Trying to install Drupal modules and themes: keep getting error "does not contain any .info.yml files."

Question: I am new to Drupal. I am running Drupal 8. I have tried to install three different themes and modules, and keep getting this error:

does not contain any .info.yml files

Including with the Beale Street module with a 8.x release.
Why am I seeing this error? Are .info.yml files a newish requirement that most themes don't have yet? Where can I get themes that include <code>.info.yml</code> files?
Answer: TL;DR you're trying to install a theme or module in Drupal 8, which doesn't contain the required files. You might be trying to install a Drupal 7 (or earlier) module by mistake, or it may not be a Drupal module at all.
The 8.x-dev branch of the Beale Street theme is most definitely not Drupal 8 compatible. It's a straight copy of the current 7.x-dev branch, so it hasn't been converted yet. The maintainer has said as much.
Converting a module/theme from 7.x to 8.x requires a lot more work than just adding a yaml file, and if you don't find one in a particular release you can safely assume it hasn't been converted yet.
There are lists of modules and themes on Drupal.org that are tagged with 8.x. As you've seen, not all of them are ready yet. Bear in mind quite a few will still be in -dev, so they're not expected to be useable.


How to allow more roles can add users in Drupal 7?

Question: I have created Four Roles – A, B, C, D
Home » Administration » Configuration » People – I have set visitors can create an account. A, B, C roles could register from my front end site. And I want that My C role users could create A and D role accounts. I have assigned permissions "Administer users" and "View user profiles" to my C role user. Now my C role user can view link "admin/people". Here I want to control "Show only users where" and "Update options" form.
Just like - "Show only users where" form shows only two roles A and D and other relevant thinks
Please give me some advice...
My English is not good... Sorry for it
Answer: You can do this using Views and Views_bulk_update module. First, install both these modules. Don't forget to enable views_ui module also.
Then go to Structure->Views. Create a new view with page-display and fetching user's data.
Now, add the relevant fields there, like user-name, email etc. Now, in the filter section, add a filter of "role" and expose it. You can add more filters and expose them.
Also, add fields regarding bulk operations and select the operations you wish to perform e.g. changing email, deleting user.
Now, give this page a "path" in the page-setting section.
Finally, save this view and go to the path you gave it. It should be up and running.
PS: If you couldn't comprehend above, you will need to learn views module. It's a very powerful module and needs some time to grasp. See some videos on youtube to learn it. For your simple purpose, it would take an hour or so to learn.


rsyslog change timestamp format for specifix filter

Question: I wish to change my rsyslog timestamp format to RFC-3339 of specific log file (msg).
I have the following file /etc/rsyslog.d/10-zn.conf
with the following content:
:msg, contains, "my_prefix"       /var/log/zn.log

which means that save to /var/log/zn.log all of the lines which contains "my_prefix".
I wish to change the timestamp from RSYSLOG_TraditionalFileFormat which is %b %d %H:%M:%S
to RFC-3339 but I can find out how to do it just for the logs which contains my prefix, is there any way to do it?
thank you
Answer: Found the right configuration
if $msg contains '{{my_prefix}}' then {
        action(type="omfile" file="/var/log/zn.log" template="RSYSLOG_FileFormat")
}

RSYSLOG_FileFormat template already come with RFC3339 timestamp


Evaluate $\frac{1}{4}\int \frac{dx}{(kx^{2}+ax+b)^{2}}$

Question: I would like this integral:
$$\frac{1}{4}\int \frac{dx}{(kx^{2}+ax+b)^{2}}$$
I used substitution $x+ \frac{a}{2k} = \frac{\sqrt{4kb-a^{2}}}{2k} \tan \theta$.
This will reduce the denominator to
$$
\left(\left(\frac{\sqrt{4kb-a^{2}}}{2k}\tan\theta \right)^{2} + \frac{4kb-a^{2}}{4k^{2}}\right)^{2} = \left(\frac{4kb-a^{2}}{4k^{2}}\right)^{2} \sec^{4}\theta ,$$
and integral is reduced to
$$\frac{1}{4k^{2}}\frac{16k^{4}}{(4kb-a^{2})^{\frac{3}{2}}2k} \int \cos^{2} \theta d\theta = \frac{2k}{(4kb-a^{2})^{\frac{3}{2}}}\left(\frac{\theta}{2}+\frac{1}{4}\sin(2\theta)+c\right)$$
$$= \frac{2k}{(4kb-a^{2})^{\frac{3}{2}}} \left(\frac{\arctan\left(\frac{2k(x+\frac{a}{2k})}{\sqrt{4kb-a^{2}}}\right)}{2}+\frac{\sin(2 \arctan\left(\frac{2k(x+\frac{a}{2k})}{\sqrt{4kb-a^{2}}}\right)}{4}\right).$$
Is there a simpler solution?
Comment: You can look up a closed form for this integral [here](http://en.wikipedia.org/wiki/List_of_integrals_of_rational_functions#Integrands_of_the_form_xm_.2F_.28a_x2_.2B_b_x_.2B_c.29n). If you want the method, I'll post an answer.
Comment: @Dylan I propose this formula in my answer, I would like to know your method to make the calculus so If you can answer I would be very nice ! :)
Comment: @Shadock I've posted my answer :)
Answer: Hint: Evaluate first $I(b)=\displaystyle\int\frac{dx}{kx^2+ax+b}$ , and then differentiate with regard to b.
Comment: Ah, Feynman's trick :)
Answer: Based on your work, I'm making the assumption that determinant $\Delta = a^2 - 4kb < 0$
To make this simple, I'm going to write
$$ kx^2 + ax + b = k \left(x + \frac{a}{2k} \right)^2 + \frac{4kb - a^2}{4k} = k(u^2 + m^2) $$
where $u = x + \frac{a}{2k}$ and $m = \frac{\sqrt{4kb - a^2}}{2k}$. We have
$$ \int \frac{dx}{(kx^2 + ax + b)^2} = \frac{1}{k^2} \int \frac{du}{(u^2 + m^2)^2} $$
The trick is performing integration by parts on this integral
$$ \int \frac{du}{u^2 + m^2} \tag{1}$$
We should get
$$ \begin{align} \int \frac{du}{u^2 + m^2}
&= \frac{u}{u^2 + m^2} + \int \frac{2u^2}{(u^2 + m^2)^2} \\
&= \frac{u}{u^2 + m^2} + \int \frac{2(u^2 + m^2) - 2m^2}{(u^2 + m^2)^2} \\
&= \frac{u}{u^2 + m^2} + 2 \int \frac{du}{u^2 + m^2} - 2m^2\int\frac{du}{(u^2+m^2)^2}
\end{align} $$
Rearranging the terms
$$\int \frac{du}{(u^2 + m^2)^2} = \frac{u}{2m^2(u^2 + m^2)} + \frac{1}{2m^2} \int \frac{du}{u^2 + m^2}$$
As you might know, $(1)$ is just the arctangent function:
$$ \int\frac{du}{u^2 + m^2} = \frac{1}{m}\,\arctan \left(\frac{u}{m} \right) + C $$
And so
$$\int \frac{du}{(u^2 + m^2)^2} = \frac{u}{2m^2(u^2 + m^2)} + \frac{1}{2m^3} \,\arctan \left(\frac{u}{m} \right) + C$$
After some algebra:
$$ \int\!\frac{dx}{(kx^2 + ax + b)^2} = \frac{2kx + a}{(4kb-a^2)(kx^2 + ax + b)} + \frac{4k}{(4kb - a^2)^{3/2}}\, \arctan \left(\frac{2kx + a}{\sqrt{4kb - a^2}} \right) + C $$
Comment: Wow ! Nice ! :)
Answer: The method is correct. You just made some computational mistakes.
You got the substitution and denominator correctly.
The integral is reduced to $\frac{1}{2\sqrt{4bk-a^2}}\int \cos^2{\theta} d\theta$. You also did the integral correctly.
Answer: I don't know the demonstration but I have this formula :
$$
\int \frac{dx}{(ax^2+bx+c)^2}=\frac{2ax+b}{(4ac-b^2)(ax^2+bx+c)}+\frac{2a}{4ac-b^2}\int \frac{dx}{ax^2+bx+c}
$$
And after you can use one of this for the second term (it depends on your discriminant)
$$
\int \frac{dx}{ax^2+bx+c}=\frac{1}{\sqrt{b^2-4ac}}ln\left(\frac{2ax+b-\sqrt{b^2-4ac}}{2ax+b+\sqrt{b^2-4ac}}\right)
$$
Or
$$
\int \frac{dx}{ax^2+bx+c}=\frac{2}{\sqrt{4ac-b^2}}*tan^{-1}\left(\frac{2ax+b}{\sqrt{4ac-b^2}}\right)
$$
Shadock


Visualizing the intersections of many sets

Question: Is there a visualization model that is good for showing the intersection overlap of many sets?
I am thinking something like Venn diagrams but that somehow might lend itself better to a larger number of sets such as 10 or more. Wikipedia does show some higher set Venn diagrams but even the 4 set diagrams are a lot to take in.
My guess as to the final result of the data would be that many of the sets won't overlap so it is possible that Venn diagrams would be fine -- but I would like to find a computer tool that will be able to generate that. Its looks to me like Google charts doesn't allow that many sets.
Comment: Related, but for small number of sets (for reference): http://stats.stackexchange.com/questions/4211/how-to-visualize-3d-contingency-matrix
Answer: When you have a large number of sets, I would try something that is more linear and shows the links directly (like a network graph).  Flare and Protovis both have utilities to handle these visualizations.
See this question for some examples like this:
Comment: Nice graph, but it doesn't answer the initial question, as you can't represent the intersection of 3 or more sets. Is there a variant of it that does ?
Comment: I'm not aware of any way to do it; my webvis package provides a wrapper for Protovis, but it would be a lot of work to get it to make this graphic.  Incidentally, this paper introduces the "arc diagram" which is related: http://ieg.ifs.tuwien.ac.at/~aigner/teaching/ws06/infovis_ue/papers/arcdiagram_01173155.pdf
Comment: @suncoolsu , the R package diagram may be able to do the same "arc diagram" Shane pointed to. It looks like it would be hard work though to get the "plot web" to look like the visual above though. http://cran.r-project.org/web/packages/diagram/vignettes/diagram.pdf .
Comment: (+1) Nice answer! - I especially like the graphics. I was wondering if there is a way to do this in R?
Comment: and Andy. Thank you for your answers. @Shane, I have seen your webvis package. But I still need to explore it further. I do like protovis graphs a lot. They have a great website.
Comment: @suncoolsu Regretfully, the package is far from "complete" and I have very little time to spend on it.  Maybe one of these days.  I'd love to expose things like the above graphic so that they would be trivial to create.
Comment: It would be great if you give a basic output of the command with two example sets.
Answer: This won't compete with @Shane's answer because circular displays are really well suited for displaying complex relationships with high-dimensional datasets.
For Venn diagrams, I've been using the venneuler R package. It has a simple yet intuitive interface and produce nifty diagrams with transparency, compared to the basic venn() function described in the Journal of Statistical Software. It does not handle more than 3 categories, though. Another project is eVenn and it deals with $K=4$ sets.
More recently, I came across a new package that deal with higher-order relation sets, and probably allow to reproduce some of the Venn diagrams shown on Wikipedia or on this webpage, What is a Venn Diagram?, but it is also limited to $K=4$ sets. It is called VennDiagram, but see the reference paper: VennDiagram: a package for the generation of highly-customizable Venn and Euler diagrams in R (Chen and Boutros, BMC Bioinformatics 2011, 12:35).
For further reference, you might be interested in

Kestler et al., Generalized Venn
  diagrams: a new method of visualizing
  complex genetic set relations,
  Bioinformatics, 21(8), 1592-1595
  (2004).

Venn diagrams have their limitations, though. In this respect, I like the approach taken by Robert Kosara in Sightings: A Vennerable Challenge, or with Parallel Sets (but see also this discussion on Andrew Gelman weblog).
Comment: It looks good. i would have loved it if it would accept non numericals. It seems one has to transform their data to a numerical list first.
Comment: For practical purposes, it would be awesome to include some screengrabs
Answer: We developed a matrix-based approach for set intersections called UpSet, you can check it out at http://vcg.github.io/upset/. Here is an example:

The Matrix on the left identifies the intersection a row represents, the last row here, for example, is the intersection of the "Action, Adventure, and Children" movie genres. The bars to the right show you the size of the intersection, 4 in this example.
You can also plot attributes of the intersections or other selections, etc. Check out the website for details.
There is now also a static version for R which you can find on the website mentioned above, or by going here: https://github.com/hms-dbmi/UpSetR/
A state of the art report on set visualization is accessible at http://www.cvast.tuwien.ac.at/SetViz - most of these are academic though and don't come with readily available code.
Comment: As for me the image you posted is rather an example of overplotting, with too much information packed up on a single plot...
Comment: @Tim. While I understand what you're saying, it isn't really overplotting as all visual elements are clearly visible and separated. You could argue the plot is too complex to readily discern but this could just as well be related to you not being trained in using the plot - not all visualizations can or should be aimed at untrained users, as simplifications often lead to limited scope (e.g. poor scalability of venn diagrams)
Comment: @ThomasP85 there was much research that shows that people are really *bad* in visual interpretation of plots (even "the" experts) including even such basic stuff like pie charts. In most cases complicated visualization leads to misinterpretations and misunderstandings.
Comment: @Tim I agree that simple is always better, but complex questions sometimes have complex answers. The reason this question was posed in the first place is that there, to this date, isn't a compelling, simple visualisation technique to deal with large numbers of set intersections. The accepted answer only concerns itself with 2-degree intersects which, as the number of sets increase, are a smaller and smaller part of the total number of intersects.
Comment: ... and your example with pie charts are related to the fact that humans (expert or not) are horrible at comparing angles, which is why pie charts should never be used :-)
Comment: Also, the fundamental part of this chart is only a matrix that identifies the set combination and the bar charts. Here are examples of the simplest version: https://goo.gl/QL1jTB

This does exactly what a venn diagram can do. The deviation plots and the box plots show data that you couldn't sensibly plot in a venn diagram, but you don't have to use that.


Insert same row values except some columns

Question: I have a table like this but not just 5 columns(maybe greater than 10)
ID  |   FileName    |   Type    |   Other1  |   Other 2
1       image1.eps      3           assff       12321
2       image2.eps      3           asdfs       12321
3       image3.eps      3           asdaf       24124

And a query like this:
DECLARE @FileName NVARCHAR(2000)
SET @FileName = 'image1.eps'

INSERT INTO DigitalAssets
VALUES(
    (SELECT max(ID)+1 FROM DigitalAssets)
    ,(SUBSTRING(@FileName,0,LEN(@FileName)-4)+'.jpg')
    ,(1)
    ,(SELECT TOP 1 Other1 FROM DigitalAssets WHERE FileName = @FileName )
    ,(SELECT TOP 1 Other2 FROM DigitalAssets WHERE FileName = @FileName )
)

Now I want to create a stored procedure that will insert the same values except id, filename, and type . I can do it like this but there are too many columns(or am I just lazy). What is the proper way to do this?
Comment: You do know there's something like IDENTITY for inserting IDs? http://msdn.microsoft.com/en-us/library/ms186775.aspx
Answer: I'm suspecting your ID has been set its identity to true. This code might work for you.
DECLARE @FileName NVARCHAR(2000)
SET @FileName = 'image1.eps'

INSERT INTO DigitalAssets([FileName], Type, Other1, Other2)
SELECT SUBSTRING(@FileName,0,LEN(@FileName)-4)+'.jpg',1, Other1, Other2
FROM DigitalAssets WHERE FileName = @FileName

In case it is not, you could try this.
DECLARE @FileName NVARCHAR(2000)
SET @FileName = 'image1.eps'

INSERT INTO DigitalAssets(id, [FileName], Type, Other1, Other2)
SELECT (SELECT id
FROM DigitalAssets o1
WHERE NOT EXISTS (SELECT 1 FROM DigitalAssets o2 WHERE o2.id > o1.id))
SUBSTRING(@FileName,0,LEN(@FileName)-4)+'.jpg',1, Other1, Other2
FROM DigitalAssets WHERE FileName = @FileName


How to detect a change in any of a form's input fields using jQuery?

Question: I'm using the following snippet to detect every time a particular form input field changes.
$( '#textbox' ).on( 'input', function() {
    // Do something here
});

This particular input field belongs to a form which has checkboxes, radio buttons and more text input fields. Is there a way to detect when there is a change to any of the form's fields?
Comment: Events bubble up, so you can bind the event handler to the `form` element: `$( 'form' ).on( 'input', function(e) {
 console.log(e.target);
});`
Comment: What does the `'e'` do in `function(e)`?
Comment: `e` is the event object, it's `target` property refers to the target of the event.
Answer: Try,
$('#Form input').on( 'input', function() {
  //This would be called if any of the input element has got a change inside the form
});

Comment: Is there any way to accomplish this same solution when there is no 'form' on the page?
Comment: @KirbyL.Wallace What is holding that input elements?
Comment: what if i add some text to textbox and removed it or cleared it? will this be treated as change or no change occured. How do i accomplish as if no change occured.
Answer: Try this:
HTML:
<form>

<input type='text' />

<input type='text' />

<input type='checkbox' />

</form>

JQuery:
$('form :input').change(function(){
   alert("Form changed");
});

JSFiddle Demo
Answer: $("form :input").change(function() {

});


The Hyperplane $s = \sum a_i x_i$ in $\mathbb{P}^n_k$ contains a closed point $P$ if and only if $s \in \mathfrak{m}_P \mathscr{L}_P$.

Question: Let $X \hookrightarrow \mathbb{P}^{n}_k$ be a closed subscheme with $k$ an algebraically closed field. Then, the line bundle $\mathcal{O}(1)$ on $\mathbb{P}^n_k$ pulls back to $\mathscr{L} = \mathcal{O}_X(1)$ which is generated by the global sections $x_0, \dots, x_n$. Let $P$ and $Q$ be closed points and suppose $s = \sum a_i x_i$ defines a hyperplane containing $P$ and not $Q$.
Then, $s$ defines a global section of $\mathscr{L}$ and I would like to show that $s \in \mathfrak{m}_P \mathscr{L}_P$ and $s \notin \mathfrak{m}_Q \mathscr{L}_Q$. I do not see how to prove this although it seems intuitive.
For context, this is the situation in Hartshorne's proof of Proposition II.7.3. Please let me know if you need me to clarify any notation.
My Attempt:
I'll let $I$ be the homogenous ideal of $X$. Then $(\mathcal{O}_X)_{P} = \left(k[x_0, \dots, x_n]/I \right)_{(\mathfrak{p})}$ where $\mathfrak{p} = \langle P_ix_j - P_Jx_i\rangle$ is the ideal of the closed point $P = [P_0: P_1: \cdots : P_n]$, since $k$ is algebraically closed. Then, $\mathfrak{m}_P$ is the extension of this ideal in the degree 0 localization $\left(k[x_0, \dots, x_n]/I \right)_{(\mathfrak{p})}$. Then, we know that $\sum a_i P_i =0$. I'm then confused how to write $\sum a_ix_i$ as a product of elements of $\mathfrak{m}_P$ and $\mathscr{L}_P$.
Any help is greatly appreciated.
Answer: Let $f$ be a linear form with $P,Q\in D(f)$. The sections of $\mathcal{O}_{\Bbb P^n}(1)$ over $D(f)$ are $f\cdot k[\frac{x_0}{f},\cdots,\frac{x_n}{f}]$, so the sections of $\mathscr{L}$ over $X\cap D(f)$ are $f\cdot k[\frac{x_0}{f},\cdots,\frac{x_n}{f}]/I_X$. Next, $s$ vanishes at $P$ iff $s=f\cdot\frac{s}{f}=f\cdot \sum a_i\frac{x_i}{f}$ also vanishes at $P$. Going to stalks, $f\in\mathscr{L}_P$ and $\frac{s}{f}\in\mathfrak{m}_P$, so $s\in \mathfrak{m}_P\mathscr{L}_P$ iff $s$ vanishes at $P$. The claim for $Q$ is proved in exactly the same manner.
Comment: Dear KReiser, thank you very much for the nice answer. I apologize for taking so long to accept the answer and give the bounty; I did not know they were separate selections. Also, I have been moving these past weeks so I have not been as attentive as I would have hoped to be. Either way, I appreciate your insight.
Comment: Don't worry about it, I've also been a bit busy lately. Glad to help!


Converse proof: A positive random variable has a MGF iff its distribution has a tail which is exponentially bounded

Question:
A positive random variable, $Z$ has a MGF iff the distribution of $Z$ has a tail which is exponentially bounded.

I am looking at a proof for this. The converse part goes as follows.
Suppose the distribution of $Z$ has an exponentially bounded tail i.e.,
$$P(Z>x)\le Ke^{-cx}$$
for some $c,K$ and all $x$. Then for $\theta<c$, $$E(e^{\theta Z})<\infty~\text{iff}~E(e^{\theta Z}-1)<\infty.$$
However,
$$E(e^{\theta Z}-1)=E\int_0^\infty \theta e^{\theta u}\mathbb{I}_{[u<Z]}du.$$
I don't understand how this last integral came to be. Seems to be coming from Fubini's theorem maybe, but kind of confused how.
Answer: There is a typo in $$E(e^{\theta Z-1})=E\int_0^\infty \theta e^{\theta u}\mathbb{I}_{[u<Z]}du.$$ It should read $$E(e^{\theta Z})=E\int_0^\infty \theta e^{\theta u}\mathbb{I}_{[u<Z]}du.$$
For any positive r.v. $Y$ we have $EY=\int_0^{\infty} P(Y>y)dy$. Take $Y=e^{\theta Z}$. You get $E(e^{\theta Z})=\int_0^{\infty} P(e^{\theta Z}>y)dy$. Make the substitution $y=e^{\theta v}$. You get $E(e^{\theta Z})=\int P(Z>v) \theta e^{\theta v}dv$. Write $P(Z>v)$ as $E\mathbb{I}_{Z>v}$ and interchange the integral and the expecation.
Comment: Oh right, silly of me! This explains it.


How do I solve: $x'=x^2-1$?

Question: $x'=x^2-1$; $x(0)=1$
This is what I have done so far:
$\frac{dx}{x^2-1}=dx\left(\frac{1}{2(x-1)}-\frac{1}{2(x+1)}\right)=dt$
After integrating both sides:
$\frac{1}{2}\log(x-1)-\frac{1}{2}\log(x+1)=t+c$
I then should apply the initial conditions to find c:
$\frac{1}{2}\log(1-1)-\frac{1}{2}\log(1+1)=0+c$
$c=\frac{1}{2}\log(0)-\frac{1}{2}\log(2)$
This is where I get a bit confused. Isn't $\log(0)=-\infty$? If so, what does c equal in this case?
Comment: $$x' = x^2 - 1 \Longrightarrow x' - 1 = x^2$$

so take $v = x^{1-2} = x^{-1}$ and then you have $\frac{dv}{dt} = -x^{-2}\frac{dx}{dt}$ and now we can move on. So multiply everything by $\frac{dv}{dx}$.
Answer: You are correct, and that's a sign that there is no solution of the form you chose with initial condition $x(0)=1$.
There is however another solution. Note, that when dividing by $x^2-1$, you implicitly assumed that $x\neq\pm 1$. But $x=\pm1$ are indeed solutions! Thus, the general solution to your ODE is:
$$y = \frac{1-e^{2t+2C}}{1+e^{2t+2C}}\ \text{or} \ y=\pm1$$
Comment: Arguably $C\to\infty$ gives $y=-1$ and $C\to-\infty$ gives $y=1$.

How do I solve: $x'=x^2-1$?


Applications of group theory to classical mechanics

Question: Today, a friend and I solved a classical mechanics problem using group theory. The problem was the following:

Around a circumference, there are $N$ children evenly spaced. In the center, there is a tire. Each children pulls the tire by a rope with equal forces. Is the resultant force always zero?

My friend associated each force vector with a complex root of unity, and using the fact that the group of the $N$-roots of unity is cyclic, showed the identity:
$$1 + \zeta + \zeta^2 + \cdots + \zeta^{n-1} = 0$$
which equals saying that the resultant force is zero. I considered the set $\Omega$ of all permutations of the children, with a group action $\pi\colon \mathbb{Z}/N\mathbb{Z}\times \Omega \to \Omega$ by cyclic permutations. I considered the "force" function $f\colon \Omega \to \mathbb{R}^2$ which associated each system with it's resultant force vector. I also considered the group action $\varphi\colon \mathbb{Z}/N\mathbb{Z} \times \mathbb{R}^2 \to \mathbb{R}^2$ by rotations of the plane. Then, I argumented the following identities for all $S \in \Omega, x \in \mathbb{Z}/N\mathbb{Z}$:
$$f(\pi(x, S)) = \varphi(x, f(S))$$
$$f(\pi(x, S)) = f(S)$$
which implied $f(S)$ is a fixed point of $\varphi$, and thus is always the zero vector.
I never expected a application of group theory to classical mechanics (though I know about it's uses in crystallography). Are there other well know examples of this?
Comment: Ultimately, group theory is the study of *symmetry*.  In many situations, the symmetry of a problem makes it easier to solve, or guarantees a certain outcome.  In the easiest examples, one could intuitively figure out how to exploit that symmetry.  However, in situations involving elaborate mathematical structures, group theory allows us to accomplish these ends systematically.
Comment: I would expect that you could find some interesting examples in chemistry.
Answer: (I would leave a comment, but apparantly I'm not allowed to do that yet)
If you ask a physicist what group theory is, his answer will probably come out to be "the study of symmetry". Symmetry plays a huge role in modern physics and also in Classical Mechanics. The modern treatment of Classical Mechanics, involving symplectic and poisson manifolds, makes heavy use of groups.
One of the important points where group theory comes in is, that constants of motion (observable quantities of a system, that do not change with time) correspond to invariance of the equations of motion under the smooth action of a group. This is called Noether's theorem and remains very important beyond Classical Mechanics. Well-known conservation laws like energy, momentum and angular momentum correspond to the invariance of the system in question under time translation, space translation and rotation. The symmetry group of classical mechanics is called the Gallilei group. The symmetry group of relativistic physics is the Poincaré group. Modern physics is full of group theory (Lie groups are used most often): For example the Wightman axioms for quantum field theory require to specify an irreducible representation of the Poincaré group. The classification (due to Wigner) of (certain) irreducible unitary representations of the Poincaré group leads physicists to the classification of elementary particles according to their mass and spin.
If you want to find out more about applications of group theory to mechanics, I would recomend the books by V. Arnold (Mathematical Methods of Classical Mechanics) or Marsden and Ratiu (Introduction to Mechanics and Symmetry).
Comment: I really didn't expect such profound study of symmetry on classical mechanics. Though both of these books seems a bit unaccessible for a undergraduate, I think I'll benefit from a short, informal reading at the local library, just to get a feel of it (especially Mardsen's and Ratiu's book). Thanks!
Comment: The point re: "beyond classical mechanics" is an important one: Most of the applications I know of are not _classical_ but quantum (either at the level of QM or QFT), though Noether's theorem is certainly relevant in classical mechanics.


Text geometry not changing size even after changing height and size parameters

Question: I have an issue with loading text in my react three fiber project, although the text renders ( because i see a very tiny pixel of the text color at the position i placed the text). But the text refuses to resize or become bigger to be seen properly and i've searched it seems like no one has faced this issue before,heres my code for the font loader for the text:
extend({ TextGeometry })

  const font = new FontLoader().load('node_modules/three/examples/fonts/droid/droid_sans_bold.typeface.json');

and code for rendering the text itself:
<mesh position={[-170,30,0]}>
      <textGeometry args={["DP LAYER", {font,size: 80,
      height: 5,
      curveSegments: 12,
      bevelEnabled: true,
      bevelThickness: 10,
      bevelSize: 8,
      bevelOffset: 0,
      bevelSegments: 5 }]}  />
      <meshBasicMaterial color="red" />
 </mesh>

not really sure of what can be causing this.
Answer: Your font parameter is not a object and therefor the options object may not work as intended...

should be:
{font:font, size:80,
...
}

Comment: I tried your solution but didn't work


Covert list to Map with list in Kotlin

Question: This might be a common question, but I did not find anything specific to what I am looking for. Also, I am newbie to Kotlin.
Here is my existing code that I want to simplify in Kotlin. The below code is in Java and I am looking for Kotlin equivalent of it
Travserse through the list of items, identify if it contains MEAT or EGG and accordingly put it in a Map with a LIST. The key to MAP is MEAT/VEG.
final Map<TYPE, List<String>> itemtypeToContent = new HashMap<>();
        itemtypeToContent.put(TYPE.MEAT, new ArrayList<>());
        itemtypeToContent.put(TYPE.VEG, new ArrayList<>());

        foodList.forEach(item -> {
            if (containsMeat(item)) {
                itemtypeToContent.get(TYPE.MEAT).add(item);
            } else if (containsEgg(item)) {
                itemtypeToContent.get(TYPE.VEG).add(item);
            } else {
                // log invalid item - skip
            }
        });
        return itemtypeToContent;

enum TYPE {
MEAT,
VEG
}

class Item {
String name,
List<String> ingredients
}

input:
List<Item> foodList = {{Omlette, {egg, onion, salt, pepper, mushroom}},
                       {ScrambledEggs, {egg, milk, salt, pepper}},
                       {ChickenTacos, {chicken, onion, salt}}
                       {Fries, {potatoes, salt}}}

output:
Map {MEAT, [{ChickenTacos, {chicken, onion, salt}}]
     VEG,  [{Omlette, {egg, onion, salt, pepper, mushroom}},
            {ScrambledEggs, {egg, milk, salt, pepper}}]}

We skipped FRIES because it did not contain meat or egg
Comment: You should also invest some time into explaining your code and what you are doing there, instead of just dumping some code.
Comment: Well, essentially, if people do not immediately understand your question (and the code) after the first read, you will be getting a downvote for "unclear". So it is in your own interest to always go the extra mile when it comes to making it crystal clear and providing all the necessary context possible. SO is a place for high quality questions only (and answers).
Comment: Sorry, what exactly is your question or problem?
Comment: I was wondering if we can simplify this in Kotlin by using groupBy?
Comment: I assumed the input and output would be enough to explain what the code is expected to behave. My bad. Updated the description
Comment: What have you tried in Kotlin?
Comment: I tried associateBy/groupBy with keySelector but felt it was making the code more complicated
Comment: Maybe you should try showing the code you attempted and explaining what you didn't like. That would be more helpful than "rewrite this code in a diff language for me"
Comment: @meso What should the result be when a dish contains both meat and egg?
Comment: Great question - I would prefer it be part of MEAT since that is the first check.

Note - this is not my actual problem, I have tried to simplify this for SO and avoid giving out internal details of my actual code.
Answer: You basically want to categorise dishes based on whether they contain meat or not, so assuming you only have 2 categories you can do it like this
fun main() {
    val dishes = listOf(
        Dish("Omelette", listOf("egg", "onion", "salt", "pepper", "mushroom")),
        Dish("ChickenTacos", listOf("chicken", "onion", "salt")),
        Dish("ScrambledEggs", listOf("egg", "milk", "salt", "pepper")),
        Dish("Fries", listOf("potatoes", "salt"))
    )

    val grouped = dishes.groupBy {
        when {
            containsMeat(it) -> IngredientType.MEAT
            containsVeg(it) -> IngredientType.VEG
            else -> null
        }
    }
        .filterKeys { it != null }

    println(grouped)
}

This prints:
{
    VEG=[Dish(name=Omelette, ingredients=[egg, onion, salt, pepper, mushroom]), Dish(name=ScrambledEggs, ingredients=[egg, milk, salt, pepper])],
    MEAT=[Dish(name=ChickenTacos, ingredients=[chicken, onion, salt])]
}

Comment: yes this helps a lot. I can definately try to build things on top of it
Comment: This is pretty close to what I want, but in this case FRIES would be added as VEG when I want it to be discarded since it does not contain MEAT or EGG
Comment: not sure exactly what the logic for excluding "fries" is, but if you know how you want to group things, you can do it similarly to this
Comment: Thank you so much for your help! Appreciate it :)

Covert list to Map with list in Kotlin


OpenVPN Wrapper

Question: Is it possible to use openvpn as "a wrapper" for certain scripts?
So that
a) The VPN is built up for a script and terminated after the script has finished
b) Only the traffic of that script is sent through the vpn
Answer: A) Sure.  You can start up the openvpn client via a script.  Something like openvpn --config /path/to/config.cfg should be sufficient, if everything relevant to your connection is contained in /path/to/config.cfg.  The VPN tunnel can then be taken down by killing that process.
B) This is a bit harder, but only a bit.  Typically, you would do this by firewall rules, to restrict VPN traffic to what you want to permit.  If you don't have these firewall rules, anything on the client box can send traffic across the VPN (It won't necessarily happen; if the VPN is to a private network, and no other process on the machine cares, there probably won't be any traffic.  But, if you have a requirement to permit only certain traffic, then you should write up firewall rules that specifically permit this traffic and block everything else.)

OpenVPN Wrapper


How to order a list according to elements using a target vector?

Question: I have a list of lists. I want to order this according to a reference vector. This is similar to this question on ordering dataframes. However I struggled to implement it.
I want to sort this list below by its 'key' according to the order in the 'target' vector.
target <- c("c", "b", "a")
L <- list(
          X = list(key = "a", val = 6),
          Y = list(key = "b", val = 5),
          Y = list(key = "b", val = 0),
          Z = list(key = "c", val = 4)
          )

Answer: Here is one approach:
L[order(vapply(L,
               function(x, target) which(x$key == target),
               target = target,
               FUN.VALUE = 1L)
        )
 ]
#$Z
#$Z$key
#[1] "c"
#
#$Z$val
#[1] 4
#
#
#$Y
#$Y$key
#[1] "b"
#
#$Y$val
#[1] 5
#
#
#$Y
#$Y$key
#[1] "b"
#
#$Y$val
#[1] 0
#
#
#$X
#$X$key
#[1] "a"
#
#$X$val
#[1] 6

Answer: The following works for me - written line by line for expository purposes
# Get keys from the original list
sapply(L, `[[`, "key")
# Use match to order these
match(sapply(L, `[[`, "key"), target)
# Now select those items from the original list using the reference from match
L[match(sapply(L, `[[`, "key"), target)]

Comment: You need `order`: `L[order(match(sapply(L, "[[", "key"), target))]`.
Comment: I dont think works. The 'Z' element seems to be lost.
Comment: Adding order does the trick: `L[order(match(sapply(L, `[[`, "key"), target))]`
Comment: So `match(sapply(L, `[[`, "key"), target)` gives `3 2 2 1`, and `order(match(sapply(L, `[[`, "key"), target))` gives `4 2 3 1`. Is this just a (clever) 'trick' to get a unique index in the appropriate 'order'


Is there a module/way to send an email quarterly to a list of people about all the new content that has been published since the last email?

Question: I need to be able to take all the users who sign up for updates on a webform and on an editable frequency email them the new content (that I choose to send them) that has been published since the last email. Do any of y'all know if there is a module/way currently that I can do that? And if not what the best way to do that would be?
As an example, how would I send all the people from this webform results list a quarterly email informing them of all the blog posts that have been published since the last quarter?
Answer: This is a really broad question so this will be a broad answer.

how would I send all the people from this webform results list a quarterly email informing them of all the blog posts that have been published since the last quarter?

First, how to get a list of all blog posts that have been published since the last quarter?  This can be done with the Views module; it's quite easy to generate a filtered list of content.
How to send the email?  Well, I wouldn't use Webform for this; I would use Simplenews instead.  This is by far the most popular Drupal module for mailing lists, and offers the great advantage of being open source, so you don't have to pay Mailchimp or another company for your newsletter.  The disadvantage is that it is not super easy to set up.


measure development - removing items from an item pool due to ceiling effect

Question: During the early stages of scale development, many items within our item pool were found to have a strong ceiling effect with low score variability. In order to attempt create a meaningful measure with useful score variability, the decision was taken to reduce the size of the item pool and only include items with the most central mean scores and the largest standard deviations. Only these items were put forward into subsequent exploratory and confirmatory factor analysis. Two questions. One - does this seem sensible? Two - can you suggest examples from the literature where the same has been done or is recommended? With thanks.
Answer: This makes good sense. You create a scale to distinguish between different individuals. Some are low on some traits and high on others. If you have items that aren't discriminating between people (i.e., individuals tend to respond the same and thus the item has a low SD), then the item isn't useful in your scale.
A good reference for this would be any psychometric text book. In particular, in item response theory (IRT), items that have a low discrimination are not as desirable. This likely isn't the type of reference you're looking for, but it does support what you are doing.


get account name for IIS anonymous user

Question: I'd like to get the name of the anonymous user account for an IIS install. It's easy enough to assume that it's the machine name, but in the event that the machine name has changed I'd like to still know what it is. Ultimately I'd like to be able to drop this into a bat file or vbscript that I'm using for a website deployment.
The I've gleaned following from the MSDN:
dim schemaObject: set schemaObject = GetObject("IIS://localhost/schema/anonymoususername")
dim schemaObjectType: schemaObjectType = schemaObject.syntax
WScript.Echo( schemaObjectType )

GetObject() is returning an IISSchemaObject but what property represents the name itself? It's not obvious and I haven't found much in the way of documentation.
Alternatively, is there a way to call the adsutil script and only return the value you're interested in?
cscript adsutil.vbs get w3svc/anonymoususername
anonymoususername          : (STRING) "IUSR_SERVER-NAME"

I only want "IUSR_SERVER-NAME"
Answer: What's wrong with looking at the %COMPUTERNAME% environmental variable and pre-pending IUSR_?
Comment: Well, then that isn't going to work. Your question only asks about the built-in anonymous account. If you have other requiments, update the question to reflect that.
Comment: It didn't occur to me but it makes perfect sense. What if it's an account other than the default IUSR?
Comment: It's not the right solution, is what's wrong with it. It's hardcoding something and making assumptions that are invalidated in many, many environments.
Comment: @TristanK I would assume that the OP was asking for something specific to his environment. This, obviously, isn't an answer to everyone, but the OP specifically says `I only want "IUSR_SERVER-NAME"`. This is the simplest way to fulfill that very specific requirement.
Comment: His opening line is: "I'd like to get the name of the anonymous user account for an IIS install. It's easy enough to assume that it's the machine name, but in the event that the machine name has changed I'd like to still know what it is." ... using that as context, I read the closing remarks like "only return the value you're interested in" and "I only want IUSR_SERVER-NAME" as being around string formatting for something that's name-value-in-quotes formatted (this "anonymoususername          : (STRING) "IUSR_SERVER-NAME"") isn't easily usable as output without a string formatting FOR loop.
Comment: I did read. It's really a poorly asked question, but I think we're going to have to agree to disagree. FWIW, I did upvote your answer. If you really feel like I didn't answer the question, as asked, go ahead and downvote me. I don't take it personally :)
Comment: @MDMarra. "It's easy enough to assume that [the anonymous user account for an IIS install] is the machine name, but in the event that the machine name has changed I'd like to still know what it is." Seems pretty straight forward to me, but thanks for your input!
Answer: ADSUtil just uses GetObject under the covers (IIS is exposed as a garden variety ADSI provider), so you can simply target the property you're interested in (if you know the path) with something like
set oSite = GetObject("IIS://localhost/W3SVC/1/ROOT")
Wscript.echo oSite.AnonymousUserName

for the default web site, or this (as in your example above) for the box level setting.
set oMasterSite = GetObject("IIS://localhost/W3SVC")
Wscript.echo oMasterSite.AnonymousUserName

That covered, it's important to note that the anon username could be reset at basically any folder level in the IIS hierarchy.
Comment: Currently the deployment scripts I've inherited are hardcoded to use the machine name (and they're always using the default website). More often than not this works fine, but more recently I've been encountering issues with the IUSR account being something different and I'd like to be able to account for it. Given the VBScript examples I'd encountered until now I wasn't expecting the property name to be so obvious. I was looking for a "Value" or "Name" or something. Thanks!

get account name for IIS anonymous user


Dominio .com tem mais relevância que .tk para o google?

Question: Eu gostaria de saber se um domínio .com (www.example.com) é mais relevante do que o domínio .tk(www.example.tk). Ou isso não têm importância para o Google?
Comment: @AmadeuAntunes +1 porque a pergunta é interessante, no entanto votei pra fechar porque parece não ser do escopo, no entanto mesmo fechando ela ainda será publica e ganhará pontos com ela talvez e ajudará outras pessoas, o fechamento é realmente apenas por ser off-topic, no entanto pode ser que mesmo votando ela ainda se mantenha aberta *"pela aceitação da comunidade como um bom assunto"*, pois mesmo que tenhamos um escopo ainda sim algumas perguntas off são aceitar "pela comunidade". :)
Comment: Não posso perguntar isso aqui?
Comment: Penso que sua pergunta não esteja relacionada com programação. Obs: não negativei.
Comment: Posso remover se não se enquadrar aqui
Comment: Mas como têm haver com sites achei que poderia
Comment: Acredito que o @rubStackOverflow tem razão, pois a pergunta não se refere a programação. Achei importante responder porque esse mito existe até hoje e a resposta poderá servir de referência para outras pessoas com a mesma dúvida :)
Answer: Não, não é mais relevante.
Conforme este post (em inglês) de um dos engenheiros da equipe de qualidade de buscas  do Google, isso é um mito e o domínio de nível maior (TLD) não tem relevância na avaliação do site ou página.
Porém, se uma busca é feita, por exemplo, no Brasil, um TLD .br tem  mais chances de aparecer nas primeiras posições.
Segue um link que explica sobre os fatores de ranking:
Google's 200 Ranking Factors (em inglês)
Comment: Porquê o negativo? Ajude comentando para ajudar o colega a entender o motivo, assim ele pode ajudar/resolver/editar/melhorar/positivar, ou talvez você esteja totalmente errado!
Answer: De fato, extensões de domínio não interferem em um primeiro momento no ranking do Google. O que vale é a idade do site, reputação, backlinks e sobretudo o conteúdo.
No entanto, domínios .TK sofrem muito spam e abuses. São tratados como domínios "sujos". Há algum tempo, o Google penalizou todo o TLD .TK .
Ao invés de usar um .TK, recomenda-se usar um blogspot.com ou wordpress.com . A nivel de SEO tem muito mais efeito.


A question with an odd hypothesis.

Question: Let $S$ be a discrete valuation ring and $R\subset S$ be a proper subring (also a DVR).  Assuming that $M$ and $N$ are the respective maximal ideals of $R$ and $S$ and that $N\cap R = M$, then the quotient field of $S$ is a proper subfield of the quotient field of $R$.
My Idea:  Take $x\in S - R$ which must be non-zero.  Then $(x)$ is an ideal of $S$.  Since $(x)\neq 0$ and $S$ is a discrete valuation ring, then we must have that $(x)$ is an ideal of $S$.
I know this doesn't go very far, but there are a few hypothesis that are bizarre to me.
The requirement that $N\cap R = M$ sounds a bit like the requirements of the "going up" theorem [of which there seems to be quite a few versions :(] but since $R$ is integrally closed, $S$ cannot be integral over $R$.  So this is paragraph I have all but completely dismissed.
To complete the story, I am stuck.
Comment: The first paragraph is a question and the rest is what you've tried, if I got it well? It is not obvious from the question.
Comment: Yep!  That's correct.
Answer: I think you are implicitly assuming that $R$ is also a DVR, so I will also use this.
Assume the fraction fields of $R$ and $S$ are equal:  $R\subseteq S\subseteq \text{Frac}(R)$. Let $0\neq a\in S$, we want to show that $a\in R$: If $v_R(a)\geq 0$ we're done, so assume $v_R(a)<0$, which implies $v_R(a^{-1})>0$ and so $a^{-1}\in M\subseteq N$, but that is impossible as $a\in S\Rightarrow a^{-1}\notin N$.
We have shown that all $a\in S $ satisfy $v_R(a)\geq 0$ and so $R=S$.
EDIT: In fact it is enough to assume that $R$ and $S$ are valuation rings.
Assume the fraction fields of $R$ and $S$ are equal. Take $a\in S\backslash R$. Since $R$ is a valuation ring $a^{-1}\in R$, but $a^{-1}$ is not a unit in $R$ and hence is in the maximal ideal $M$ of $R$. $a^{-1}\in M\subseteq N\subseteq S$. This is a contradiction, as $a^{-1}\in N$ implies that $a^{-1}$ is not a unit in $S$ and hence $a\notin S$.
Comment: No need to be sorry.  You've laid this out in a very basic way.  I should be able to follow it immediately.  The only thing slowing me down is that we were given a different definition of a DVR, so in order to use your argument, I first must prove the equivalent of definitions (which a peer of mine says is possible with a couple of theorems we proved in class, thankfully).

To clarify: me not yet checking the answer in no way means that I don't accept/believe/trust it.  I just have to catch up.  :)
Comment: Thanks so much.  You are indeed correct about my mistake.

So whenever we are dealing with a DVR is it true that we are entitled to a discrete valuation map $v_{R}$?
Comment: @borninthe80s: In fact I took this as a definition of a DVR, but there is a long list of equivalent definitions, see [Wiki](http://en.wikipedia.org/wiki/Discrete_valuation_ring).
Actually the use of a discrete valuation hides what is really going on. Please see my edit for a clearer and more general solution.
Comment: @borninthe80s: Also, you might not know, but it makes this page more organised if you mark correct answers by ticking the symbol under the vote buttons.
Comment: Thanks for the follow up.  I usually don't check the answer until I've successfully worked through it.  But I do always accept a correct answer when this happens.  And I've no doubt that your answer is correct.  (In the meantime I certainly upvoted it.  I hope this is OK.)
Comment: By "check" I mean mark as correct.
Comment: @borninthe80s: Sorry, of course that's OK :)

A question with an odd hypothesis.


What is the equivalent implementation of service POJOs (jBoss services in jboss 6 AS) of EJB 3.0 in EJB - 3.2

Question: Service POJOs are available which is used to define as jBoss services (in Jboss AS 6) in EJB 3.0 and the tutorial is http://docs.jboss.org/ejb3/app-server/tutorial/service/service.html and below are the related annotations.
<code>import org.jboss.ejb3.annotation.Depends;
import org.jboss.ejb3.annotation.Management;
import org.jboss.ejb3.annotation.Service;
</code>
Similarly, could anyone please tell me the equivalent implementation in EJB 3.2 as I could not find any related jars or tutorials in wildfly 8 application server.
Answer: The functionality of org.jboss.ejb3.annotation.Depends and org.jboss.ejb3.annotation.Service can be replaced by:

javax.ejb.DependsOn
javax.ejb.Singleton
javax.ejb.Startup

There is no replacement for org.jboss.ejb3.annotation.Management


error message using modals for login

Question: i need to show a dialog box if login failed. now i'm able to show the error line inside the form, but i need to show the error message using modals.
here's my code:
$sfAuth = new SfAuthenticate();
$sfHelper = new SfHelper();

$user = $_POST['txtUsername'];
$pass = $_POST['txtPassword'];

$checkUser = $sfAuth->checkUserJobSeeker($user);

if($checkUser)
{
    $login = $sfAuth->loginJobSeeker($user, $pass);
    if($login)
    {
        echo $sfHelper->redirect('forms/jobSeeker/HomeJobSeeker.php');
    }else{

        echo $sfHelper->redirect('forms/jobSeeker/formLoginJobSeeker.php?err=Invalid Username or Password');
    }
}else{
    echo $sfHelper->redirect('forms/jobSeeker/formLoginJobSeeker.php?err=Sorry, We Cannot found your Username');
    }

i want to show the dialog box after redirecting to the login form.
can anyone help me please?
Answer: Have a look at this fiddle, it should work: http://jsfiddle.net/7PwWp/5/
As to launching the modal window on user error, you can add a condition:
<?php if(isset($_GET['err']): ?>
  launchWindow('#message');
<?php endif; ?>

In the message box, you can put:

<?php echo (isset($_GET['err'])? $_GET['err']:''; ?>

Comment: ah yes.. updated now to include close statement. just click on 'close' or outside of the modal to close it
Comment: I suspect some extra code would be required to close the modal box afterward to return back to the main view?
Answer: To show a modal dialog box you'll need javascript. Check this previous SO question: How to create popup window(modal dialog box) in HTML). I would, similarly, recommend checking out jQueryUI which is an extension of the javascript library jQuery.
In 3 steps, here's how this works:
Include jQuery and jQueryUI library scripts in the page

<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/themes/base/jquery-ui.css" type="text/css" media="all" />

Create the markup for the modal dialog to be displayed
Doesn't need to be fancy but note the id tag as jQuery uses that to know which element to display in dialog.

This is the message inside the modal dialog.

Show the dialog using jQueryUI

See a full working example here: http://jsfiddle.net/wjp94/3/
Answer: put this code on formLoginJobSeeker.php file
<?php
if($_GET['err'] == "Sorry, We Cannot found your Username")\
{
echo ''
}
?>

Answer: If you want to show dialog then you have to use jquery dialog
Add following code to your page;

<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/themes/base/jquery-ui.css" type="text/css" media="all" />

         <?php if(isset($_GET['err'])) echo $_GET['err'];?>

<?php if(isset($_GET['err']){ ?>

<?php } ?>

if you want to see how your modal looks like check on this link
http://codebins.com/bin/4ldqp8p
Answer: Solved?
If not, here is my solution.
Redirect to sth like that (notice #run_modal):
`forms/jobSeeker/formLoginJobSeeker.php?err=YOUR_MESSAGE#run_modal`

and JS:
function detectModalParam()
{
    var hash = $(location).attr('hash');

    if (hash == '#run_modal')
    {
        YOUT_MODAL_FUNCTION();
    };
}

$(document).ready(function()
{
    detectModalParam();
}

error message using modals for login


Is there some way to quantify melodic transitions?

Question: Are there any theories that model how to measure the pleasantness of  transitions between notes in a melody?
I'm imagining some kind of "distance" measurement of some sort in a similarity space whereby we gravitate toward certain melodies and the less similar a melody is to a pleasing one, the more displeasing we find it.
Answer: I would say no, there is none, but not because it is absolutely theoretically impossible to model pleasantness of a sequence of notes, but because the search space and variables of this model are unimaginably huge that makes it impossible to come up with a decent model, even if one exists. For example, pleasantness is judged differently by people of different counties, people of different ages, people of different music backgrounds, ..... and even for the same person in different moods, different ages, ....).
In fact, in the late eighties, the topic of Generative Music started to get some attention from computer scientists who worked in the fields of artificial intelligence and machine learning. Generative Music is used to describe music pieces generated automatically or semi-automatically by computers.
In order to do that, the machine must have a model based on which, tries to form a sequence of notes which have a high chance of being pleasant to a specific audience. Back then, it turned out that like painting, poetry or any form of art, it is impossible to model pleasantness of a work of art.
Today, only a few research groups are still working on the topic of generative music around the world.
Comment: Not to mention the industries that make billions of dollars doing it, but that's not really "music" anymore ;p
Answer: Yes, Treatises and papers on what makes a melody good vs. bad have been written since antiquity.  For example Gradus Ad Parnassum by Johann Joseph Fux, 1725.
Pitch Structure of Melodic Lines: An Interface between Physics and Perception by Rafael G. Hurtado. http://mindmodeling.org/cogsci2011/papers/0843/paper0843.pdf may be what you're looking for.  The author specifically references "the existence of preferences for certain
elements in a given melodic line" and "pleasant sensations in the listener" in the abstract.
In the realms of computer science and music theory there are plenty of examples of melodic analysis based on more objective criteria than "pleasantness", for example, Melodic analysis with segment classes by Darrell Conklin is an example of a paper about using machine learning to sort melodies into style categories http://link.springer.com/article/10.1007/s10994-006-8712-x#page-1
Comment: This is precisely true; a big problem is that a lot of those with an inclination toward engineering disciplines have no interest in music (or at least, no particularly remarkable ability) while most musicians haven't the slightest interest in learning the technical details of computer programming.  Which is a real shame, because most of our cultural frontiers lie in this direction (or, in the direction of total corporate-cultural feudalism)
Answer: No, there is not. "Pleasantness" is subjective. There is only dissonance and consonance, and even that is relative.


Why do all links change colour when only one is clicked?

Question: I'm completely stumped on this one - I have a pretty basic document with an ordered list containing anchors and hidden divs that show when a link is clicked. The problem is when one link is clicked all links change colour as per the a:visited css rule. This does not happen in IE10 (only the visited link changes colour as expected) but it does happen in Opera, Chrome and Firefox.
Here's the markup: http://jsbin.com/usUwecE/3/edit - I'm pretty new to web design so it could be something really obvious, but any help would be appreciated. Cheers!
Answer: That's because they all point to the same URL, so when you click on one they all return that they've been visited.
Answer: remove hash
instead of #javascript:; use javascript:; in your code
Answer: As everydayghost said all the href attributes target to #javascript:; which is the same page in address. In order to change this you have to make every href unique ie. href="#div1", href="#div2" ...


Try to integrate LinkedIn in iPhone application

Question: I have download the source from https://github.com/ResultsDirect/LinkedIn-iPhone . Demo working fine, and try to use in my application.
I have followed all the steps already whatever required as mention here in post ...
But I have getting the error
<code>"_OBJC_CLASS_$_RDLinkedInEngine", referenced from:
"_OBJC_CLASS_$_RDLinkedInAuthorizationController", referenced from:
</code>

When I comment the lines of RDLinkedInEngine and RDLinkedInAuthorizationController then error are removed
<code>- (void)loadView {
    [super loadView];
//    rdEngine = [[RDLinkedInEngine engineWithConsumerKey:kOAuthConsumerKey consumerSecret:kOAuthConsumerSecret delegate:self] retain];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
//    if( !rdHasAppeared ) {
//        UIViewController* controller = [RDLinkedInAuthorizationController authorizationControllerWithEngine:rdEngine delegate:self];
//        if( controller ) {
//            [self presentModalViewController:controller animated:YES];
//            rdHasAppeared = YES;
//        }
//        else {
//            NSLog(@"Already authenticated");
//        }
//    }
}
</code>
I my application I have already integrated MGTwitterEngine from source https://github.com/bengottlieb/Twitter-OAuth-iPhone  Which is wokring ok.
Amit Battan
Answer: most probably you need to add some static library (.a file)... or src folder itself from linkedIn source...
Comment: I missed the point ...`4- select   "LinkedInClientLibrary.xcodeproj" that you dropped in the right side marke checkbox " LinkedInClientLibrary.a"`.... that error goes ok.. but new error comes 'Command /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/gcc-4.2 failed with exit code 1'
Comment: you need to right click on the error and select open these latest result as transcript text file and see what causing that error.... post it here as well
Comment: you have added 2 file in which size_t EstimateBas64EncodedDataSize(size_t inDataSize) function is define... need to remove one....
Comment: may be you have added same file... one from LinkedIn source and one from twitter or any other external source
Comment: yes may be that... because both using oAuth.. my test application in which I am only using linkedin is working fine..... so any solution for it mehta ji  by I use both in same...
Comment: a lot of confusion here.... when I again starting step by step adding linkedin files then it give me 73 errors...http://developer.linkedin.com/servlet/JiveServlet/download/8628-1663/1.png http://developer.linkedin.com/servlet/JiveServlet/download/8628-1662/2.png http://developer.linkedin.com/servlet/JiveServlet/download/8628-1661/3.png
Comment: you missed to add header path in your project... Or you missed to add some framwork in your project...
Comment: I am not sure what I am missing.... but surely missing something ...bcoz now am even not able rum a new test app which has no MGTwitterEngine.... http://db.tt/Zlxu72t ... http://db.tt/fCv1MkL ... http://db.tt/BHWciQD
Comment: you need to figure this out yourself... some header paths are missing that is for sure... try from square1
Comment: @mihir Thanks.. the lot of error issue solved and only one same error left `Command /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/gcc-4.2 failed with exit code 1
` ... and it works fine with out MGTwitterEngine
Comment: my folder name in which project has space ... due this these lot of errors occurs...
Answer: I have gone through the same issue. It can be solved by setting Library Dependency. Select project target and then select general. There you will find Direct dependencies. Add LinkedInLibrary from LinkedInClientLibrary.xcodeProject
Answer: @mihir
<code>Build butterfli of project butterfli with configuration Debug

CompileC build/butterfli.build/Debug-iphonesimulator/butterfli.build/Objects-normal/i386/butterfliViewController.o /Users/pratgupta/Desktop/butterfli/Classes/butterfliViewController.m normal i386 objective-c com.apple.compilers.gcc.4_2
cd /Users/pratgupta/Desktop/butterfli
setenv LANG en_US.US-ASCII
setenv PATH "/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/gcc-4.2 -x objective-c -arch i386 -fmessage-length=0 -pipe -std=c99 -Wno-trigraphs -fpascal-strings -fasm-blocks -O0 -Wreturn-type -Wunused-variable -isysroot /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.1.sdk -fexceptions -fvisibility=hidden -mmacosx-version-min=10.6 -gdwarf-2 -fobjc-abi-version=2 -fobjc-legacy-dispatch -D__IPHONE_OS_VERSION_MIN_REQUIRED=40100 -iquote /Users/pratgupta/Desktop/butterfli/build/butterfli.build/Debug-iphonesimulator/butterfli.build/butterfli-generated-files.hmap -I/Users/pratgupta/Desktop/butterfli/build/butterfli.build/Debug-iphonesimulator/butterfli.build/butterfli-own-target-headers.hmap -I/Users/pratgupta/Desktop/butterfli/build/butterfli.build/Debug-iphonesimulator/butterfli.build/butterfli-all-target-headers.hmap -iquote /Users/pratgupta/Desktop/butterfli/build/butterfli.build/Debug-iphonesimulator/butterfli.build/butterfli-project-headers.hmap -F/Users/pratgupta/Desktop/butterfli/build/Debug-iphonesimulator -iquote/Users/pratgupta/Desktop/butterfli/LinkedInClientLibrary -I/Users/pratgupta/Desktop/butterfli/build/Debug-iphonesimulator/include -I/Users/pratgupta/Desktop/butterfli/OAuthConsumeriPhoneLib -I/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.1.sdk/usr/include/libxml2 -I/Users/pratgupta/Desktop/butterfli/build/butterfli.build/Debug-iphonesimulator/butterfli.build/DerivedSources/i386 -I/Users/pratgupta/Desktop/butterfli/build/butterfli.build/Debug-iphonesimulator/butterfli.build/DerivedSources -include /var/folders/RE/RE2wCP+eEqaZg4J2Og3nmE+++TI/-Caches-/com.apple.Xcode.501/SharedPrecompiledHeaders/butterfli_Prefix-aeetprdcvcynktfkafjmijthtlhp/butterfli_Prefix.pch -c /Users/pratgupta/Desktop/butterfli/Classes/butterfliViewController.m -o /Users/pratgupta/Desktop/butterfli/build/butterfli.build/Debug-iphonesimulator/butterfli.build/Objects-normal/i386/butterfliViewController.o

/Users/pratgupta/Desktop/butterfli/Classes/butterfliViewController.m:321: warning: property 'fbPermissions' requires method '-fbPermissions' to be defined - use @synthesize, @dynamic or provide a method implementation

Ld build/Debug-iphonesimulator/butterfli.app/butterfli normal i386
cd /Users/pratgupta/Desktop/butterfli
setenv MACOSX_DEPLOYMENT_TARGET 10.6
setenv PATH "/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/gcc-4.2 -arch i386 -isysroot /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.1.sdk -L/Users/pratgupta/Desktop/butterfli/build/Debug-iphonesimulator "-L/Users/pratgupta/Desktop/butterfli/Twitter+OAuth/Libraries & Headers" -F/Users/pratgupta/Desktop/butterfli/build/Debug-iphonesimulator -filelist /Users/pratgupta/Desktop/butterfli/build/butterfli.build/Debug-iphonesimulator/butterfli.build/Objects-normal/i386/butterfli.LinkFileList -mmacosx-version-min=10.6 -all_load -Xlinker -objc_abi_version -Xlinker 2 -framework Foundation -framework UIKit -framework CoreGraphics -lOAuth -lxml2 /Users/pratgupta/Desktop/butterfli/LinkedInClientLibrary/build/Debug-iphonesimulator/libLinkedInClientLibrary.a -o /Users/pratgupta/Desktop/butterfli/build/Debug-iphonesimulator/butterfli.app/butterfli

ld: duplicate symbol _EstimateBas64EncodedDataSize in /Users/pratgupta/Desktop/butterfli/LinkedInClientLibrary/build/Debug-iphonesimulator/libLinkedInClientLibrary.a(Base64Transcoder.o) and /Users/pratgupta/Desktop/butterfli/Twitter+OAuth/Libraries & Headers/libOAuth.a(Base64Transcoder.o)
collect2: ld returned 1 exit status
Command /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/gcc-4.2 failed with exit code 1
</code>
Comment: you have added 2 file in which size_t EstimateBas64EncodedDataSize(size_t inDataSize) function is define... need to remove one....


Language regularity implications

Question: I have to decide whether this implications are true or false and prove it.
Will you help me?
$L.\{a,b\}^{*}$ is regular $\implies$ $L$ is regular
$L.\{a,b\}^{*}$ is not regular $\implies$ $L$ is not regular
Thanks
Answer: For the first, consider any irregular $L\subset \{a,b\}^*$ with $\epsilon\in L$. What do you conclude?
For the second, what can you say about $L.\{a,b\}^*$ if $L$ is regular?
Comment: Thanks for your response.                                          a) Any language on alfabet {a,b} concated to {a,b}* must be regular because L.{a,b}* = {a,b}*                                             b) There is no language which is not regular when concated to {a,b}*, so the first term is always false so implication is always true. Am'I right?
Comment: @Milwoukee: What you say for (a) is not true; it **is** true for languages that contain $\epsilon$, which may be what you meant, but if $\epsilon\notin L$, then $L\cdot\{a,b\}^*\ne\{a,b\}^*$. What you say for (b) is again not true as you said it; what is true (and what I suspect you meant) is that if $L$ is regular, then $L\cdot\{a,b\}^*$ is regular, which does indeed mean that the implication in the problem is true.

Language regularity implications


Insert Node into a Tree - Racket

Question: I am trying to add a new node to the tree. The following are my definitions and function type:
<code>(define-struct (Some T)
  ([value : T]))

(define-type (Option T)
  (U 'None (Some T)))

(define-type BST (U 'E Nd))

(define-struct Nd
  ([root : Integer]
   [lsub : BST]
   [rsub : BST]))

(: insert : Integer BST -> BST)
;; insert an item into a tree
;; note: do not insert duplicate items
(define (insert n x)
  (match x
    ('E 'E)
    ((Nd ro ls rs)
     (cond
       ((= (size x) 1) (Nd ro (Nd n 'E 'E) 'E))
       (else
        (Nd ro ls rs))))))
</code>
Insert is the insert that will insert the node into the tree.
The following is the command that I will give:
<code>(insert 10 (Nd 1 (Nd 2 (Nd 4 'E 'E) (Nd 5 'E 'E)) (Nd 3 (Nd 6 'E 'E) (Nd 7 'E 'E))))
</code>
And it should insert ten into the tree. However, I am learning independently at home and I have NO idea what to do. Please help. Thank you so much!
Comment: In case you've missed them, there are two good books available for free online: [SICP](https://mitpress.mit.edu/sicp/) and [HtDP](http://www.htdp.org/). They're not about Typed Racket, but the principles are the same.
Answer: You're missing the recursion, and your base case is wrong.
Inserting in an empty tree creates a tree with one node.
Inserting in a non-empty BST has three cases:

If the item is the same as in this node, return the tree unchanged
If the item is smaller than this node, insert in the left subtree
Otherwise, insert in the right subtree

Something like
<code>(define (insert n x)
  (match x
    ('E (Nd n 'E 'E))
    ((Nd ro ls rs)
     (cond
      ((= n ro) x)
      ((< n ro) (Nd ro (insert n ls) rs))
      (else     (Nd ro ls (insert n rs)))))))
</code>
The tree you're aiming to insert in isn't a BST though, so this won't work.
Your tree has the following structure:
<code>   1
  /\
 2  3
 /\ /\
4 5 6 7
</code>
A search tree with those elements would look like this:
<code>   4
  /\
 2  6
 /\ /\
1 3 5 7
</code>
which is
<code>(Nd 4 (Nd 2 (Nd 1 'E 'E) (Nd 3 'E 'E)) (Nd 6 (Nd 5 'E 'E) (Nd 7 'E 'E)))
</code>

Insert Node into a Tree - Racket


how to see executed hql as sql query in console in grails application

Question: i want to see executed hql in my grails app as sql query in console. like in hibernate we can set this in config file. like
<property name="show_sql">true</property>
    <property name="format_sql">true</property>
    <property name="use_sql_comments">true</property>

Answer: There are two things you have to do.
First, in your Datasource.groovy you have to enable logging of SQL:
dataSource {
   dbCreate = ...
   url = ...
   ...
   logSql = true
}

Secondly, you have to enable the log4j settings in your Config.groovy:
log4j = {
   ...
   debug 'org.hibernate.SQL'
   trace 'org.hibernate.type'
}

With both of these changes in place you will see your SQL/HQL statements being logged.
Comment: i am facing this problem, [http://stackoverflow.com/questions/2536829/hibernate-show-real-sql], can i set up http://www.mkyong.com/hibernate/how-to-display-hibernate-sql-parameter-values-solution/ in grails
Comment: That's a different question than the one you have posted here. I would recommend you post a new question asking how to setup P6Spy with Grails.


Proof of $L^2(X, H)$ isomorphic to $L^2(X) \otimes H$

Question: Let $(X, \mu)$ be a measure space and let $H$ be a Hilert space. Let $L^2(X, H)$ denotes the class of all functions $f: X \rightarrow H$ such that $\int ||f(x)||^2d\mu(x) < \infty$.How to prove that $L^2(X, H)$ isomorphic to $L^2(X) \otimes H$? Is it true alwys or do we need any assumtions?
Comment: The Hilbert spaces should be separable and $\otimes$ is the [tensor product of Hilbert spaces](https://en.wikipedia.org/wiki/Tensor_product_of_Hilbert_spaces)
Answer: Let $\mathcal{S}_{X,H}\subseteq L^2(X,H)$ denote the space of simple functions, i.e. functions of the form $f(x)=\sum_{i=1}^n e_i 1_{A_i}$, where $e_i\in H$ and the $A_i$ are disjoint and have finite measure. The function $e_i 1_{A_i}$ is to be understood as the function takes value $e_i$ on $A_i$ and $0$ else.
Likewise, define $\mathcal{S}\subseteq L^2(X)$ be the usual simple functions.
Let $\otimes_{Vect}$ denote the algebraic tensor product, and define
$T: \mathcal{S}\otimes_{Vect}H\to \mathcal{S}_{X,H}$
to be the linear extension of
$$
T( 1_{A}\otimes e)=e1_{A}
$$
Then, we see that for $g_1,g_2$ of the form $\lambda_j 1_{A_j}$ and $e,f\in H$, we have
$$
\langle T(g_1\otimes e),T(g_2\otimes f)\rangle_{L^2(X,H)}=\int_X 1_{A_1}(x)1_{A_2}(x) \langle e,f\rangle_H \textrm{d}\mu(x)=\mu(A_1\cap A_2)\langle e,f\rangle_H =\langle g_1,g_2\rangle_{L^2(X)}\langle e,f\rangle_H=\langle g_1\otimes e,g_2\otimes f\rangle_{L^2(x)\otimes H},
$$
and hence, $T$ is an inner-product preserving linear isomorphism. Furthermore, $\mathcal{S}\otimes_{vect} H$ is clearly dense in $L^2(X)\otimes H,$ since $\mathcal{S}$ is dense in $L^2(X)$. This implies that $L^2(X)\otimes H$ is isomorphic to the closure of $\mathcal{S}_{X,H}$ in $L^2(X,H)$, and this is the space of so-called strongly measurable $L^2(X,H)$-functions.
Hence, a necessary and sufficient condition is that $L^2(X,H)$ is isomorphic to its subspace of strongly measurable functions, and I'm sadly not an expert on this, but this is apparently not always the case.
Comment: +1 does separability imply this condition, that You mentioned at the end?
Comment: Definitely: Let $(e_n)_{n\in \mathbb{N}}$ be an ONB of $H$ and note that any $f:X\to H$ can be written $f(x)=\sum_{n=1}^{\infty} \lambda_n(x) e_n$. Note that $f_N=\sum_{n=1}^N \lambda_n(x) e_n$ clearly belongs to the closure of $\mathcal{S}_{X,H}$ by simply approximating each $\lambda_n$ by simple functions. However, $||f-f_N||^2=\int_X \sum_{n>N} |\lambda_n|(x)^2\textrm{d} \mu(x),$ which goes to $0$, since $f\in L^2(X,H)$. Separability is, of course, crucial to this proof, but I don't know if it's necessary to have an argument of this form.
Comment: Excellent answer, I would guess separability is necessary too, on non-separable Hilbert spaces [this post](https://mathoverflow.net/questions/230423/nonseparable-hilbert-spaces) is interesting


Python Firebase Admin Sdk Query Timestamp

Question: How can I retrieve documents that have a createdAt timestamp newer than a certain date?
Something like:
firstDayOfMonth = datetime.date.today().replace(day=1)
transactions = db.collection('productTransactions').where('createdAt', ">=", firstDayOfMonth).get()

Comment: Hi did you find a way to do this query in Python?
Answer: The problem is that your firstDayOfMonth is of class date, while the Firebase uses format Timestamp for dates and time (which is datetime in Python).
You can do:
firstDayOfMonth = datetime.date.today().replace(day=1)
# datetime.date(2019, 2, 1)

dt = datetime.datetime.combine(firstDayOfMonth, datetime.datetime.min.time())
# datetime.datetime(2019, 2, 1, 0, 0)

transactions = db.collection('productTransactions').where('createdAt', ">=", dt).get()


How can I access all objects of class data.frame inside .GlobalEnv in R

Question: I have 8,000 data.frames inside my global environment (.GlobalEnv) in R, for example
head(ls(.GlobalEnv))
#[1] "db1" "db2" "db3" "db4" "db5"
tail(ls(.GlobalEnv))
#[1] "db7996" "db7997" "db7998" "db7999" "db8000"

How can I access each of the data.frames?
I could access the data.frames using .GlobalEnv$"db1", but it is useless because I want to carry out a linear regression for each one.
Answer: You could use a combination of eapply and mget to put all data.frames that are present in the global environment in a list:
x <- eapply(.GlobalEnv, 'is.data.frame')
dflist <- mget(names(x[unlist(x)]), .GlobalEnv)

Then you can use for example lapply(dflist, ...) to run a regression on each of them.

A very concise alternative approach contributed by @RichardScriven in the comments is:
dflist <- Filter(is.data.frame, as.list(.GlobalEnv))

Comment: nice, hadn't thought of `eapply`
Answer: The simplest approach I can think of would be a basic for loop using mget.
for(df in ls(.GlobalEnv)){
    print(get(df))
}

You can then apply whatever operation you like on the mget result.
Note - this assumes the only variables in the environment are data.frames for your purposes as it doesn't discriminate  A more restrictive for loop would be:
for(df in ls(.GlobalEnv)){
    if(is.data.frame(get(df))){
        print(head(get(df)))
    }
}

which just uses is.data.frame to check if the object is indeed a data.frame.
Answer: Perhaps:
.Globalenv[ls()]

Can also restrict to only items beginning with 'db' using regex patterns
Comment: I don't understand this.  You can't subset an  environment.  Once you fix the typo in `.GlobalEnv` it still gives an error.
Answer: I have found another solution:
db1 <- data.frame(x = c(1,2,3),y = c(1.1,1.2,1.3))
db2 <- data.frame(x = c(1,2,3,4),y = c(2,2.1,2.2,2.3))
db3 <- data.frame(x = c(1,2,3,4,5),y = c(3,3.1,3.2,3.3,3.4))
ls()
#[1] "db1" "db2" "db3"
nombres <- ls()
eval(parse(text = nombres[1]))
#  x   y
#1 1 1.1
#2 2 1.2
#3 3 1.3
lm(y~x,data = eval(parse(text = nombres[1])))

Thanks!