How to get dropdown menu to push other dropdowns down

Question: I am trying to fix my mobile view website by having it push the content down when the user clicks on a drop down button, currently what it does is this:

My current html is below, I just need it to simply push the rest of the content straight down when the user clicks on the dropdown and when they click on something else it pushes it back up:
return (

          <HamburgerButton click={props.closeClickHandler} />

      <form className="form-inline mt-5 mb-5 ">
          <input
            type="text"
            className="form-control ml-auto mr-auto"
            placeholder="Search.."
            size="45"
          ></input>
        </form>

          <Link to="/" className="dropDownButton">Home</Link>

          Masculine

Test 1

Test 2

Test 3

Test 4

Test 5

          Feminine

Test 1

Test 2

Test 3

Test 4

Test 5

          Collections

Test 1

Test 2

Test 3

Test 4

Test 5

          Contact Us

  );
};

and my css is
.dropDownButton {
  float: left;
  max-width: 100%px;
  width: 100%;
  height: 65px;
  line-height: 65px;
  position: relative;
  text-transform: uppercase;
  font-size: 3rem;
  color: rgba(0, 0, 0, 0.7);
  white-space: nowrap;
  cursor: pointer;
}
.dropDownButton:hover{
  background: #d5d5d5;
  border-radius: 5px;
}
.dropDown-menu{
  position: relative;
  top: 0%;
  left: 0;
  width: 100%;
  padding: 0;
}
.dropDown-menu li {
  background: #666;
  color: rgba(255, 255, 255, 0.7);
  display: none;
}
.dropDown-menu li:hover{
  background: #606060;
}
.dropDownButton-menu li:last-child{
  border-radius: 0px 0px 5px 5px;
}
.dropDownButton:hover .dropDown-menu li {
  display: block;
}
.dropDownButton:hover .dropDown-menu.reg-menu li{
  perspective: 1000px;
  opacity: 0;

  animation-name: reg-menu;
  animation-duration: 500ms;
  animation-timing-function: ease-in-out;
  animation-fill-mode: forwards;
}
@keyframes reg-menu {
  0% {
    opacity: 0;
    transform: translateX(0%) translateY(0%);
  }
  100% {
    opacity: 1;
    transform: translateX(0%) translateY(100%);
  }
}

any help would be appreciated! Thank you!
Comment: Your question is missing some things to be considered good: Runnable code, code reduced to the core of the question and code, that has some quality (the code is - besiedes the error you mentioned - not clean at all).
Answer: Remove height: 65px; from .dropDownButton and fix the other styling issues.

let barClasses = 'something';
let closeClickHandler = function() {};

ReactDOM.render(

      <form className="form-inline mt-5 mb-5 ">
          <input
            type="text"
            className="form-control ml-auto mr-auto"
            placeholder="Search.."
            size="45"
          ></input>
        </form>

          Home

          Masculine

Test 1

Test 2

Test 3

Test 4

Test 5

          Feminine

Test 1

Test 2

Test 3

Test 4

Test 5

          Collections

Test 1

Test 2

Test 3

Test 4

Test 5

          Contact Us

    ,
  document.getElementById("react")
);
.dropDownButton {
  float: left;
  max-width: 100%px;
  width: 100%;
  /* height: 65px; */
  line-height: 65px;
  position: relative;
  text-transform: uppercase;
  font-size: 3rem;
  color: rgba(0, 0, 0, 0.7);
  white-space: nowrap;
  cursor: pointer;
}
.dropDownButton:hover{
  background: #d5d5d5;
  border-radius: 5px;
}
.dropDown-menu{
  position: relative;
  top: 0%;
  left: 0;
  width: 100%;
  padding: 0;
}
.dropDown-menu li {
  background: #666;
  color: rgba(255, 255, 255, 0.7);
  display: none;
}
.dropDown-menu li:hover{
  background: #606060;
}
.dropDownButton-menu li:last-child{
  border-radius: 0px 0px 5px 5px;
}
.dropDownButton:hover .dropDown-menu li {
  display: block;
}
.dropDownButton:hover .dropDown-menu.reg-menu li{
  perspective: 1000px;
  opacity: 0;

  animation-name: reg-menu;
  animation-duration: 500ms;
  animation-timing-function: ease-in-out;
  animation-fill-mode: forwards;
}
@keyframes reg-menu {
  0% {
    opacity: 0;
    transform: translateX(0%) translateY(0%);
  }
  100% {
    opacity: 1;
    transform: translateX(0%) translateY(100%);
  }
}


Can an old "stereo mike mixer" be used on a computer?

Question: I'm pretty new to recording and I just picked up a vintage "transistorized stereo mike mixer" from a flea market. The guy said it worked perfectly and I could hook it up to my computer with the right cords. Here's some pictures of the thing

Would a left and right audio to usb cord do the trick?
I'm looking to use this with Reaper, by the way.
Thank you!
Answer: Yes, you can. You'll need a stereo RCA to 1/8" adapter like this.

And then connect the 1/8" into the line input on your computer's sound card.
Comment: That's too bad. I tried to find a cheap USB sound adapter but all the ones I found only had a mic input and no line input. If you want to keep looking around you might be able to find one. But IMO, a better option would be to simply get a USB audio interface with built in mic preamps. How much did you get that mic mixer for? You might be able to return/sell the mixer you got. There are many 2 channel units in the $99 range like the Mackie Onyx Blackjack. This will give you significantly better sound quality.
Comment: Thank you, but I'm using my laptop, which only had a headphone jack. Am I just out of luck now? EDIT: Okay, it might function as both. I'll play around with it in a moment
Comment: Yeah, it seems like that's not gonna work :c
Comment: @Tekkerue Just picked up an Onyx Blackjack and it's a solid interface for the price.
Answer: Generally speaking mixers used for live sound are too noisy to use for recording applications. So, technically, 'yes' you could hook it up, but realistically, it wont make a very nice noise.
The sound quality would be made even worse if you tried to plug the mixer directly into a mic socket on a PC/laptop as the mic socket will try to amplify the signal (unless it is specifically a line level input - if it's got a picture of a mic, its a mic input, not a line input).
Be careful using USB sound adaptors as they tend to be 16bit rather than 24bit that most audio devices work at -  this will further reduce the quality of the signal.
You're best bet would be to get a proper dedicated audio device, you can pick a new one with two mic/line inputs for around £100.
Comment: Alright thank you. That's very sound advice. I just picked this thing up for $4, so it's not much of  loss :P


addFileAttachmentAsync download failed for file hosted in azure blob storage

Question: I have created an Outlook web addin that attaches files to an email.
When using the "addFileAttachmentAsync" method of the Outlook JS API to attach a file that is hosted in Azure Blob Storage I get a "Download Failed" on the attachment. The response of the method is "Success" though.
Files hosted elsewhere attaches correctly.
This works perfectly in Outlook 2016 MSO (16.0.9126.2259).
It breaks in Outlook 2016 MSO (16.0.10827.20084).
I found a similar post on stack overflow which says it was fixed in Outlook 2016 MSO (16.0.8431.2110). Reference to the link
Could this functionality have been broken again?
Comment: Can you access the link in IE11 directly? Could you also share the link to the file so we can test it on our end?
Comment: Yes, the file opens in IE11 directly. You can test with the following link: https://qorussparkdfwedev.blob.core.windows.net/composecachedesktopv4rk3k8/test.docx
Comment: Have you been able to make any progress with the document link I've provided in the comment?
Comment: Any updates on this?
Comment: Thanks for reporting this issue. We have been able to repro the issue, and the bug has been put in the backlog, but is unknown when it will be fixed. Currently the problem repros even outside the addFileAttachmentAsync,  if you try to attach the file via URL from the UI, so the bug has been forwarded to the appropriate team. The workaround is currently to host the file elsewhere. Note that this workaround may be necessary going forward even after a fixed build comes out, as there will be older clients that still have this bug.
Answer: We have fixed the bug and the fix should be available in build 16.0.12625.10000 or later. Depending on the release channel you are on, getting an updated build can take anywhere from 4-8 weeks.


what is the best and fastest way to get the row number

Question: Suppose I have the data in below format in my table, I have to fetch the decile, so what is the best and fastest Query in SQL server to get the correct decile.
suppose I have two parameters in my scalar function,

PerformanceValue
Measureid

suppose I pass 11.22 in performance value parameter and 3 in measureid, the scalar function should return 3
suppose I pass 85.54  in performance value parameter and 4 in measureid it returns 10
suppose I pass 54.00 in performance value parameter and 4 in measureid it return 7.2
Comment: I suggest you normalize your table to store atomic values in each column and avoid the repeating group. It will then be easier to query simple and perform better too.
Comment: The last case which you posted - is it supposed to return 7.2? Or was that supposed to read just 7? Is the image your current data format?
Comment: Please read http://meta.stackoverflow.com/questions/285551/why-may-i-not-upload-images-of-code-on-so-when-asking-a-question/285557 and the accepted answer
Answer: The table you need contains MeasureID, the number range (e.g from_value and till_value) and Decile. Then use a simple WHERE clause:
select decile
from mytable
where measureid = 4
  and 54.00 between from_value and till_value;

Answer: As others have mentioned. The best course of action would be to correct the table design. Of course we all live in the real world and that bay not always be possible.
The following uses the idea of a "semi-perminant" table in tempdb. That will be updated with new measurements w/o having to reprocess the underlying based table with every execution. This should yield the fastest possible execution times short of a full table redesign & process redesign.
 IF OBJECT_ID('tempdb..#TestData', 'U') IS NOT NULL
DROP TABLE #TestData;

CREATE TABLE #TestData (
    Measured INT NOT NULL PRIMARY KEY CLUSTERED,
    Decile_3 VARCHAR(15) NOT NULL,
    Decile_4 VARCHAR(15) NOT NULL,
    Decile_5 VARCHAR(15) NOT NULL,
    Decile_6 VARCHAR(15) NOT NULL,
    Decile_7 VARCHAR(15) NOT NULL,
    Decile_8 VARCHAR(15) NOT NULL,
    Decile_9 VARCHAR(15) NOT NULL,
    Decile_10 VARCHAR(15) NOT NULL
    );
INSERT #TestData (Measured, Decile_3, Decile_4, Decile_5, Decile_6, Decile_7, Decile_8, Decile_9, Decile_10) VALUES
    (1, '54.67 - 35.91', '35.90 - 25.63', '25.62 - 19.34', '19.33 - 14.15', '14.14 -  9.10', ' 9.09 -  3.34', ' 3.33 -  0.01', '0'),
    (2, '53.85 - 64.74', '64.75 - 70.90', '70.91 - 86.68', '89.32 - 92.92', '92.91 - 96.54', '96.55 - 98.67', '96.55 - 98.67', '>= 98.68'),
    (3, '11.22 - 18.57', '18.58 - 24.99', '25.00 - 31.84', '31.85 - 38.92', '38.93 - 47.86', '47.87 - 59.99', '60.00 - 79.01', '>= 79.01'),
    (4, '14.13 - 23.25', '23.26 - 33.02', '33.03 - 43.58', '43.59 - 53.96', '53.97 - 63.60', '63.61 - 74.54', '74.55 - 85.52', '>= 85.53'),
    (5, '12.41 - 22.21', '22.22 - 32.30', '32.31 - 40.86', '40.87 - 47.91', '47.92 - 55.25', '55.26 - 63.06', '63.07 - 73.22', '>= 73.23');

-- SELECT * FROM #TestData td'

--======================================================================
--======================================================================

