importXML in google spreadsheet two separated tags

Question: one more problem. I have following structure of XML:
<player>
 <id>12</id>
 <name>pl_name</name>
 <experience>
  <points>147</points>
  <level>10</level>
 </experience>
 <skills>
  <fight>0.00</fight>
  <defend>3.45</defend>
 </skills>
</player>

i want to be written just two tags. Lets say fight skill and level in my gdoc. so something like this:
=ImportXML("http://api.mysite.net/xml/user/id/"&C5; "/*(what here?)")

If it's possible :) thank you
Answer: The "query" argument of the ImportXML is an XPATH query. To get the experience level of the player you have several routes.  The easiest to understand is
=ImportXML("http://api.mysite.net/xml/user/id/"&C5; "/player/experience/level")

Another alternative, taking into account that the level element has a unique name, is this:
=ImportXML("http://api.mysite.net/xml/user/id/"&C5; "//level")

Both of those formulas would return 10 as the answer based on the XML that you gave.


How to use the same JQuery effect for different divs with same class

Question: I'm not really into using javascript and jQuery so please add detailed answers.
I need to add a jQuery effect to different divs with the same class, so that when I click on a div 1 with class item, another div info will appear in a specific container.
Also, if I click on div 2 with the same class item, another div pics will appear in the same container as info while info will disappear.
I was going to use this:
$(document).ready(function(){
    $("#box1").click(function(){
        $("#box1").fadeOut(250);
    });
    $("#box1").click(function(){
        $("#box2").fadeIn(500);
    });
});

But this is not valid for using about 10 divs and another 10 displaying and hiding divs.
I would use many lines of code and I am not sure that it would work.
Comment: Show us an example of your html.  We can get you pointed in the right direction much easier, then.
Comment: Store the element in a variable to save a lot of time.
Comment: You have to call and understand Jquery selectors.
Comment: please post you html code so we can understand better.
Answer: You could use the selector $(".item") to get all the divs you're interested in.
Class selector sounds like what you need: http://api.jquery.com/class-selector/
You can differentiate the ids once you're inside the click call and take a different action. but the class selector will let you use the click event handler on all of the divs you're interested in.
sample code below
$(document).ready(function(){
    $(".item").click(function(e){
        // output the id of the clicked item
        console.log($(e.target).attr("id"));

        if($(e.target).attr("id")=="box1"){
            //do something for if the clicked item is box1.
            $("#box1").fadeOut(250);
            $("#box2").fadeIn(500);
        }

    });
});

Answer: Without your html, it's hard to say exactly.  But, here's a starter point.
Your existing jQuery is like so, which is grabbing every div by ID.
$(document).ready(function(){
    $("#box1").click(function(){
        $("#box1").fadeOut(250);
    });
    $("#box1").click(function(){
        $("#box2").fadeIn(500);
    });
});

An improvement would be to use a class rather than an ID, and you could do something like so.
NOTE: The below assumes you assign either a different class, or an additional class of itempic to the div(s) you want to trigger the pics to be displayed:
$(document).ready(function(){
    $(".item").click(function(){
        $(".info").fadeOut(250);
    });
    $(".itempic").click(function(){
        $(".pics").fadeIn(500);
    });
});

If you have multiple divs that are going to have this same functionality (for example, you've got a bunch of products, each with an info box and a pic box), then you'll need to do something with "containing" the selectors to the given items.  With some example HTML, I could provide an answer that takes that into account.
Answer: Structure you html similar to this

info contents

pic contents

your contents

your contents

..etc.

and use
$(function(){
    $('#container').children().hide(); // initial hiding

    $('.item').click(function(){
        var relatedId = $(this).data('related');
        $(relatedId).show().siblings().hide();
    });
});

Demo at http://jsfiddle.net/gaby/mTSZv/
Comment: Your solution seems to be the best but It didn't work for me !!
I did exactly what you have done and it didn't work !! Note: I've put the text in the divs with class "item" inside an  tag and arranged the "item" divs in a "ul" list..
Answer: When selecting with jQuery you need to use #id_name for IDs and .class_name for classes. When selecting div, tr, td, ... you need no special symbol before the name. So:
$('#id_name').click(); // click on every item of the ID 'id_name'
$('.class_name').hide(); // make all items invisible that have class 'class_name'
$('tr').addClass('class_name'); // adds the class 'class_name' to all tr items

IDs are unique. Classes can appear more than once.
Just read the examples on jQuery API
In order to get started with JS jQuery is very good. Very fast to do, but don't forget jQuery is a library that has to be loaded making these short commands possible. Pure javascript will be faster.
Don't forget, you can combine JS and jQuery, as jQuery is JS. Switching to pure JS will also make you see what your scripts exactly do.


facing issue while displaying various views in same page using angular 2+

Question: here i am trying to display the 3 different views in the same page buy button press but here i unable to proceed for that if press 2nd view and i am getting the 3rd view also
below is my code:

This is page 1

        <button class="btn btn-primary" (click)="testOne()">Page 1
         </button>

         <button (click)="page3()" >click here for page 3</button>

 this is page 2

        <button class="btn btn-primary" (click)="back()">Back to page1</button>

Page 3

 showData = true;

  testOne(){
    this.showData = false;
  }

  back(){
    this.showData = true;
  }

  page3(){
    this.showData = false;
  }

stackblitz url  :   https://stackblitz.com/edit/angular-vyw1cs
Comment: Yes as per your code it will display 2 and 3 at once. You can use three different parameter to show and hide views.
Comment: could u modify the stack where it should be done
Answer: you have to do like below:
link is here: https://stackblitz.com/edit/angular-wphb4k
Answer: One method is to set your *ngIf to evaluate if it's on a page number, then act accordingly:
html

This is page 1

        <button class="btn btn-primary" (click)="showData = 2">Page 2
         </button>
         <button (click)="showData = 3" >page 3</button>

 this is page 2

        <button class="btn btn-primary" (click)="showData = 1">Page 1
         </button>
         <button (click)="showData = 3" >page 3</button>

Page 3

        <button class="btn btn-primary" (click)="showData = 1">Page 1
         </button>
         <button (click)="showData = 2" >page 2</button>

component.ts
showData = 1
stackblitz example
https://stackblitz.com/edit/angular-9scudq
Comment: i am already using a button event to display to fire another event and here now what happens is now i have to use 2 button events


Plotting summary statistics with mean, sd, min and max?

Question: I am from an economics background and usually in the discipline the summary statistics of the variables are reported in a table. However, I wish to plot them.
I could modify a box plot to allow it to display the mean, standard deviation, minimum and maximum but I don't wish to do so as box plots are traditionally used to display medians and Q1 and Q3.
All of my variables have different scales. It would be great if somebody could suggest a meaningful way by which I could plot these summary statistics. I can work with R or Stata.
Comment: Welcome to the list. If you are asking about `R` commands then this question is off-topic here. But it seems you are asking primarily about what a good plot would look like and secondarily about how to create it. If so, I suggest deleting "with R" from your title and maybe stating, in the body, that you have `R` available.
Answer: There is a reason why Tukey's boxplot is universal, it can be applied to data derived from different distributions, from Gaussian to Poisson, etc. Median, MAD (median absolute deviation) or IQR (interquartile range) are more robust measures when data deviates from normality. However, mean and SD are more prone to outliers, and they should be interpreted with respect to the underlying distribution. The solution below is more suitable for normal or log-normal data. You may browse through a selection of robust measures here, and explore the WRS R package here.
# simulating dataset
set.seed(12)
d1 <- rnorm(100, sd=30)
d2 <- rnorm(100, sd=10)
d <- data.frame(value=c(d1,d2), condition=rep(c("A","B"),each=100))

# function to produce summary statistics (mean and +/- sd), as required for ggplot2
data_summary <- function(x) {
   mu <- mean(x)
   sigma1 <- mu-sd(x)
   sigma2 <- mu+sd(x)
   return(c(y=mu,ymin=sigma1,ymax=sigma2))
}

# require(ggplot2)
ggplot(data=d, aes(x=condition, y=value, fill=condition)) +
geom_crossbar(stat="summary", fun.y=data_summary, fun.ymax=max, fun.ymin=min)

Additionally by adding + geom_jitter() or + geom_point() to the code above you can simultaneously visualise the raw data values.

Thanks to @Roland for pointing out the violin plot. It has an advantage in visualising probability density at the same time as summary statistic:
# require(ggplot2)
ggplot(data=d, aes(x=condition, y=value, fill=condition)) +
geom_violin() + stat_summary(fun.data=data_summary)

Both examples are shown below.
Comment: I'd prefer a violin plot over this.
Comment: Depending on the purpose of the analysis, mean and standard deviation is exactly what you need. I don't understand however the inconsistancy in R's summary.data.frame. It shows means but no sds. I can't think of many situations where means are useful but standard deviations misleading.
Comment: @TWL: The topic is much too broad to discuss here. But take for instance economic evaluations of drugs: For the patient, maybe it's important to know median treatment duration, while for the health insurance company it's the mean treatment duration because they need to pay it for each patient. A curious fact: In the case of the exponential distribution, mean +/- 1 standard deviation covers 68% of all mass, mean +/- 2 sds covers about 95% of all mass. As for the normal. (But it's mere chance ;))
Comment: Thanks all, I like the proposed violin plots so will go ahead with that choice :-)
Comment: Indeed, sometimes you need to see the mean and the SD so that you judge whether they are useful....
Comment: @MichaelMayer, regarding the summary.data.frame, I am not sure why sd is not reported. My concern about plotting mean +/- sd is that it indicates a symmetric distribution of values around mean. This is not true for some skewed distributions, in which case the position of the median with respect to the IQR would be more valuable. Hence, the summary statistic should be primarily chosen based on the underlying distribution.
Comment: @MichaelMayer, many thanks for this example. It illustrates the difference nicely.
Comment: @Ridhima, I have noticed that you have unchecked this answer after a while, could you let me know the reason? I'd greatly appreciate your feedback.
Comment: God knows how that happened, sorry about this :-)
Answer: There are myriad possibilities.
One option I have seen used which avoids confusion with boxplots (assuming you have medians or original data available) is to plot a boxplot and add a symbol that marks the mean (hopefully with a legend to make this explicit). This version of the boxplot that adds a marker for the mean is mentioned, for example in Frigge et al (1989) [1] :

The left plot shows a + symbol as a mean marker and the right plot uses a triangle at the edge, adapting the mean marker from Doane & Tracy's beam-and-fulcrum plot [2].
See also this SO post and this one
If you don't have (or really don't want to show) the median a new plot will be needed and then it would be good for it to be visually distinct from a boxplot.
Perhaps something like this:

... which plots the minimum, maximum, mean and mean $\pm$ sd for each sample using different symbols and then draws a rectangle, or perhaps better, something like this:

