Linha e coluna javascript/Jquery

Question: Preciso de um script puro ou com jquery que execute uma estrutura de linha e coluna. Exemplo, se o usuario digitar 7 tenho que imprimir a seguinte estrutura:
x
xx
xxx
xxxx
xxxxx
xxxxxx
xxxxxxx

Tentei utilizar for porém só executa a linha.
Answer: Tem várias formas de fazer isso. Quando você diz imprimir, vou usar o console para mostrar o resultado.
var numero = 7; // Número inserido pelo usuário.
var caracter = 'x'; // Caracter que deseja imprimir.
var resultado = ''; // Variável para armazenar o resultado e imprimir.

for(i = 0; i < numero; i++){
    resultado = resultado + caracter;
    console.log(resultado);
}

Isso irá resultar no console:
x
xx
xxx
xxxx
xxxxx
xxxxxx
xxxxxxx

Comment: Perfeito, muito obrigado!
Comment: De nada, disponha!

Linha e coluna javascript/Jquery


What is Azure Data Explorer? A Datalake? A datawarehouse?

Question: As the title says, I'm confused about the role Azure Data Explorer has in the Azure data ecosystem. The documentation states that it's an analytics tool, but technically it ingests data from different sources such as kafka, spark and go on.
Is it some kind of enhanced datawarehouse?
TIA
Answer:
"For our own troubleshooting needs we wanted to run ad-hoc queries on
the massive telemetry data stream produced by our service. Finding no
suitable solution, we decided to create one"
                            - Ziv Caspi Architect, Azure Data Explorer -

Once we established the need, we can discuss the implementation.
Here are some key features:

The service is distributed and can be easily scaled out (or in) which makes it good fit for big data (big as you need).
The data is ingested into the service in batch/stream and stored in a propriety format.
The data is stored in tables (columns & rows).
Columns' data types include bool, int, long, real, decimal, datetime & timespan as well as native support for JSON (the dynamic data type).
Everything is indexed, including free text that is tokenized and indexed with Full-text search index, which mean we can find rows with specific tokens in sub-seconds - seconds.
The data is stored in a columnar format which makes it great for aggregations on large volumes.
ADX has its own highly intuitive query language, KQL (Kusto Query Language), which supports numerous analytical features including distributed joins.
ADX has native support for time-series with a lot of built-in functionality around it (forecast, anomaly detection etc.).
Since the service was created to handle telemetry and telemetry does not change over time, the service was created as append only (inserts) + built-in support for data retention.
Later on, soft & hard deletes were added.
As of today, updates are not supported.

Here is some additional reading:

Ziv Caspi: Azure Data Explorer Technology 101
Brian Harry: Introducing Application Insights Analytics
Uri Barash: Azure Announcements: Azure Data Explorer


Using Code Behind Model with MVC