-- create a semi-perminant unpivot table in temp db that simply adds new measurement as opposed to
-- reporcessing the entire base table with every execution.
IF OBJECT_ID('tempdb.dbo.UnpivotData', 'U') IS NULL
BEGIN   -- DROP TABLE tempdb.dbo.UnpivotData;
    CREATE TABLE tempdb.dbo.UnpivotData (
        Measured INT NOT NULL,
        dType TINYINT NOT NULL,
        BegRange DECIMAL(9,2) NOT NULL,
        EndRange DECIMAL(9,2) NOT NULL,
        PRIMARY KEY CLUSTERED (Measured, dType)
        );
END;
INSERT tempdb.dbo.UnpivotData (Measured, dType, BegRange, EndRange)
SELECT
    td.Measured,
    d.dType,
    r.BegRange,
    r.EndRange
FROM
    #TestData td
    CROSS APPLY ( VALUES (3, td.Decile_3), (4, td.Decile_4), (5, td.Decile_5), (6, td.Decile_6),
                            (7, td.Decile_7), (8, td.Decile_8), (9, td.Decile_9), (10, td.Decile_10)
                            ) d (dType, dValue)
    CROSS APPLY ( VALUES (
                        CASE
                            WHEN CHARINDEX(' - ', d.dValue) > 0 THEN LEFT(d.dValue, 5)
                            WHEN LEFT(d.dValue, 2) = '>=' THEN RIGHT(d.dValue, 5)
                            WHEN LEFT(d.dValue, 2) = '<=' THEN '0'
                            ELSE d.dValue
                        END,
                        CASE
                            WHEN CHARINDEX(' - ', d.dValue) > 0 THEN RIGHT(d.dValue, 5)
                            WHEN LEFT(d.dValue, 2) = '>=' THEN '9999999.99'
                            WHEN LEFT(d.dValue, 2) = '<=' THEN RIGHT(d.dValue, 5)
                            ELSE d.dValue
                        END
                        ) ) r (BegRange, EndRange)
WHERE
    NOT EXISTS (SELECT * FROM tempdb.dbo.UnpivotData ud WHERE td.Measured = ud.Measured);

-----------------------------------------------------------

-- Querieng from the temp table is now quite easy.
DECLARE
    @Measure INT = 4,
    @PerformanceVal DECIMAL(9,2) = 85.54;

SELECT
    ud.Measured,
    ud.dType,
    ud.BegRange,
    ud.EndRange
FROM
    tempdb.dbo.UnpivotData ud
WHERE
    ud.Measured = @Measure
    AND @PerformanceVal BETWEEN ud.BegRange AND ud.EndRange;

Results...
Measured    dType BegRange                                EndRange
----------- ----- --------------------------------------- ---------------------------------------
4           10    85.53                                   9999999.99

Answer: Here's another option that may end up being faster as it starts by doing an index seek on Measurid so that only a single row of data needs to be parsed...
DECLARE
    @Measureid INT = 4729,
    @Value DECIMAL(9,2) = 85.0;

IF OBJECT_ID('tempdb..#UnpivotData', 'U') IS NOT NULL
DROP TABLE #UnpivotData;

SELECT
    td.Measureid,
    d.dType,
    BegRange = ISNULL(CAST(r.BegRange AS DECIMAL(9,2)), 0),
    EndRange = ISNULL(CAST(r.EndRange AS DECIMAL(9,2)), 0)
    INTO #UnpivotData
FROM
    #TestData td
    CROSS APPLY ( VALUES (3, td.Decile_3), (4, td.Decile_4), (5, td.Decile_5), (6, td.Decile_6),
                            (7, td.Decile_7), (8, td.Decile_8), (9, td.Decile_9), (10, td.Decile_10)
                            ) d (dType, dValue)
    CROSS APPLY ( VALUES (
                        CASE
                            WHEN CHARINDEX(' - ', d.dValue) > 0 THEN LEFT(d.dValue, 5)
                            WHEN LEFT(d.dValue, 2) = '>=' THEN RIGHT(d.dValue, 5)
                            WHEN LEFT(d.dValue, 2) = '<=' THEN '0'
                            ELSE d.dValue
                        END,
                        CASE
                            WHEN CHARINDEX(' - ', d.dValue) > 0 THEN RIGHT(d.dValue, 5)
                            WHEN LEFT(d.dValue, 2) = '>=' THEN '9999999.99'
                            WHEN LEFT(d.dValue, 2) = '<=' THEN RIGHT(d.dValue, 5)
                            ELSE d.dValue
                        END
                        ) ) r (BegRange, EndRange)
WHERE
    td.Measureid = @Measureid;

------------------------------------------------------

SELECT
    ud.Measureid,
    ud.dType,
    ud.BegRange,
    ud.EndRange
FROM
    #UnpivotData ud
WHERE
    @Value BETWEEN ud.BegRange AND ud.EndRange;
GO


Menu on the taxonomy term page