... which plots the minimum, maximum, mean and mean $\pm$ sd for each sample using different symbols and then draws a line (in fact at present that's actually a rectangle as before, but drawn narrow; it should be changed to drawing a line)
If your numbers are on very different scales, but are all positive, you might consider working with logs, or you might do small multiples with different (but clearly marked) scales
Code ( presently not particularly 'nice' code, but at the moment this is just exploring ideas, it's not a tutorial on writing good R code):
fivenum.ms=function(x) {r=range(x);m=mean(x);s=sd(x);c(r[1],m-s,m,m+s,r[2])}
eps=.015

plot(factor(c(1,2)),range(c(A,B)),type="n",border=0)
points((rep(c(1,2),each=5)),c(fivenum.ms(A),fivenum.ms(B)),col=rep(c(2,4),each=5),pch=rep(c(1,16,9,16,1),2),ylim=c(range(A,B)),cex=1.2,lwd=2,xlim=c(0.5,2.5),ylab="",xlab="")
rect(1-1.2*eps,fivenum.ms(A)[2],1+1.4*eps,fivenum.ms(A)[4],lwd=2,col=2,den=0)
rect(2-1.2*eps,fivenum.ms(B)[2],2+1.4*eps,fivenum.ms(B)[4],lwd=2,col=4,den=0)

plot(factor(c(1,2)),range(c(A,B)),type="n",border=0)
points((rep(c(1,2),each=5)),c(fivenum.ms(A),fivenum.ms(B)),col=rep(c(2,4),each=5),pch=rep(c(1,16,9,16,1),2),ylim=c(range(A,B)),cex=1.2,lwd=2,xlim=c(0.5,2.5),ylab="",xlab="")
rect(1-eps/9,fivenum.ms(A)[2],1+eps/3,fivenum.ms(A)[4],lwd=2,col=2,den=0)
rect(2-eps/9,fivenum.ms(B)[2],2+eps/3,fivenum.ms(B)[4],lwd=2,col=4,den=0)

[1] Frigge, M., D. C. Hoaglin, and B. Iglewicz (1989),
"Some implementations of the box plot."
American Statistician, 43 (Feb): 50-54.
[2] Doane D.P. and R.L. Tracy (2000),
"Using Beam and Fulcrum Displays to Explore Data"
American Statistician, 54(4):289–290, November


Exit and hitting times for the Bessel process $\textrm{d}X_t=\frac{n-1}2\frac{\textrm{d}t}{X_t}+\textrm{d}B_t$

Question: I am trying to analyse the exit time $T_1:=\inf\{t:X_t\notin[\alpha,2]\}$ and hitting time $T_2:=\inf\{t:X_t=0\}$, where $\alpha<1$ is a constant, and $X_t$ follows the Bessel process defined by the SDE
$$\textrm{d}X_t=\frac{n-1}2\frac{\textrm{d}t}{X_t}+\textrm{d}B_t,$$
with $n\neq0$, $X_0=1$ a.s. and $X_t$ is defined until it hits zero or infinity. I want to find $\mathbb{P}(X_{T_1}=\alpha)$ and $\mathbb{P}(X_{T_2}=0)$.
Here's what I've done so far:
a) I am told to show that $\frac1{X_t^{n-2}}$ is a local martingale. By Ito's formula, I have
$$\textrm{d}\left(\frac1{X_t^{n-2}}\right)=-\frac{n-2}{X_t^{n-1}}\textrm{d}X_t+\frac{(n-1)(n-2)}{2X_t^n}\textrm{d}X_t^2.$$
Since $\textrm{d}X_t^2=\textrm{d}B_t^2=\textrm{d}t$, therefore
$$\textrm{d}\left(\frac1{X_t^{n-2}}\right)=-\frac{n-2}{X_t^{n-1}}\left(\frac{n-1}2\frac{\textrm{d}t}{X_t}+\textrm{d}B_t\right)+\frac{(n-1)(n-2)}{2X_t^n}\textrm{d}t=-\frac{n-2}{X_t^{n-1}}\textrm{d}B_t.$$
Since the drift term is zero, therefore $\frac1{X_t^{n-2}}$ is a local martingale.
b) By the optional stopping theorem, $\mathbb{E}(X_{T_1})=\mathbb{E}(X_0)=1$ a.s. Since $\mathbb{P}(X_{T_1}=\alpha)+\mathbb{P}(X_{T_1}=2)=1$ and $\alpha\mathbb{P}(X_{T_1}=\alpha)+2\mathbb{P}(X_{T_1}=2)=1$, of which I can rearrange to get $\mathbb{P}(X_T=\alpha)=\frac1{2-\alpha}$.
My issues now:
a) For the optional stopping theorem, I have implicitly assumed $X_t$ is a martingale and that $T_1$ is a stopping time with bounded expectation. For the latter I have seen many of those proofs on stackexchange, so my concern lies with the former.  I know that bounded local martingales are martingales, but $\frac1{X_t^{n-2}}$ is not bounded and in integrating $\textrm{d}\left(\frac1{X_t^{n-2}}\right)$ I get $\frac1{X_t^{n-2}}=1-(n-2)\int_0^t\frac{\textrm{d}B_s}{X_s^{n-1}}$, which is not very informative (to me).
b) What are the usual steps in finding $\mathbb{P}(X_{T_2}=0)$? Is it a Borel-Cantelli argument? I have seen some for BMs, but I am unclear if they extend to $X_t$.
Answer: (a) Since we stopped this local martingale by $T_1$, it is a bounded martingale.
(b) As you define $T_2$ as the hitting time of $0$. The real question to ask here is whether $\mathbb{P}(T_2 < \infty)$. This is related with recurrence and transience of the process. And in this could be done by, similarly in this question, replacing $T_1 :=\inf\{t:X_t\notin[\alpha,R]\}$ and let $\alpha \to 0$ and $R \to \infty$.
And here is a probably easier way for this problem: note that the Bessel process is the Euclidean norm from $n$ dimensional Brownian motion $B_t$. The stopping time $T_1$ is the same as the first time that $B_t$ hits sphere with radius $\alpha$ or $2$. And the corresponding probability could be computed by optional stopping.


Help With Audit log Setup

Question: I'm setting up an audit log for a large network of Drupal 7 sites with dozens of editors and 5 developers.
These events are already covered:
Content Create, Content Update, Content Delete, User Login, User Logout, User Create, User Update (hook_user_update).
But I'm having a hard time logging:

Change in permissions
Change in settings