Question: I am trying to use ASP.NET Server Controls (ASP.TextBox etc) with MVC (to take advantage of the validation power, designer support etc). How can I shoehorn this into MVC architecture? For example, how can my button.click route to the controller or how can the data inside my server controllers be accessed via viewPage?
Can point me to an article or reference that will help to clear up my messy design? Or, is it better for me to stick to MVC and inline styles?
Answer: I would stick with the MVC way or revert to web forms... Are you trying to get support for designers using dreamweaver?  That's actually a good point, mvc's HtmlHelper is not dreamweaver friendly.
Comment: even VS Desginer cannot show the elements generated using HTMLHelper Object so in practice you cant have WYSWYG kind support in MVC :(
Comment: I should mention, working with designers has been harder with mvc :/  having explain the views is getting a bit old
Answer: I wouldn't try to mix the two; they are very different approaches, and aren't really compatible with each-other during the same page request. RenderPartial might work, but I wouldn't wager any money.
Note that for MVC views, the code-behind file (usually empty) is also being removed in the RC.
Comment: Yes I agree with your , but my point is that Microsoft still can embed the Server Controls in MVC architecture and after delving in their details i realized the MVC framework by MS or MonoRail by Open Source guys do not have much differences then,

Using Code Behind Model with MVC


Solve the linear congruence: $2^{2015}x\equiv 1\pmod {13}$

Question: Solve the linear congruence: $2^{2015}x\equiv 1\pmod {13}$
$x\equiv (2^{2015})^{\phi(13)-1}\equiv (2^{2015})^{12-1}\equiv 2^{22165}\equiv y\pmod{13}$
$22165=13\cdot 1705$
$y=2^{13} $ or $y=2^{1705}$
Is this correct?
Comment: Your answer should be among $\{0,1,2,\ldots,12\}$.
Comment: Much easier is to multiply both sides by $2$ and note that $2016\equiv 1\pmod{13}$. Note there is only one solution modulo $13$. The logic of yourr argument is not clear. The $\varphi$-function part is right, though too elaborate for this problem.
Answer: By Fermat's Little theorem: $2^{12}\equiv 1\pmod{13}$.
$$2^{2015}\equiv 2^{2015\bmod {12}}\equiv 2^{11}\equiv \frac{1}{2}\equiv \frac{14}{2}\equiv 7\pmod{13}$$
So you're solving $7x\equiv 1\pmod{13}$.
$$7x\equiv 1\equiv 14\pmod{13}\stackrel{:7}\iff x\equiv 2\pmod{13}$$

Using your method: you've found that $x\equiv 2^{22165}\pmod{13}$. By Fermat's Little theorem:
$$2^{22165}\equiv 2^{22165\bmod 12}\equiv 2^{1}\equiv 2\pmod{13}$$
Your argument was alright until you said "$y=2^{13}$ or $y=2^{1705}$". It's unclear what logic you were using there.


Modify field names in REST export

Question: I want to use a custom field in my Views REST export, but rather than having "nothing": "My custom text", I would like "mycustomtext": "My custom text". Is there a way to do this from within the UI?
Answer: Serializer settings: force using field & json
Show: fields
Show settings: type an alias for each field
Above settings are shown in the images below
Comment: Despite "no code answer" requested, it's also quite easy to provide your own Normalizer class if this doesn't exactly suit.

Modify field names in REST export


How to add CC to a webform email?

Question: I'm using Drupal 7.
Is it possible to add a CC to a webform email?
I was using
function theme_webform_mail_headers($variables) {
  $headers = array(
    'X-Mailer' => 'Drupal Webform (PHP/' . phpversion() . ')',
  );
  return $headers;
}

changing it with
    function MYTHEME_webform_mail_headers($variables) {
      $headers = array(
'CC' => 'email@example.com', 'X-Mailer' => 'Drupal Webform (PHP/'. phpversion() .')',
 );
      return $headers;
    }

It does not work, I've cleared all the chaches and it does not add the CC.
How could I add the CC?
Thanks in advance.
Comment: Instead of a CC:, why not just add the e-mail address on the "E-mails" tab of the webform content?  You can easily send the output of the webform to any number of e-mail addresses.
Comment: One of the receiving email is a component. How can I add a component and an email? If I put %value[email] it does not accept it.
Answer: Just posting this for future viewers:
You can add a hook to the theme_webform_mail_headers in your theme's template.php
function mytheme_webform_mail_headers($variables) {
    $headers = array(
    'X-Mailer' => 'Drupal Webform (PHP/' . phpversion() . ')',
    );

    $headers['cc'] = 'firstname.lastname@example.com';

    return $headers;
}

Answer: It shouldn't be done in theme, but in a module (business vs presentation logic).
Don't know if it's still relevant, but this post explains how to mail to several addresses.
Comment: Same question I asked Patrick.
Answer: I actually patched webform_reply_to to work with webform-7.x-4.0-rc3 (using patch identified in Issues) and then modified it to create a Cc header field instead of Reply-To.
In order for it to work with multiple email addresses, you need to comment out the validate call in the module.
Also, email type fields won't take multiple addresses, so you need to use a textfield for your cc field on the form and use the token for that field instead of selecting a pre-defined email field.
Works well, though.

How to add CC to a webform email?


95% confidence interval for p in R

Question: I have to construct a 95% confidence interval using R, but I'm completely lost :(
This is the assignment:

In a random sample of 200 claims filed against and insurance company
  writing collision insurance on cars, 84 exceeded \$1200. Construct a
  95% confidence interval for the true proportion of claims filed
  against this insurance company that exceed \$1200.

Please help me :(
Comment: Please add the `[self-study]` tag & read its
[wiki](http://stats.stackexchange.com/tags/self-study/info). Then tell us
what you understand thus far, what you've tried & where you're stuck. We'll
provide hints to help you get unstuck.
Comment: Are you having a trouble understanding how to program this or how to calculate the confidence interval mathematically or both?  I'm afraid if it's just how to implement this in R, it's off topic and better suited for the Stack Overflow boards.
Comment: Why would you use `t.test` when you're dealing with a *proportion*?
Comment: No I know how to use R, but I don't understand how I can find the answer using R by inserting my values in to an "equation" saying fx. 'qnorm(37,100,5)'.

Mathematically I would solve by using this equation (but that's not my problem): x/n -(Zaplha/2)sqrt((x/n(1-x/n))/n)<p<x/n+(Zapha/2)sqrt(x/n(1-x/n)/n).
Comment: If i had a set of data, I would copy them into R and use the function "t.test(arg)" and it would have given me the 95% confidence interval, but now that I'm only provided with the above mentioned data, I don't know which function(s) to use to find the 95% confidence interval :(

So I guess i would say I'm having trouble programming this.
Comment: `prop.test( 84, 200 )`
Answer: Well let's go on what you've given us, and what you've demonstrated that you understand.
You've told us that you know you want to solve:
$$
\frac{x}{n} \pm z_{\alpha/2} \sqrt{\frac{x/n \times(1-x/n)}{n}}
$$
So plugging in the relevant values into the equations which you've given us will give us the solution.
The only question remains is exactly what is $z_{\alpha/2}$, and what is its distribution?
Once you can solve that you can easily determine the confidence interval simply by entering the equation like you would in any other programming language:
<code>x = ??
n = ??
z = ??
xn = x/n

zstat = z * (sqrt(xn*(1-xn))/sqrt(n))
lowerci = (xn - zstat)
upperci = (xn + zstat)
</code>

Other things that you can think about:

What exactly is the distribution you are assuming the question?
Is normality assumption required?
Is there an exact test?
Why would/wouldn't t-test function work out in this case?

95% confidence interval for p in R


Probability and Stats: 100 random samples, lognormal random variable, probability that average is less than 9?

Question: So we have a lognormal random variable Y with mean 10.2 and standard deviation 15.3. If we take 100 random samples with these properties, what is the probability that the average for this sample is less than 9?
Is the central limit theorem relevant here? I'm having trouble because of that "average" part.
Answer: The Central Limit Theorem is very relevant. Let $S$ be the sum of your lognormals. We are interested in the random variable $X=\dfrac{S}{100}$.
Since $S$ is a sum of quite a few nicely behaved independent identically distributed random variables, $S$, and therefore $X$, the sample average (sample mean) has a distribution which is nicely approximated by a normal.
Note that $X$ has mean $10.2$. The variance of $S$ is $(100)(15.3)^2$. Thus the variance of $X$ is $\dfrac{1}{100^2}(100)(15.3)^2=\dfrac{(15.3)^2}{100}$. So the standard deviation of $X$ is $\dfrac{15.3}{10}$. (We could have written this down directly: I wanted to mention the theory.)
Now you want the probability that a normal with known mean $10.2$ and standard deviation $1.53$ is less than $9$. I expect that this is a standard calculation for you.
Comment: Absolutely it is! Thank you so much, I wasn't sure if I should go down this route so thanks for clearing things up!!


Can't decide database structure. Which one should i go for?

Question: I'm developing small application for a company. What they want me to do is some kind of event website which they can add participants for each event. My question is should I have one table for all the participants for all events or should I create a table for each event and store participants inside it ?
Sorry about my English if there are any grammar errors.
Answer: You should have 3 tables:
One with participants (participant_id, name, address...)
One with events (event_id, date, place...)
and one with participants to the events (id, participant_id, event_id)
Answer: Personally, I would use three tables. The first stores the list of events, the second stores the list of participants, and the third contains the relationship between events and participants (stores event_id and participant_id combinations).
That allows you to keep a list of participant details that's separate from any given event, so they can be invited to/added as participants of future events from a pre-populated list, rather than requiring the same details to be added repeatedly.
Answer: Tables for events, participants and their relations. Read about data normalization.
Answer: The following tables should help you map the requirement:
Events - to hold all the Event specific Information
Users - to hold all the Users in the website (remember, a user can participate in more than 1 event)
Participants - this holds the relationship (many to many) for the users who participate in the Events
So sample columns:

Events - event_name, event_description, event_date
Users - first_name, last_name, email
Participants - event_id(fk : Events.id), user_id(fk: Users.id)


Help with induction - For $n > 1$ a natural number $n-1$ is also a natural number.

Question: The problem I am stuck on is this one:  If $n>1$ is a natural number then $n-1$ is also a natural number.  I am told to use induction.
Normally I would just do the following:
My statement is $P(n)=n-1$ such that $n-1$ is a natural number.
Base case.  Since $n>1$, I use the base case of $n=2$.  Thus $P(2)=1$ and this is a natural number.  Now I choose some $k \in \mathbb{N}$ such that $k > 2$.  So $P(k)=k-1 \in \mathbb{N}$.
Past this point I get speculative.
Now for my inductive step.  $P(k+1)=(k+1)-1=k$.  I don't know if this is allowed, but I noticed that by rearranging $P(k+1)=(k-1)+1 \Rightarrow P(k+1)=P(k)+1$.
Comment: No you are still a bit confused about it. $P(n)$ has to be a statement and you prove the statement to be true for all $n$ using induction. Your statement $P(n)$ should be something like "the number $n-1$ is a natural number". You then proceed to prove that P(2) is true, i.e. "the number $1$ is a natural number" and that for $k>2$, $P(k+1)$ is true given that $P(k)$ is true, i.e. "the number $k+1$ is a natural number" given that "the number $k$ is a natural number".
Comment: Dont you mean to say that $P(n)$ is the statement that $n-1$ is a natural number?
Comment: Yes, that is correct.  I have added that.
Answer: We want to show that if the result is true for $n=k$, then it is true for $n=k+1$. Of course it is true for $n=k+1$, we do not even have to use the induction hypothesis.
To put the point in logical form, we want to show that $A(k)\implies A(k+1)$. If we can prove $A(k+1)$, then we have shown that $A(k)\implies A(k+1)$.
Comment: In my answer above, I gave an induction proof (apart from not verifying the base case, since you had done that).
Comment: @EMKA: Yes, we are dealing here with a trivial case of induction, and sometimes when a problem is too easy, it can cause trouble. Induction basically says that if we start at $1$ and keep taking unit steps forward, we travel through all the positive integers.
Comment: With regards to this problem, I'm still unsure how to proceed with induction.
Comment: I guess I'm being tortured because the previous problem in this set, which involved proving the identity $1^2+2^2+...n^2=\frac{n(n+1)(2n+1)}{6}$ involved some computation.


Extracting a Value From an XML File in C#

Question: Can someone help me out with extracting the "Value Y" of 4.247 in this XML file. I've searched through previous threads but can't seem to apply them to this structure.
<Chart1>
    <Chart1_SeriesGroup_Collection>
        <Chart1_SeriesGroup Label="MP_Trend_Data\MP_Prog/MP_DAILY_FLOW">
            <Chart1_CategoryGroup_Collection>
                <Chart1_CategoryGroup Label="12/24/2017 1:58:19 AM">
                   <Value X="0001-01-01T10:30:00+10:30"/>
               </Chart1_CategoryGroup>
               <Chart1_CategoryGroup Label="12/24/2017 1:58:19 AM">
                   <Value X="0001-01-01T10:30:00+10:30"/>
               </Chart1_CategoryGroup>
               <Chart1_CategoryGroup Label="12/24/2017 1:59:19 AM">
                   <Value X="0001-01-01T10:30:00+10:30"/>
               </Chart1_CategoryGroup>
               <Chart1_CategoryGroup Label="12/24/2017 1:59:19 AM">
                   <Value X="0001-01-01T10:30:00+10:30"/>
               </Chart1_CategoryGroup>
               <Chart1_CategoryGroup Label="12/24/2017 1:58:19 AM">
                   <Value Y="4.24700021743774" X="2017-12-24T12:28:19.333+10:30"/>
               </Chart1_CategoryGroup>

code I've tried:
var xDoc = XDocument.Load("C:\\attachment\\Flow.xml");

        XmlDocument xml = new XmlDocument();
        xml.LoadXml(xDoc.ToString());

        XmlNodeList xnList = xml.SelectNodes("/Chart1/Chart1_SeriesGroup_Collection/Chart1_SeriesGroup[@Label='MP_Trend_Data\\MP_Prog/MP_DAILY_FLOW']");

        foreach (XmlNode Node in xnList)
        {
            XmlNodeList ynList = Node.SelectNodes("/Chart1_CategoryGroup_Collection/Chart1_CategoryGroup/Value");
            foreach (XmlNode Node2 in ynList)
            {
                textBox1.Text = Node2.Attributes["Y"].Value.ToString();
            }
        }

Comment: What have you tried ? Your code ? Errors ? We can't just write for you!
Comment: This is not a free coding service. You need to try for yourself and ask a question when your code does not work. Please read [ask].
Comment: Please post a complete and valid XML example.
Comment: I've tried this:

var node = xmlDocument.SelectSingleNode("//*[@label='MP_Trend_Data\\MP_Prog/MP_DAILY_FLOW']");

to try and extract the node but it's returning a null value
Comment: @Chris edit your question to include details. Do not comment question specifics
Answer: var xmlStr = @"
    <Chart1>
        <Chart1_SeriesGroup_Collection>
            <Chart1_SeriesGroup Label='MP_Trend_Data\MP_Prog/MP_DAILY_FLOW'>
                <Chart1_CategoryGroup_Collection>
                    <Chart1_CategoryGroup Label='12/24/2017 1:58:19 AM'>
                        <Value X='0001-01-01T10:30:00+10:30'/>
                    </Chart1_CategoryGroup>
                    <Chart1_CategoryGroup Label='12/24/2017 1:58:19 AM'>
                        <Value X='0001-01-01T10:30:00+10:30'/>
                    </Chart1_CategoryGroup>
                    <Chart1_CategoryGroup Label='12/24/2017 1:59:19 AM'>
                        <Value X='0001-01-01T10:30:00+10:30'/>
                    </Chart1_CategoryGroup>
                    <Chart1_CategoryGroup Label='12/24/2017 1:59:19 AM'>
                        <Value X='0001-01-01T10:30:00+10:30'/>
                    </Chart1_CategoryGroup>
                    <Chart1_CategoryGroup Label='12/24/2017 1:58:19 AM'>
                        <Value Y='4.24700021743774' X='2017-12-24T12:28:19.333+10:30'/>
                    </Chart1_CategoryGroup>
                </Chart1_CategoryGroup_Collection>>
           </Chart1_SeriesGroup>
        </Chart1_SeriesGroup_Collection>
    </Chart1>";

var xml = XElement.Parse(xmlStr);
var firstY = xml.Descendants("Value").FirstOrDefault(v => v.Attribute("Y") != null);
if (firstY != null)
{
    var y = firstY.Attribute("Y").Value;
}

Comment: Thanks JohnyL. How do I get my xml file into a string format as above?
Comment: @Chris -Pardon?
Answer: Try xml linq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            var results = doc.Descendants("Chart1_CategoryGroup").Where(x => x.Element("Value").Attribute("Y") != null).Select(x => new {
                label = (DateTime)x.Attribute("Label"),
                y = (double)x.Element("Value").Attribute("Y"),
                x = (DateTime)x.Element("Value").Attribute("X")
            }).ToList();
        }
    }
}


Making sense of the RHEL release string when looking at yum info output?

Question: I am trying to understand how interpret the release field displayed by yum info on RHEL 6. for example the commands below give wildly different values for Relase, what exactly is release refering to, the RHEL server release, the package release?
# yum info java-1.7.0-openjdk.x86_64
Loaded plugins: product-id, rhnplugin, security, subscription-manager
Updating certificate-based repositories.
Unable to read consumer identity
Available Packages
Name        : java-1.7.0-openjdk
Arch        : x86_64
Epoch       : 1
Version     : 220.127.116.11
Release     : 2.2.1.el6_3.3
Size        : 25 M
Repo        : rhel-x86_64-server-6
Summary     : OpenJDK Runtime Environment
License     : ASL 1.1 and ASL 2.0 and GPL+ and GPLv2 and GPLv2 with exceptions
Description : The OpenJDK runtime environment.

# yum info java-1.7.0-oracle.x86_64
Loaded plugins: product-id, rhnplugin, security, subscription-manager
Updating certificate-based repositories.
Unable to read consumer identity
Available Packages
Name        : java-1.7.0-oracle
Arch        : x86_64
Epoch       : 1
Version     : 220.127.116.11
Release     : 1jpp.5.el6_3
Size        : 38 M
Repo        : rhel-x86_64-server-supplementary-6
Summary     : Oracle Java Runtime Environment
License     : Oracle Binary Code License Agreement for the Java SE Platform Pr
Description : The Java Runtime Environment (JRE) contains the software and tools
            : that users need to run applets and applications written using the Java
            : programming language.

# yum info httpd
Loaded plugins: product-id, rhnplugin, security, subscription-manager
Updating certificate-based repositories.
Unable to read consumer identity
Installed Packages
Name        : httpd
Arch        : x86_64
Version     : 2.2.15
Release     : 15.el6_2.1
Size        : 2.9 M
Repo        : installed
From repo   : rhel-x86_64-server-6
Summary     : Apache HTTP Server
URL         : http://httpd.apache.org/
License     : ASL 2.0
Description : The Apache HTTP Server is a powerful, efficient, and extensible
            : web server.

Answer: The two attributes can be summarised as follows

Version - This is the upstream version, in your Java example, JDK 126.96.36.199 from Oracle
Release - This is the RPM package maintainers version of the rpm package itself, in the JDK 1.7 example this is "1jpp.5.el6_3". Let's say the package maintainers fix a bug in the RPM packaging (e.g. forgotten documentation) then they can increment the "Release" field to a newer version e.g. "1jpp.6.el6_3" (admittedly, this is a complex release number)

I hope that clarifies what is going on.
Comment: el6_2 or el6_3 indicate the version of Red Hat Enterprise Linux where the package last received a significant update. The last digit doesn't just receive vanity increases. The *1jpp.5* is also an upstream (JPackage) release, which Red Hat does not increment. The appropriate bugfix release for this package would most likely be *1jpp.5.el6_2.1*.
Answer: The Release field of an RPM is set by whoever created the package, usually the developer working on packaging it. The format is completely arbitrary, and one does not necessarily have any relation to another.
That said, Red Hat will always put el# or el#_# in their Release field, indicating the major and minor versions of RHEL for which the package was built.
Comment: The field is *not* completely arbitrary. While it doesn't follow guidelines as strict as, say, [SemVer](http://semver.org), Red Hat and Fedora packages are bound by the [Fedora Packaging Guidelines](http://fedoraproject.org/wiki/Packaging:NamingGuidelines#Package_Versioning).
Comment: What the RPM software accepts in the field is completely arbitrary. What Red Hat actually uses the field for is not.
Comment: Good distinction. :)


How to use resampling to reconstruct an obesity cohort?

Question: In a study, the administrative data contains everyone in a population. I am using ICD-10 code E65-E68 (excluding E66.3 which is overweight) to construct the obese cohort. Conversely, the rest of the population who didn't receive these codes will be considered as non-obese. The problem is 1) the code is not completely recorded in the dataset (which leads to low sensitivity (or a lot of false negatives) but high specificity), and 2) while the ones who got the obesity code is highly accurate (high specificity), they tend to be more obese and severe than the average obese population (which cannot be directly observed in the current study).
In the literature, they found that the sensitivity using this method ranges between 10% to 50%. I wonder if I can conduct a sensitivity analysis in which I reconstruct the "obesity" cohort from sampling people who are originally labelled into the non-obese cohort. For example, I can sample a certain percentage of the overweight and another percentage from non-obese and non-overweight individuals into the obese cohort to account for the potential high false negative rate. Is there a formalized way to do this? I try to find appropriate literature, but couldn't find anything directly addresses my set-up.

Edited to provide more information
The study objective is to compare the costs due to utilized clinical services between the obese and non-obese cohorts. The clinical utilization information is recorded in the dataset already. Because of the low sensitivity and the readily-identified obese individuals using this approach are likely more severe and using/costing more with the clinical services, my intent is to reconstruct the obese cohort in sensitivity analysis to reduce the underlying bias (towards overestimation of the higher costs amongst the initially identified obese cohort).
For example, some of the overweight individuals should probably have a true obese status, so I'd like to resample some of these overweight individuals into the new "obese" cohort. Same thing goes with the non-overweight/non-obese individuals.
All the variables indicative to obese status will be used to identify the obese individuals. For our discussion, we can assume there is no other information in the database that further inform/relate to the obesity status.
Comment: Please say more about what you're trying to accomplish with your study, in particular what you hope to achieve by accounting for the potentially high false negative rate. Do the data include information that might be associated with obesity status (height, weight, other informative ICD codes)?
Comment: I have added information in the OP.
Answer: If there were a set of cases that you were reasonably certain not to be obese, just as you are reasonably certain that those with particular ICD codes are obese, it might be possible to turn this into a missing-data problem for which there are well established techniques.
Once you have identified cases that are pretty definitively in one or the other category, you label those cases accordingly and then label the other cases as having missing data. Provided that the probability of that missingness is only a function of the information you have, then your data are technically "missing at random" (MAR). That's a much less stringent requirement than for data to be "missing completely at random" (MCAR) in which there is simply a single probability of missingness that applies throughout.
Although your data then would certainly not be MCAR, they would be MAR if the available information on ICD codes, clinical services utilized, provider information, patient characteristics and demographics, etc., was associated with the probability of being missing, and there was no unknown information associated with the probability of being missing. There is no way to prove that a data set is MAR, but it often is a reasonable assumption. That judgment would depend on your knowledge of the subject matter.
If the MAR assumption is reasonable you would use the standard multiple imputation approach. You probabilistically impute obesity-class assignments for all the "missing" values several times, based on the information that you have, generating several complete (albeit imputed) data sets. The higher the fraction of missing data, the more imputation sets you typically have to produce. You then do your analysis on each of those data sets, and combine the results in a way that takes into account the variability both of the modeling itself and of the imputations.
Stef van Buuren, a leader in the field of imputation, has a freely available web book that describes the theoretical basis and practical implementation of multiple imputation. Think about this approach carefully, as it seems to accomplish in a principled way the type of analysis you wish to perform.
One warning, though: obesity is not really an all-or-none phenomenon. It's on a continuum of severity, so that it might be more reliable to evaluate costs along a more graded measure of obesity. For example, if you do the above and find lower costs associated with obesity than you would have just based on the ICD codes, then one could argue that all you are really doing is shifting a threshold at which you assign the all-or-none "obese" label. In general it's not a good idea to break down a continuum into categories. Anything you can do to obtain something other than a binary obese/not distinction would probably be more generalizable and useful way to determine the association of obesity with costs.
Comment: @KubiK888 how likely is someone not even labeled "overweight" to be obese? That's key. I don't know much about ICD coding, so read van Buuren and see if MAR might apply. The more I think about this, though, the more skeptical I am that the simple obese/not will be very informative. To start, why not just use the 3 classes you do have available from ICD: obese, overweight but not marked obese, and others? That at least would put some bounds on the problem. I don't see a way just to "resample" those last 2 classes in a way that would accomplish what you want, outside of multiple imputation.
Comment: Thanks for the insight, I will look closer but like some clarification. The challenge with the current setup is we are only highly certain with individuals identified as obese. From the non-obese individuals, there may be markedly large amount who are obese but not recorded. Likewise, overweight is a subset of the non-obese cohort, it's reasonable to assume quite a portion of them is indeed obese (but wrongly labeled as overweight). Since it's more likely for well-managed and lesser obese individuals to be mislabeled as non-obese, will the MAR assumption be unlikely to hold true?


Common algorithm with an order of Θ(2^n)

Question: What would be a common algorithm with an order of Θ(2^n)? When I say "order", I mean time complexity analysis.  I was thinking exponential growth but are there any that are more computer science oriented?
Comment: Testing the satisfiability of a Boolean formula by enumerating all possible assignments?
Comment: Do you mean to ask for algorithms which run in $\Theta(2^n)$?  (Any polynomial algorithm is $O(2^n)$.)  Are you looking for best-known algorithms that run in $\Theta(2^n)$, or does any problem with a natural $\Theta(2^n)$ algorithm suffice?  Do you care about additional polynomial factors?  For example, the natural dynamic programming solution to the Traveling Salesman Problem runs in $\Theta(2^n \cdot n^2)$.
Comment: any algorithm that enumerates the subsets of a set to find a subset with a certain property
Comment: @Trevor: Your question is ambiguous. You say $O(2^n)$. Even printf("hello world") is $O(2^n)$. Once someone points out a mistake (see Zach's comment), why don't you edit the question to correct it? Also, you are missing the model of computation. I presume you mean the word RAM model.
Comment: @Trevor: I would say BigOh is most commonly _misused_ in algorithm analysis. Take your question for instance. Were you looking for O(n) time algorithms? Probably not, but O(n) algorithms are also O(2^n)...
Comment: In algorithm analysis, Big-Theta is usually reserved for instances where we know the algorithm is optimal.  For example, addition of two $n$-digit numbers must take $\Omega(n)$ because it takes $O(n)$ just to read and write the number.  Grade-school addition of two $n$-digit numbers gives us a $O(n)$ algorithm, so addition can be performed in $\Theta(n)$.  The same applies for comparison-based sorting algorithms; we can prove a $\Omega(n\log{n})$ lower-bound, and so we say that merge sort runs in $\Theta(n\log{n})$.
Comment: @Trevor: I have flagged your comment. In any case, I am confident I know what you wanted. It seemed like you had some misconceptions about BigOh (and I think you still do, based on your not editing the O to be theta) and I was just trying to help you clarify it. I will try once more: BigOh = Upper Bound. Omega = Lower Bound. Theta = Upper and Lower. Good luck.
Comment: Wouldn't a simple brute force comparison algorithm do the job? Say for example the problem would be to find the longest path on a weighted binary tree and you do so by checking out each path (starting from some fixed root vertex) of the tree, you would easily get $2^n$ operations.
Comment: @David: That's if $n$ is the depth of the tree -- but one would usually take $n$ to be the number of nodes -- then if you determine the weights in a single traversal (which is easy) it takes $O(n)$, and even if you do it inefficiently and add up the weights separately for each path, it would still take only $O(n\log n)$.
Comment: @Zach: Anything with a natural Θ(2n) suffices, but I was looking for a common one so I could view some psuedo-code to see how it functions methodically. The TSP is a good example because it does increase exponentially with the number of cities he visits, but again, I would like to use an algorithm that has been documented in code.
Comment: @Moron see edit.
Comment: @Trevor: Insufficient. It still means the same thing.
Comment: @Moron Then I don't understand what your definition of order is.  If you look at the Insertion Sort algorithm it has a worst case scenario of order W(n^2).  It takes roughly n^2 times to complete the basic step of the algorithm for an arbitrary number n.  I need an algorithm that uses 2^n.
Comment: @Trevor: There is a difference between BigOh, Omega and Theta. You are using BigOh, where I presume you mean Theta.
Comment: @Moron If a function is in both BigO and Omega isnt it also in Theta? Big O is the most commonly used asymptotic notation for comparing functions, although in many cases Big O may be replaced with Big Theta Θ for asymptotically tighter bounds.
Comment: Fair enough. You win.
Comment: @Trevor: In the case of describing the running time for an insertion sort, Big-Oh makes sense.  Saying that insertion sort takes $O(n^2)$ time guarantees that the time taken will be within a constant factor of $n^2$.  Note that sometimes insertion sort performs better than this though; for sorted inputs, it runs in $\Theta(n)$.
Comment: Cool, thanks, Zach.  My algorithms class is a pain because the book is terrible and all the teacher does is read directly from the book...
Comment: I found Anany Levitin's book "Introduction to the Design and Analysis of Algorithms" very good on covering both subjects. http://www.aw-bc.com/info/levitin/
Comment: Not much of an example, but a naïve implementation of the simplex method for linear programming will require exponential time if given the Klee-Minty problem.
Answer: The naive algorithm for $3$-coloring takes time $2^n$, though this is not optimal (Wikipedia mentions a $1.3289^n$ algorithm). Lots of other NP-complete programs have $2^n$ algorithms (or in general $c^n$), and it is conjectured that some of them in fact require time $c^n$; if this is true then randomness doesn't help for efficient computation (BPP=P).
Comment: See http://www.math.ias.edu/~avi/PUBLICATIONS/MYPAPERS/IW97/proc.pdf.
Comment: Just curious: Your last sentence means that if the exponential time hypothesis is true, then P=BPP?
Answer: According to Wikipedia, "Solving the traveling salesman problem using dynamic programming" is an exponential time problem. They write $2^{O(n)}$, I'm not sure it's the same as $O(2^n)$. Am I right in thinking that it is the same?
Comment: No. Try $2^{3n}$.
Comment: @Didier Piau: right, thanks!


Multilingual websites - Hiding site till ready

Question: I am having basic workflow problem in creating translated website in Drupal 7. A site was handed to me which was already live(lets say www.mywebsite.com). It is having two languages already (English-www.mywebsite.com and Finnish-www.mywebsite.fi).
Now I need to add new language translation(Swedish). www.mywebsite.se already point to old D6 site (www.oldmywebsite.se). Also in language interface(admin/config/regional/language) Swedish domain entered is old one(i.e. www.oldmywebsite.se) to help visitor still access old site.
Question:
So how can I create new Swedish dev site, something like se.www.mywebsite.com which will be hidden from public but I can still work on translations and it will later replace old Swedish site. Which modules to use or what I need to do at Drupal and domain level?
I have not worked on any translation setup before so I am feeling completely lost.
Any help will be appreciated.
Summary :
www.mywebsite.com      :   new English
www.mywebsite.fi       :   new Finnish
www.oldmywebsite.se    :   old Swedish site

se.www.mywebsite.com   :   Want to create dev Swedish site which will later replace old swedish site

Answer: As long as you do not add se.www.mywebsite.com to the DNS nobody will find it.
You locally can add se.www.mywebsite.com to your hosts file and point it to a IP (maybe your localhost). When ready to be launched you can add a pointer from se.www.mywebsite.com to the IP of the production server.
Comment: I like your solution also, too bad can't flag two answers as solutions. Thanks alot!!
Comment: Great. Glad you got it worked out.
Answer: One option would be to password-protect your dev site; I've been doing this with a test subdomain for a while. You want to add something like this to the beginning of your Drupal .htaccess file:
AuthUserFile /path/to/.htpasswd
AuthName "Development Site"
AuthType Basic

# Change the below to match your actual domain.
SetEnvIfNoCase host se\.www\.mywebsite\.com is_dev

Order deny,allow
Deny from all
Allow from env=!is_dev
Require valid-user
Satisfy Any

You can refer to this if you're unfamiliar with .htaccess password protection or how to generate a .htpasswd file. Anyone who attempts to access the submdomain you have under development will be prompted by the server (Drupal need not get involved) to enter a username and password before they continue.
This could cause conflicts if you have any existing .htaccess-based allow/deny restrictions on your site or any portion of it, but should not conflict with the security restrictions Drupal has later in its default .htaccess file, and it definitely won't interfere with any Drupal modules that restrict access at the PHP/session level.
And as always when editing Drupal's .htaccess, make sure you back up the file and/or copy the changes over whenever you update Drupal core, because odds are it will be overwritten.


Removing Routed Event Handlers through Reflection?

Question: Background:  I'm using WPF and C# (3.5) and am working on an app that allows a user to view a form/window/usercontrol that's already part of a compiled assembly.  When they view it, they should be able to click on any control (buttons, textboxes, even labels), a little popup editor should appear by the control where they can then type in a tooltip, helpID, etc., for that control.
The long and short of it:  I need to imitate a basic design view in WPF.  Which means I need to do at least the following:

Load the usercontrol/window from a given assembly (no problem)
Instantiate it the usercontrol/window (no problem)
Clear all subscribed EventHandlers for all its controls
Assign my own "ShowEditorPopup" EventHandler to each control (shouldn't be a problem)

First off, if anybody has suggestions on an easier or better route to take, please let me know.  (Apparently there is no DesignHost kind of component for WPF (like I've read .NET 2 has), so that's out.)
I'm stuck on the bolded item - clearing any subscribed EventHandlers.  After digging around some and getting into Reflector, I've come up with this cool chunk of dangerous code (here, I'm just trying to get all the EventHandlers for a single Button called someButton defined in the XAML):
<Button Name="someButton" Click="someButton_Click"/>

Here's the code (you can run it from the someButton_Click eventHandler if you want):
public void SomeFunction()
{
// Get the control's Type
Type someButtonType = ((UIElement)someButton).GetType();

// Dig out the undocumented (yes, I know, it's risky) EventHandlerStore
// from the control's Type
PropertyInfo EventHandlersStoreType =
        someButtonType.GetProperty("EventHandlersStore",
        BindingFlags.Instance | BindingFlags.NonPublic);

// Get the actual "value" of the store, not just the reflected PropertyInfo
Object EventHandlersStore = EventHandlersStoreType.GetValue(someButton, null);

// Get the store's type ...
Type storeType = EventHandlersStore.GetType();

// ... so we can pull out the store's public method GetRoutedEventHandlers
MethodInfo GetEventHandlers =
        storeType.GetMethod("GetRoutedEventHandlers",
        BindingFlags.Instance | BindingFlags.Public);

// Reflector shows us that the method's sig is this:
// public RoutedEventHandlerInfo[] GetRoutedEventHandlers(RoutedEvent routedEvent);

// So set up the RoutedEvent param
object[] Params = new object[] { ButtonBase.ClickEvent as RoutedEvent };
// I've also seen this for the param, but doesn't seem to make a difference:
// object[] Params = new object[] { someButton.ClickEvent };

// And invoke it ... and watch it crash!
GetEventHandlers.Invoke(someButton, Params);
}

It works up to the Invoke, which returns:  Object does not match target type (ie, my params or target object are messed).  I've found you can resolve this with:
GetEventHandlers.Invoke(Activator.CreateInstance(someButton.GetType()), Params);
// Also doesn't work...

When I set a watch on the GetEventHandlers MethodInfo, it looks great, it just doesn't like what I'm passing it when I call the Invoke.
I feel like I'm at the very last step of how to get a list of the RoutedEvent Handlers (like good old GetInvocationList(), which doesn't work for WPF RoutedEvents, apparently).  From there, it'll be simple enough to remove those Handlers from each control and have an eventless form, which I can then add my own events to.
Any clues?  Again, if there's a better/easier way to do the task overall, let me know :)
Comment: Wow, you did a great work, I was just trying to do the same. You just gave me the starting point I needed.
Answer: What if you take a different approach. You could call EventManager.RegisterClassHandler() for all events, and then in your handler (assuming the event is for a control on the design surface, and not part of your UI) mark the event as handled.  This should prevent it from being forwarded on to the controls on your design surface, since class handlers are called before standard event handlers.
You'd still need to use reflection to get the list of events provided by a control, but at least this way you wouldn't be using reflection to remove the events. Also, if the assembly you load also registers a class handler (likely before your code does), theirs would be called first, but I would guess that this would be a rare occurrence.
Comment: Great suggestion.  I was wondering if it were possible to block another other events from firing by setting Handled = true, but I didn't know that "Class Handlers" are fired first.

I'll give it a try.  Thanks!
Comment: Pure genius!  After looking at http://www.switchonthecode.com/tutorials/wpf-snippet-class-event-handlers for a related example, my button do anything anymore.  Exactly what I needed.  Thanks!!  Now I'm wondering just how many RoutedEvents I should block besides a simple Button.ClickEvent...  maybe the safest thing would be to "pre-handle" all RoutedEvents returned from EventManager.GetRoutedEvents().  But that's another issue :)

Thanks again!
Comment: And the special cases you mentioned where it could potentially cause problems shouldn't be an issue in our case.  What you've given me fits the situation great.
Comment: I have a similar issue.
I want to clear all the handlers (im talking about private handlers in .NET) for a TextBoxBase.TextChanged.
Answer: If you use GetEventHandlers.Invoke(EventHandlersStore , Params) it seems to work well and does not crash.
Answer: Using your code from above I did this:
// Get the control's Type
Type controlViewType = ((UIElement)control).GetType();

// Dig out the undocumented (yes, I know, it's risky) EventHandlerStore
// from the control's Type
PropertyInfo EventHandlersStoreType =
controlViewType.GetProperty("EventHandlersStore",
BindingFlags.Instance | BindingFlags.NonPublic);

// Get the actual "value" of the store, not just the reflected PropertyInfo
Object EventHandlersStore = EventHandlersStoreType.GetValue(tree, null);
var miGetRoutedEventHandlers
EventHandlersStore.GetType().GetMethod("GetRoutedEventHandlers",
BindingFlags.Public | BindingFlags.Instance);
RoutedEventHandlerInfo[] res =
(RoutedEventHandlerInfo[])miGetRoutedEventHandlers.Invoke(EventHandlersStore,
new object[] { CheckedTreeViewItem.CheckedEvent });

Once you have that then the only problem is that you now have the method info, so you need to get an instance to the object that implements that method. Usually event handlers are defined on the Window or Page object. So to get it:
    var parent = VisualTreeHelper.GetParent(control);
    while (!(control is Window) && !(control is Page))
    {
           parent = VisualTreeHelper.GetParent(parent);
    }
And with that instance you can then invoke the event wtih:
res.[0].Handler.Method.Invoke(parent, new object[] { control, new RoutedEventArgs() }


Does a rest in a harmony exercise make consecutive parallels acceptable?

Question:
In bar 4 there is a rest after the C which I have harmonized with V. In bar 5 there is a leap up to F which I would like to harmonize with I but that would give me parallel 5ths in the outer voices. Or would it? Does the rest mean that the next chord can be harmonized as I wanted?
Comment: Depends, you have to realize that the rules are due to what sounds "correct". A composer would not blindly apply the rules. It is not about right or wrong, it is about degree(no pun intended). Not all parallels are bad and sometimes you find them in "masters" works. A parallel starting and ending phrases will generally not be as problematic if it is clear there is a close(the close itself closes the ambiguity generated by parallels). Parallels are simply an issue with quality where the independence of independent melodies are lost. They generally also sound weak because there are betterchoices
Answer: No, neither the use of a rest or the Unison escapes the problem of consecutive octaves.
What I'm seeing is the chance at chord repetition. You have a C, then a F and then a C again. All these can be considered the same chord. To be specific b-flat: V. You can consider what inversion works best in regards to what goes before and after it.
Comment: Harmonies extend through an immediately following rest. In a biography of Corelli, there is a story about exercises Corelli gave to some students. The students claimed that there were lots of "parallels"; the Corelli suggested remembering the extension of a harmony through the succeeding rest.
Comment: If neither Bars 1-2 nor Bar(s 4-)5 scream "use the same chord for all notes, ignoring inversions" to you, Bar 7 surely should.
Comment: 5th,8tv 5th in the outer voices hardly Makes for a good soprano Dekkadeci, imperfect consonances on those notes sound much better.  That is why I didnt want the same bass note for all 3 soprano tones.
Comment: @armani - I actually think, of the ones I listed above, Bars 1-2 sound the worst when harmonized with the same chord (ignoring inversions) throughout. Both Bars 4-5 and Bar 7 sound better.
Comment: I harmonized those first 3 notes with a I V6 I figure and it sounds good. My books stress that you only really want a perfect consonance for the 1st chord and at points of repose or cadences. My harmonization gets me an octave then a 6th and then a 10th for the Db of bar 2. The C of bar 4 I harmonized with V for an idiomatic P5 in the outer voices. I didnt want to use only root position V for bar 5 because of the perfect consonances I would have in the outer voices (3 in a row) so finally I used V to V6 for bar 5. This gives me a 10th for the second chord.
Answer: Given that you seem to be instructed to use only I or V; and are asked to harmonise "every note", I'd guess that in this instance there wouldn't be much opportunity for such parallels, since these and other rules of voice leading generally apply to changes between chords, not repetitions of the same (and there are not too many chords that can go on a Db if the only choice you have is Bbm or F...); and on top of that, given proper voice leading, it is usually preferrable for voices to not jump wildly up and down (since the point is them being singable).
However, more generally, and ignoring what modern theory textbooks might say, the above answer (by Neil Meyer) is wrong. While not something which should be taken for granted, consecutive fifths specifically at a rest in the music (i.e. at fermatas) happen frequently enough in the chorales of J.S. Bach, that it's clear that these can be acceptable, and are certainly not a case of "never", at least in the mind of that particular composer. Although they tend to mostly be 5ths and not 8ves (though the latter do appear), and in contrary motion (and to repeat the point, at fermatas), all of which combined rather attenuate the negative effects of such otherwise objectionable progressions (Dahn, Luke, 2018, "Consecutive Fifths & Octaves in the Bach Chorales").


Research areas/topics in Resource Allocation.

Question: I want to investigate different models/theories/areas of research for problems in Resource Allocation.
In general terms, by 'resource allocation' I mean problems that involve a finite amount of resources that need to be allocated across demand so some function is optimized. For example, a taxi company has a finite number of vehicles to serve clients to maximize profit, or minimize customer dissatisfaction/wait times, or whatever function is being optimized.
So far my basic google/wikipedia search has brought up:
1) stochastic scheduling which is broken down into various categories, such as Batch scheduling, Multi-armed Bandit Problems, Queueing systems.
2) Also I've ran into the term Operations Research, which also happens to have a journal that I can look into, I believe problems of this nature are addressed here.
3) I've also noticed papers where people discuss resource allocation problems using Potts Models, which come from statistical physics.
Can you point me to any other directions where problems specifically in Research Allocation are discussed, or any stats/other textbooks that touch on this topic? Thanks!
Answer: Introductory textbooks in the areas of operations research, management science and (maybe) industrial engineering will usually cover research allocation models, particularly those that are deterministic (all model parameters, such as supplies and demands, are assumed known at the outset). Typically those books will be organized around model types (linear programming, integer programming, network models, dynamic programming ...) rather than problem types, so you may need to flip through one, looking for the examples, and identify examples that fit your resource allocation paradigm.


Cannot find default credentials in Cloud Run

Question: I am writing a program that speaks with Cloud Spanner in Postgres Dialect. My application is a gin server and I am using pgadapter to connect as mentioned in this doc.
My application runs fine locally. But when I deploy it to cloud run, I get the following log.

The error basically comes from the StartPGAdapterWithCredentials function.
func StartPGAdapter(ctx context.Context, project, instance string) (port int, cleanup func(), err error) {
    credentials, err := google.FindDefaultCredentials(ctx)
    fmt.Println("credentials " + (credentials.ProjectID) + "json " + utils.ToString(credentials.JSON) + "ts " + utils.ToString(credentials.TokenSource))
    if err != nil {
        return 0, func() {}, err
    }
    return StartPGAdapterWithCredentials(ctx, project, instance, credentials)
}
func StartPGAdapterWithCredentials(ctx context.Context, project, instance string, credentials *google.Credentials) (port int, cleanup func(), err error) {
    if credentials == nil {
        return 0, func() {}, fmt.Errorf("credentials cannot be nil")
    }
    if credentials.JSON == nil || len(credentials.JSON) == 0 {
        return 0, func() {}, fmt.Errorf("only JSON based credentials are supported")
    }
    credentialsFile, err := os.CreateTemp(os.TempDir(), "pgadapter-credentials")
    if err != nil {
        return 0, func() {}, err
    }

On my local system, GOOGLE_APPLICATION_CREDENTIALS is set and hence it is able to get the credentials. However, this is not working in cloud run.
How do I get it to run in cloud run?
Additional Info : followed the example present here.
Comment: Hi @Matteo, thanks for the comment. But as mentioned in the question, the code working fine on the local setup. It fails in cloud run. I am not setting any GOOGLE_APPLICATION_CREDENTIALS there. I guess it should fetch from the well-known file or metadata server or something...
Comment: Be sure the `GOOGLE_APPLICATION_CREDENTIALS` point to a valid json file that contains the service account credentials. See also https://github.com/GoogleCloudPlatform/golang-samples/blob/b4e5aa87903747985c8c096f29598d0de5b6cbbc/monitoring/README.md#using-a-service-account
Comment: How do you start PGAdapter? In your container? Can you show this part?
Comment: I am following this example https://github.com/GoogleCloudPlatform/pgadapter/blob/postgresql-dialect/samples/golang/pgx/pgx_sample.go
Comment: The Cloud Run metadata server does not return JSON credentials. It returns an OAuth token. I am not familiar with that library but the code requires JSON credentials (a service account JSON file).
Comment: I am calling this function (FindDefaultCredentials) https://pkg.go.dev/golang.org/x/oauth2/google#FindDefaultCredentials.   Are you saying this requires a service account JSON file to work? How will I deploy this to cloud run then? There should be a way for applications to get access to the service account associated with the revision I think...
Comment: Cloud Run does not provide access to the underlying service account JSON credentials. Cloud Run provides OAuth and OIDC tokens. The code you are using requires JSON credentials.
Answer: It seems that you are trying to start PGAdapter in an embedded container on Cloud Run, and then copy the service account credentials from your environment to the PGAdapter embedded container. The problem is that Cloud Run does not provide access to the underlying service account file. Instead, you should just let the Google Cloud libraries get the default credentials of the environment.
The difficult part in your example is that you are starting PGAdapter in an embedded container, which means that there are no default credentials in that environment. The recommended way to run PGAdapter on Cloud Run is to include it in your main container. That will make it possible for PGAdapter to just fetch the default credentials that are provided by Cloud Run. That means that you should not specify the -c /path/to/credentials.json argument when starting PGAdapter.
There are (at least) two ways that you can include PGAdapter in your main container:

Add the Java .jar file build to your Docker image and start PGAdapter in your container. See [this example] for how to start PGAdapter directly from .jar files. This also requires you to add a Java JRE to your Docker image.
Let your Docker build extend the PGAdapter base Docker image. This will automatically include all dependencies that are needed for PGAdapter. You will have to override the ENTRYPOINT of the base image.

See PGAdapter Cloud Run Sample for Go for an extensive (runnable) sample for the latter option.


Webform submitted data field names

Question: I am beginning a module which implements the hook_webform_submission_insert. I am successfully getting the following data from my implementation of that hook:
stdClass Object
(
    [nid] => 3401
    [uid] => 1
    [submitted] => 1425491295
    [remote_addr] => http://myserver.com
    [is_draft] => 0
    [data] => Array
        (
            [2] => Array
                (
                    [value] => Array
                        (
                            [0] => Chandler Mann
                        )

                )

            [3] => Array
                (
                    [value] => Array
                        (
                            [0] => email@example.com
                        )

                )
.
.
.

I need to write code to programmatically map each value index to node fields in a process of creating nodes from custom code.
However, as the output above does not have field names, it's difficult to map correctly to the necessary node fields.
Can anyone advice how I might discover what name webform assigns to the field#id 2, 3 etc as in my code sample above?
Answer: The $node argument to hook_webform_submission_insert() contains the info you're looking for. For a Webform node, you'll find an array $node->webform->components where, for example, $node->webform->components[2] would correspond to the item whose value is "Chandler Mann" in your data.
Answer: The $submission->data array is keyed by Webform internal component IDs, which you can't see from the admin interface.
You can build a helper array mapping form keys to component IDs:
$compMap = array();
foreach ($node->webform['components'] as $c) {
  $compMap[$c['form_key']] = $c['cid'];
}

Then you can get the values by form keys as follows:
if (array_key_exists($compMap[$key], $submission->data)) {
  $value = $submission->data[$compMap[$key]]['value'][0];
}
else {
  // No value was entered for this field.
}

Note, that the value will be in the ['value'][0] element only for "simple" fields, like text or number. For other types, e.g. reference fields, check your data.

Webform submitted data field names


Can I use an RODC for Active Directory athentication if the writeable DC is not available for several months?

Question: We are running an Read-Write DC at our home office which we are using for authentication when were are working there. It works fine as long as we are at the office, but we are going to be on the road for a few months, and and IT infrastructure at our office will have to stay offline during this time.
I read several times that it's not a good idea to expose a DC to the internet, so I was thinking of setting up RODC on a cloud server instead and caching some credentials there.
Would I be able to authenticate against the RODC if the writeable DC was offline for several months? I'm worried that my credentials might be cached at first but expire at a later time.
Comment: Why not just have a VPN between your laptops and the home office DC? Seems like it'd be easier.
Comment: from what i did read about the RODC it can reduce the amount of WAN traffic, which could be nice in off-site locations with bad internet access.

for the question: increase the duration until your credentials expire.
Comment: @Nathan: Unfortunately I cant do that because the home office won't even exist while we are away. All equipment from our office will be in storage during that time.
Answer: Nathan is right IMO, but I'll address your actual "questions":

I read several times that it's not a good idea to expose a DC to the
  internet, so I was thinking of setting up RODC on a cloud server
  instead and caching some credentials there.

The RODC still has to replicate with the DC at your HQ.  And the cloud server itself would either have to be exposed to the internet or you'd have to setup a tunnel to that cloud instance (which further upvotes Nathan's comment).

Would I be able to authenticate against the RODC if the writeable DC
  was offline for several months? I'm worried that my credentials might
  be cached at first but expire at a later time.

If the RODC can't get replication from the RWDC then only cached account credentials from users that have authenticated against the RODC while it was able to talk to the RWDC will be allowed to login.
Honestly, Nathan is right...or simply just login to the laptops with cached credentials to begin with...if you aren't connected to the network the laptops will still accept your cached credentials on them.  You might run into issues when you return though with the workstation's account itself having trust relationship issues to the domain if it hasn't contacted the DC in 30 days (by default).
Comment: Unfortunately I can't vpn into the home office's DC because the home office won't even exist while we are away. All equipment from our office will be in storage during that time.
Comment: Then just use cached credentials or create local accounts on your laptops/computers while everything is in storage.
Comment: TheCleaner: I thought of using local accounts as well, but then I'll have to figure out how to offer securely encrypted drive shares between the laptops when using a public WiFi. We'll need that to work on our software while being away. As for cached credentials: Would we be able to share a folder with IPSec encryption when no DC is available?
Comment: Use Dropbox for Business or a similar cloud-hosted environment for file sharing.  Online code repositories as well.  You might even find after relying on such SAAS/IAAS that you like them even better for the mobility they provide.
Comment: I think I found a solution: I'll just stick to local user accounts and buy a cheap travel router like the TP-Link TL-MR3020 or the Asus WL-330N3G for travelling. Thanks for all your help, I'm not sure why you've been downvoted.
Comment: No downvotes that I can see?  Glad you got it worked out.


How to create a copy of a directory on Linux with links

Question: I have a series of directories on Linux and each directory contains lots of files and data. The data in those directories are automatically generated, but multiple users will need to perform more analysis on that data and generate more files, change the structure, etc.
Since these data directories are very large, I don't want several people to make a copy of the original data so I'd like to make a copy of the directory and link to the original from the new one. However, I'd like any changes to be kept only in the new directory, and leave the original read only. I'd prefer not to link only specific files that I define because the data in these directories is so varied.
So I'm wondering if there is a way to create a copy of a directory by linking to the original but keeping any changed files in the new directory only.
Answer: It turns out this is what I wanted to:
cp -al <origdir> <newdir>

It will copy an entire directory and create hard links to the original files. If the original file is deleted, the copied file still exists, and vice-versa. This will work perfectly, but I found newdir must not already exist. As long as the original files are read-only, you'll be able to create an identical, safe copy of the original directory.
Comment: It's possible to do this when the original files are not read-only, but any changes made to either copy will be made to both copies equally, so hard linking is not suitable if you want to be able to modify the copied file without modifying the original.
Comment: If the files are read-only, then whatever program modifies (and saves) the file must overwrite the file, rather than modify it in-place. For `cp`, `cp -f` will accomplish this.
Answer: However, since you are looking for a way that people can write back changes, UnionFS is probably what you are looking for. It provides means to combine read-only and read-write locations into one.

Unionfs allows any mix of read-only and read-write branches, as well as insertion and deletion of branches anywhere in the fan-out.

Originally I was going to recommend this (I use it a lot):
Assuming the permissions aren't an issue (e.g. only reading is required) I would suggest to bind-mount them into place.
mount -B <original> <new-location>
# or
mount --bind <original> <new-location>

<new-location> must exist as a folder.
Comment: Thanks for the suggestions! I tried the mount bind and was able to create a new mount point. However: 1) I have thousands of directories, which would require thousands of mounts 2) I created a file in the new directory and it also showed up in the original directory
Comment: Thousands of directories but not a single root to them which could be used? You would need at most as many mounts as users in such a scenario. Even if different users have different sub-folders of that single common root, the number of mounts would still equal the number of users.
Comment: A duplicate tree is possible... but changing things at the OS level isn't ideal. I think I may try to just recursively create links to the files and directories in the original, and just make sure the original files are read only
Comment: @GregB: but in your question you state that you want to allow changes as well? I'm confused.
Comment: I do want to allow changes to anything in the directory, in theory. But if I'm only able to create a duplicate read only tree of links, even if they can only add, but not modify existing files, then that will be good enough.


Fitting distributions in R

Question: I hope you are very well. I have a big dataset (~9 million registries) and I have 2 variables $X$=purchase amount and $Y$=frequency of purchase. I would like to know what distribution should I use for each variable and fitting its distribution with R. For example, for $X$ I'm testing with package 'mixtools' but the results are not really good. I want to create a simulation model, that simulates that variables. First of all, I'm selecting appropriate probability distributions (and associated parameters) to describe the behavior of each uncertain input variable. Thanks.
UPDATE: I have replaced the pdf with a histogram for each variable.
Comment: Could you indicate *why* you are fitting distributions to these data and what you hope to accomplish with the result?
Comment: `Y` looks geometric. Is there a relationship between the two?
Comment: I hope you are doing well too.
Comment: Yes. The top image is the purchase amount (X), the bottom image is the frequency of purchase (Y).
Comment: I'm going to bet that $Y$ is discrete (times per day) and your automatically-chosen bandwidth is too narrow to be useful. A simple histogram or table would be better in this case.
Comment: @whuber: I want to create a simulation model. First of all, I'm selecting appropriate probability distributions (and associated parameters) to describe the behavior of each uncertain input variable. Thanks.
Answer: I'd say you don't need a density estimate at all. With millions of data points, you have a sample that's large enough that it can serve as your simulation model. Simply select data points at random (with replacement) to carry out your simulations.
Comment: Great answer! No need to bother with a guess at a named distribution just because it has a name. @MSV since your variables are related, sample from them together. Don't pick a random X and a random Y, pick a random (X, Y) pair.
Comment: +1 However, MSV, while for very large data sets this is probably the approach I'd suggest (taking into account @shujaa's clarification), one must understand that this approach nevertheless contains assumptions (such as independence of (x,y) pairs from other pairs, that the future will be like a random sample of the past). By the way, your histograms in your question should really have more bins.

Fitting distributions in R


Como acessar um atributo de um objeto dentro de uma pilha de Objetos

Question: Tenho vários objetos da classe Veiculo com placa, modelo e anoFabri como atributos, dentro de um pilha que criei (Pilha.java).
Preciso aplicar um método na classe Pilha, que retire os objetos da pilha até encontrar um Veiculo que tenha o anoFabri menor que 2000.
Pilha:
public class Pilha implements TAD_Pilha {
    private int topo;
    private int MAX;
    private Object memo[];

    public int getTopo() {return topo;}
    public void setTopo(int topo) {this.topo = topo;}
    public int getMAX() {return MAX;}
    public void setMAX(int MAX) {this.MAX = MAX;}
    public Object[] getMemo() {return memo;}
    public void setMemo(Object[] memo) {this.memo = memo;}

    public Pilha(int qtde){
        topo = -1;
        MAX = qtde;
        memo = new Object[MAX];
    }

    @Override
    public boolean isEmpty(){ return(topo==-1);}
    @Override
    public boolean isFull(){ return(topo==MAX-1);}

    @Override
    public Object push(Object x){
        if(!isFull() && x != null){
            memo[++topo] = x;
            return x;
        }
        else
            return null;
    }

    @Override
    public Object pop(){
        if(!isEmpty())
            return memo[topo--];
        else
            return null;
    }

    @Override
    public Object top(){
        if(!isEmpty()){
            return memo[topo];
        }
        else
            return null;
    }

    @Override
    public String toString(){
        if(!isEmpty()){
            String msg="";
            for(int i=0; i<=topo; i++){
                msg += memo[i].toString();
                if(i != topo) msg += ", ";
            }
            return ("Pilha = [" + msg + " ]");
        }
        else
            return "Pilha vazia!";
    }
}

Veiculo:
public class Veiculo {
    private String placa;
    private String modelo;
    private int anoFabri;

    public Veiculo() {
    }

    public Veiculo(String placa, String modelo, int anoFabri) {
        this.placa = placa;
        this.modelo = modelo;
        this.anoFabri = anoFabri;
    }

    public String getPlaca() {
        return placa;
    }

    public void setPlaca(String placa) {
        this.placa = placa;
    }

    public String getModelo() {
        return modelo;
    }

    public void setModelo(String modelo) {
        this.modelo = modelo;
    }

    public int getAnoFabri() {
        return anoFabri;
    }

    public void setAnoFabri(int anoFabri) {
        this.anoFabri = anoFabri;
    }

    @Override
    public String toString() {
        return placa + " " + modelo + " " + anoFabri; //To change body of generated methods, choose Tools | Templates.
    }
}

Comment: Pode adicionar adicionar o código dessas classes mencionadas na pergunta?
Answer: Você poderia fazer algo assim:
public void RemoveVeiculosAnoFabriMaior1999() {
    while (topo > 0) {
        Veiculo veiculo = (Veiculo) memo[topo];
        if (veiculo.getAnoFabri() < 2000) break;
        memo[topo--] = null;
    }
}

Comment: Só pra saber (que a pergunta é antiga), votei negativo porque pilha seletiva é um TAD muito incomum, considero um erro de design.


Rails 4/ ajax - NoMethodError - undefined method `id' for nil:NilClass - Passing variable to js modal

Question: I have a pretty simple Ruby On Rails app with bootstrap 3 for the front end: I have Deals, and each Deal has_many Opportunities.
On each Deal page (url of deal page is for example myapp.com/id=1), I want to have a textual link that says "view deal's opportunities" and when clicked, it trigger when clicked the appearance of content inside a Bootstrap modal.
I'm getting all mixed up because on this Deal Page, I use Deal's controller action called "showcase". BUT to generate the modal via ajax,as you see below, I use another action called "show_opportunities" and inside it, the app seems not to know @deal (because@deal is defined in a different Deal's action). I think that where the problem comes form but I am not totally sure.
Here is the error I am getting and my code:
Completed 404 Not Found in 3ms

ActiveRecord::RecordNotFound - Couldn't find Deal without an ID:
 activerecord (4.2.0) lib/active_record/relation/finder_methods.rb:433:in `find_with_ids'
  activerecord (4.2.0) lib/active_record/relation/finder_methods.rb:71:in `find'
  friendly_id (5.1.0) lib/friendly_id/finder_methods.rb:20:in `find'
  app/controllers/deals_controller.rb:70:in `show_opportunities'

This line where 70 with the error is "@deal = Deal.friendly.find(params[:id])" (see below)
controller/deals_controller.rb (using @Pavan feedback)
    # used so that old urls created for deals redirects to the new ones created
    # indeed with friendly_id, the url is taken from the title :/deals/title
    # but if we edit the deal title to deal/title2, the old url was still    working
    # we need to redirect the old url
    # source - github.com/norman/friendly_id/issues/385
    before_filter :find_deal,
       :only => [  :showcase ]
    before_filter :ensure_canonical_deal_path!,
      :only => [  :showcase ]

def showcase
    @deal = Deal.friendly.find(params[:id])

    respond_to do |format|
      format.html # showcase.html.erb
      format.json { render json: @deal }
    end
end

def show_opportunities
    @deal = Deal.friendly.find(params[:deal])
    @opportunity = Opportunity.where('deal_id = ? AND deal_type = ?',
                             @deal.id, "high tech").first

    respond_to do |format|
      format.js
    end
end

protected

def find_deal
   @deal = Deal.friendly.find params[:id]
end
def ensure_canonical_deal_path!
   if request.path != deal_page_path(@deal)
        redirect_to deal_page_path(@deal, :format => params[:format]), :status => :moved_permanently
        return false
   end
end

app/views/deals/showcase.html.erb
<% if @deal.present? %>
   this is the beginning
   <%= render 'deals/deal_info_zone', locals:{deal: @deal} %>
   this is the end
<% end %>

views/deals/_deal_info_zone.html.erb

    <%= link_to "view infos of Opportunities", deal_opportunities_modal_path, deal: @deal, remote: true %>

views/deals/deal_opportunities_modal.js.erb
Here is the modal trigger via ajax: views/deals/opportunity_modal.
Note here how I tried here to pass Deal but without success so that the line
$('body').append('<%= j render partial: "deals/deal_opportunities_modal", locals:{deal: @deal} %>');
$('#myModal').modal('show');

/app/views/deals/_deal_opportunities_modal.html.erb

          <%= @opportunity.name %>

routes.rb
match '/deals/:id', # this is the Deal page
    to:   'deals#showcase',
    via:  'get',
    as:   :deal_page

match '/opportunity_modal',
    to:   'deals#show_opportunities',
    via:  'get',
    as:   :deal_opportunities_modal

How to make this work ?
EDITED my question with Pavan feedback
SOLUTION
I finally found my error:
What I did was wrong: indeed when I hovered above the link 'view opportunities' I could see the url that the linking was pointing at was localhost:3000/opportunity_modal. but how impossible! I can't give the same url to all the links 'view opportunities' that would appear in all the diffreent Deal pages(id=1, id=2,...).
So I changed the route to:
 match '/deals/:id/opportunity_modal',
 to: 'deals#show_opportunities',
 via: 'get',
 as: :deal_opportunities_modal

and it works!!!
Answer:
NoMethodError - undefined method `id' for nil:NilClass

@deal is nil, you need to define it in the show_opportunities method.
def show_opportunities
  @deal = Deal.friendly.find(params[:id])
  @opportunity = Opportunity.where('deal_id = ? AND deal_type = ?', @deal.id, "high tech").first
   respond_to do |format|
     format.js
   end
end

Update:
Firstly, change deals = Deal.friendly.find(params[:id]) to @deal = Deal.friendly.find(params[:id]) in showcase method.
And pass it as a locals in <%= render 'deals/deal_info_zone' %> like
<%= render 'deals/deal_info_zone', locals:{deal: @deal} %>, then pass it to link_to in _deal_info_zone.html.erb

    <%= link_to "view infos of Opportunities", deal_opportunities_modal_path, deal: @deal, remote: true %>

And finally access it in the show_opportunities method like @deal = Deal.friendly.find(params[:deal])
Comment: Isn't it bad like i.e not DRY ? I am repeating the same thing I have on the action above it (5 lines above it i am already defining @Deals on the action called #showcase), and they're both on the same view ( it's the same url I am loading that activate these 2 Deal controller's actions).
Comment: also isn't it bad to load twice : the same resource for performance/speed: when the page first loads it loads #showcase and the first time deal = Deal.friendly.find(params[:id]), then if I click on the link 'view opportunities', it will load again the same deal = Deal.friendly.find(params[:id]). Is it right?
Comment: couldn't i use/link or do sth not to repeat it?
Comment: @Mathieu You can pass it as `locals` to `<%= render 'deals/deal_info_zone' %>` but again you have to define it in the `show_opportunities` method to use here `@opportunity = Opportunity.where('deal_id = ? AND deal_type = ?', @deal.id, "high tech").first`
Comment: I tried it but it generated an Error= > see my question Edit
Comment: Actually if you look at my original code, I am trying already to pass the variable in the js render: $('body').append('<%= j render partial: "deals/deal_opportunities_modal", locals:{deal: @deal} %>');
$('#myModal').modal('show'). But does not work either.
Comment: I need to tell Rails: hey the @deal you need in #show_opportunities is just the deal you loaded when loading the page myapp.com/deal_id=5 so take this deal (the one with id=5)
Comment: sorry got it, will try
Comment: Not working, still getting the same error, would the full Error log be useful?
Comment: I edited my question: I added a piece of code in app/views/deals/showcase.html.erb :  <% if @deal.present? %>. I had not put the whole view code in the view here for the sake of simplicity maybe but maybe it's important.
Comment: Edited my question with your elements
Comment: @Mathieu Before the error message was showing in method `winalert` isn't it?
Comment: typo my bad: Error is in method `show_opportunities'. It's still not getting the deal.id! i've put wherever I could locals:{deal: @deal} : inside app/views/deals/showcase.html.erb, inside views/deals/deal_opportunities_modal.js.erb, but still no success
Comment: @Mathieu Try changing `<%= link_to "view infos of Opportunities", deal_opportunities_modal_path, deal: @deal, remote: true %>` to `<%= link_to "view infos of Opportunities", deal_opportunities_modal_path, deal: @deal.id, remote: true %>`
Comment: if not I'm wondering if this has not sth to do with friendely_ip, I'll check that after trying your suggestion
Comment: as regards friendly_id, I have not mentionned it because I have too many methods in my Deals controller but I have find_deal and ensure_canaonical_deal_path that you can see here on this page https://github.com/norman/friendly_id/issues/385, look for Parndt message in a code where he writes "ensure_canonical_product_path!"
Comment: I added in my controller the before_filter introduced for reasons related to friendly_id, maybe it's because of them my app can not find the ID.
Comment: hehe I think at last I found somebody with my weird problem: http://stackoverflow.com/questions/32030893/couldnt-find-model-without-an-id-rails-4-custom-controller-action
Comment: other people blocked because .friendly.find did not work: http://stackoverflow.com/questions/19732047/troubleshooting-friendly-id-w-rails-4-working-as-expected-in-rails-console-ge
Comment: But I am not sure it's due to Friendly _id: indeed if I put the opportunity = Opportunity.where('deal_id = ? AND ...inside the method #showcase, and do not use a modal but just try to display inside the normal page opportunity values such as  opportunity.name, it works. It's really when I move " opportunity = Opportunity.where('deal_id = ? AND ." inside another method called #show_opportunities and try to display it inside a modal that it goes crazy
Comment: Found it!!!!!!!!!!!!!!!!!!!!!!!!! man, it was not related to friendly_id. What I did was wrong: indeed when I hovered above the link 'view opportunities' i could see the url that the linking was pointing at was localhost:3000/opportunity_modal. but how impossible! I can't give the same url to all the links 'view opportunities' that would appear in all the diffreent Deal pages(id=1, id=2,...). So I changed the route to:   match '/deals/:id/opportunity_modal',
    to:   'deals#show_opportunities',
    via:  'get',
    as:  :deal_opportunities_modal # path for rake route path, and it works!!!
Comment: I'll upvote your answer as it might not have worked without all the suggestions you made.


Meta curious badge bug

Question: I am already meet the requirement for the curious badge still it is showing in list. It is bug or something i missed?
Answer: See this answer.
The condition which you need to meet to achieve this badge is :

(total questions - negative questions - closed - early deleted)/total questions >= 0.5

I can see only 9 questions under your belt now. So based on that questions you should get this badge. However as you can see in the given answer, you may have some closed/deleted questions which are older than 60 days in your history, which may be preventing this.
So You are not alone, lot of awesome-heart people suffer the same. Best of luck.
PS: May be moderators can give you more details regarding the calculation.
Comment: Thanks for info.

Meta curious badge bug


If $\sup \{a_n\mid n\in \mathbb{N}\}=1$ then $\frac{1}{1-a_n}\to\infty$

Question: Suppose $(a_n)$ is a sequence such that $a_n<1$ for all $n$ and $s:=\sup \{a_n\mid n\in \mathbb{N}\}=1$. I want to prove that $\frac{1}{1-a_n}\to\infty$.
My initial approach: let $M>0$ and $\varepsilon=1/M$. Then, there exists $N_1\in\mathbb{N}$ such that $a_{N_1}>s-\varepsilon=1-1/M$. Then: $$\frac{1}{1-a_{N_1}}>M$$
But to prove that $\frac{1}{1-a_n}\to\infty$ I must find $N$ such that for all $n>N$ : $\frac{1}{1-a_{n}}>M$. How can I find such $N$?
Comment: What if $a_n = (-1)^n - \frac{1}{n}$?
Comment: As @dtldarek notes, your claim isn't true.
Comment: @dtldarek - right, thanks. By the way, am I correct that $1/(1-a_n)$ is not bounded from above when $s=1$?
Comment: @user254036 Yes, you are correct, you have already proved that for any $M$ there exists $N_1$ such that $1/(1-a_{N_1}) > M$.
Answer: The claim clearly isn't true, as the sequence \begin{align}a_{2n}&=1-\frac1{2n}\\ a_{2n+1}&=0\end{align}
satisfies $a_n<1$ and $\sup_n a_n = 1$, but $\frac1{1-a_{2n+1}}=1$ for all $n$, so $$\liminf_{n\to\infty} \frac1{1-a_n}=1.$$ This example also shows that $\limsup_{n\to\infty}a_n=1$ isn't a sufficient condition for $\frac1{1-a_n}\to\infty$.
However, $\lim_{n\to\infty}a_n=1$ is sufficient. If $M>0$, then choose $N$ so that $n\geqslant N$ implies $$1-a_n<\frac1M.$$ Then for $n\geqslant N$,
$$\frac1{1-a_n}>M, $$
so that $$\frac1{1-a_n}\stackrel{n\to\infty}\longrightarrow \infty. $$
Answer: It's not a correct statement. Let $a_n = \sin n$. It's obviously that $\sup a_n = 1$; but limit $\dfrac{1}{1-\sin n}$ doesn't exists.
Answer: The answers given here are all good, but they choose sequences that are too complicated. The sequence $a_n = \frac 1 n$ for $n \ge 1$ has $\sup _n a_n = a_1 = 1$, but $\frac 1 {1-a_n} \to 1$, so the statement is false.


Help with a probability problem

Question:
DISCLAIMER: This is school related, however it's not homework.
  This is from an exercise document one of the previous students posted.
  Sadly, there are no solutions, so I can't verify if I'm thinking about
  the problem the right way.

The problem:

There are ten boxes. In 9 of the boxes, there are 2 white balls
  and 2 black balls. In the tenth box there is 5 white and 1
  black ball. By random chance, a white ball was picked. What's the
  probability the white ball was inside the tenth box?

To illustrate my understanding of the problem:

The way I am thinking about solving the problem

$H_{1...9}$: Picked from inside a box containing 2b & 2w balls
$H_{10}$: Picked from inside a box containing 1b & 5w balls;
Picking a box: $\Pr(H_{1...10})=\frac{1}{10}$
A white ball is picked: $A$.
The white ball was picked from one of the nine boxes: $\Pr(A|H_{1...9})=\frac{2}{4}$
The white ball was picked from the tenth box: $\Pr(A|H_{10})=\frac{5}{6}$
Calculate that the probability that the white ball was picked from within the tenth box:
$$ \Pr(H_{10}|A) = \frac{\Pr(H_i)\Pr(A|H_i)}{\Pr(A)} $$
Where $\Pr(A)$ is:
$$\Pr(A) = \sum_{n=1}^{10}\Pr(H_n)\Pr(A|H_n)$$
So, in the end I'm left with:

$$
\Pr(H_{10}|A) =
\frac{\Pr(H_i)\Pr(A|H_i)}
{9*[\Pr(H_{1...10})\Pr(A|H_{1...9})]+ \Pr(H_{1...10})\Pr(A|H_{10})}
$$

Can someone point me in the right direction if this is wrong? Thanks! Also, sorry for creating noise, in the unlikely scenario that this is actually correct.
Comment: You are absolutely correct with the approach and I believe in your last step, the denominator should be $9[Pr(H_{1...9})Pr(A|H_{1...9})]+Pr(H_{10})Pr(A|H_{10})$. Just pointing out a notation error. A classic example of Bayes !! The worst thing that someone could do to this problem is provide some prior probabilities about picking boxes. Then you just would have had to play around with $P(H_{i})$ too.
Comment: @Sudarsan Oh, thanks! I used $\Pr(H_{1...10})$ because it's same for all of the ten hypotheses: $\frac{1}{10}$, but it does look neater with your notation! Thanks :-)
Comment: Also I hope you could see the difference between the following 2 questions here:
a. A ball is drawn at random; what is the probability that it is a white ball and it is from the 10th box? (A slightly different question)
b. A ball is drawn at random and it is white; what is the probability that it came from the 10th box? (Your question).

As an exercise on probability it's always good to think about more questions as there are always subtle differences.
Comment: @Sudarsan Oh yes, I see the difference.
Answer: What you've done is correct, though you can shorten it a little by thinking of the first nine boxes as one box that you pick with probability $0.9$. Then the probability of drawing a white ball is $$\frac9{10}\cdot\frac12+\frac1{10}\cdot\frac56=\frac{32}{60}\;,$$ to which the last box contributes $\frac5{60}$, so the desired probability is $$\frac{5/60}{32/60}=\frac5{32}\;.$$
Or you can be really slick and notice that the probabilities aren't changed if we add one white and one black ball to each of the first nine boxes. Now, however, all boxes contain the same number of balls, so picking a box at random and then drawing a ball from the box is equivalent to picking a ball at random: each ball has one chance in $60$ of being chosen. And since there are now $32$ white balls, $5$ of which are in the last box, we get the desired result immediately.
Comment: @destielstarship: You're welcome! I have to admit that I didn't notice the slick solution until I'd already done the other calculation and was looking for a nice way to check it.
Comment: Oh, this is just *brilliant*, but I'm afraid this way of thinking is way too elegant and advanced for me! I can just marvel at your logic. Thanks!

Help with a probability problem


How to give time delay for PhonenumberUtils.PAUSE() in android?

Question: I am creating a conference manager application .I am Using the PhonenumberUtils.PAUSE() for time delay during the call.It is only working for few seconds.I want to make it pause for more seconds according to my wish.How can i do that can anyone help me?
String telUri = "tel:" + 121 + PhoneNumberUtils.PAUSE +  4
        +  PhoneNumberUtils.PAUSE + 6 ;
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(telUri));
startActivity(callIntent);

Now the call is going to 121 and without any time delay it is executing the number 4 and same as 6 .I want to give time delay for 121 and 4 .How can i give?
Answer: the PhoneNumberUtils.PAUSE will wait for 2 seconds ,and the value for PhoneNumberUtils.PAUSe is ",".
ProfileDo profile = adapter.getProfile(profileid);
    String call = "tel:";

    for (StepDO step : profile.getSteps()) {

//Encoding the value if it contains any symbol like #
        String value = URLEncoder.encode(step.getValue());

        int delay = step.getDelay();
        String pausesStr = "";
        for (int i = 0; i < delay/2; i++) {
            pausesStr += PhoneNumberUtils.PAUSE;
        }
        call += value + pausesStr;

        System.out.println(""+call);
    }
    Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(call));
    startActivity(callIntent);
}

}
Answer: That's a dialer thing, the time it takes for one pause is not really under your control but is usually 2-3 seconds. If you want a longer pause - just use two pauses in succession.
Also, use StringBuilder (memory reasons)
String doublePause = PhoneNumberUtils.PAUSE + PhoneNumberUtils.PAUSE;
StringBuilder sb = new StringBuilder("tel:").append(121).append(doublePause).append(4).append(doublePause).append(6);
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(sb.toString()));

Comment: Thanks.In my case I am getting the delay time  from the user how can I  set the user delay time
Comment: I'm not sure what user delay time is
Comment: You mean, you want to allow user to set the exact delay value? Can't do that, but you can let user select it with 3-sec delta. Like, field, + and - buttons. User hits + and the field increases from 3 sec to 6 sec --- and internally you just use 2 pauses instead of one. Or, you can just use a combo box instead of all that. Just give user 3-4 options (e.g. {3, 6, 9, 12}) --- they are very unlikely to ever need more than that.
Comment: ya correct but whatever value the user is giving as the delay should act according to the users delay ...If you have free time check this link  https://play.google.com/store/apps/details?id=com.naresh.confmgr&hl=en
Comment: Yes, that's exactly what I'm talking about. You can see on screenshots, that the delay is always an even number: 2, 4, 8. You need to use something other than a `TextField` to restrict user input to the values you want. Just leave them no options to input delays that you can't use, make them choose from the list of possible delays you define. It's even more convenient - no need to type the numbers on the screen keyboard. Users will be OK with that, I promise :)
Comment: Thanks for looking into this issue seriously .My requirement is to create the same application like conference manager .Is this the only way to solve the problem  or do you know any another way to solve it.send your mail id .so that i can send my project to you.
Comment: Is there any possible way to do that? kindly reply me.
Comment: No, there's not really much I can tell you. There are no other ways to solve this that I know of, aside from implementing your own dialer app with all the low-level phone stuff. But seriously, it's ok to restrict users in this regard.


Proving enumerate(...) to range(len(...)) equality

Question: I'm trying to prove the equality of the following Python constructs in Coq: for i, _ in enumerate(l, s) and for i in range(s, len(l) + s)
I've made recursive definitions of both enumerate and range functions, also came up with some additional theorems to aid myself in achieving the original goal and successfully proved them.
However, I got stuck somewhere mid-way. I ended up with the following goal: [] = [s], which is obviously false. That's why I specialize'd nil_cons in attempt to use discriminate, but that didn't help: "No primitive equality found."
I'm sure there should be some other way around, I just don't see it.
That's what I got so far:
   Require Import Coq.Lists.List Coq.Bool.Bool Coq.Arith.Minus.

   Import Coq.Lists.List.ListNotations.

   Fixpoint _range (a b d : nat) :=
     match d with
       | 0 => []
       | S n => a :: _range (S a) b n
     end.

   Definition range a b := _range a b (b - a).

   (*
   Fixpoint less n m : bool :=
     match n, m with
       | 0, 0       => false
       | 0, S _     => true
       | S _, 0     => false
       | S n, S m   => less n m
     end.

   Fixpoint range (a b : nat) :=
     if less a b then
        match b with
          | 0 => []
          | S n => range a n ++ [n]
        end
     else [].
   *)

   Eval compute in range 0 0.
   Eval compute in range 0 5.
   Eval compute in range 5 0.
   Eval compute in range 5 10.

   Theorem range_eq_empty : forall (s : nat),
                            range s s = [].
   Proof.
      induction s. reflexivity. unfold range. rewrite <- minus_n_n. reflexivity.
   Qed.

   Fixpoint enumerate (T : Type) (l : list T) (s : nat) :=
     match l with
       | [] => []
       | h :: t => (s, h) :: enumerate T t (S s)
     end.

   Eval simpl in enumerate nat [0;1;2;3;4] 0.
   Eval simpl in enumerate nat [5;6;7;8;9] 5.

   Theorem enum_prop_fwd : forall (T : Type) (l : list T) (s : nat),
                           enumerate T l s = [] -> l = [].
   Proof.
      intros. induction l. reflexivity. pose proof nil_cons. symmetry. specialize (H0 T a l). discriminate.
   Qed.

   Theorem enum_prop_bwd : forall (T : Type) (l : list T) (s : nat),
                           l = [] -> enumerate T l s = [].
   Proof.
      intros. rewrite H. reflexivity.
   Qed.

   Theorem enum_map_prop_fwd : forall (T : Type) (l : list T) (s : nat),
                               enumerate T l s = [] -> map fst (enumerate T l s) = [].
   Proof.
      intros. rewrite H. reflexivity.
   Qed.

   Theorem enum_map_prop_bwd : forall (T : Type) (l : list T) (s : nat),
                               map fst (enumerate T l s) = [] -> enumerate T l s = [].
   Proof.
      intros. pose proof (enum_prop_bwd T l s). induction l. reflexivity.
      apply H0. symmetry. pose proof nil_cons. specialize (H1 T a l). discriminate.
   Qed.

   Theorem enum_revert : forall (T : Type) (l : list T) (a : T) (s : nat),
                         s :: map fst (enumerate T l (S s)) = map fst (enumerate T (a :: l) s).
   Proof.
      intros. induction s; reflexivity.
   Qed.

   (* for i, _ in enumerate(l, s) = for i in range(s, len(l) + s) *)
   Theorem abc : forall (T : Type) (l : list T) (s : nat),
                 map fst (enumerate T l s) = range s (length l + s).
   Proof.
      intros. induction (length l). induction l. induction s. rewrite range_eq_empty. reflexivity.
      rewrite range_eq_empty. reflexivity. rewrite range_eq_empty. rewrite <- enum_revert. symmetry.
      rewrite range_eq_empty in IHl. pose proof (enum_prop_fwd T l s (enum_map_prop_bwd T l s IHl)).
      rewrite H. compute. pose proof nil_cons. specialize (H0 nat s []). discriminate.

Answer: You can start your proof of abc by just an induction on l
(not an induction on length l).
Arithmetic equalities  which appear in the proof are solved with lia.

 Require Import Lia.

 Theorem abc : forall (T : Type) (l : list T) (s : nat),
                 map fst (enumerate T l s) = range s (length l + s).
   Proof.
     induction l.
     - intro s; cbn; now replace (s - s) with 0 by lia.
     - destruct s as [| s].
       + cbn; rewrite IHl; unfold range; do 2 f_equal; lia.
       + cbn; rewrite IHl; unfold range; cbn.
         replace (length l + S s - s) with (S (length l)) by lia.
         cbn; do 2 f_equal; lia.
   Qed.

Comment: Thanks. It seems I went a little bit overboard with those inductions :)
Here is final result: https://gist.github.com/limitedeternity/5b848f8442248efa8f1db73e2dac164b
Comment: You may simplify further some proofs. For instance `enum_map_prop` can be proved with just `destruct l ; [reflexivity | discriminate].`


Convert jquery function into javascript

Question: I have to use javascript for below mention work which is done in jquery and working perfect. Reason to use javascript is to know how it can be done with javascript.I google it but not find any clue to how get it done
http://jsfiddle.net/2vP24/
$('.first').find('.sub1').next().css('background','#ff0000')

Comment: get jQuery source and work it out, will take some time :)
Answer: You won't find a solution for exactly that line of code if that's what you were looking for. If you dig into the DOM you'll eventually figure out what you need, but here's a way, assuming there's only one .sub1 inside each .first.
var els = document.querySelectorAll('.first');

[].forEach.call(els, function(el) {
  var next = el.querySelector('.sub1').nextSibling;
  next.style.backgroundColor = '#ff0000';
});

Comment: No, IE9+ only. If you want older browser I'd stick to jQuery instead of the otherwise ugly code you'll have to write...But I'll leave that up to you, you have the link to the docs and some code to work with.
Answer: If you don't care about supporting older browsers, this should do the same thing:
[].forEach.call(document.querySelectorAll('.first .sub1 + *'), function(elem) {
    elem.style.backgroundColor = '#ff0000';
});

Convert jquery function into javascript