Question: maybe the solution to my problem is quite simple but I can not find a way on the taxonomy term page to show a menu block!
I use drupal 8 with bartik theme and have a menu based on taxonomic terms (Module: Taxonomy Menu + Menu Block). This menu is also always displayed everywhere (with the set content types). Just not on the taxonomy term page (the page where all entries are displayed from a taxonomy item in a teaser view).
if I look under Structure> Block Layout> Navigation> Configuration: is there "page" there I tried to enter URL of the taxonomy terms or also / * but both remains without effect.
Comment: Please post the Visibility settings for your block.
Comment: ok I have posted a few pictures
Comment: Because taxonomy terms are not content types, the visibility setting won't match
Comment: If I got this right, you want the menu to be visible on _any_ page. In this case remove _all_ visibility settings, completely empty visibility setting means "visible everywhere".
Answer: As mentioned in comments if you want it shown everywhere you should untick the Type options, then they apply anyway. And on the Seite delete everything, that should show it everywhere too without restrictions (no need for /*).
But I think your particular configuration isn't working because you have included the /de/ in your path under Seite, the language prefix is not part of the Drupal path. Remove it from there and it should work.
Instead of:
/de/tutorial/erste-schritte
it should say:
/tutorial/erste-schritte
You have the Visibility limited to the German language under the Sprache tab.

Menu on the taxonomy term page


Using feols() vs plm() vs lm() in panel regressions in R

Question: I am using panel data at the district level. My outcome variable is the share of employed individuals in a given district. I am regressing this variable on a binary treatment dummy called "treat", which is also at the district level. I am also adding year and district fixed effects.
I used three different methods as shown below in reg1, reg2, and reg3, which use feols(), plm(), and lm() functions, respectively. While using the lm() function, I add the factor() function to include the fixed effects.
As the results below show, the coefficients on treat are very different in terms of direction, magnitude, and significance level. I'm trying to understand which function suits my current situation, but also to understand the general situations on when to use these functions and their differences.
library(fixest)
reg1 <- feols(emp ~ treat, data, panel.id = ~year + district)
                Estimate   Std. Error  t value   Pr(>|t|)
      treat    -0.066819   0.012030   -5.55442   1.4402e-03 **

library(plm)
reg2 <- plm(emp ~ treat, index = c("year", "district"), data = data, model = "within", effect = "twoways")
               Estimate    Std. Error  t-value   Pr(>|t|)
      treat   -0.0370409   0.0067479  -5.4892    4.3e-08 *

reg3 <- lm(formula = emp ~ treat + factor(year) + factor(district), data = data)

               Estimate    Std. Error  t value   Pr(>|t|)
      treat    0.0060141   0.0130635   0.460     0.645280

Comment: The code looks okay to me. Could you share a subset of the data? If not, what kind of data are you working with? Is this repeated cross-sectional data? Are covariates excluded?
Comment: @ThomasBilach, how can I share a subset of the data? I'm using cross-sectional individual-level data, but these regressions aggregate observations at the district level, so basically, it's a district-level panel. Covariates are excluded in all three regressions for now.
Comment: Is your question about the differences in the code or the differences in the regression types?
Answer: Apparently, feols only identifies the panel units via panel.id, without then also running a fixed-effects regression. To get one, specify the fixed effects as follows:
library(plm)
library(fixest)

data("Grunfeld", package = "plm")

plm.reg <- plm(inv ~ value + capital, data = Grunfeld, model = "within", effect = "twoways")
fixest.reg <- feols(inv ~ value + capital | firm + year, data = Grunfeld)
lm.panelreg <- lm(inv ~ value + capital + factor(year) + factor(firm), data = Grunfeld)

summary(plm.reg)
summary(fixest.reg)
summary(lm.panelreg)

To see that feols runs a plain pooled OLS regression in "your" specification, consider
fixest.reg2 <- feols(inv ~ value + capital, data = Grunfeld, panel.id = ~firm + year)
lm.linreg <- lm(inv ~ value + capital, data = Grunfeld)

summary(fixest.reg2)
summary(lm.linreg)

Why lm returns yet other data in your code (in mine we get the same results for all three) is as of yet unclear to me. Is your panel balanced?
Comment: I think plm uses the first columns to identify by default. If the code does not work on your data, that seems to strengthen @ThomasBilach's point that looking at the data would be relevant.
Comment: Hi Christoph, thank you so much for the detailed response! I saw that you didn't mention the fixed effects variables for the PLM regression. Although it worked for the Grunfield data you used, it is showing an error for the data I'm using [Error in plm.fit(data, model, effect, random.method, random.models, random.dfcor, : empty model]. Also, I think my PLM regression with my code above and your fixest regression are giving the same results. That's something! The lm regression still gives different estimates. And, yes, my data is a balanced panel at the district level.
Comment: Thanks! I think we found the error. For some reason, the panel wasn't balanced. Maybe that's causing the issue.
Comment: Wansbeek, T.J. and A. Kapteyn, 1989, Estimation of the error components model with incomplete panels, Journal of Econometrics 41, 341–361 could be relevant to spell out details,


CICD Pipeline Deployment stage unable to come out after successful deployment

Question: Background : Spring boot application deployment using cicd pipeline declarative script
Issue :
The spring boot application jar file is able to launch successfully. After some time we can access application health info also from browser but the build job is unable to exit from deployment stage. It is spinning at this stage continuously.
Action Taken: even we have added timeout=120000 in launch command but no change in behaviour.
Help : please help us how can we make clean exit after deployment stage from jenkin cicd declarative pipeline.
We are ssh'ing and executing our launch command. The code is like:
sshagent([sshAgent]) { sh "scp -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -v *.jar sudouser@${server}:/opt/project/tmp/application-demo.jar" sh "ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null sudouser@${server} nohup '/opt/java/hotspot/8/64_bit/jdk1.8.0_141/bin/java -jar -Dspring.profiles.active=$profile -Dhttpport=8890 - /opt/project/tmp/application-demo.jar ' timeout=120000" }

I need to come out (clean exit) from jenkins build after deployment stage is successful.
Answer: You need to add the '&' to the start process in backgroud
Example:
nohup '/opt/java/hotspot/8/64_bit/jdk1.8.0_141/bin/java -jar -Dspring.profiles.active = $ profile -Dhttpport = 8890 - /opt/project/tmp/application-demo.jar &

You can also put an 'if' condition for when the log appears 'started in' to exit execution.
Example:
status(){
  timeout=$1
  process=$2
  log=$3
  string=$4
  if (timeout ${timeout} tail -f  ${log} &) | grep "${string}" ; then
    echo "${process} started with success."
  else
    echo "${process} startup failed." 1>&2
    exit 1
  fi
}

start_app(){
   java -jar -dspring.profiles.active=$profile -dhttpport=8890 - /opt/project/tmp/application-demo.jar >> /tmp/log.log 2>&1 &
   status "60" "application-demo" "/tmp/log.log" "started"
}

Comment: we have tried  appending '&' in launch command but there is no change in behavior..its spinning after deployment and not exit from pipeline script.
Comment: Please, try ` 2>&1 &`


What is the skewness of the difference between two binomial random variables?

Question: I have two binomial random variables:
$$
X_1 \sim \text{Binom}(n_1,p_1), \\[6pt]
X_2 \sim \text{Binom}(n_2,p_2).
$$
I know that the individual skewnesses are:
$$
\mathbb{Skew}(X_1) = \frac{1 - 2p_1}{\sqrt{n_1 p_1 (1-p_1)}}, \\[6pt]
\mathbb{Skew}(X_2) = \frac{1 - 2p_2}{\sqrt{n_2 p_2 (1-p_2)}}. \\[6pt]
$$
What is the skewness of the difference $X_1-X_2$?
Comment: 1. Are $X_1$ and $X_2$ intended to be independent? 2. "*I am not interested in the absolute difference as it collapses to another binomial distribution*" no, in general it doesn't. The absolute difference of two sums is not the same thing as the sum of absolute differences. 3. Presumably you seek the moment-skewness ($\mu_3/\sigma^{3})$, rather than some other skewness measure. Is that correct?
Comment: 4. Your title says "binomial averages" but it looks like $X_1$ and $X_2$ are sums of Bernoullis, not averages, so $X_1-X_2$ is simply the difference of two binomial variates.  You might say "binomial random variables" or "binomial sums" or even just "binomials" in the title but it doesn't look like the "averages" fits here.
Answer: Assuming you do seek the third-moment skewness and assuming independence, the third central moment of $X_1-X_2$ is
\begin{eqnarray}
E[((X_1 - X_2) - (\mu_1-\mu_2))^3 ]&=&E[(X_1 - \mu_1 - (X_2 -\mu_2))^3 ]\\\\
&=& E[(X_1-\mu_1)^3] - 3E[(X_1-\mu_1)^2]E(X_2-\mu_2)   \\\\
           & & \qquad + 3E(X_1-\mu_1)E[(X_2-\mu_2)^2] - E[(X_2-\mu_2)^3]\\\\
&=& E[(X_1-\mu_1)^3] - 0 + 0 - E[(X_2-\mu_2)^3]\\\\
&=&\sigma_1^3 (1-2p_1)/\sqrt{n_1p_1(1-p_1)}
\\\\
 & & \qquad-\hspace{1mm}\sigma_2^3 (1-2p_2)/\sqrt{n_2p_2(1-p_2)}\\\\
&=&n_1p_1(1-p_1) (1-2p_1) \hspace{1mm} - \hspace{1mm} n_2p_2(1-p_2) (1-2p_2)
\end{eqnarray}
The variance of $X_1-X_2$ is
$$\sigma_1^2+\sigma_2^2= n_1p_1(1-p_1)+n_2p_2(1-p_2)$$
Hence (if I made no errors) the skewness should be
$$\frac{n_1p_1(1-p_1) (1-2p_1) -n_2p_2(1-p_2) (1-2p_2)}{[n_1p_1(1-p_1)+n_2p_2(1-p_2)]^{\frac{3}{2}}}$$


How to prevent Pico.css to take over as the default css?

Question: I really like Pico, but it conflicts with other libraries I use when it tries to be the main driver of all the styles of e.g. form elements.
I would like to run Pico in a mode, where it is isn't affecting anything, unless i would write something like class="pico" or something similar, then it would apply its styles to this particular element.
Is that possible?
Comment: Conflicting CSS is never fun, you should get into the practice of working with single style sheets and modifying them or creating your own from scratch (with CSS reset sheet). With your supplied description of the problem I couldn't give you an easy answer making this question invalid. Perhaps try ChatGPT for help.
Comment: I'd never heard of that framework before, but at a glance of their introduction page it sounds like the main point of it is to be the "default", to apply semantically to the markup rather than needing explicit classes and other customizations to use it.  It sounds like what you want is in direct opposition to what the tool is designed to do.  You may be able to get around this by modifying their CSS to add your `.pico` class to all selectors, which you'd have to do any time you update the library.
Comment: You could ask the developer(s). The website contains a mail address: email@example.com, a GitHub link: https://github.com/picocss/pico/issues and a Twitter link: https://twitter.com/picocss. They can answer your question or even implement it as a new feature.
Answer: Following the comments, there are no way to do this automatically.
The only way would be to do it manually, as David mention in the comments:
You may be able to get around this by modifying their CSS to add your .pico class to all selectors, which you'd have to do any time you update the library.
Comment: I downvoted because this answer is based on guesses in the comments. It could be correct, but it could also be wrong.
Comment: Yes, I acknowledge that the entire question and answer are weak, and won't  accept my own answer. For what it's worth, I managed to get a solution running with using Davids suggestion, adding ".pico" to all selectors, using ChatGPT for efficiency. This is not a good solution, since 1: I don't know if ChatGPT did any errors (but looks fine so far), and 2: Can't easily update Pico.css (alltho Pico.css hasn't been updated for three months, so this particular release seems stable enough, for a little while atleast).


How to initialize the following static variable?

Question: I am trying to implement Singleton design pattern in heap data structure but how should I initialize the following static variable called root? Compiler gives me an error

expected initializer before '*' token

<code>class node
{
    public:
    node *lft,*rght;
    static node* root;
    node()
    {
        lft=NULL;
        rght=NULL;
    }
    int val;
}

node* node::root=NULL;
</code>
Comment: You have a missing `;` after the class declaration.
Comment: How can something like a node be a Singleton? Even the class definition itself acknowledges the existence of multiple instances.
Comment: I got it. I applied singleton in a wrong purpose.
Answer: First of all your question doesn't really make much sense (A singleton Node?)
You're missing a semicolon after your class definition.
Research singletons, improve your design, and I suggest you create a singleton NodeTree or something if you're dead set on using the singleton design. Nodes should not be singletons, as there will be more than one of them.
Comment: A node tree should not be a Singleton either.
Comment: A particular NodeTree might be a singleton, but I agree that in general they shouldn't be. I used the phrase "dead set" for a reason.
Comment: That's not completely true! There are well defined use cases of using a double linked lists `head` as a Singleton (global variable). E.g. we're doing consciously for keeping a globally accessible list of threads with our OSAL.
Comment: I would do that as a singleton node wrapper, not a singleton node, for clarities sake. Either way it wouldn't be a static member of the node class.
Comment: @πάνταῥεῖ: I still don't understand how this is a Singleton. It's just a special instance of the same class, isn't it?
Comment: @ChristianHackl I have to admit we're using an intrusiive linked list for the particular case mentioned.


ASP.NET MVC JQuery - flexible alghoritm for calling asp.net mvc methods

Question: Greetings,
i would like to prepare some good "machine" for calling asp.net mvc methods from jquery.
The concept is as follows:
The concept is to have a one method each requests will be calling. By using visitor pattern I will be able to determine what kind of operation i should do.
public interface IRequestVisitor
{
    void VisitRequest_GetPersons(CRequest_GetPersons request);
    void VisitRequest_RemovePerson(CRequest_RemovePerson request);
}

Creating some abstract request:
public abstract class CRequest
{
    public abstract void AcceptVisitor(IRequestVisitor visitor);
}

and the implementation of concrete request:
public class CRequest_GetPersons: CRequest
{
    public CRequest_GetPersons(Guid schoolROWGUID)
    {
        SchoolROWGUID = schoolROWGUID;
    }
    public Guid SchoolROWGUID={get;private set;}

    public override void AcceptVisitor(IRequestVisitor visitor)
    {
        visitor.VisitRequest_GetPersons(this);
    }
}

And the implemetation of visitor:
public void CRequestVisitor : IRequestVisitor
{
    public CResponse ResponseResult {get;private set;}

    public void IRequestVisitor.VisitRequest_GetPersons(CRequest_GetPersons request)
    {
        //code responsible for getting persons
        Result = new CResponse_GetPersons_Success(List<Person>)
    }
    public void VisitRequest_RemovePerson(CRequest_RemovePerson request)
    {
        //code responsible for removing person
        Result = new CResponse_RemovePerson_Success();
    }
}

The action each js methods will execute is as follows:
public ActionResult AjaxRequest(CRequest request)
{
    CRequestVisitor visitor = new CRequestVisitor();
    request.AcceptVisitor(visitor);
    return JSON(visitor.Result);//return some result

}

I have also found how asp.net mvc methods can be called using jquery

I would like to know how can I pass the rowguid of currently selected school.
And how can I access list of persons returned as JSON object?
Answer: You can pass parameters, that will be passed to parameters of the action method, by adding it to the URL:
/Test/Request?school=1
Replace 1 with the guid, and the guid will be passed back.
Comment: You can't pass a whole object in a get operation; you would have to use an Html.BeginForm to post an object's data to the server.

In either approach, you can't pass objects, you can only pass each property value of the object.  So you could render all of the property values to HTML elements, and post them to the server, and reload the object (or requery the object if all you need is view only operation).

So you can't pass a Person, but the person's name, address, and all other properties of person.
Comment: ok..and how to pass for instance whole object(e.g. of type Person)
Comment: additionally i can't pass just guid. The expected argument is of type CRequest. Any ideas?


What purpose does MyClass.class.getName() serve?

Question: I'm reviewing code that features this construction.  MyClass is the name of a class.  Why would a someone use
String name = MyClass.class.getName();

instead of
String name = "MyClass";

given that the class name is already identified in the former?  Is there something I'm missing?
Comment: These two lines of code don't do the same thing. Unless the class is in the default package (which is a bad, bad practice). The first one keeps doing the right thing if you rename or move the class. The second doesn't.
Comment: In some code, a Class object may represent one of many different classes. The `getName()` method allows you to get the name of the specific class represented.
Answer: If the class is later renamed, then the MyClass.class.getName() reference will need to be checked and fixed up in order to compile (or will be fixed up automatically by the IDE). The string will not, which means it will compile correctly, but not actually work correctly, which is worse because it hides the problem.
Referring to the class name this way is an application of the Don't Repeat Yourself principle.
Answer: If you accidentally spell the first one MyClas.class.getName(), it won't compile. The second one will.
Also, as JB Nizet points out, getName includes the full package hierarchy in the name. For example, if MyClass is under the com.piotrchernin package, MyClass.class.getName() will be "com.piotrchernin.MyClass", not "MyClass".
Comment: @YassinHajaj: I'm not sure what you're trying to say there. Were you thinking of `getSimpleName()`?
Comment: [Indeed, my bad sorry](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/Class.java#Class.getSimpleName%28%29)
Comment: Thank you!  I have to note that of all the documentation, tutorials, and SO questions I've reviewed to learn about this, not one (even the official docs) bothered to state clearly that getName() returns the full hierarchy of the class.
Comment: @PiotrChernin: On one hand, the `getName` docs don't directly state it. On the other hand, they do give the example that `String.class.getName()` returns `"java.lang.String"`, which includes the package hierarchy, and if you follow the JLS references, you can find the sections on [binary name](https://docs.oracle.com/javase/specs/jls/se8/html/jls-13.html#jls-13.1) and [canonical name](https://docs.oracle.com/javase/specs/jls/se8/html/jls-6.html#jls-6.7).
Answer: The method getName():

Works for code that has a Class object, but does not know the actual class.
Continues to work after the class has been renamed.
Works on Class objects representing arrays.

Code that does not know the class
As you note, one way to obtain a Class object is MyClass.class. However, it is not the only way. You can also call the method getClass() on an object of a class -- even in code that's referring to the object via an interface or superclass type. And some code receives a Class object from a caller.
As an example of the former, consider the following class hierarchy and factory method:
public interface IFoo { }
public class AlphaFoo implements IFoo {}
public class BetaFoo implements IFoo {}
public FooFactory {
  public static IFoo makeFoo() { ... }
}

The caller of the factory does not know what kind of IFoo will be returned. If you wanted to debug-print the actual class received from the factory, you could do this:
IFoo foo = FooFactory.makeFoo();
System.out.println( foo.getClass().getName() );

Refactoring
As an example of resilience to refactoring, consider this creation of a standard Java logger:
public class Bar {
   private static final Logger s_logger = Logger.getLogger(
     Bar.class.getName() );
   ...
}

If I rename the class using my IDE's refactoring tools, the logger name will update automatically.
Arrays
You can call getName() on a Class object representing an array.
String[] strs = new String[] { "alpha", "beta", "gamma" };
System.out.println( strs.getClass().getName() );

The output is:
[Ljava.lang.String;

Now, you might ask how this is useful. This syntax turns out to be how array arguments are expressed in calls to the JNI method GetMethodID(), which is necessary to call Java methods from C/C++.


Two data sources and two outlets in ember.js

Question: I'm trying to create something really simple with ember.js, and I'm getting badly lost between old examples, new examples, and extensive documentation.
I want to create an application with no functionality, that simply shows two sets of data in two columns. The real application uses JSON data from two different sources and is more complicated, but the problem reduces to getting the below to work:

and in the javascript something like
App = Ember.Application.create({
  rootElement: '#appholder'
});

App.LeftController = Ember.ArrayController.extend({
  model: function() {
    return ['left one', 'left two'];
  }
});
App.RightController = Ember.ArrayController.extend({
  model: function() {
    return ['right one', 'right two'];
  }
});

App.IndexRoute = Ember.Route.extend({
    renderTemplate: function() {
      this.render('left', {
        outlet: 'left',
        controller: 'left',
      });
      this.render('right', {
        outlet: 'right',
        controller: 'right',
      });
    }
});

to output the hoped for result, a left column with list entries from one data source and a right column with two entries from another column.
Could somebody ideally provide a js fiddle with the above adapted to working code? Any part of it can change, to use {{render}} or {{view}} in the templates and whatever the js should be.
Thank you for any help
http://emberjs.jsbin.com/mifer/2/edit
Comment: put your code into here http://emberjs.jsbin.com/ then share the link in your post... it would also be helpful to explain what is not working about your code... any errors?  We can give you suggestions and solutions, but dont expect someone to just do it for you.
Comment: @Grapho jsfiddle added, I've created all elements of a large dashboard application in ember using various remote data sources, but cannot find a way to output them all on the same page. Have tried multiple approaches and read multiple examples over the past several hours. Really stuck on something which seems incredibly simple. Any help at all would be appreciated
Answer: Here is a working JSBin
First in order to use a function as a property, you must make it a computed property with the property() function:
App.LeftController = Ember.ArrayController.extend({
  model: function() {
    return ['left one', 'left two'];
  }.property()
});

Secondly, the renderTemplate code is in the wrong place. You put it in the index route but in reality it should be in the application route. If you had {{outlet}} in your application template, the index template would have been rendered into it. Then, if you had those two named outlets inside the index template, what you had would have almost worked (you need to call this.render() or this._super() whenever you use renderTemplate if you want the route template to render.
But, you have two named outlets which you want to manually render into inside of your application template. Hence:
App.ApplicationRoute = Ember.Route.extend({
  renderTemplate: function(){
    this.render();
    this.render('left', {outlet: 'left', into: 'application'});
    this.render('right', {outlet: 'right', into: 'application'});
  }
});

Now this next approach is how I tackle multiple models in my dashboard application. I am constantly needing to replace the sections of widgets so I use multiple named outlets. I've restructured your code so that the application template renders the index template into its single unnamed outlet.
Keys to this approach:
App.IndexRoute = Ember.Route.extend({
  model: function(){
    return Ember.RSVP.hash({
      left:  ['left one', 'left two'],
      right: ['right one', 'right two']
    });
  },
  renderTemplate: function(controller, model){
    this.render();
    this.render('left', {outlet: 'left', into: 'index', controller: 'left', model: model.left});
    this.render('right', {outlet: 'right', into: 'index', controller: 'right', model: model.right});
  }
});

Whenever you need to return multiple models, and you want your route to block until all models are returned, use Ember.RSVP.hash. You return multiple promises, each as properties of your returned model. RenderTemplate takes two parameters, controller and model so you access your model in the renderTemplate to manually pass the model into the controller of the template you are rendering.
As a slight alternative to this approach, if you need to render multiple datasources on the page, but you do not ever need to dynamically replace the whole template backing one of the models (ie render once and done), you can use the {{render}} helper.

The benefit of this code is that our route has simplified.
App.IndexRoute = Ember.Route.extend({
  model: function(){
    return Ember.RSVP.hash({
      left:  ['left one', 'left two'],
      right: ['right one', 'right two']
    });
  }
});

But, we have lost the ability to easily render something else here via action since we no longer have named outlets.
Comment: perfect, thank you so much, and also for any further edits on various ways to approach this :)
Comment: @MarkPfennig edits made. hope this helps! Let me know if you have any other questions
Comment: thank you for all your help @sunrize920 - I found a slight nuance with the second example where model.left and model.right were both overriding model when using async data. Resolved the issues by removing `, model: model.left` and specifying `{{#each item in model.left}}` in the template. Here's the modified example using remote data http://emberjs.jsbin.com/koconu/1/edit


How to estimate the probability that a single value follows the same distribution as a a set of values

Question: This question is a possible duplicate of this one but I would like to go a bit further.
I have a set of values $X=x_1, x_2, \cdots, x_n$ that are iid estimates of a reference value $y$ given by a Monte-Carlo like algorithm. I know my reference value $y$ and I would like to assess the quality of the prediction given by the algorithm.
An indicator of the quality of the prediction could be the answer to the following question:
What is the probability of picking $y$ using the distribution of $X$?
I know about the solution based on the rank of the reference value proposed here but it seems limited to me. In the example below the estimated values (blue bars) follow a long tailed distribution and the orange, green and red bars are three different cases of reference value. The orange and the green bars have the same rank but it seems pretty obvious to me that the probability of the orange bar being picked from the blue bars distribution is higher that for the green bar. The green and the red bars have a different rank but I would intuitively say that their probability of being picked using the blue bars distribution is quite similar.

I intuitively think there could be some kind of moment-like indicator to estimate how the distribution fits with the reference. For example:
$I=\sqrt{\frac{\sum_{i}^{n}{(x_i-y)^2}}{n}}$
But I don't know how to relate it to a probability of the reference being picked using the same distribution as the sample points.
Is there any method giving a better answer to this question than the rank-based method?
Edit: I precise that I have no assumption about the distribution of $X$.
Comment: I am facing a similar challenge, so i was wondering how did you tackle this problem?
Answer: There are two approaches here.
For clarity, let's call your set of sampled values $X$,
and your single reference value $y$.
Parametric Approach
Are the values $X$ distributed according to any known parametric distribution, for example the log-normal distribution? If so, you can estimate the parameters of this distribution ($\mu$ and $\sigma$ for the log-normal), and then use the cumulative distribution function for that distribution, with those parameters, find the p-value:
the probability of finding a value as extreme or more extreme than $y$ under this distribution.
mu = 2
sigma = .5
X = rlnorm(1000, mu, sigma)
y = 25

hist(X, breaks = 20)
abline(v=y, col='red', lwd=2)

estimated.mu = mean(log(X)) # ≈ 2
estimated.sigma = sd(log(X)) # ≈ .5

# Probability of getting a value of y or lower from this distribution
p.low = plnorm(y, estimated.mu, estimated.sigma, lower.tail = T)
# Probability of getting a value of y or higher
p.high = plnorm(y, estimated.mu, estiated.sigma, lower.tail = F)
(p.value = 2*min(p.low, p.high))
# ≈ 0.015

Non-parametric approach
If $X$ doesn't match any known distribution,
you can do something a little more naive,
and just count the proportion of $X$ that is above or below $y$.
# Observed proportion of values lower than y
approx.p.low = mean(y > X)
# Observed proportion of higher
approx.p.high = mean(y < X)
(p.value.alt = 2*min(approx.p.low, approx.p.high))
# ≈ 0.015

Note that neither of these approaches works properly if $X$ is
bimodally distributed, since they won't pick up on cases where $y$
falls between the two modes.
Comment: Unfortunately, I have no assumption about the distribution of $X$, so I can only use the non-parametric approach.
The main drawback I see to your proposal is that it does not take into account the distance of $y$ to the elements of $X$ but only its rank. So the orange and green bars would have the same probability with this method.


Memory used by a process under mac os x

Question: Given a PID, how can I get the memory currently used by a process ? Specifically I am looking for:

The private physical memory (RAM) used by the process
The swap space used by the process

But I am not interested in mapped files and shared memory. In short, I would like to determine how much memory (RAM and swap) would be freed by terminating the PID.
Comment: Have a look at http://stackoverflow.com/questions/131303/linux-how-to-measure-actual-memory-usage-of-an-application-or-process
Comment: Thank you, but this article refers to tools that aren't available on mac (/proc, pmap, smem, htop, gcore) or to things such as valgrind which aren't an option. I am mainly looking for a way of finding the memory (RAM) and SWAP used by a process, programatically. PS could work, but it does not report that. I should have tagged objective-c instead of cocoa. But It would not be better. C/c++ calls are good as well as long as they can be placed on a MAC OS platform.
Answer: Would this be useful? You can use the ps command with various options to get at least some of those things:
ps -o rss -o vsz -o pid

will give you the resident set size, the virtual size, and the process ID. I see from the man page that -o paddr gives the swap address, but I don't see which option gives you the swap size.
Comment: Or even simpler: `ps -o rss,vsz,pid`.
Comment: Thank you for your reply. I believe this command will return the address space size ? Does RSS include the shared / mapped memory as well ? (note: `-p pid`).
Comment: As a note if you're using this to get memory programmatically, shelling out to `ps` is extremely expensive https://github.com/schneems/get_process_mem/issues/31
Answer: You can use Mach's task_info call to find this information. Here is code which works on OS X v10.9, and which gets the virtual process size of the current process:
#include <mach/mach.h>
#include <mach/message.h>  // for mach_msg_type_number_t
#include <mach/kern_return.h>  // for kern_return_t
#include <mach/task_info.h>
#include <stdio.h>

int main(void) {
  kern_return_t error;
  mach_msg_type_number_t outCount;
  mach_task_basic_info_data_t taskinfo;

  taskinfo.virtual_size = 0;
  outCount = MACH_TASK_BASIC_INFO_COUNT;
  error = task_info(mach_task_self(), MACH_TASK_BASIC_INFO, (task_info_t)&taskinfo, &outCount);
  if (error == KERN_SUCCESS) {
    // type is mach_vm_size_t
    printf("vsize = %llu\n", (unsigned long long)taskinfo.virtual_size);
    return 0;
  } else {
    printf("error %d\n", (int)error);
    return 1;
  }
}

I think that this excludes shared memory segments, but I'm not sure.
Comment: Thanks a ton for this! The code here returns info for the current process. Do you know how to retrieve the resident set size for a different PID on mac?

Memory used by a process under mac os x


como forçar um buffer a se comportar como uma string em C?

Question: Estou recebendo um buffer da internet, acredito que para percorrer esse buffer e encontrar o último caractere, é preciso encontrar o caractere '\0'. Mas não existe '\0' em um buffer.
É possível forçar esse buffer a se comportar como uma string?
Answer: Acrescenta p '\0' ao buffer. Mas atencao a dados binarios!!
length = recv(socket, buffer, sizeof buffer - 1, 0);
buffer[length] = 0; // adiciona terminador


A book for questions on coordinate geometry

Question: Can someone recommend me a book on coordinate geometry which focuses mainly on question solving and consists of ample amount of tough
 hybrid problems on 2 or more conics, topics like common tangents, etc
Answer: You can go with Advance Problems in Co-Ordinate Geometry by Vikas Gupta , it has ample of good questions


What is the dimension of a subspace containing $(1,1,1)$?

Question: Say $S=\{{(x,y,z):x=y=z}\}$, then every vector in $s \in S$ can be represented as $\lambda \cdot (1,1,1)$ with $\lambda \in R$. Vector $(1,1,1)$ is trivially independent since it is not zero.
Also, $sp(\{(1,1,1)\})=S$.
This tells us that $(1,1,1)$ is a basis of $S$ and
$\dim (S)=1$. However, I can continue the decomposition: $$ s = \begin{pmatrix}\lambda\\0\\0\end{pmatrix} +
\begin{pmatrix}0\\\lambda\\0\end{pmatrix}+\begin{pmatrix}0\\0\\\lambda\end{pmatrix}$$ These vectors are obviously independent and span $S$ as well. So $\dim (S) = 3$, but we just saw that $\dim (S) = 1$. What is the right answer ? Thank you.
Answer: The vectors $\begin{pmatrix}\lambda\\ 0\\ 0\end{pmatrix}$, $\begin{pmatrix}0\\ \lambda\\ 0\end{pmatrix}$, $\begin{pmatrix}0\\ 0\\ \lambda\end{pmatrix}$ are not in $S$ for nonzero $\lambda$.
Comment: Amazing, thank you ! In general that would be the right way to find a basis, right ? Decompose as much as possible as long the the vectors belong to the set.
Comment: @Kreol Sure. See [here](https://math.stackexchange.com/questions/732467/how-do-i-find-a-basis-for-the-subspace-of-mathbbr4-spanned-by-the-four-vec) for an example given some vectors. In your example, if we allow say, $\pmatrix{1 \\0\\ 0},\pmatrix{0 \\ 1\\ 0},\pmatrix{0 \\ 0\\ 1}$ to be in $S$, then $S$ would no longer be closed under vector addition and scalar multiplication. In general you can find some set of vectors that are in $S$ that span $S$, then check if they are linearly independent by reducing the matrix with rows as said vectors.


SQL stored procedure conditional update for one of the cloumns

Question: I have this update statement in my SP:
ALTER PROCEDURE [dbo].[mySP]
      @ID INT
    , @valA NVARCHAR(500)
    , @valB NVARCHAR(500)
    , @valC NVARCHAR(500)
    , @flag BIT = 0
UPDATE mt
    SET mt.colA = @valA,
        mt.colB = @valB,
        mt.colC = @valC,
        mt.colD = GETUTCDATE()
    FROM dbo.mytable mt
    WHERE mt.ID = @ID

I want to change it to update colD only if @flag is 1. What would be the best and efficient way without impacting the performance of the SP much?
Comment: Use `case when @flag = 1 then...` expression.
Answer: Would seem the easiest way would be to use a CASE expression:
mt.colD = CASE @Flag WHEN 1 THEN GETUTCDATE() ELSE mt.ColD END

Comment: in order to know the impact of this change do I have to benchmark it? I am just concerned that I do not end up adding a delay considering that this SP will be called thousands of time in less than 5 mins.
Comment: This isn't going to have any impact compared to the query you already had, @favier .
Answer: Try this:
ALTER PROCEDURE [dbo].[mySP]
      @ID INT
    , @valA NVARCHAR(500)
    , @valB NVARCHAR(500)
    , @valC NVARCHAR(500)
    , @flag BIT = 0
UPDATE mt
    SET mt.colA = @valA,
        mt.colB = @valB,
        mt.colC = @valC,
        mt.colD  = case when  @flag = 1 then  GETUTCDATE() else  mt.colD END
    FROM dbo.mytable mt
    WHERE mt.ID = @ID


In Python, can I use mean, median, minimum, maximum, standard deviation, population size, and single sample to generate statistically identical data?

Question: Example situation

After each exam, the professor provides the following information.

Minimum Score
[Arithmetic] Mean
Median
Maximum Score
Standard Deviation

I also know what my score was as well as how many students took the exam.

Restating question in light of example
Is there a known way in Python to take this other information into account such that calculating the mean, median, minimum, st. deviation, and maximum of the resulting dataset is an exact match for the given actual mean, median, minimum, and maximum AND that my score is among the output dataset?
numpy.random.normal() doesn't give me what I want
I know that I can use numpy.random.normal to generate random data that tends toward a given distribution, e.g., numpy.random.normal(loc=median_of_scores, scale=sigma_of_scores, size=num_of_scores), but that only tends toward the statistical parameters. Also, it doesn't take into account known pieces of information (my score, the median, the minimum score, and the maximum score). Adding my score, the minimum score, and the maximum score would further warp the randomly-generated data away from the known population numbers.
Other use-cases
While my example is specific to a college course, I imagine this problem is also faced by any Python developer who works with datasets that they're only allowed to know the statistics of (for privacy reasons). For quality testing, I imagine these developers would want a way to create statistically-indistinguishable data.
Comment: This seems like you really have a math or statistics question, rather than a programming question.
Comment: I think it's definitely at the intersection of the two, Karl, but a math solution wouldn't be very helpful without an accompanying explanation in how to implement it in Python. Alternatively, if someone said "you can use this library to do what you want," and didn't explain the underlying mathematics, the answer would be acceptable to me.
Comment: Do you seek to do either of the following?  Generate a random variate from a distribution with the same mean, median, minimum, maximum, and standard deviation, or calculate the distribution function of that distribution?  See also: https://stackoverflow.com/questions/61433438 .
Comment: @PeterO., it doesn't need to be random. For example, if I was given "Mean = 3, Min = 2, Max = 5, Population size = 3, Median = 2, St. Dev = 1.414, Example sample = 2", {2, 2, 5} would be an acceptable output. Any discrete set of elements that, if tested, would yield the same values for the provided statistical tests would suffice.
Answer: Yes, there is.  You have four data points out of N: the low, median, and high scores, as well as your own.  You have the equations for mean and stdev.  You need to generate more scores until  you are down two those two equations, and only two unknowns (missing scores).
You already have 4 scores; you need N-2 scores.  Generate some however you like, within certain limits:

Keep an eye on the over-under balance; if you get too many above (or below) the median and mean, you'll need to compensate by replacing those values.
Keep an eye on the spread: your variance is a "budget" on that spread.  If you exceed that budget, you'll have to replace a few outliers.

With a little testing and replacement, you should get to a set of N-2 values that have the same median, close to the same mean, and a variance that's somewhat below the needed figure.  At this point, you have an easy solution (although tedious) to hit both the desired variance (and stdev) and mean.
From here, it's just a matter of doing the algebra and coding the expressions to compute the two missing scores.

Do take note that your phrase "statistically identical data" is not achievable in general, without duplicating the original data set.  There are many more statistics one can apply, enough that in the extreme case, there is no substitute mathematically possible.  A set of N scores can always be uniquely specified by judicious choice of N statistics.
Comment: [1, 2, 3, 4, 5, 6] - has a median of 3.5 which is not an element of the sample.
Comment: This is false as it goes against the formal definition of the median - that half of the population/sample has value greater than the median and half - lower. If you have a median of 3 in this case then you have 2 data points that have lower values and 3- higher.
Comment: @Prune, is the "formal definition" something like "an element in a set where no more than half of the elements in the set are less than it and no more than half of the elements are greater than it"? If that's so, wouldn't 3 and 4 equally have a claim to being the median?
Comment: There are many concepts and inequivalent definitions of the median (and of other quantiles) of a dataset.  See https://stats.stackexchange.com/questions/24112 and https://stats.stackexchange.com/questions/134229 for some of our discussions about this.  In the present instance it will suffice for the OP to adopt *some* definition of the median, but the nature of the solution will not change as a result--this is just a detail.
Comment: Median does not necessarily belong to N if N has an even number of members.
Comment: @pavel Yes, it does.  By formal mathematical definition, the median is an element of the sample.
Comment: Again, the formal stats definition, not the colloquial "gotta cut it in half" kludge.  The median of your sample is 3, not 3.5
Comment: Numpy, R and Matlab all give 3.5 as median for this sample.
Comment: The formal definition from my mathematical and psychological statistics class is the largest value M for which at least 50% of the sample is <= M.  For a set with even size, *conventional* use is the mean of the middle elements.  This is a trivial point, as the approach above will work for either interpretation.  Unless stated otherwise, I assume the rigorous definition.
Comment: *The formal definition from my mathematical and psychological statistics class is the largest value M for which at **least** 50% of the sample is <= M.* -- the formal definition as i know it replaces "least" in with "most" and also adds that *"and at most 50% of the sample/population is >= M"*


Loop through an array of strings and render it as a Prop in a Component in React

Question: Questions similar to this were either irrelevant or complicated. I've referred to this SO thread but still not getting my desired output.
Desired output:
Hi there, Anna!
Hi there, Je!
Hi there, Ram!

I've tried playing around with .map() but only resulted in no output.
Here is the code I've written:
import React from 'react';
import ReactDOM from 'react-dom';

class Greeting extends React.Component {
  render() {
    return
Hi there, {this.props.firstName}!
;
  }
}

const names = ["Anna", "Je", "Ram"];
const greet_em = names.map(name => (<Greeting firstName={name}/>));

ReactDOM.render(
  {greet_em},
  document.getElementById('app')
);

Comment: I think you're trying to render multiple elements and react root expects a single child, my suggestion would be may be try to wrap the {greet_em} with React fragment i.e `<>{greet_em}`
Answer: Make sure your separate components' JSX are wrapped within a containing element.

const { Component } = React;

class Greeting extends React.Component {
  render() {
    return
Hi there, {this.props.firstName}!
;
  }
}

const names = ["Anna", "Je", "Ram"];
const greet_em = names.map(name => (<Greeting firstName={name}/>));

ReactDOM.render(

{greet_em}
,
  document.getElementById('react')
);


Combinations of Words...Power Set?

Question: I'm looking to crack a password I forgot. I know all the words possibly used in the password however some may be used or not. Example: HarryMetSally could be the password but I might use a wordlist of "Harry" "Billy" "Sally" and "Met" to combine to crack.
If I have 16 words but 14-16 were probably used, how would I code in C++ or Python to have 16 words (or 20, 25, 30 words) randomly joined together and used 1 at a time or 2-16 together not in the same order even.
Example:
Words: Harry Billy Sally Met
Combination examples:
Harry
Billy
SallyBilly
BillySally
HarryMetSally
HarrySallyMet
I've searched the internet extensively and tried Excel forums as well. Any guidance?
Comment: Certainly! https://wiki.python.org/moin/BeginnersGuide
Comment: If you use Python, you might be able to use [`itertools.combinations`](https://docs.python.org/3.4/library/itertools.html#itertools.combinations) or other functions in the same module. If you look towards the bottom of the documentation, they have an example of how you'd calculate a power set using it.
Comment: This seems like a huge number of possible permutations...
Comment: Is this an exercise or a matter of practicality? If you actually forgot your password, I doubt that your first idea is to write a python script to brute force it.
Comment: Appreciate the feedback. I have locked 35,000 professional photos in a rar file. I know the words that I used to protect it. It is very important I can run a word list against the rar file to unlock it. Thanks!
Answer: You said random...
<code>#include <iostream>
#include "stdlib.h"
#include "time.h"

#define NUM_WORDS 3
char* words[NUM_WORDS] = {
    "Foo",
    "Bar",
    "Baz"
};
typedef unsigned long long ULL;

ULL fact(ULL n, ULL lowerLimit = 1)
{
    if (n <= lowerLimit) return 1;
    return n * fact(n - 1);
}
int main()
{
    srand(time(NULL));

    // I can try single words all by myself, so start at 2 or more words
    for (int nWords = 2; nWords <= NUM_WORDS; ++nWords)
    {
        // calculate the number of possibilities
        // but since it's random, triple it for good measure
        ULL nIters = fact(NUM_WORDS, NUM_WORDS - nWords) * 3;
        for (ULL iter = 0; iter < nIters; ++iter)
        {
            for (int iterWord = 0; iterWord < nWords; ++iterWord)
            {
                int ix = rand() % NUM_WORDS;
                std::cout << words[ix];
            }
            std::cout << std::endl;
        }
    }
    return 0;
}
</code>
Comment: You're a smarty :). It runs nicely on a C++ online compiler.

Combinations of Words...Power Set?


Definir a cor de uma série em um novo gráfico na planilha

Question: No VBAProject tenho uma linha que seleciona uma determinada série do gráfico
Sub MudaCor()
ActiveChart.SeriesCollection(n).Select
End Sub

Sendo "n" o numero da serie que eu preciso selecionar.
as cores das series de um gráfico, seja de barras ou mesmo linhas, o excel determina por si.
Como mudar a cor dessa série, usando uma linha de codigo no VBA, para a cor que eu desejar??
Sub MudaCor()
    ActiveChart.SeriesCollection(n).Select
    ExemploSerie.Mudacor (???)
End Sub

Answer: Fiz um script para gerar um novo grafico, conforme os parametros de cor definidos e celulas de uma coluna, conforme linhas que contenham valor em celula.

A Função Contalinhas serve para detectar onde há celulas com valores, para
  delimitar os dados do grafico:

 Function ContaLinhas(area As Range) As Long

    Dim celula As Range, TotalLinhas As Long
    TotalLinhas = 0
    For Each celula In area
        If celula <> "" Then
            TotalLinhas = TotalLinhas + 1
        End If
    Next
    ContaLinhas = TotalLinhas
End Function

Aqui eu tenho o Range e as Cores do grafico definidas

Sub NovoGrafico()

'Os dados estão contidos na coluna "A" (apenas como exemplo)

C = ContaLinhas(Range("A:A"))

'Cria um novo grafico com os parametros a serem definidos

    ActiveSheet.ChartObjects("Superar").Activate
    ActiveChart.SeriesCollection.NewSeries
    ActiveChart.SeriesCollection(1).Values = Range(Cells(2, 2), Cells(C, 2))
    ActiveChart.SeriesCollection(1).XValues = Range(Cells(2, 1), Cells(C, 1))
    ActiveChart.SeriesCollection(1).Interior.Color = RGB(255, 255, 255)
    ActiveChart.SeriesCollection(1).Border.Color = RGB(0, 0, 0)
End Sub

Ou seja,
Tenho um script que cria um novo gráfico com as cores Branca e Preta, respectivamente, Interior e bordas.


Solving Rational Equations w/ a Trinomial

Question: $$\frac{7}{2x^2-x-1}=\frac{5}{x-1}$$
I've factored it to
$$\frac{7}{2x(x-1)(x-1)}=\frac{5}{x-1}$$
and then multiplied everything by
$$\frac{2x(x-1)(x-1)}{1}$$
to get $$7=5(2x)(x-1)$$
And this is where I'm stuck. Do I multiply the terms on the right side or subtract one to the other?
Comment: a second degree polynomial cant factor to get a $x^3$ if you multiply factors together
Comment: If you had the right factorization then what you could do is to multiply with least common divisor, then you would get an easier one.
Comment: Okay, yes, I misread the question!
Answer: You factored incorrectly.
You should have $\displaystyle \frac{7}{2x^2-x-1}=\frac{5}{x-1}$.
That would become $\displaystyle \frac{7}{(2x+1)(x-1)}=\frac{5}{x-1}$
Multiply both sides by $\displaystyle (x-1)(2x+1)$ assuming $\displaystyle x \neq 1,-\frac12$ to get $7=5(2x+1)$.
Therefore, $7=10x+5$, then $10x=2$, and so $\displaystyle \boxed{x=\frac{1}{5}}$.
Answer: moving all terms to the left and factorizing we get
$$-2\,{\frac {5\,x-1}{ \left( x-1 \right)  \left( 2\,x+1 \right) }}=0$$
from here we get the searched solution.


How can I make an array in python whose elements are 2 array

Question: I am doing a classification problem. My training set is X_train containing 60000 elements and each element has 784 features (basically the intensity of pixels of an image). I want to reshape the images in a 28 * 28 array and store them in another array. I tried but can't find a solution. How can I do that?
for x in range(60000):
    X_new=X_train[x].reshape(28,28)

len(X_new)

I expect len(X_new) be 60000 but its length is showing as 28.
Comment: I've seen this error too many times (overwriting a variable each time instead of appending to a list), but this might be the purest example. I wonder if there is a duplicate I can point people to?
Answer: Without context, both other answers might be right. However, I'm going to venture a guess that your X_train is already a numpy.array with shape (60000, 784). In this case len(X_train) will return 60000. If so, what you want to do is simply:
X_new = X_train.reshape((-1, 28, 28))

Comment: Thank you so much for such a great help.
Answer: You should assign X_train[x] instead of X_new:
for x in range(60000): X_train[x] = X_train[x].reshape(28,28)

otherwise, X_new will store only the last element of the list. You can create a new array if you do not want to spoil the old one:
X_new = [X_train[x].reshape(28,28) for x in range(60000)]

Answer: Possibly you mean to do this:
X_new = []
for x in range(60000):
    X_new.append(X_train[x].reshape(28, 28))

len(X_new)

You can also use a list comprehension
X_new = [x.reshape(28, 28) for x in X_train]


A função não adiciona á lista

Question: ESTA É A SOURCE:
#include <iostream>
#include "gestor.h"
using namespace std;

int menu()
{
int opc;

    cout << "Faca a sua escolha!" << endl;
    cout << "1-> inserir avaria!" << endl;
    cout << "2-> listar avaria!" << endl;
    cout << "0-> sair" << endl;
    cin >> opc;

    return opc;

    }
    gestor *criargestor()
    {
    gestor*g;
    g = new gestor();
   return g;

}

void destruirgestor(gestor*g)
{
delete g;
}

void main()
{
   gestor *g;
   g = criargestor();
int opcao;

do
{
    opcao = menu();

    switch (opcao)
    {
    case 1: g->addavaria();
        break;
    case 2:g->listaravarias();
        break;
    case 0:
        break;
    default:
        cout << "invalido!\n" << endl;
    }
} while (opcao!= 0);
destruirgestor(g);
}

ESTE E O HEADER FILE avaria.h
#pragma once
#include<string>
#include<iostream>
#include<locale.h>
using namespace std;
class avaria
{
int codigoavaria;
string nome;
string descricao;
public:
avaria(void);
avaria(int cod,string nm,string des);
void mostrar();
~avaria();
};

ESTE É O AVARIA.CPP
#include "avaria.h"

 avaria::avaria(void)// construtor da função vai inicializar as variáveis.
 {
cout << " passei na função= [" << __FUNCTION__ << "]" << endl;
}
avaria::avaria(int cod, string nm,string des)
{
setlocale(LC_ALL, "portuguese");
cout << " passei na função= [" << __FUNCTION__ << "]" << endl;
codigoavaria = cod;
nome =nm;
descricao = des;

}
void avaria::mostrar()
{
setlocale(LC_ALL, "portuguese");
cout << " passei na função= [" << __FUNCTION__ << "]" << endl;
cout << " codigo =" << codigoavaria << endl;
cout << "nome =" << "[" << nome << "]" << endl;
cout << "descrição" << "[" << descricao << "]" << endl;

}

avaria::~avaria()
{
setlocale(LC_ALL, "portuguese");
cout << " passei na função= [" << __FUNCTION__ << "]" << endl;
}

ESTE É O GESTOR.H
#pragma once
   #include
   #include
   #include"avaria.h"
   class gestor
   {
    list lav;
public:
gestor();
void addavaria();
void listaravarias();
~gestor();
};

ESTE É O GESTOR.CPP
#include "gestor.h"

gestor::gestor()
{

}

 void gestor::addavaria()
{
 setlocale(LC_ALL, "portuguese");

string descricao;
string nome;
int tipo;
avaria*av = NULL;

cout << "Introduza o tipo de avaria! (1) electrica (2) mecanica" <<         endl;
    cin >> tipo;
    cin.ignore();
    cout << " Introduza o nome da avaria!" << endl;
    getline(cin, nome);
    cout << "Introduza a descrição da avaria!" << endl;
    getline(cin,descricao);
    av = new avaria (tipo,nome,descricao);

}
 void gestor::listaravarias()
{
cout << "N. de Elementos da Lista = " << lav.size() << endl;
for (list<avaria*>::iterator Iter = lav.begin();
    Iter != lav.end(); Iter++)
{
    cout << "................................." << endl;
    cout << endl;
    (*Iter)->mostrar();
    cout << endl;
    cout << "..................................." << endl;
}
}

gestor::~gestor()
{
}

O que se passa é o seguinte a função addavaria() não parece estar a adiciona nenhuma avaria á lista, cada vez que compilo adiciono uma avaria e logo a seguir faço mostrar e a função diz que estão zero elementos adicionados á lista.
o programa é em c++ e está a funcionar com uma classe gestor (não tem hierarquia) que tem como função gerir todas as avarias da classe avaria.
Comment: se precisarem de algumas imagens que não estejam visiveis digam me
Comment: Não coloque imagens com código, coloque o código.
Comment: posso lhe mandar o meu programa por email?
Comment: Não, coloque o código que dê para vermos o erro e nada mais que isto. Se isto não for possível, a pergunta não pode ser feita aqui.
Comment: e bastante codigo e não consigo organizar a pergunta, com os cpps separados dos .hs
Comment: http://pt.stackoverflow.com/help/mcve
Comment: edições foram feitas ;)
Comment: Pelo que entendi voce cria o objeto avaria e não adiciona ele na lista da classe gestor. Só precisa adicionar na lista.
Comment: Como e que faço isso?
Answer: Em gestor::addavaria(), av não está sendo adicionado à lista, ou seja, tá faltando um lav.push_back(av).

A função não adiciona á lista


Listing or Working With a Range in the Shell

Question: Is there any way I can target a range of a-c* in one go?
For example, instead of doing this individually;
/home/a*
/home/b*
/home/c*

I've tried testing with ls, but not sure if it's working right.
ls /home/[a-c]*

Comment: `ls /home/[a-c]*` seems to work ok. I've added an alternate way of expanding a sequence.
Answer: ls /home/{a..c}*

(This is some extra text to meet the minimum body length.)
Answer: Alternatively, if you want a non-contiguous list:
ls /home/[aceg]*
will list /home/a*, /home/c*, /home/e*, /home/g*


jQuery UI selectable dblclick not firing in IE9 (works great in FF)

Question: I've got a small problem.  I've got a standard search screen (Perl, jQuery, css, html) when the results are returned I use jquery ui selectable and print the results as ordered list, list items.  This has been working fine where the user single clicks the desired record and presses the edit button, using the id selected, I redirect them to the "edit/view" screen.
Today I was asked to add double click functionality, meaning the user double clicks on the desired record and is taken to the "edit/view" page.  I develop in FF and our users use IE9 (UGGGGGGGG!!!!!!!!!!).  So I wrote it in FF and got it working pretty easily.  Here is my selectable section of code
<code>$(function() {
$("#selectable").selectable({
      selecting: function(event, ui){
            if( $(".ui-selected, .ui-selecting").length > 1){
                  $(ui.selecting).removeClass("ui-selecting");
            }
            if( $(".ui-selected")) {
                    $("#editbtn").prop("disabled", false);
            }
      },
      stop: function() {
                    var result = $( "#select-result" ).empty();
                    $( ".ui-selected", this ).each(function() {
                            result.html('<input type="hidden" id="clientid" name="clientid" value="'+$(this).attr("id")+'">');
                    });
            }
});
$("ol li").on("dblclick", function() {
    alert("hey man!");
    var client_id = $("#clientid").val();
    window.location = "client?client_id="+client_id+"&user_id=$user_id";
});
});
</code>
I do a few things here as I'm sure you can see... I prevent lassoing and selecting multiple records, and on select I throw the ID selected into a hidden input so I can use the id in a redirect both with jQuery and with Perl.
The new piece I've added at the bottom is the double click.  I started with $('#selectable').dblclick and it worked perfectly in FF.  Then I tested it in IE9 since that's what the users use and the double click doesn't fire at all.
I changed it to $('body').dblclick to make sure I wasn't crazy and of course the alert fired in IE9.  And, twice now, by randomly double clicking records like a crazy man I've gotten the dblclick event to fire in IE9.  It's almost like it is hidden behind the selectable event.  I messed around with distance: 1, which actually caused the doubleclick event to fire in IE9, but then it prevents me from actually selecting a record and therefore the id is undefined.
Thanks in advance for the help.  me=newbie.
Answer: Well, I did look in a lot of places before making the above post.  Laughably, one of the first posts I looked at contained the answer and I just didn't pick up on it.
I basically added:
cancel: '.ui-selected' within .selectable({
as directed here:
How to enable dblclick event on elements which was binded with JQuery UI Selectable plugin?


Pólya-Burnside Method of Enumeration with Necklace

Question: Use the Pólya-Burnside Method of Enumeration or just the Burnside theorem to find the number of different types of circular necklaces that could be made from the following beads (assuming all are used on the necklace):
1: Three black and three white beads.
2: Four black, three white, and one red.
In these problems, the necklace composition is considered equivalent to another if you can flip the necklace over or rotate it such that it matches the other.
I don't know how to do this. I understand the method of enumeration but I don't know how to apply it to here. Any help would be great, thank you in advance!
Answer:
The cycle index polynomial of $D_6$ is $\frac{1}{12}[x_1^6+3x_1^2x_2^2+4x_2^3+2x_3^2+2x_6]$. So, the number of necklaces is the coefficient of $a^3b^3$ in the expansion of

$$ \frac{1}{12}[(a+b)^6+3(a+b)^2(a^2+b^2)^2+4(a^2+b^2)^3+2(a^3+b^3)^2+(a^6+b^6)],$$
which is equal to $\displaystyle \frac{1}{12}\left[\binom{6}{3}+3\binom{2}{1}\binom{2}{1}+2\binom{2}{1}\right]=3$.

The cycle index polynomial of $D_8$ is $\frac{1}{16}[x_1^8+4x_1^2x_2^3+5x_2^4+2x_4^2+4x_8]$. So, the number of necklaces is the coefficient of $a^4b^3c$ in the expansion of

$$\frac{1}{16}\left[(a+b+c)^8+4(a+b+c)^2(a^2+b^2+c^2)^3+5(a^2+b^2+c^2)^4+2(a^4+b^4+c^4)^2+4(a^8+b^8+c^8)\right]$$
which is equal to $\displaystyle \frac{1}{16}\left[\binom{8}{4}\binom{4}{3}+4\binom{2}{1}\binom{3}{2}\right]=19$.


How do I configure subdomain url as one.mysite.com/subdomain1

Question: I am a Drupal Developer currently working on Drupal 7.15 multi domain site. In my site, I have already installed Domain module and configured the domains as:

Main domain - mysite.com (say 1st level)
Sub Domains - one.mysite.com, two.mysite.com, ... (say 2nd level)

Now I need the 3rd level Domains as:
one.mysite.com/subdomain1,
one.mysite.com/subdomain2,
one.mysite.com/subdomain3.

But my control panel only has the option of setting this as one.subdomain1.mysite.com
Can any one help on this. Either how to configure the subdomain as of my requirement or else how to re-write the url?
Thanks
Comment: http://browse-tutorials.com/tutorial/drupal-7-multi-site-localhost-xampp-or-windows-example
Answer: The Subfolders Domain module sounds like it'll handle what you're after. Additionally, you may want to read through my blog entry about serving Domain Access-controlled sites from subfolders instead of subdomains.
Answer: You can check the server side configuration.The sub folders module is for the purpose of sub directory multi sites configuration. And this will not be useful for this scenario I think.
Answer: Frankly, there are many ways to achieve this. I am just listing a few that come to my mind.

Check out the settings.php, it has some info on this. I think using that and .htaccess we can achieve this.
You can also do this by configuring the Virtualhost in a way that achieves this type of setting for you.
I also have used services like pound, using which we can direct each request based on our requirement.


Como corrigir estes estilos para contornar o erro relatado?

Question: Estou modificando inputs checkbox escondendo-os e chamando labels para receber a função de checked.
Como poderão ver no FIDDLE e também nos códigos demonstrados abaixo, ao clicar em ordem crescente, o efeito é atribuído todos os checkeds que estão em seguida do clicado.
Porém, o que pude observar enviando $_POST do formulário, é que por mais que o efeito CSS tenha sido atribuído, os inputs não se tornam checkeds, então é um erro de lógica no CSS.

Como deixar os efeitos de label independentes e remover este erro de
  lógica do código css?

.hidden { display:none }
#checkboxes input[type="checkbox"].drm ~ label {
  float: left;
  cursor: pointer;
  vertical-align: middle;
  margin: 0px 2px 0px 8px;
  width: 37px;
  line-height: 37px;
  text-align: center;
  border: 1px #898989 solid;
  background-color: #FFF;
  color: #3F3F41;
  font-size: 13px;
  text-transform: uppercase;
}

#checkboxes input[type="checkbox"].drm ~ label:hover {
  border:1px #052245 solid;
  background-color:#052245;
  color:#FFF;
}

#checkboxes input[type="checkbox"]:checked.drm ~ label {
  border:1px #052245 solid;
  background-color:#052245;
  color:#FFF;
}

  <input id="dorm1" class="hidden drm" type="checkbox" name="dorms[]" value="1">
  1
  <input id="dorm2" class="hidden drm" type="checkbox" name="dorms[]" value="2">
  2
  <input id="dorm3" class="hidden drm" type="checkbox" name="dorms[]" value="3+">
  3+

Answer: Usando radio buttons
Se quer que ao clicar no 3+ inclua todos os anteriores, o ideal não é usar checkbox, mas sim radio button, pois a semântica do checkbox é de seleção independente. A do radio button é de seleção de um valor apenas.
Neste caso você trataria no server side os valores anteriores. Note que com esta técnica, a ordem dos ítens no HTML é invertida, do 3 para o 1.

.hidden { display:none }
#checkboxes { float:left }
#checkboxes label {
  float: right;
  cursor: pointer;
  margin: 0px 2px 0px 8px;
  width: 37px;
  line-height: 37px;
  text-align: center;
  border: 1px solid #898989;
  background-color: #FFF;
  color: #3F3F41;
  font-size: 13px;
}

#checkboxes label:hover,
#checkboxes input:checked ~ label {
  border:1px solid #052245;
  background-color:#052245;
  color:#FFF;
}

  <input id="dorm3" class="hidden" type="radio" name="dorms" value="3+">
  3+
  <input id="dorm2" class="hidden" type="radio" name="dorms" value="2">
  2
  <input id="dorm1" class="hidden" type="radio" name="dorms" value="1">
  1

Checkboxes independentes
Se você quer utilizar cada checkbox independentemente, precisa mudar o seletor.

O seletor ~ pega todos os elementos seguintes.
O seletor + pega apenas o imediatamente seguinte.

Veja a diferença:

.hidden { display:none }
#checkboxes input[type="checkbox"].drm + label {
  float: left;
  cursor: pointer;
  vertical-align: middle;
  margin: 0px 2px 0px 8px;
  width: 37px;
  line-height: 37px;
  text-align: center;
  border: 1px #898989 solid;
  background-color: #FFF;
  color: #3F3F41;
  font-size: 13px;
  text-transform: uppercase;
}

#checkboxes input[type="checkbox"].drm + label:hover {
  border:1px #052245 solid;
  background-color:#052245;
  color:#FFF;
}

#checkboxes input[type="checkbox"]:checked.drm + label {
  border:1px #052245 solid;
  background-color:#052245;
  color:#FFF;
}

  <input id="dorm1" class="hidden drm" type="checkbox" name="dorms[]" value="1">
  1
  <input id="dorm2" class="hidden drm" type="checkbox" name="dorms[]" value="2">
  2
  <input id="dorm3" class="hidden drm" type="checkbox" name="dorms[]" value="3+">
  3+

Answer: Você precisa controlar isso com javascript, atualizei seu fiddler, da uma olhada.
A propriedade checked não é acessada por css, o check está indo apenas o escolhido pois o mecanismo da label checava automático.
Segue abaixo um código simples que resolve o problema.
$(document).ready(function(){

  $('.montserrat').bind('click',function(){
      var text = $(this).text();
      var triggerCascade = false;

      $.each($('input[type="checkbox"]'),function(idx,obj){

        //Tornar checked true todos após o escolhido
        if(triggerCascade){
            $(obj).attr('checked',true);
        }

        //Identifica o ponto de corte
        if($(obj).val()==text){
          triggerCascade = true;
        }
      });
  });

});

Comment: Assim que eu clico no número 1, ele continua marcando todos. Preciso que marque somente o que eu cliquei. Eu fui até o FIDDLE que me mandou e não parece estar funcionando.
Comment: Obrigado pela ajuda ... aguardo feedback do funcionamento ...
Comment: Desculpa, entendi que vc queria em cascata os checked, atualizei o fiddler, mas com a dica do Bacco, que é a correta.


Dvorak Plagiarized Beethoven?

Question: I've just analyzed the beginning and the tempo of the scherzo of Dvorak's 9th symphony.  When I did it, I've realized he had "copied" the scherzo of Beethoven's 9th!  What is going on here?
Comment: While I'm not nearly knowledgeable enough to post an answer; perhaps "plagiarism" is't the best way of thinking about it. See the Wikipedia page for [musical quotation](https://en.wikipedia.org/wiki/Musical_quotation). This was quite common in classical music and I don't think it would be considered unethical in the sense that we would think about "plagiarism" today.
Comment: Odd--I've listened to both symphony scherzos, and Dvorak's scherzo' s opening never struck me as resembling the opening of that Beethoven work. I'm willing to believe the resemblance is coincidence (or just a sign that Beethoven's works have influenced Dvorak).
Comment: They are both Scherzos.  Are you seriously suggesting that the tempo indication of "Molto vivace" on both is an indication of plagiarism?
Comment: I imagine it is purposeful. I'm not posting this as an answer because I haven't really studied the piece's history, so I am not confident in my conclusion. But I seem to recollect that Dvorak was trying to fit the music of underprivileged American groups into the great classical tradition.  If I'm right, it is probably a purposeful reference, meant to evoke Beethoven directly.
Answer: The first theme uses D A F D or ^1 ^5 ^3 ^1.
The second uses E E B B E B or ^1 ^1 ^5 ^5 ^1 ^5. (The opening phrase ends at bar 6. Bar 7 onward starts up a new phrase.)
The figures are similar - based on an octave and eighth notes, but the metrical placement is different.
The two are similar in that both outline a minor chord, at the same fast tempo. That certainly will give them a similar feel.
But in classical music this level of similarity is common.
Did the Beethoven 'inspire' the Dvorak? Seems reasonable, but I wouldn't call it plagarism. It's way, way  more import to see how the theme is developed.
Comment: I see what you mean and edited my answer. After looking at the full score I see the first phrase - the thing we are really comparing - only goes to bar 6 in Dvorak. The Beethoven phrase is obviously 8 bars in the full score. I don't know if you intentionally tried to shoehorn the Dvorak excerpt to match Beethoven, but that kind of comparison is misleading. I think this should be compared as phrase to phrase, because phrases are the _meaningful musical gesture_.
Comment: Nice answer.  However, the second is E-B-E-B-G-E, so it is 1-5-1-5-3-1.
Comment: Actually, the intro phrase extends towards the end of my attachment.  I've connected each boxed parts with a line, based on their congruence.  Plus, they're both scherzos in Molto Vivace!
Answer: I dispute the idea that these passages are even similar, and from the perspective of 21st century copyright law in the US, this would probably not constitute "plagiarism" at all. In order to qualify as copyright infringement, these two passages would need to be so similar that a person without musical training would recognize them as the same.
These two passages aren't really that similar. It's true that the notes in the first four bars are the same (if transposed to the same key), but those notes are the tonic and dominant of the key - the most commonly used notes in Western music. The rest of the passage is wholly different, except that both end on the tonic (again, extremely common in Western music).
Lastly, the rhythms are completely different. Beethoven's rhythm is based off of a dotted quarter note, while Dvorak's is two eighth notes. Harmonically, Beethoven returns to the tonic in measure 6, while Dvorak delays it to measure 8.
It's certainly possible that Dvorak was inspired by this Beethoven passage, but it does not even come close to the standard of plagiarism.
Of course, US copyright law would have no influence over these pieces written in Europe, but this method of analysis is what's used to determine copyright infringement. If you're interested in learning about US copyright law, I recommend this website from the George Washington Law School: https://blogs.law.gwu.edu/mcir/
- It has information nearly all federal musical copyright cases in US history.
Comment: "US copyright law would have no influence over these pieces written in Europe": yes it would.  Pieces written in Europe are protected against infringement in the US by US law, including against infringement by other pieces written in Europe.  The real reason US copyright law isn't relevant to these pieces is that they were written before US copyright protection was extended to musical compositions.
Answer: My memory is faulty to extreme,  but...
A mid-20th century Eastern Euro or Russian composer (Prokofiev maybe) was disgusted enough with Shostakovitch's Bolero in his (Dmitri) 7th symphony that he (the disgusted composer) deliberately satirized the Bolero theme in a symphony of his own.
However, so far as NewWorld Symphony vs. Beethoven 9th,  I am in the camp that says it's a weak equivalence in the first place and probably just a "likeable" rhythm for a Scherzo.  I don't think the two pieces correlate.
Comment: Also, the third movement of Berio's Sinfonia is basically the scherzo from Mahler Symphony No. 2 with a bunch of other musical quotations laid on top of it!

Dvorak Plagiarized Beethoven?


Ajax pager failure in view after modifying view on hook_views_query_alter

Question: The requirement is for different pages on the website to show different Twitter feeds according to the current page. There is a context (triggered according to the path) that inserts a view block into the footer. A custom module kicks in when the query for the view block is about to be executed. The module does some simple processing to determine what Twitter feed(s) are required to be displayed on the current page.
So, the custom module contains:
<code>/**
 * Implementation of hook_views_query_alter
 */
function twitter_feed_selector_views_query_alter(&$view, &$query) {

  if ($view->name == 'tweets') {

    // Some processing...

    $feed = _twitter_feed_lookup($matching_path);
    $view->query->where[1]['conditions'][0]['value'] = $feed;

  }
}
</code>
However, the view block has a lite pager and Ajax enabled. And when the user clicks on the pager links to see the next/previous page of tweets, no tweets are coming back from the view.
I can't find how to get around this. If I turn off Ajax on the view, all is well, but the whole page is reloaded each time the pager is clicked -- which is way too clunky.
Can anyone suggest a means to make my amendments to the view query work nicely also with the Ajaxed results from the pager?
Answer: When the view query is being called from inside the pager, the requesting URL is different. It becomes: '/views/ajax'. This URL does not match any that had been specified in my context, so no results were returned.
I solved the problem by checking if the query view is being called within the pager -- i.e. if $_SERVER["REQUEST_URI"] == '/views/ajax'. If so, then I extract the correct path instead from $_SERVER["HTTP_REFERER"]. If not, then it's okay to accept the path from $_SERVER["REQUEST_URI"].


Derivation of Hard Thresholding Operator (Least Squares with Pseudo $ {L}_{0} $ Norm)

Question: The problem is given by:
\begin{equation}
\widetilde{f} = \arg \min_{f} \frac{1}{2} {\left\| f - x \right\|}_{2}^{2} + \lambda {\left\| f \right\|}_{0}.
\end{equation}
How do I find the closed form solution for hard thresholding operator?
I have intuition that $f_i=0$ or $f_i=x_i$ for minimum but can anyone explain the cases and conditions in detail?
Comment: You should note that, despite the "convex-optimization" tag, _this is not convex_. The improper use of the $\|\cdot\|_0$ notation often leads people to believe that it is. But the cardinality function is not a norm, and it is not convex, and writing it that way is an abuse of notation.
Comment: By inspection: $$f_i=\begin{cases} 0 & \tfrac{1}{2}|x_i|_2^2 \leq \lambda \\ x_i & \text{otherwise}\end{cases}$$
Comment: Yes I know it is not convex I just tagged to reach out to large community
Comment: You should not do that. Tag for accuracy in categorization.
Comment: Can you please explain the conditions on $x_i$ ? How do we arrive there
Comment: I just noticed that if $f_i\neq 0$, then the best you can do is to set $f_i=x_i$, in which case that component's contribution to the objective is $\lambda$.
Comment: Related to https://math.stackexchange.com/questions/4429642.
Answer: The problem can be written as:
$$ \arg \min_{f} \frac{1}{2} {\left\| f - x \right\|}_{2}^{2} + \lambda {\left\| f \right\|}_{0} = \arg \min_{f} \frac{1}{2} \sum_{i = 1}^{n} \left( {f}_{i} - {x}_{i} \right)^{2} + \lambda \mathbb{1}_{ \left\{ {f}_{i} \neq 0 \right\} } $$
Due to its component wise property one could basically solve the Scalar Problem:
$$ \arg \min_{ {f}_{i} } \frac{1}{2} \left( {f}_{i} - {x}_{i} \right)^{2} + \lambda \mathbb{1}_{ \left\{ {f}_{i} \neq 0 \right\} } $$
Now, in case $ {f}_{i} = 0 $ the cost is $ \frac{1}{2} {x}_{i}^{2} $. Hence as long $ \frac{1}{2} {x}_{i}^{2} \leq \lambda $ it is worth to set $ {f}_{i} = 0 $.
In the other case ($ {f}_{i} \neq 0 $) the minimum value of the cost function is $ \lambda $ where $ {f}_{i} = {x}_{i} $.
Hence:
$$ \tilde{f}_{i} = \begin{cases}
0 & \text{ if } \frac{1}{2} {x}_{i}^{2} \leq \lambda \\
{x}_{i} & \text{ if } \frac{1}{2} {x}_{i}^{2} > \lambda
\end{cases} $$
Which is the Hard Threshold operator.


Conjugate priors for dynamic model $x_{t+1}=Ax_{t}+\eta_t$

Question: What conjugate priors do we have for the model(multivariate) $x_{t+1}=Ax_{t}+\eta_t$, where $\eta_t\overset{iid}\sim N(0,\Sigma)$?
I was thinking of using $\tilde{x}=Diag[x_1,...,x_{n-1}]$, $\tilde{y}=Diag[x_2,...,x_{n}]$ and simply use the usual conjugate priors for the Bayesian multivariate linear regression.
Will there be any problem, if I do this?
Comment: One issue to watch out for is making sure you're not placing a bunch of the prior mass on "explosive" regimes, e.g., where coefficients on autoregressive terms are >1.
Answer: Bottom Line
You're right. You can rewrite the model as a multivariate linear regression and simply use the conjugate prior for that model.
Some Detail
The model you wrote down is a vector autoregression. You wrote it with a single lag and no intercept term, but the general model with $p$ lags is
$$\underbrace{\mathbf{y}_t}_{n\times 1}=\underbrace{\mathbf{b}_0}_{n\times 1}+\underbrace{\mathbf{B}_1}_{n\times n}\mathbf{y}_{t-1}+...+\mathbf{B}_p\mathbf{y}_{t-p}+\underbrace{\mathbf{u}_t}_{n\times 1},\quad\mathbf{u}_t\sim N(\mathbf{0},\,\underbrace{\boldsymbol{\Sigma}}_{n\times n}).$$
If for each $t$ you define the vector
$$\underbrace{\mathbf{x}_t}_{(np+1)\times 1} = [\mathbf{y}'_{t-1} \quad \mathbf{y}'_{t-2} \quad...\quad \mathbf{y}'_{t-p}\quad 1]'$$
and the matrix
$$\underbrace{\mathbf{B}}_{(np+1)\times n}=\begin{bmatrix}\mathbf{B}'_1\\\mathbf{B}'_2\\\vdots\\\mathbf{B}'_p\\\mathbf{b}'_0\end{bmatrix}$$
then you can rewrite the VAR model as a multivariate regression:
$$\mathbf{y}'_t=\mathbf{x}'_t\mathbf{B}+\mathbf{u}'_t,\quad\mathbf{u}_t\sim N(\mathbf{0},\,\boldsymbol{\Sigma}).$$
The conjugate prior for $\mathbf{B}$ and $\mathbf{\Sigma}$ is the Matrix Normal Inverse Wishart Distribution. That is
$$\begin{align*}\mathbf{\Sigma}&\sim IW(d_0,\, \mathbf{\Psi}_0) \\
\mathbf{B}\,|\,\mathbf{\Sigma}&\sim MN(\bar{\mathbf{B}}_0,\, \mathbf{\Omega}^{-1}_0,\,\mathbf{\Sigma}).\end{align*}$$
$d_0$, $\mathbf{\Psi}_0$, $\bar{\mathbf{B}}_0$, and $\mathbf{\Omega}^{-1}_0$ are prior hyperparameters that you set as the researcher.