Any ideas how to go about logging that to watchdog?
Answer: Both of these are forms, so you can do something with a hook_form_alter.  The easiest thing to do is do a View Source, find the form, and look at the ID on the <form> element.
The permissions form is user_admin_permissions.  My suggestion would be to alter the form to add a new submit handler, eg
function mymodule_form_user_admin_permissions_alter(&$form, &$form_state, $form_id) {
  $form["#submit][] = 'mymodule_log_permission_change';
}

The settings changes are going to be tricky, as they are spread across many, many forms.  The idea is the same, you just need to figure out whether you are on a setting for or not.  You could alter all of the important setting forms, or you could try using the base hook_form_alter() and check the $form_id.  You could also try checking the URL from withing the submit handler, as many of the settings live under /admin.
Comment: this could be of help : http://drupal.org/project/macro
Comment: and this is a quick thing to see which form you are on : https://github.com/mojzis/fapidev

Help With Audit log Setup


Compare two data frames to return True or False

Question: I need to create function which will return True or False, when value from first data frame is equal to value from second data frame.
df1 (Look up dataframe)
  root
 |-- Customer_ID: string (nullable = true)
 |-- Customer_Name: string (nullable = true)

df2 (in coming data frame)
 root
 |-- CustomerID: string (nullable = true)
 |-- CustomerName: string (nullable = true)
 |-- Address: string (nullable = true)
 |-- ZipCode: double (nullable = true)
 |-- State: string (nullable = true)

df1.id [123, 234, 345, 456, 567]
df2.id [123, 567]

def fn_new_function(df1, df2):
   is_same = df2.join(df1,df2('CustomerID') == df1('Customer_ID'), how='inner') \
            .where(df2['CustomerName'] == df1['Customer_Name'])\
            .count() == df2.count()

   if is_same.count() > 0:
      return True
   else:
      return False

Following error is ....
Traceback (most recent call last):
  File "/---/process_files.py", line 234, in <module>
    main()
  File "/---/process_files.py", line 456, in fn_new_function
    is_same = df2.join(df1,df2('id')!=df1('c_id'), how='inner') \
TypeError: 'DataFrame' object is not callable

Comment: What is your desired output? What are you trying to do? Seems like using a `join` would be appropriate here.
Answer: If your data frames have the same schema, you can substract and check that the result is empty:
is_same = df1.subtract(df2).count() == 0

If you just want to check that all id fields from both data frames match (different schema), you can just compare DFs of ID fields:
is_same = df1.select('id').subtract(df2.select('id')).count() == 0

Note that this doesn't take order into account.
To verify that all records in df2 match the name defined in df1, then you can use a join and a filter:
is_same = df2.join(df1, on='id', how='inner')\
             .where(df1['CustomerName'] == df2['CustomerName'])\
             .count() == df2.count()

This version does an inner join and filters out anything that does not have a matching name in the 2 data frames. The assumption is that the resulting count would be the same as total records in df2 if all names match.
Comment: I have added schema for both data frames in my question.
Comment: And you're checking all record in `df2`? (if lookup name of all customers in df2 match, then return true)?
Comment: Yes df2 is in coming record, I will check all records df1 which is kind of look up(view) and when I find first occurrence in df1, function should return True, when no record found in df1, return False.
Comment: thanks for your time and patience, I modify my function I am getting error message... not sure what I am doing wrong.
Comment: @SM `is_same` is a boolean. The function should just return it, not call `.count` on it
Answer: def fn_new_function(df1, df2):

   df1.show()
   df2.show()

   is_same = df1.join(df2,df1('Customer_ID') == df2('CustomerID'), how='inner') \
            .where(df1['Customer_Name'] == df2['CustomerName'])

   if is_same.count() > 0:
      return True
   else:
      return False


Considering $\epsilon$ intuitively in limit proof

Question: I'm having rather difficult time in trying to use $\epsilon$ argument appropriately.
For example here is my simple $\epsilon$ proof in one question. The question is as follow: Prove if $s_n \geq 0$ for $n \geq k$ and $\lim_{n \to \infty} s_n = s$ exist, then $s \geq 0$.
My try:
We know $s_n \geq 0$ and according to the limit definition, for each $\epsilon >0$ there exist $n$ such that $| s_n - s | < \epsilon$ for $n \geq N$. We consider the case where $s_n - s > 0$, thus $s > s_n - \epsilon$. But we can find any $\epsilon$ and $n$ such that $s_n - \epsilon \geq 0$. Thus $s > s_n - \epsilon \geq 0$. For the second case, if $s_n - s < 0$ and $s_n \geq 0$ then $s \geq 0$.
Is this the right way to use $\epsilon$, that is, treating it as arbitrary positive number that can be chosen so that we can have the desired inequality, as long as that inequality is derived from limit definition?
Answer: If we use the $\epsilon-N$ definition, because $\lim_n s_n=s$, so for any $\epsilon >0$, there  exists $N\in\mathbb{N}$ such that for all $n\geq N$, we have $|s_n-s|<\epsilon$, so $s>s_n-\epsilon \geq -\epsilon$.
Notice that $s>-\epsilon$ for any $\epsilon >0$, so we must have $s\geq 0$.
Comment: No, you need not to consider whether $s_n$ is bigger than $s$ or not. Form $|s_n-s|<\epsilon$, we can get $s_n-\epsilon s_n-\epsilon$ is what we want because the condition is $s_n\geq 0$, they have the same direction of inequlity.
Comment: Do we need to consider the case where $s_n - s < 0$ for the absolute value inequality in the proof?
Answer: You cannot find $n$ such that $s_n - \epsilon \geq 0$. Not if $s_n = 0$.
What you need to use is that if $s < 0$ then there is a large gap between $s$ and any of the $s_n$. Suppose $s = -\epsilon$. Then for no $n$ do we have $|s_n - s| < \epsilon/2$.
Comment: Why it is so? Is it because $s_n < -\epsilon / 2$? (Contradicting the assumption) Also why do we need a factor of a half there?
Comment: @vonTeslacx, $|s_n-s| = s_n+\epsilon \geq \epsilon$. We don't really need a factor of half. It's only there to emphasize that *some* small number fits in the gap.
Comment: Ok so intuitively the assumption fails because of the existence of a gap between the final limit and the term that cannot be reduced by adjusting $s_n$?
Comment: @vonTeslacx, right.
Answer: I'm not sure if this is what you would like to see but I think I would rather prove this by contradiction.
Suppose $s < 0$ and that $|s| > \varepsilon$ for some $\varepsilon > 0$. Thus there exists an $N \in \mathbb{N}$ such that for all $n \geq \mbox{max}(N,k)$, $|s - s_n| < \varepsilon$. Therefore $s_n < 0$ for all $n \geq N$. A contradiction.


Writing a script to find what computer a user is logged into

Question: So I want to specify a username and return the computer name. When I run this, it tells me that my $computers obj is null. Why would
$computers = Get-ADComputer | where {$_.accountdisabled -eq $false}
return null?
My script so far looks like this:
Function Get-Username{
$Global:Username = read-Host "Enter a username"
if ($Username -eq $null){
    Write-Host "Username can't be blank. Enter username"
    Get-Username
}
$UserCheck = Get-ADUser -Filter 'Name -like $Username' | FT Name, SamAccountName -A
if($UserCheck -eq $null){
    Write-Host "Invalid username, enter username"
    Get-Username
}
}

Get-username

$computers = Get-ADComputer | where {$_.accountdisabled -eq $false}
foreach($comp in $computers){
    $Computer = $comp.Name
    $ping = New-Object System.Net.NetworkInformation.Ping
    $Reply = $null
    $Reply = $ping.send($Computer)
    if($Reply.status -like 'Success'){
        $proc = gwmi win32_process -computer $Computer -Filter "Name = 'explorer.exe'"
        ForEach($p in $proc){
            $temp = ($p.GetOwner()).User
            if($temp -eq $Username){
                Write-Host "$Username is logged on $Computer"
}}}}

Answer: First thing I see is when i run 'Get-ADComputer' it wants a filter.
After the filter is applied i still dont see "accountdisabled" property for Get-AdComputer, I think you mean "Enabled"
$computers = Get-ADComputer -Filter * | where {$_.Enabled -eq $false}

You might want to change that filter before running.
Edit: sorry; to find the properties run Get-ADComputer | Get-Member this will show you a list of all properties.This is my #1 used cmdlet.


Organizing data into a different format in Excel

Question: I have some data that I downloaded and I need to organize it differently because there are hundreds of items already and there will probably be thousands before it's done. The simplified format when I copy/paste into excel is as follows: (Each new line is a new cell, including the space. Everything is in one column.)
Permit #:
1
Permit Type:
Solar
Status:
Completed

Permit #:
5
Permit Type:
Roof
Status:
Expired

What I need is to reorganize that into rows and columns with the Permit #, Permit Type, and Status at the top and the corresponding value below. Then I'll be able to look for duplicate and further organize it as needed. So an example with the above sample would look like this:
Permit #:   Permit Type:   Status:
1           Solar          Completed
5           Roof           Expired

So, I need a way assign specific cells to be referenced in that way and the reference has to skip a number of rows each time.
The best I've gotten is using OFFSET but when you drag that function down, the reference cell only goes from A2 to A3 etc. Where I need the reference cell to also move down the list by the same as the offset. In my actual data I need it to OFFSET +16 rows. So I need the reference argument in OFFSET to be dynamic in that way.
What would work is if I write the function =OFFSET(A2, 16,0) and drag it down, the reference argument would change to =OFFSET(A18, 16, 0).
Is that possible? Or if someone has a better way to accomplish the same thing, I'm all ears.
Comment: What about the text to columns tool? then you could re-join what you need or drop what you don't...
Comment: I understand the desire to split one cell into 3 cells, but where does OFFSET come into play here? Why do you care about rows? That's not obvious with how you wrote your question. This may have to do with improper formatting of your sample data. See [How to format tables](https://meta.stackoverflow.com/questions/302471/how-to-put-tables-in-stack-overflow)
Comment: I can't control the formatting of the sample data. The data is the result of a public U.S. government website search. The OFFSET idea was just the best idea I've had so far since the data comes out in a long string under one column and in a repeating pattern.
Comment: As far as text to column, I tried that too but couldn't get a delimiter to work consistently. That was also after trying to add delimiters with find and replace. For instance, finding all of the "permit #:" and replacing with "@permit #:" and then using the "@" as a delimiter in text to column.
Answer: This is a quick approach, based on the pattern shown in the input data.
=LET(in, TOROW(A:A,1), nf, 3, seq, SEQUENCE(nf,,1,2),w, WRAPROWS(in,2*nf),
 data, CHOOSECOLS(w,seq+1),header,UNIQUE(CHOOSECOLS(w,seq)),VSTACK(header, data))

It assumes there is no need to clean the data, all field names are the same, etc. The name nf, represents the number of fields per record. It considers the field values in the even columns and the field names in the odd ones. TOCOL with the second input argument removes the empty rows that act as a record delimiter.


Do I need to call CompleteMessageAsync when I'm in ReceiveAndDelete mode?

Question: I have the following Azure Service Bus code:
private async Task startInternalAsync(CancellationToken cancellationToken) {
    await using var client = new ServiceBusClient(_connectionString);
    try {
        var processor = client.CreateProcessor(_queueName, new ServiceBusProcessorOptions {
            ReceiveMode = ServiceBusReceiveMode.ReceiveAndDelete,
            PrefetchCount = 100
        });

        processor.ProcessMessageAsync += messageHandler;
        processor.ProcessErrorAsync += errorHandler;

        await processor.StartProcessingAsync(cancellationToken);
        await cancellationToken.WhenCanceled();

        _logger.LogDebug("Cancellation requested.  Stopping the receiver...");
        await processor.StopProcessingAsync();
        _logger.LogDebug("Stopped receiving messages.");
    }
    catch (TaskCanceledException) {
        _logger.LogDebug("Cancellation requested.  Exiting.");
    }
    catch (Exception ex) {
        _logger.LogError("Message processing exception.  Exiting.", ex.Message);
    }
}

private async Task messageHandler(ProcessMessageEventArgs args) {
    string body = args.Message.Body.ToString();
    _logger.LogDebug($"Received msg: {body}");

    // complete the message. message is deleted from the queue.
    await args.CompleteMessageAsync(args.Message);
}

private async Task errorHandler(ProcessErrorEventArgs args) {
    await Task.Yield();
    _logger.LogError(args.Exception.ToString());
}

Do I actually need to call await args.CompleteMessageAsync(args.Message) in my messageHandler, though?  I'm in ReceiveAndDelete mode so that should immediately delete the message from the ASB queue upon retrieval, but is CompleteMessageAsync() still needed in order to remove it from the local queue?  Or can I just remove that call?
Answer: You don't need to call CompleteMessageAsync as the message will automatically be deleted once delivered.
In fact, I remember that calling this method actually throws an error when the message was fetched in ReceiveAndDelete mode.


Are these legit FLAC music files?

Question: I'm new to HiFi music and I'd like to experience the full potential of my new headphones.
I've heard that FLAC files of ~900kpbs bitrate are the best and that their sizes are ridiculously huge, I;ve looked up everywhere on the internet for these, all the
 music services I'm subscribed to only support regular MP3 quality and when I tried looking up torrent sites they claim it's FLAC of a 880kpbs bit rate but the sizes are too small for such thing, they're just 20mb max.
TL;DR: Where do you get legit FLAC (or insane high quality) music?
Comment: Hi Mohamed - this is a site about writing music and playing musical instruments, not really about getting hold of music as a consumer.
Comment: Having said that - the way I get FLACs is usually to buy the CD of music thing I want, and rip it to FLAC! As Tetsujin says, that doesn't mean it's "insane high quality" - it's CD quality, which I would describe as "*sane* high quality" insofar as you're very unlikely to benefit from anything better.
Comment: tbh, I rip my own CDs to high bit-rate AAC, which even as a 'professional' sound engineer i find to be completely acceptable. I drop those to 128 for portability, iPhone & in the car etc. Can't tell any difference on a headset or when the car's running.
Answer: "Insane high quality music" is a bit of a misnomer.
FLAC, same as MP3 & AAC, are usually ripped from CDs by other consumers with no real idea of what they're doing, so they're only 16-bit 44.1kHz anyway. 880kbps is a rational value for a heavily compressed FLAC [full rate, uncompressed is 1141kbps], but I wouldn't trust illegal torrents as far as I could spit them.
True high quality is 24-bit, 88kHz [or even 176 or 192 (for video)], which is only obtainable on USB key, or these days digital download. Google 'Beatles 24 bit masters' for an early example. Even these were 'only' 44.1kHz, as most consumers 10 years ago couldn't handle higher bit rates.*
For regular consumer audio, just buy the AACs from iTunes, which are converted directly from 24-bit masters - which is the common delivery method these days. All other formats are downwardly-derived from these 24-bit masters, not from 16-bit CDs.
If you can actually tell the difference I'd be hugely surprised. Most people's ears are just not that discerning.
*The Beatles remasters were actually made at 24-bit, 192kHz, they just weren't released that way, they were dropped to 44.1 so regular consumers could actually play them.
I'm aware this is really off-topic, but I thought an explanation was worth it, even if it is short-lived.
Answer: If you have a pair of headphones and an internet connection, it isn't much. Find out what the quality bottleneck is in your listening system. It is possible that something like your audio interface or headphone amplifier is degrading the sound more than 320 kbps mp3 compression ever can.
FLAC means Free Lossless Audio Codec https://en.wikipedia.org/wiki/FLAC
Lossless means that the audio coding itself won't lose more information than what's already lost in the source material. As a consumer you have little means to know how lossy the material is compared to what there was at some point during production. Perhaps the record company told the mastering engineer to squeeze out all dynamics from the audio, so it's rubbish to star with, FLAC or whatever. If you're not an expert, you can only look at numbers and magic words like "FLAC", "high-quality" or "remaster". If it makes you happy, then you've found happiness.
Numbers and magic words won't necessarily say much about the technical or artistic quality or fidelity of the content. Even if the record company calls something a "remaster", it may not have been made from actual masters:

That's sad. (I hope this provokes you to study the subject to learn what a "master" means in music production, and how things work in general.)
What to do? What hi-fi lovers do, they obtain old physical copies of recordings. CDs and vinyl LPs. I don't even have a vinyl player myself ... I should get one. If music means anything to me, it shouldn't be too much trouble to raise my backside from the couch, walk to the stereo system and put on a record!? I do that with CDs though.
CDs can be losslessly converted to e.g. WAV or FLAC files. FLAC files are much smaller than WAVs.
Answer: FLAC is a compression system.  It takes a WAV or AIFF audio file and makes it smaller.  Its selling point is that it does this with no quality loss.   But it doesn't ADD quality!
You could look for high sample/bit rate WAV files as well.   But they haven't caught on much.  There's some argument for using high rates while recording and mixing, but not much evidence that anyone can hear the difference over CD quality at the distribution stage.

Are these legit FLAC music files?


Problem with hearing singing voice different than the outcome

Question: I have been trying to learn a bit of singing starting last month, but I'm not getting anywhere. I have the problem that the things I sing in my head sound fine to me, but I know for a fact from feedback that it sounds horrible and is super off key to people hearing it. I hear different tones in my head than the ones I actually produce.
Is that a known problem, and does anyone know how to fix it?
I tried singing along to my tuner, and according to that my voice is just very loud background noise and doesn't have notes.
Comment: Have you tried recording yourself and listening to it?
Comment: Additional reference: https://music.stackexchange.com/questions/69824/do-out-of-tune-singers-hear-that-theyre-off
Comment: Somehow I can't really trust your tuner that saying your voice is just very loud background noise *and doesn't have notes*, unless you're really singing too loud/close to the tuner, or you're really making some kind of percussion-like/noise sounds. Try humming (e.g. a constant note) instead and see if the tuner catches it, or if it's broken.
Comment: @piiperiReinstateMonica You should make that an answer!
Answer: As ever - find a teacher! Not easy right now, I understand, but hopefully soon.
A tuner isn't tangible enough. You need an instrument. Yes, it may incur some extra learning, but at the end, the benefits outweigh the struggles.
A cheap keyboard will be beneficial, as you will find your way round it quite quickly. Play a note, sing it. Record what you do, so you can hear both the played and sung notes, for comparison. Most people are not tone deaf. It might just be that you are in the minority, but that's doubtful. keep playing and singing a few notes each day, and listen to the improvement.


How static variable works inside Instance Method - Singleton

Question: I followed a tutorial to implement Singleton and its working fine .Below is the code:
@implementation DKSingle

static DKSingle *dKSingle = nil;

+(id)dKSingleInstance{

    if (!dKSingle) {
        dKSingle = [[DKSingle alloc]init];
    }
    return dKSingle;
}

-(id)init{

    if (!dKSingle) {
        dKSingle = [super init];
    }
    return dKSingle;
}

@end

My question is dKSingle is a static variable, then how come it works inside the instant method
init . Please help me to understand.
Comment: You can use static variables in instance methods. However, the inverse is not true. You cannot access instance variables in a static method.
Comment: You are the right teacher!These are the concepts i missed during my OOP .Can you share any sites,books where i learn everything from OOP.
Comment: http://www.raywenderlich.com/45940/intro-object-oriented-design-part-1
Answer: Static variables are variables that are stored in what's called "static" storage which is allocated at application launch and exists for the lifetime of the application. In objective c, they are not part of the class, but their accessibility is scoped to where the variable is defined. Also, they differ from instance variables in that there is only one instance for your entire application, not one per object created.
Typically, a better way to define the singleton pattern in Objective-C is like so:
+ (instancetype)dKSingleInstance {
    static DKSingle* dKSingle;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        dKSingle = [[DKSingle alloc]init];
    });
    return dKSingle;
}

This makes the static variable scoped to just the one method. Also, by using a dispatch_once, you offer some thread safety for initializing your static variable.
Comment: Thanks for the answer sandy! But from learning of oops is that instance method cannot access static variable . In my example it happening and working also.Can you please help me from oop concept.
Comment: Static variables are the opposite of OOP. OOP is set up to encapsulate data so that only an object can modify its state and those modifications occur by calling exposed methods. A static variable does not belong to any object. It belongs to the application. Many consider it an [anti-pattern](http://stackoverflow.com/q/12755539/1270148) for this reason.


How to derive type-2 maximum likelihood method for RVM regression

Question: According to PRML book(7.85,7.86,exercise 7.12), the marginal likelihood for RVM regression is
$$ \ln p(y|X,\alpha,\beta)=−1/2\{N\ln2π + \ln|C| + y^TC^{−1}y\} $$
$$ A=diag\{\alpha_1,..,\alpha_D\} $$
$$ C=\beta^{-1}I+\Phi A^{-1} \Phi^T $$
$$ \Phi=[\phi(x_1); \phi(x_2)...; \phi(x_N)]$$
or equivalently(MLaPP book exercise 13.3):
$$ \ln p(y|X,\alpha,\beta)= \frac 1 2\ln \beta - \frac \beta 2 ||y-Xm||_2^2+\frac 1 2 \sum_j\ln\alpha_j-\frac 1 2m^TAm+\frac 1 2\ln|\Sigma|-\frac D 2\ln2\pi$$
$$ m=\beta\Sigma\Phi^Ty $$
$$ \Sigma=\beta\Phi^T\Phi+A $$
to maximize the marginal likelihood, we take derivatives of it with respect to $\alpha_i$ and setting these to zero.
But, I can't derive the iterative update formula (7.87) in PRML book:
$$ \alpha_i^{new}=\frac {1-\alpha_i\Sigma_{ii}} {m_i^2} $$
The book (and Tipping's RVM paper) seems to treat vector $ m $ as constant when compute $ \frac {\partial \ln p(y|X,\alpha,\beta)} {\partial \alpha_i} $, while treat $ \Sigma $ as function of $ \alpha_i $, but I think both of them are dependent on $ \alpha_i $.
Did I misunderstanding something here?
Answer: You are right in saying that m depends on αi.
The authors are eluding a subtelty there. It is the same one they describe on p.318, where aN* is equivalent to m and θ to αi in this case.
The contribution of m to the gradient of the marginal likelihood w.r.t αi is zero. m is the mean (and thus mode) of the posterior distribution for the weights, so its gradient with respect to m vanishes, and its gradient w.r.t αi is the dot product of that zero gradient with the gradient of m w.r.t αi.
The same trick is also used for equation 3.89 and 7.115.


Importing a return value in Python

Question: I have the following function in a file named contacts.py.
def analytics_dict(parameters: dict) -> dict:
    github_repo, ending = parameters.get("BP_FILE").split(
        "/blob/"
    )
    github_sha, gearsfile = ending.split("/")
    github_url, github_repo_name, github_org_name = github_repo.rsplit("/", 2)
    return {
        "name": parameters.get("BP_NAME"),
        "deployment_gearsfile_url": parameters.get("BP_FILE"),
        "github_org_name": github_org_name,
    }

I need to use the "name" value in a different file named department.py.
I am doing an import in department.py file as
from department import analytics_dict as analytics

candidate_name = analytics_dict.get("name")

I see an error -  AttributeError: 'function' object has no attribute 'get'
Can someone please let me know the right way to import the value?
Comment: As you've shown it, your code shouldn't give you that error; it should be giving an `ImportError` or `NameError` instead. Your module is named `contacts` but you're importing from `department`. And you import the function as `analytics`, then try to refer to it as `analytics_dict`.
Answer: You need to call the function to get the dict:
candidate = analytics_dict()

and then you can access the name inside the dict:
candidate_name = candidate['name']

You can also do it all in one line as long as each individual piece (the function call and the dictionary lookup) is there in the right order:
candidate_name = analytics_dict()['name']

Comment: Note: you didn't include the entire `analytics_dict` function definition so I'm not sure if it has any required arguments.  If so, you will need to provide those as well.
Comment: I just noticed that the first line got truncated by stackoverflow. Here is the first line:

def analytics_dict(parameters: dict) -> dict:
Comment: In that case when you call `analytics_dict` you need to provide the `parameters` that tell the function where the github repo etc are.

Importing a return value in Python


Find the volume of $K=\{(x,y,z):|x-z^2|+|y-z^2|+z^2\le1\}$

Question: How can I find the volume of $K=\{(x,y,z):|x-z^2|+|y-z^2|+z^2\le1\}$?
First, $z^2\le1$ since $|x-z^2|+|y-z^2|\ge0$
This would give me $$\int \limits_{-1}^1 \left(\iint\limits_K \,dx\,dy\right)\,dz$$
where $K=\{(x,y):|x-z^2|+|y-z^2|\le1-z^2\}$
Now I don't recognize this form of $K$, though $i$ does look look like a square if you let the absolute values represent intervals with respect to the $x$- and $y$ axis. How can I calculate the double integral?
Thanks! Alexander
Answer: Switch to "spherical" coordinates
\begin{align}
\left |x-z^2 \right | &= r^2\sin^2\theta \sin^2 \phi \\
\left |y-z^2 \right | &= r\sin^2 \theta \cos^2 \phi \\
z &= r \cos \theta
\end{align}
or after some manipulation, you can get completely parametrized version of the region
\begin{align}
x &= r^2 \left(\pm \sin^2\theta\sin^2\phi + \cos^2\theta \right )\\
y &= r^2 \left(\pm \sin^2\theta\cos^2\phi + \cos^2\theta \right )\\
z &= r\cos \theta
\end{align}
I leave showing that $\phi \in [0, \frac \pi 2]$, $\theta \in [0, \pi]$  and $r \in [0, 1]$ to you.
Now, you can easily plot that region

I'm not sure if you can see it, but it has sail-shape.
After that, the whole integration should be reduced to
$$
I = \left | \int_0^1 \int_0^{\frac \pi 2} \int_0^\pi J (\phi, \theta, r)\, d\theta\, d\phi\, dr \right |
$$
where $J(\phi, \theta, r)$ is the Jacobian of the transformation.
$$
J = \left |\begin{array}{ccc}
x_\phi & x_\theta & x_r \\
y_\phi & y_\theta & y_r \\
z_\phi & z_\theta & z_r \\
\end{array}\right |
$$
Again, I'll leave its calculation to you as an exercise. Answer is below
$$
J(\phi, \theta, r) = \pm 2r^4 \sin 2\phi \sin^3 \theta
$$
You have four regions with different signs of Jacobian (recall expressions for $x$ and $y$), and in each region Jacobian has constant sign. Due to the symmetry, volume of each region is the same, so you can calculate only one of them. Finally,
$$
I = 4\cdot 2 \int_0^1 \int_0^{\frac \pi 2}\int_0^\pi r^4 \sin 2\phi \sin^3 \theta\, d\theta\, d\phi\, dr = \frac {32}{15}.
$$
Comment: I don't know how to determine the are of integration for the spherical coordinates here. Maybe I can use the identity $|x-z^2| +|y-z^2|+z^2\leq1$, but the $\pm$ signs confuses me once in the expression.Please give me an idea of how to start.
Thanks a lot!
Comment: @Alexander after changing coordinates, your identity simply becomes $r \le 1$, which is reflected in first pair of integration limits. Other ones can be found through analyzing angles $\theta$ and $\phi$, just start varying them one by one to see when they start giving the same value, basically you need to find a period of $\sin^2\phi\sin^2\theta + \cos^2\theta$ and other functions there. As for the $\pm$, it follows from the fact that if $|a| = b$ then $a = \pm b$.
Answer: Let $k=z^2$, then $0\leq k\leq1$.
Now, rewriting the set K,
$$K=\{(x,y);|x-k|+|y-k|\leq 1-k\}$$
We have to consider four  cases:
1.$x,y\geq k$, then the inequality is just,  $x+y\leq1+k$
2.$x,y\leq$, then the inequality is just, $x+y\geq3k-1$
3.$x\geq k,y\leq k$, then the inequality is just, $x-y\leq1-k$
4.$x\leq k,y\geq k$, then the inequality is just, $y-x\leq1-k$
When $k$ attains its minimum value ($k=0$), then $K$ is a square of side 2, other hand, when $k$ attains its maximum value ($k=1$), $K$ is a degenerate square.
The point is, how estimate the square's area variation?
For this, note that the side of a square is just the distance between the lines $x+y=1+k$ and $x+y=3k-1$
This way if the square has side iqual $\ell$, then
$\ell=\sqrt{2}(1-k)$
Hence
$A(k)=2(1-k)^2$ where $0\leq k\leq1$
Or
$\displaystyle\iint\limits_K \,dx\,dy=2(1-z^2)^2$
Now,
$V=\displaystyle\int_{-1}^1 A(z)\,dz$
$V=2\displaystyle\int_{-1}^1(1-z^2)^2\,dz$
$V=\dfrac{32}{15}$


React components unmount and remount when dispatching redux action in lifecycle methods

Question: This occurs with React + Redux Saga application my team is working on
We buy the React Isomorphic theme from Themeforest which bundles the Redux, Saga, and React Router V.4. We are now working on top of it.
I have been using React for a while but new to Redux and never experienced with such behavior. The problem is that whenever I dispatch an action, the component unmounts and remounts as the state changes
Okay, what I am doing is to fetch some user data from the API but. So this is how I come up with the following action & reducer
<code>// Actions.js

const UserActions = {
    FETCH_USER_REQUEST: 'FETCH_USER_REQUEST',
    FETCH_USER_SUCCESS: 'FETCH_USER_SUCCESS',
    fetch_users: () => {
        return {
            type: UserActions.FETCH_USER_REQUEST
        }
    }
}

export default UserActions;
</code>
And the reducer
<code>// Reducer.js
export default function UserReducer(state = initialState, action) {
    switch (action.type) {
        case 'REQUEST_USER_SUCCESS':
            return state.set('user_list', action.user_list);
        default:
            return state;
    }
}
</code>
With Redux Saga, the middleware is created to handle async actions. This is how it looks
<code>// Saga.js
import { all, takeEvery, call, put, fork } from 'redux-saga/effects';
import {get, post} from 'axios';

export function fetchUser() {
    return get('https://mockapi.testapp.dev/users')
    .then(response => {
         return response.data;
    }).catch(error => {
         return error.data
    });
}

export function* fetchUserRequest() {
    yield takeEvery('FETCH_USER_REQUEST', function*() {
        const resp = yield call(fetchUser);
        yield put({
            action: 'FETCH_USER_SUCCESS',
            user_list: resp
        });
    });
}

export default function* rootSaga() {
   yield all([
      fork(fetchUserRequest)
   ]);
}
</code>
Now I implement the code in my component like this
<code>// App.js
import React, {Component} from 'react';
import {connect} from 'react-redux';
import UserActions from './actions/UserAction';

const mapStateToProps = (state, ownProps) => {
    return {
        userList: state.User.get('user_list')
    }
}

const mapDispatchToProps = dispatch => {
    return {
        fetchUser: () => dispatch(UserActions.fetch_users())
    }
}

class App extends Component {
    componentDidMount() {
        this.props.fetchUser();
    }

    render() {
        // ... The rest of the rendering processes
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(App);
</code>
Now that you can see, with the behavior mentioned prior to this. Dispatching an action via this.props.fetchUser() cause the state to change but what I don't expect is that the component shouldn't unmount and remount because once it does so, an infinite loop occurs because the componentDidMount runs over and over and state also changes accordingly.
What I expect is to fetch the data from the API once the component mounts without remounting itself once the state changes for any reason because the theme we purchased is equipped with other base components which make use of Redux-saga to handle state and async actions. For example, the collapsable sidebar triggers a dispatch which changes the state that controls its bahavior once the users click on the it. Currently, once it does that my current component immediately unmounts unexpectedly.
Is there any possible way to solve such a problem or this is the default behavior of Redux?
Comment: I meet this problem with in my React Native project
Comment: @Chatthana Janethanakarn - Can you show your render function? it will be helpful for understanding the entire flow, thanks :)
Comment: same for me, any updates?
Comment: Have you tried using `componentWillMount` instead of `componentDidMount`. Also the component would remount if when rendering the `` component you added a key that is dynamic such as ``

Changing routes remounts components, if you could share your route file maybe there's something there I could find.
Comment: I put your code and put it to codesandbox and I can't reproduce the problem: https://codesandbox.io/s/lpl7x everything works as it should (I had to fix some typos which I assume get there while writing the question)
Comment: the strange thing that I see is that you have state.set that probably mean that the sate is not a plain object, wich is discuraged as per redux documentation - https://redux.js.org/style-guide/style-guide#do-not-mutate-state - https://redux.js.org/style-guide/style-guide#do-not-put-non-serializable-values-in-state-or-actions - please use { usersList:[] }
Comment: also why are you using
UserActions  = {
    FETCH_USER_REQUEST: 'FETCH_USER_REQUEST',
    FETCH_USER_SUCCESS: 'FETCH_USER_SUCCESS',
    ...
}  if you don't use UserActions.FETCH_USER_REQUEST ?
Comment: I am also facing the same issue of mounting and remounting
do we have any update on this issue?
Answer: using StrictMode in your application : when the component is first mounted: strictmode will simulate mounting, unmounting and remounting to detect any hidden bug in the code.
It's a development tool to try to help you find bugs in your code. like unclean side effects in the use effects.It will run the useEffects twice. It will also detect deprecated code and show you a warning in the console.
It's a development tool that helps you find bugs in your code related to double rendering or forgetting to clean up your side effects.
You may wanna try uncommenting strictMode if you are using it. Let's see if it will solve the issue


Rename file extension using case and recursion

Question: Can someone create a short code that will rename a files extension in a sub directory using a command line option -r?
So if i have a file a.txt in folder called loc. I enter this "change -r txt doc" and the file will become a.doc in the loc sub directory (as in loc/a.doc).
I need to add this to a code of mine. Also the reason why I want to use a case statement is because I will be adding more options in the future.
Comment: Have you tried?  What didn't work?  Please ask a specific question.
Comment: I just can't do it. I looked at an example of a case statement and I don't know how to apply it to this. I'm trying to add it to this:

for newext in *$.txt
do
  export NAME=`basename $newext $.txt`
  mv $NAME$.txt $NAME$2.doc
done
Comment: Seems weird to want to rename .txt into .doc. And to write a custom script with options to do a `find ... -exec mv "{}" ...` Anyway, it may be worth noting that some distributions have a nice rename command taking Perl regexes: `rename 's/\.txt$/.doc/' *.txt`
Answer: If I understand your question correctly, you want to change file extensions recursively.
Script change.sh:
# recursive rename:       ./change.sh -r -f txt -t doc
# current directory only: ./change.sh -f txt -t doc

find_depth="-maxdepth 1"    # defaults to current directory

while getopts "rf:t:" Option
do
case $Option in
    f ) from=$OPTARG ;;
    t ) to=$OPTARG ;;
    r ) find_depth="" ;;
esac
done
shift $(($OPTIND - 1))

for file in $(find . $find_depth -name "*.$from")
do
    mv $file "${file/.$from/.$to}"
done

Edited in response to your comment.
Comment: -1. what if file names have spaces? and since using bash, use `$()` instead of backticks
Comment: I removed the spaces around the `=` in your variable assignments.
Comment: Yeah, that's it. Some questions, how do I apply that to a case (i want to use a case for this task, since i want to add more options)? And what if I want to specify any file extension, do I use $1 and $2? How will that work?
Comment: Thanks lecodesportif! I think I can work with something like that. About the case....I want to have 3 options: 1. if the user enters "change -r txt doc", a file extension gets changed in a subdirectory. 2. If the user enters nothing, "change txt doc", it just changes a file extension in the current directory. 3. But if a user enters "newext -n -r doc", it should rename files that end with .-r or .-n (this will rename all files in the current directory called *.-r as *.doc)
Comment: My edit answers your points 1 and 2. Your point 3 is unclear, but it should be easy to change the example.
Answer: To get extension and use case/esac
extension=${filename##*.}
case "$extension" in
  "doc" ) ... ;;
  "txt" ) ... ;;
esac


Apagar valor do placeholder no input ao clicar utilizando AngularJS

Question: Alguém sabe como posso apagar o valor do placeholder ao clicar no campo utilizando apenas AngularJS?
Exemplo: Ao clicar, some automaticamente a palavra nome.

<input type="text" ng-model="inputText" placeholder="Nome" />
Answer: Da seguinte forma:

<input type="text" ng-model="inputText" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Nome'" placeholder="Nome" />
Comment: Obrigado Thiago
Answer: Com angular, só lembrando que o comportamente normal o input oculta o placeholder quando há valor, mas, essa é uma forma de remover placeholder ao receber o focus e quando perde o foco é atribuído novamente o valor Nome no placeholder

var app = angular.module('app', []);
app.controller('ctrl', ['$scope',
  function($scope) {
    $scope.init = function() {
      var ele = angular.element("#input1")[0]
      ele.addEventListener('focus',
          function() {
              ele.setAttribute('placeholder', '');
          });
      ele.addEventListener('blur',
          function() {
              ele.setAttribute('placeholder', 'Nome');
          });
    }
    $scope.init();
  }
]);

  <input type="text" id="input1" ng-init="inputText=''" ng-model="inputText" placeholder="Nome" />

Comment: Obrigado pela explicação detalhada.


Notation for a repeat section with 2 different beginnings

Question: I have written a hornpipe in AABB format which also has a counter-melody.
On the first time through the A section the counter-melody rests until halfway through the second bar. On the second repetition it comes in straight away. In fact the entirety of the first two bars of the counter-melody is different, but after that it's the same until the last bar which has a first and second ending bar.
My first attempt involves placing the begin repeat sign at the beginning of the third bar and having a 3 bar first ending - which actually contains the first 2 bars of the next repeat - and a one bar second ending that continues into the B section.
Although this works it is quite unintuitive and seems to really confuse people.
Can someone provide a better answer, before I give up, unroll the repeats and write it out in full?
Comment: What is going to be written for each of the two players? Two separate parts? Or is everything contained on the one copy?
Comment: I am putting both parts in parallel on the same sheet for now.
Comment: Probably be simpler to write out the parts separately. Job done - one to each player.
Comment: Thanks for your comment, but I'm not sure how it would help. My question is about notating repeat structures where the first few bars are different on the second repeat. If I write the counter-melody on a separate sheet I will still need to represent this repeat structure. Or I could unroll the loop and write it out in full, but that doesn't depend on separating the parts.
Comment: Your first attempt is correct. Players are used to first and second time sections containing more than one bar, and are *not* used to them coming at the *start* of the repeated section.
Comment: Related: [How to denote a note that should only be played during first repeat without voltas?](https://music.stackexchange.com/questions/72887/how-to-denote-a-note-that-should-only-be-played-during-first-repeat-without-volt/72888#72888), and [Small changes between 1st and 2nd endings](https://music.stackexchange.com/questions/97960/small-changes-between-1st-and-2nd-endings)
Answer: You can put a bracket over the first bar and a half with text saying "2x only". Clarify with "(both x)" where it starts the first time. This kind of indication is completely standard in musical theater, and jazz and pop charts.
Comment: That notation is common in "formal" orchestral music as well.
Comment: But if it gets complicated, write it out.


In LilyPond (piano staff) how can I type two eighth notes for different hands?

Question: In LilyPond, while writing a piano staff, how can I type two eighth notes, so that one is played with the left and the other with the right hand?

Example. I want to produce this highlighted separation:
Answer: In order not to complicate the example by adding additional spacing until LilyPond prefers to pick a kneed beam on its own, I am using a voicing change to get this, moving from "first voice" settings in the lower staff to "fourth voice" setting in the higher.  Usually \voiceOne/\voiceTwo (can be implied by << ... \\ ... >>) should be used for the outermost voices in a staff, but since the voice from the staff below is likely only an occasional visitor, I am giving it the \voiceFour treatment.  If the resulting arrangement is not satisfactory, one might temporarily adjust the lower voice of the upper staff to \voiceFour instead and return it afterwards (except that in this minimal example there is no separate history afterwards) to \voiceTwo.
global = { \key e \minor \time 2/4 }
{
  <<
    \new Staff = "high"
    { \global
      \new Voice {
        << { e''8 b' } \\ <e' b'>4 >>
        r4
      }
    }
    \new Staff = "low" \with { \clef bass }
    { \global
      \new Voice { \voiceOne g8
           \change Staff = "high" \voiceFour
           b
           \change Staff = "low" \oneVoice
           r4
         }
    }
  >>
}

Answer: You use multiple voices.  Here is a small example which semi-manually puts beams in the second of two voices in a << {first voice} \\ {second voice} >> construct as the autobeamer does not work across skips or rests.
\relative
{
  \key e\major
  \time 3/4
  <<
    \repeat unfold 24 { s16 e'' } \\
    <<
      \repeat unfold 2
      { gis s e s dis s e s fis s e s e s gis s fis s gis s a s fis s }
      \repeat unfold 12 { s[ s s s] }
    >>
  >>
}

Comment: Thanks for your help (+1). I actually was thinking of writing it in two separated staffs (piano, with bass + treble keys). I edited the question adding the required form.


Is the result of a print or echo a string or can they be number values in php?

Question: Can the result of a print or echo in PHP be a number value or is it always a string.
For instance:
this is the PHP code:
<?php
    $num = 10;
?>

and this is the JS code:
function isLarge(number)
{
    var s = document.getElementById("test").value;
    if (s > number)
    {
        window.alert("to large");
        return false;
    }
     return true;
}

and this is my other PHP:
<input type="text" id=""test>
<input type="button" value="click" onclick="isLarge('<?php print $num?>')">

My result is not correct if I run this. I thought the print $num was giving me a string valued numbers which are not to be compared with a number.
Comment: You do realize your assumption and question are pointless? You ask if echo outputs a string or a number. That is **pointless** to ask. Now as for why: you echo-d something, say `123`. That's a number. but what did you do in your JS: you did `isLarge('123');` -> you *quoted* it. That means you got a string. This is also not on the PHP's side of control. Had you used `isLarge(123);` then you passed **the number** to your JS. As for what the actual thing was in PHP - it's pointless. That means numbers and strings in PHP are not connected to numbers and strings in JS. At all. Ever.
Comment: Where do you give `document.getElementById("test")` a value?
Comment: Also, having mentioned what I did above, I'm giving you a -1 because you have a severe lack of knowledge on topic. This falls under basic of basic.
Answer: PHP is giving you the string representation of 10, which is also 10. However, your JS code embeds this inside quotes, making it a JS string value. Since the .value property of the input element is also a string, JS ends up comparing the two "numbers" as strings and probably giving you unexpected results.
Consider that in JavaScript:
2 > 10       ===> false (numeric comparison)
"2" > 10     ===> false ("2" converted to number)
2 > "10"     ===> false ("10" converted to number)
"2" > "10"   ===> true (string comparison!)

If you want to compare numbers, then at least one of the two operands to the comparison must be a number.
To convert the .value to a number, use parseInt:
var s = parseInt(document.getElementById("test").value, 10);

To convert the PHP variable to a number, you can simply lose the quotes around the PHP echo:
onclick="isLarge(<?php print $num?>)"

However this could result in a parse error if $num is not a number. It would be much better to use the bulletproof solution: json_encode to make sure that the value of $num safely transitions into JS-land, and then parseInt to make it a number:
onclick="isLarge(parseInt(<?php print json_encode($num);?>, 10))"

With the above technique, the worst case scenario is that if $num is garbage you will end up calling isLarge(0).
Comment: thank you it is working fine know after a I have removed the single quote '' from the php print $num
Comment: @DilshatAbduwalli: Sure, but think about the better option: how it works and why. Otherwise it's only a matter of time before you forget some detail and start having problems in similar cases.
Answer: I don't see any error in the PHP, but I see double quotes in the HTML:
<input type="text" id=""test>

Answer:
I thought the print $num was giving me a string valued numbers which are not to be compared with a number.

PHP is a loosely typed language. That means you can cross compare values of different types. If you want to ensure that the correct type is being passed, then you should be using the === operator in your JS code.
Echo prints values as a String. It is up to you to interpret that value as a number. The single quotes around your output, also tell JS to interpret this value as a string.
Answer: It's nothing to do with the PHP
With
onclick="isLarge('<?php print $num?>')

you are passing the value to Javascript function as a string. Note the ' single quotes.
If you want to compare as a number remove the '
Answer: onclick="isLarge('<?php print $num?>')"

The result of this is:
onclick="isLarge('10')"

'10' in Javascript is a string, because you put it in quotes in Javascript.
PHP output is void of any particular type, but it's basically for all intends and purposes a string. What it really depends on is how the next entity reading this output is interpreting it though.


Erro Thread Android que está crashando o app na hora da abertura

Question: Estou fazendo um projeto inicial para testar as funcionalidades da biblioteca de SpeechRecognizer da google para android, porém na hora se subir o App estou tendo problemas, nesse caso ele simplesmente fecha e sem mesmo dar uma mensagem de crash, o erro aparentemente é relacionado a Thread main(essa é uma parte do erro):
02-11 20:59:00.930 16313-16313/? E/propClient: PropClient failed to load
02-11 20:59:01.077 25677-25677/? E/adbd: recv: OPEN 0000000f 00000000 0015:73 68 65 6C 6C 3A 6C 6F 67 63 61 74 20 2D 76 20 6C 6F 6E 67 00
service_to_fd: shell:logcat -v long
02-11 20:59:01.090 16315-16315/? E/propClient: PropClient failed to load
02-11 20:59:08.294 19965-19965/? E/rs$DefaultThreadFactory: ===== Detect pool-thread leak =====
02-11 20:59:08.295 19965-19965/? E/rs$DefaultThreadFactory: dalvik.system.VMStack.getThreadStackTrace(Native Method)
java.lang.Thread.getStackTrace(Thread.java:1536)

MainActivity.kt
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.provider.Settings
import android.speech.RecognitionListener
import android.speech.RecognizerIntent
import android.speech.SpeechRecognizer
import android.support.v4.content.ContextCompat
import android.util.Log
import java.util.*

class MainActivity : AppCompatActivity() {

lateinit var sr: SpeechRecognizer

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    checkPermission()
    configureSpeechRecognizer()

}

fun configureSpeechRecognizer(){
    sr = SpeechRecognizer.createSpeechRecognizer(this)
    var mSpeechRecognizerIntent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
    mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
    mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault())

    sr.setRecognitionListener(Ouvinte())
}

fun checkPermission(){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED){
            var intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package: $packageName"))
            startActivity(intent)
            finish()
        }
    }
}

class Ouvinte: RecognitionListener{
    var TAG = "speechOuvinte"

    override fun onReadyForSpeech(p0: Bundle?) {
        Log.d(TAG, "onReadyForSpeech")
    }

    override fun onRmsChanged(p0: Float) {
        Log.d(TAG, "onRmsChanged")
    }

    override fun onBufferReceived(p0: ByteArray?) {
        Log.d(TAG, "onBufferReceived")
    }

    override fun onPartialResults(p0: Bundle?) {
        Log.d(TAG, "onPartialResults")
    }

    override fun onEvent(eventType: Int, p1: Bundle?) {
        Log.d(TAG, "onEvent: $eventType")
    }

    override fun onBeginningOfSpeech() {
        Log.d(TAG, "onBeginningOfSpeech")
    }

    override fun onEndOfSpeech() {
        Log.d(TAG, "onEndOfSpeech")
    }

    override fun onError(error: Int) {
        Log.d(TAG, "onError: $error")
    }

    override fun onResults(result: Bundle?) {
        Log.d(TAG, "onReadyForSpeech")

        var data = result!!.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)

        for(i: Int in data.indices){
            Log.d(TAG, "dados: $data[i]")
        }
    }

}

}

O layout da main é bem simples pois no momento não utilizo nenhum componente de tela.
Estou aberto a sugestões, até mesmo se quiserem me indicar um tutorial para essa biblioteca que vocês usaram e acreditam que será de grande aprendizado, por favor aproveitar essa pergunta para compartilhar! Obrigado !
Answer: Operações pesadas não podem ser feitas na MainThread, experimente abrir outra thread e colocar seu código do SpeechRecognizer nele.
    ExecutorService pool = Executors.newSingleThreadExecutor();

    Runnable task = new Runnable() {
        public void run() {
            //seu código pesado aqui
        }
    };

    pool.execute(task);


How to pass data from a FSharp.Data.CsvProvider to a Deedle.Frame?

Question: I'm trying to pass data from a FSharp.Data.CsvProvider to a Deedle.Frame.
I'm almost new in F#, and I need to convert some CSV files from culture "it-IT" to "en-US", so I can use the data.
I found Deedle, and I want to learn how to use it, but I was not able to directly convert the data from a CSV file in Deedle (at least is what is printed in F# interactive).
I noticed that the CsvProvider makes the conversion, but after some days of attempts I am not able to pass the data.
Answer: I believe that Deedle should be able to deal with CSV files that use non-US culture:
let frame = Frame.ReadCsv("C:\\test.csv", culture="it-IT")

That said, if you want to use the CSV type provider for some reason, you can use:
let cs = new CsvProvider<"C:/data/fb.csv">()

cs.Rows
|> Frame.ofRecords
|> Frame.indexColsWith cs.Headers.Value

This uses Frame.ofRecords which creates a data frame from any .NET collection and expands the properties of the objects as columns. The CSV provider represents data as tuples, so this does not name the headers correctly - but the Frame.indexColsWith function lets you name the headers explicity.
Comment: Thank you, Thomas. In F# interactive, if I send the command: frame.Rows;; I have the values the same way as they are stored in the CSV file, I mean with decimal separator as "," instead of "." . Is it normal?
Comment: That sounds like the frame is loading the date as strings.. Does the CSV provider under the type to be float?
Comment: Yes, Tomas, it's right. In FSI, frame.Rows prints data as they are stored in the file. If I print the content of frame.Rows.Values I can see the values in the correct form. Thank you for your help.


Checkbox on form submit: error keeps displaying on button click

Question: I have a form that requires a user to click a checkbox before it can submit. On Submit if the user has not checked the box I display a error message. Currently if I keep clicking the message keeps adding. How do I change this so it only displays once.
    onFormSubmit : function(isFormValid, event){
      if ($('#agree_to_terms_join').prop('checked')) {
        $('#agree_to_terms_label').parent().removeClass('has-error').find('.error').remove();
      } else {
        $('#agree_to_terms_label').parent().addClass('has-error').append(
          '
' +
            '
Message goes here
' +
          '
'
        );
        return false;
      }
    }

Answer: While this solution may require extra work and changing some html, but this is the better approach:

Keep the html block in the form itself
And toggle the visibility based on the errors using CSS.

JS
onFormSubmit: function(isFormValid, event) {
    var elem = $('#agree_to_terms_label');
    elem.is(":checked") ? elem.parent().removeClass("error"):elem.parent().addClass("error");
}

CSS:
.has-error .error {
    display: block;
}

.error {
    display: none;
}

HTML

Message goes here

You can keep this HTML in the form itself. Toggling the class will be faster than changing the DOM
Answer: It looks like you are appending and additional HTML div each time an error occurs. So every error will add another div. Usually people solve this problem by having the error Div in the original markup with a default hidden CSS class applied. When the user makes an error the hidden class is removed. When the error is fixed the hidden class is added back on.
.hidden{
  display:none;
}

It also looks like you're using jQuery, so you can just use the show() / hide() methods instead.
Answer: So I understand that if you click multiple times, it shows more than one time the same message.
You can check if the element already has class has-error.
Something like this :
onFormSubmit : function(isFormValid, event) {
  if ($('#agree_to_terms_join').prop('checked')) {
      $('#agree_to_terms_label').parent().removeClass('has-error').find('.error').remove();
  } else {
      if (!$('#agree_to_terms_label').parent().hasClass('has-error')) {
          $('#agree_to_terms_label').parent().addClass('has-error').append(
            '
' +
              '
Message goes here
' +
            '
'
          );
      }
      return false;
  }
}

Answer: Instead of using the #append method you could use the #html method like this:
    onFormSubmit : function(isFormValid, event){
  if ($('#agree_to_terms_join').prop('checked')) {
    $('#agree_to_terms_label').parent().removeClass('has-error').find('.error').remove();
  } else {
    $('#agree_to_terms_label').parent().addClass('has-error').html(
      '
' +
        '
Message goes here
' +
      '
'
    );
    return false;
  }
}

I would also suggest you to cache the jquery calls in order to improve the performance, check out this article.
Answer:

$(document).ready(function(){
    $('#submit').click(function(){
        if(!$('#checkbox').is(':checked')) {
           alert("You must check the checkbox");
        }
    });
});

<input type="checkbox" id="checkbox"/>

<button id="submit">Submit</button>
Answer: You need to check to see if you have already appended the message to the parent of #agree_to_terms_label for appending the error message.
if ($('#agree_to_terms_label+div.error').length == 0) {
  $('#agree_to_terms_label').parent().addClass('has-error').append(
    '
' +
    '
Message goes here
' +
    '
'
  );
}

Example here:
https://jsfiddle.net/he5cx50m/
Answer: You could use a variable to check if the the message was already displayed.
var isErrorMsgDisplayed = false;
onFormSubmit : function(isFormValid, event){
      if ($('#agree_to_terms_join').prop('checked')) {
        $('#agree_to_terms_label').parent().removeClass('has-error').find('.error').remove();
    isErrorMsgDisplayed = false;
      } else {
        if(!isErrorMsgDisplayed){
        $('#agree_to_terms_label').parent().addClass('has-error').append(
          '
' +
            '
Message goes here
' +
          '
'
        );
        isErrorMsgDisplayed = true;
        }
        return false;
      }
    }


Probability raffle question

Question: There is a raffle with prizes for first, second and third. There are $50$ tickets. A teacher buys $5$. What is the probability that;
$1$) wins first prize.
$2$) wins at least one prize.
Comment: The first one is pretty easy, because there are 50 outcomes and one of them is the first prize. Do you know the discrete uniform law?
Comment: The discrete uniform law states that if you have a discrete and uniform distribution (that is, discrete outcomes and each one is as likely as the other), then the probability of an event is equal to the number of favorable outcomes divided by the total number of outcomes. This can be applied in this case. What would you say, is then the probability of winning the first prize?
Comment: The number of favorable outcomes (in the first question) is 1. The total number of outcomes is 50.
Comment: sort of, i'm just stuck on how to work it out
Comment: ummm...no idea. Can you tell me?
Answer: $1$)The answer is $\frac{5}{50}=\frac{1}{10}$.
$2$)The second problem is harder, so I'll explain. We can first find the probability for  not winning any prize. the probability for not winning first prize is $1-\frac{5}{50}=\frac{9}{10}$, not winning second prize is $1-\frac{5}{50}=\frac{9}{10}$, not winning third prize is $1-\frac{5}{50}=\frac{9}{10}$. So the probability for not winning any prize is $\big(\frac{9}{10}\big)^3=\frac{729}{1000}$. So the probability for winning at least one prize is $1-\frac{729}{1000}=\frac{271}{1000}$.
Comment: thank you so much
Comment: Click the tick to accept my answer and you will get 2 reputation :)

Probability raffle question


How can I reuse subquery in condition checking in SQL Server?

Question: I want to retrieve the results from SQL Server 2012.But for checking condition I rewrote the same subquery.Is there any idea to use the subquery just once and retrieve the result?
My query:
sql = "SELECT customer_id,ISNULL(first_name, '') + ' ' + ISNULL(middle_name, ' ') + ' ' + ISNULL(last_name, ' ') AS 'Customer_name', (ISNULL(city, '') + ',' + ISNULL(district, ' ') + ',' + ISNULL(zone, ' ')) as 'Location' FROM customer_detail WHERE 1=1";

if(location != "")
{
    sql += " AND (ISNULL(city, '') + ',' + ISNULL(district, ' ') + ',' + ISNULL(zone, ' ')) LIKE '%" + location + "%'"";
}

Query after AND is same as above subquery. Thanks in advance.
Comment: Please also be very aware that if your local variable `location` is in **any** way user editable either now or in the future (eg. entered on a search form, fetched from a database table, taken as a runtime argument, etc) then you have just created a SQL injection bug - congratulations!  Please look at using [parameterized SQL queries](http://stackoverflow.com/questions/7505808/why-do-we-always-prefer-using-parameters-in-sql-statements) instead so that your code looks like this instead: `sql+=" AND (...) LIKE '%' + @location + '%'"";`
Comment: Another comment on SQL: writing this sort of thing can be slow: `SELECT ... FROM ... WHERE (ISNULL(something,' ') + ...) LIKE '%blah%'`. It will perform very poorly on any database with lots of rows.  Two reasons: SQL Server cannot use an index seek because you're applying functions to columns (`ISNULL` as well as concatenating with `+`), secondly using LIKE '%blah%' is much slower than LIKE 'blah%'.  Sometimes you need the first option, but be aware that it will be slower.
Comment: Use CTE to avoid duplicate code.
Answer: It seems you are not looking so much for sub-query than a user defined function (UDF) to merge 3 text column in a prettier way.
If you do not want to use UDF then you could use Common Table Expressions (CTE) to write the expression just once.
Using CTE has also the benefit of encapsulating your reused block right inside query, whereas the UDF would need to be added to your DB before executing your query. This may or may not be a desirable thing depending on reusability needs.
CTE solution would be along the lines of this:
WITH CTE (Id, [Name], [Location]) as
(
    SELECT customer_id,
        ISNULL(first_name, '') + ' ' + ISNULL(middle_name, ' ') + ' ' + ISNULL(last_name, ' '),
        ISNULL(city, '') + ',' + ISNULL(district, ' ') + ',' +ISNULL(zone, ' ')
    FROM customer_detail
)
select *
from CTE
where 1=1
    AND [Location] LIKE '%' + @location + '%'

Also, generally you can expect CTE to perform generally better than UDFs as the query optimizer can modify the plan to match specific query needs.
Comment: Scalar UDFs are notoriously bad for performance, and also prevent paralelism. Avoided at all cost :)
Comment: I agree UDFs are often an issue. CTE will not have that issue I assume? In the past I have replaced functions by joining in the sub query with an other apply. Would that be quicker or slower?
Comment: @vikjon0 Query optimizer works surprisingly well for CTE's in MSSQL, being able to sniff parameters and optimize plan, or even to eliminate execution completely if possible. Note that this can be different for other RDBMS, For example Postgres seems to blindly execute CTE first and then starts to think about the main query, forcing you to prefer apply. In my experience MSSQL is smarter in this regard and lets you use whatever syntax you prefer.
Answer: I would go with a reusable view and stored procedure for the actual search.
    create view vCustomerDetail
    as
        select  [customer_id]
              , isnull([first_name] + ' ', '') + isnull([middle_name] + ' ', '') + isnull([last_name], '') as [Customer_name]
              , isnull([city] + ', ', '') + isnull([district] + ', ', '') + isnull([zone], '') as [Location]
        from    [customer_detail]
    go

    create proc pCustomerDetailByLocation
    (
        @location nvarchar(200) = ''
    )
    as
    begin
        set nocount on;

        select  *
        from    [vCustomerDetail]
        where   [Location] = ''

        union all

        select  *
        from    [vCustomerDetail]
        where   [Location] like '%' + @location + '%';
    end
    go

You would call the stored procedure from your code with and pass along the location in the parameter. That way you can prevent SQL injection and also make use of better execution plan caching than with an ad-hoc query.
You can either use a union like I've done in my example, or combine it with an OR statement, like so:
    where   [Location] = '' or [Location] like '%' + @location + '%';

I found the union to be beneficial in some cases over because you're helping the optimizer split up his lookup logic.


Missing Data (mice) and Survey Package r

Question: First, I am new to analyzing public opinion polls and the r package "Survey".  I would like some advice.  I am running a regression model with weights from a Pew survey, however, I noticed that a significant portion of my data is missing because of the covariates.  As a robustness check, I would like to impute my data set.  I would like some advice on the best way to handle this in r.
I am most familiar with using the "mice" package in r to handle missing data.  I don't believe "survey" can accommodate mice.  Should I separate each imputed dataset and then perform a regression analysis (using "survey") for each dataset?  Is this the most efficient method?  Finally, how do you pool the estimates?  You don't average the estimates from all the imputed data sets, do you?
Comment: for work with the `survey` package, you probably want `mitools` and not `mice` - `mitools` was written by the author of `survey`
Comment: As far as I know, mitools is a package to handle the imputed data. mitools does not perform imputation.
Answer:
I analyzed each imputed dataset separately with the complete command.
I averaged all the coefficients.  However, to calculate the SEs, I used the formula from this site (http://circoutcomes.ahajournals.org/content/suppl/2010/01/06/3.1.98.DC1/HeDS.pdf).  Specifically, I averaged the variance of my coefficients across all my imputed data sets + (1+1/number of imputed datasets) x the between imputation variance.  Finally, I square rooted that answer.
Comment: It would be great to have an updated, live link to that article.


Denoising technique for signal with beforehand known shape (linear and exponential)

Question: I have a noisy signal which is linear and then exponential. I know the type (Gaussian additive noise) and degree (0.01) of noise. Part of the challenge is determining when the signal changed from linear to exponential. What is the best approach to denoise it?
I have tried to apply a Savitzky-Golay filter but the first derivative does not convey useful information. Please see pic below.

Code below:
from scipy.signal import savgol_filter
cleaned_signal = savgol_filter(clean_signal, 11, 1, 1)
Comment: Clarifications needed: Do you want to filter the signal (get the best estimate as of the latest sample) or smooth it (extract the signal at points in time after you have acquired points both in that point's past and future). Do you know any signal parameters ahead of time -- e.g., slope & intercept during the linear period, or parameters in the exponential period, or is just the form assumed?  Do you know the time of the transition from linear to exponential ahead of time, or is that to be determined also? Is this multivariable? Do you know the Gaussian variance?
Comment: Thank you gms for your reply. I actually want to smooth it. I do not knowo any signal parameters ahead of time, just the form. The time of transition is to be determined also. Just univariate. I know the Gaussian variance.
Comment: The chart says the green line is the derivative, but the text above says "second derivative."  The 0 values suggests it is indeed second derivative.  However, it doesn't seem possible that either the first or second derivative would remain constant during the second period (exponential growth period), since the derivative of an exponential function is also an exponential function.  Visually, it seems obviously nonzero.  Maybe there's a bug?   What is your window size in both time and number of samples?  Is the x-axis a sample number or a time variable?
Comment: I used scipy.signal import savgol_filter. Please see https://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.signal.savgol_filter.html
Comment: Sorry, I don't know scipy - someone else will have to comment on that
Comment: So it looks like a window length of 11 points, 1st order polynomial, 1st order derivative.  Either the filter isn't working, or there's a problem getting the data in or out. "clean_signal" appears to be the raw data; "cleaned_signal is the smoothed data.  Maybe try filling in "clean_signal" with a non-noisy straight line to see if you get the right derivative, to see if the problem is in the filter function?  All the derivatives should be positive,  steady at first, then exponentially increasing after the shift.  Something went wrong here - it looks like you are just filtering zero-mean noise.
Answer: Since you know that the signal is a straight line for part 1, you could start with doing a linear least squares fit over a moving time window.  An easy way to do that would be to use Savitzky-Golay smoothing, choosing a linear fit:  you choose a time window size (number of points).  You apply the smoother at each time point, and it does the linear fit based on the data within the surrounding time window.  It is explained in the Wikipedia article, at https://en.wikipedia.org/wiki/Savitzky%E2%80%93Golay_filter .  They give several variations for handling the starting point, where you don't have a full window size available.
Then, you'd want to detect the time when the exponential signal starts for part 2.  That should be obvious - the deviations between the estimate (smoother output) and the original data will start getting bigger and bigger (assuming you're monitoring exponential growth, not shrinking).  Since you know the variance, you could test for the difference from the prediction vs. the raw data.  Or alternatively, you could also use the Savitzky-Golay smoother that estimates the smoothed derivatives, not the smoothed values.  During the linear period 1, the derivative estimate should be very close to constant.  During the exponential period 2, the derivative estimate should be a function of the input signal.
Once you have picked the transition point, you could keep the previous smoothed values within part 1.  For part 2, you could transform the data by taking the logarithm for each data point in part 2 and again do linear fitting.  After that straight line fit, transform the smoothed log values back by applying the exponential function.
Comment: Please see my edit on the top.


Recursive function leads to simplifier loop in Isabelle

Question: I have the following two Isabelle definitions:
fun remove_left :: "cmd ⇒ cmd × cmd option" where
"remove_left (Comp c d) = (case remove_left c of
  (head, Some c') ⇒ (head, Some (Comp c' d)) |
  (head, None) ⇒ (head, Some d)
)" |
"remove_left c = (c, None)"

function pop_flatten :: "cmd ⇒ cmd" where
"pop_flatten c = (case remove_left c of
  (h, Some c') ⇒ Comp h (pop_flatten c') |
  (h, None) ⇒ h
)"
by pat_completeness auto
termination by(relation "measure size"; simp; metis remove_left_decreases)

(As an exercise I am proving that various versions of program flattening routines are equal.)
The simplifier seems unable to handle this. For example, when I try the following obviously false lemma:
lemma "pop_flatten c = Skip"
  apply(simp)

The simplifier immediately goes into a loop. simp_trace shows it is continuously applying the definition of pop_flatten. My suspicion is that the case expression introduces the term c' which the simplifier considers to be completely new, so it unfolds the definition again. I am unsure how to work around this, I would like to not change my definition. I tried removing the simp rules for pop_flatten as follows:
declare pop_flatten.simps [simp del]

But now several proof steps which I would normally do by simp obviously don't work anymore. My definition of cmd is standard, just a skip, sequential composition, if and while. Is there indeed an edge case in the simplifier I am running into here, or is my definition just wrong in some way I am not seeing?
Answer: It's not particularly surprising that this leads to an infinite loop: The left-hand side of the pop_flatten.simps rules is immediately applicable to its right-hand side again, so you are almost guaranteed an infinite rewrite loop.
For that reason, if you do a recursive definitions with just a single equation that isn't guarded by a condition or a pattern match, it is best to immediately delete the .simps rule from the simp set (as you have done).
If you do want to apply it, you can either apply it once in a very targeted way using apply (subst pop_flatten.simps) or you can restrict it to the particular value you want to apply it to, e.g. apply (simp add: pop_flatten.simps[of c]).
Answer: For completeness, after Manuel's suggestion, what I wound up doing was rewriting pop_flatten to have a case split in the preconditions as follows:
function pop_flatten' :: "cmd ⇒ cmd" where
"snd (remove_left c) = None ⟹ pop_flatten' c = fst (remove_left c)" |
"snd (remove_left c) ≠ None ⟹ pop_flatten' c = Comp (fst (remove_left c)) (pop_flatten' (the (snd (remove_left c))))"
by simp auto
termination
  apply(relation "measure size")
   apply(simp)
  apply(simp add: remove_left_decreases)
  by (metis option.sel prod.collapse remove_left_decreases)

I don't know exactly, but my suspicion is that this is better for the simplifier because the unfolding is now guarded by a ⟹ condition. Apparently the simplifier is allowed to punch through the case of construct (?), which was thus my faulty assumption.
I then reproved my lemmas using this version, which all became massively simpler because I could use simp instead of having to custom design terms to be substituted, and in the end (after proving equality of pop_flatten and pop_flatten') substituted the simp-unfriendly version in there to get the final lemma. I guess this is not always an option but as my functions were pretty simple I did not have to change anything else.
(Thanks a bunch Manuel!)
Comment: The disadvantage of doing it this way is that the function will not be executable unless you then prove something like the original version as a code equation again. I would suggest using your original definition, deleting the offending rule from the simp set, and proving more convenient rules (like the ones you use as a definition now) as derived rules and add them to the simpset. That's what I usually do.


Counter exchanging limit and integral

Question: Background
I came across this answer on Math SE which claimed it made a lot of sense to switch limit and integral. In response I came up with the following counter-examples:

$\lim_{w \to 0} \int_0^\infty we^{-wt}\ dt = 1$ but $\int_0^\infty \lim_{w \to 0} we^{-wt}\ dt = 0$.
$\lim_{n \to \infty} \int_0^\infty \frac{t^{n+1}}{n!} e^{-t}\ dt = \infty$ but $\int_0^\infty \lim_{n \to \infty} \frac{t^{n+1}}{n!} e^{-t}\ dt = 0$.
$\lim_{n \to \infty} \int_0^1 n^3 t^n (1-t)\ dt = \infty$ but $\int_0^1 \lim_{n \to \infty} n^3 t^n (1-t)\ dt = 0$.
$\lim_{r \to \infty} \int_{-\infty}^\infty \frac{r(rx)^3}{(rx)^4-(rx)^3+1}\ dx = \lim_{r \to \infty} \int_{-\infty}^\infty \frac{y^3}{y^4-y^3+1}\ dy \approx 2$ and $\lim_{r \to \infty} \frac{r(rx)^3}{(rx)^4-(rx)^3+1} = \frac{1}{x}$ for any $x \ne 0$. [Newly added]

Unlike the claimed method in that post, the first three counter-examples have continuous limit functions.
The third has the advantage of having the integral over a finite interval, to show that interchanging is still not valid without additional assumptions on the function sequence.
The fourth uses exactly the same technique as the claimed method (with a discontinuous limit function) and also gives an integral that is constant and independent of the limit!
Of course, these examples do not satisfy the dominated convergence theorem in various ways.
Question
Do you have any good counter-examples that actually show up in real-world problems and have an experimentally measurable implication for the real world? I somehow get the impression that the functions in the real-world might be too nice (wave functions are infinitely differentiable when you really factor everything in; in particular there are no such things as square potential wells because it is impossible to have a discontinuous change in potential!) I would be satisfied with examples in classical mechanics if the effect is measurable.
Answer: Consider the retarted propagator of a  free right moving quantum mechanical particle with linear dispersion
$$
G(\omega,k,\delta)=\frac{1}{\omega-vk+i \delta}
$$
(the $+i \delta$ is there for causality reasons and have set to  be $0$ in the end (in a limiting procedure))
Calculating the corresponding density of states requires the calculation of $\rho(\omega)=\int_{\mathbb{R}} dk G(k,\omega)$ which only makes sense if we calculate it like
$$
\lim_{\delta\rightarrow 0}\int_{\mathbb{R}} dk G(k,\omega,\delta)
$$
instead of
$$
\int_{\mathbb{R}} dk \lim_{\delta\rightarrow 0} G(k,\omega,\delta)
$$
(the second quantity clearly diverges). The reason is that we are handeling quantities which are strictly speaking only defined in a distributional sense.
Comment: There are many examples in theoretical physics where the model calculation leads to an expression (say an integral or a sum), which in a mathematical sense is not strictly defined. However based on the validity of the model, it can often be argued that the expression must exist. It is then common to make some reasonable assumption. E.g. the spectrum must have a cut-off value, or there is small convergence factor. This step validates the computation and leads (hopefully) to an acceptable result. Pure mathematicians may frown at these procedures.
Comment: For example in Quantum Mechanics certain assumptions about particle interactions must be made, otherwise the model becomes too complicated. Yet these assumptions may result in a wave-function that does not have all the required properties. Physicist then routinely repair the wave-function in an ad-hoc manner. This process is called "regularization of  the wave-function".
Comment: Thanks, but unfortunately this propagated straight over my head. Do you happen to know a simpler example?
Comment: i think similar arguments have to be made if one wants to find the Green's function for Poisson's equation via fourier transform
Comment: @M.Wind: Sorry I don't buy any of those arbitrary cut-off stuff or regularization or renormalization.
Comment: @user21820 Then you are on my side!

Counter exchanging limit and integral


Renaming all files in one folder on Mac OS X Yosemite

Question: I have a folder containing dozens of files with no extension. I want to add .txt extension to each of the file. I don't want to rename every file by double clicking and renaming manually. Is there any shell command to perform it in bulk?
Comment: There's always a shell script option: `for file in *; do mv "$file" "$file.txt"; done`.  Mac OS X doesn't come with a `rename` command, so that's as good as it gets, and not really very hard.  You'd run that in a terminal; `cd /Users/yourname/the/sub/directory` and then run the script.  I assume you have `bash` (or `ksh`) as your login shell.  The notation shown is not valid in C shell (`tcsh`).
Comment: Do not destroy questions that have answers.  Consider improving the question instead.
Answer: OS X 10.10 and above has multi-file rename built into the Finder.
Using Finder:

Select the files
Ctrl-click on one of the selected files
Choose "Rename N items..." from the menu
In the sheet that opens, click on "Replace Text" and choose "Add Text" from the menu
Enter the extension you want (e.g. .jpg)
Press the "Rename" button
Comment: Interesting — I had not noticed that before.  Thanks.
Answer: using find command
find <path to folder> -type f  -exec mv {} {}.txt \;

<path to folder> # path to folder containing your files
-type f  # find all files
-exec mv {} {}.txt # rename all files and add a .txt extension
Answer: I use the rename utility. You can easily install it with Homebrew:
brew install rename

then the syntax for achieving what you want would be:
rename 's/$/.txt/' *

if you want to check what would happen first, run
rename -n 's/$/.txt/' *