Show the isomorphism $X/\{0\} \cong X$

Question: $X/\{0\}$ is the set of singletons of $X$ so we define a mapping $T(x) = x$. Since $\{0\} \subseteq \ker T$ we have a linear mapping $\hat{T}:X/\{0\}\to X$.
But $\{0\}$ is exactly equal to $\ker T$ so $X/\ker T \cong ran T = X$ since the mapping is surjective.

Does this make sense?
Comment: Yes, it does. And it is correct.
Comment: @freakish you're right. If you could make a brief answer to that effect, it would help resolve this post.
Comment: Minor nitpick: I think you should explicitly say that $T:X\to X$. That is, "we define a mapping $T:X\to X$ by $T(x)=x$."
Answer: So yes, your reasoning seems to be correct. Although it took me a while to fully understand what you are doing here. So let's make it rigorous (for example by giving explicitely domains and codomains of each map).
Let $X$ be a group/ring/module/linear space (or anything that has an analogue of the first isomorphism theorem). Define
$$\mbox{id}:X\to X$$
$$\mbox{id}(x)=x$$
The famous identity map. Now this map is a homomorphism. Therefore by using the first isomorphism theorem we obtain an isomorphism
$$\overline{\mbox{id}}:X/\ker(\mbox{id})\to\mbox{id}(X)$$
$$\overline{\mbox{id}}(x\ker(\mbox{id}))=x$$
Since $\ker(\mbox{id})=\{0\}$ and $\mbox{id}(X)=X$ then this gives us an isomorphism
$$\overline{\mbox{id}}:X/\{0\}\to X$$
Comment: Thanks, I was using the same theorem but forgot it's name.

Show the isomorphism $X/\{0\} \cong X$


Invalid Image Path - No image found

Question: I'm getting the following error when I'm trying to upload my project into AppStore.
frist issue

Invalid Image Path - No image found at the path referenced under key 'CFBundleIcons': 'icon-76'

second issue

your binary is not optimised for iPhone - 5 - new iPhone apps and app updates submitted must support the 4-inch display on iPhone 5 and must include a launch image with the -568h size modifier immediately following th  portion of the launch image's filename. Launch images must be PNG files and located at the top-level of your bundle, or provided within each .Iproj folder if you localise your launch images. Learn more about iPhone 5 support and app launch images by reviewing the 'iOS Human interface guidelines' at 'https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/mobileHIG/Iconimages/IconImages.html#//apple_ref/doc/uid/TP40006556-CH14_SW5' and the 'IOS App Programming Guide' at 'https://developer.apple.com/library/ios/documentation/iphone/conceptual/iphoneOSProgrammingGuide/App-RelatedResources/App-RelatedResorces.html#//apple_ref.doc/uid/TP40007072-CH6-SW12

Any help on this is appreciated. Thanks.
Comment: what is your question? everything was clearly phrased on the screenshot you attached. you have to solve those issues, **(1)** adding the missing icon, **(2)** supporting iPhone5 screen size – link for guidelines attached to the error message.
Comment: maybe you haven't included app icon for and splash screen and images for iphone 5. your app is compatible for iphone 5?
Comment: My eyes are too old, and I can't read that even with my glasses. Perhaps you should add the error to the question in text format. Text format will also allow future visitors to search for it.
Comment: @jww: I have edited his question :)
Comment: @jww, you can open the image separately and you can zoom in. :)
Comment: There is no missing icons and no CFBundleIcons in my plist. But the same problem.
Answer: Go to Supporting Files -> yourproject-info.plist file, under the Icon Files -> click the down arrows and cross check the icon names and bundle icon file names.
Adding the required images and Removing the unwanted ones from your project and info.plist will easily fix this issue.
If the image exists, make sure that this image is a members of target you are building.
Answer: Well I have faced the same issue and found the solution by adding the email@example.com file at the root level As show in the image
Answer: I got the same issue.I don't think you answered the question correctly.

I'm using Images.xcassets for the AppIcon. All the sizes are included. Even the one reported missing. And there is no CFBundleIcons in my Info.plist.
I even don't use Launch images in my project. Instead I'm using LaunchScreen.xib file as the launch screen.

Invalid Image Path - No image found


Find the probability that no rock noise will be recorded for at least $30$ minutes.

Question:
Rock noise in an underground mine occurs at an average rate of three per hour. Find the probability that no rock noise will be recorded for at least 30 minutes.

I was able to get the density function for it as
$f(x)=3e^{-3x}.$$ How do I get the probability?
Is this a Poisson Distribution or Exponential?
Comment: As to your question about Poisson versus exponential, the Poisson would be used to model the **number** of events in given time. The exponential would model the waiting time for an event. Either can be used to find a correct solution  to the problem.
Comment: It sounds like you are dealing with a [_Poisson process_](https://en.wikipedia.org/wiki/Poisson_point_process). It turns out the you can consider the problem with respect to time _or_ the number of arrivals. There are many more details. It turns out that there is a particular relationship regarding the first arrival I detailed in my answer.
Comment: Integrate. More simply, you could have worked just with the Poisson distribution.
Comment: @AndréNicolas is this the one i need to find? P[X>=1/2]
Comment: Yes, that's it.
Comment: There is nothing in the question to suggest any distributional assumption whatsoever. All that is provided is an average.
Answer: If the average is $3$ per hour, then the time to the first arrival has density
$$f_X(x) = 3\exp\left\{-3x\right\}.$$
Further, the question asks $P(X> 30\text{ min}) = P(X> .5\text{ hr})$. Compute this using the usually integration.
Warning!
This is correct if you logic is that the time to the first arrival follows an exponential distribution. Otherwise, recognize that you are dealing with a Poisson distribution.
In other words,
$$A = \{\text{First arrival after 30 mins}\}\iff B =\{\text{Number of arrivals in 30 mins is zero}\}.$$
Hence
$$P(A) = P(B) = e^{-\mu t}\frac{\mu^0}{0!} = e^{-3(.5)} = e^{-1.5}=0.2231302.$$
Comment: Why is it Exponential or Poisson? There is nothing in the question to suggest any distributional assumption whatsoever. All that is provided is an average.
Comment: @wolfies Yeah, you're justified in your concern...... but it's an exercise. Most likely from a section called Poisson distribution or Exponential distribution or the like. We have to assume, otherwise it is not solvable.
Answer: Use the Poisson distribution with $\lambda = 1.5$ for a half hour period.
Then, it's just  $P(0) = e^{-1.5}$
Comment: Is this a Poisson distribution ?
Comment: The exponential distribution and the Poisson distribution are closely related, and one can often use the simpler of the two, as we can here. You can read about the relationship between them in more detail on many answers on this site.


How I Use Microsoft Web Platform Installer offline?

Question: I have a server that's behind a Windows 2012 firewall without Internet access. I need to install PHP on it, and would prefer to use the Web Platform Installer if possible. I can't find any recent information on how to do this, save for this article:
http://www.ca.com/us/support/ca-support-online/product-content/knowledgebase-articles/tec1193892.aspx
When I run the first part, I am able to generate a dump file; however, the file is only 1k and is not readable. As the WebPICMD runs I can see the list being output the screen very quickly, but for some reason it doesn't make it to the file..
C:\Program Files\Microsoft\Web Platform Installer>WebPICMD.exe /List /ListOption:All>C:\temp\dump.txt
Any feedback on this?
Comment: You can install 5.6 from it. We are doing product development and trying to keep stuff standardized if we can. What I'm asking for is doable, just need updated instructions.
Answer: You can find update documentation for the offline features of web platform installer here
I was able to run the following on my laptop to download the offline install cache for PHP56. It automatically downloads all possible prerequisites.
WebPICMD.exe /Offline /Products:PHP56 /Path:C:\webpioff

You can copy this folder to the server without internet access, launch web platform installer and click the options link on the bottom. You can then browse to and select the file "C:\webpioff\feeds\latest\webproductlist.xml" as your primary feed. Or, in command line:
WebPICMD.exe /Install /Products:PHP56 /XML:C:\webpioff\feeds\latest\webproductlist.xml


How to run a multinomial logistic regression with mixed effects in R?

Question: I'm trying to run a multinomial logistic regression with mixed effects. Let's say I have the following variables:
Participant (ten participants, each with 10 observations)
Word (ten different words, each participant sees each once)
IV (some two level grouping variable)
DV (can be 1, 2 or 3)
How would I run a multinomial logistic regression with ppt and word as random variables?
Here is some sample data:
ppt <- rep(1:10, each = 10)
word <- rep(1:10, times = 10)
IV <- rep(1:2, times = 50)
DV <- sample(x = c(1,2,3), size = 100, replace = TRUE)

d <- as.data.frame(cbind(ppt, word, IV, DV))

Comment: The package `mclogit` seems to provide this functionality.
Answer: I think one way to do this is with the glmnet package,

glmnet: Lasso and Elastic-Net Regularized Generalized Linear Models.
Extremely efficient procedures for fitting the entire lasso or elastic-net regularization path for linear regression, logistic and multinomial regression models, Poisson regression, Cox model, multiple-response Gaussian, and the grouped multinomial regression.

You need to install glmnet and its dependencies first, and R compiles a lot of C/C++ code to do this.
ppt <- rep(1:10, each = 10)
word <- rep(1:10, times = 10)
IV <- rep(1:2, times = 50)
DV <- sample(x = c(1,2,3), size = 100, replace = TRUE)

d <- as.data.frame(cbind(ppt, word, IV, DV))

# basic usage:
library(glmnet)
fit <- glmnet(as.matrix(d[,1:3]), d$DV, family = "multinomial")
summary(fit)

Maybe ask this at stats.stackexchange.com, the real experts are over there.
Comment: `glmnet` to my knowledge does not incorporate random effects, and it tries to remove variables which would not be a good idea in this (and most other) context.
Comment: Binary logistic regression is easier to do than multinomial logistic regression, and binary regression requires 96 participants just to estimate the overall intercept.  So I don't know how this project is going to work with 10 participants.  Categorical outcome variables have minimum information.
Comment: Thanks I was indeed not sure. That question was asked in a different forum, and the example was a toy example.


Android application compatible with IMAP search without using local index?

Question: I use an email account of several dozens of Giga, on computer and Smartphone.
However, most applications use a local index to speed up the search of emails (this is the case of Outlook and Thunderbird on computer).
However, on a cell phone, the memory/battery/performance does not allow to have a correct index when the mailbox is too big, and the applications are often limited to propose a search on the last weeks.
However, my IMAP server is compatible with the Full Sring search (via Apache Solr) very quickly.
Do you know a mobile application, allowing to deactivate the local search, to make an instant search via IMAP ?
Comment: Did you ever find an answer to the?
Comment: Outlook, Gmail, Samsung Email and BlueMail already tested not using IMAP search
Comment: Software and app recommendations should better be posted to  https://softwarerecs.stackexchange.com as they are not server related.
Answer: A set of features useful for (mostly: bandwidth and storage) restricted environments is dubbed the "Lemonade" profile and documented in RFC 5550. Efficient search without downloading is a major consideration, but do not be too quick to assume it is the only feature necessary to make mailing on the go a pleasant experience.
We do not do recommendations here, but afaik there are now multiple clients that implement some or many of the relevant features, and the keywords mentioned in that RFC (title) will help you tailor your search.


Binding EF to DataGrid in WPF

Question: I'm new to EF and struggling with a problem.
I have a WPF app, which contains DataGrid. Let's say it contains list of Products and additional info, so the class looks like
class Product
{
    public Product()
    {
        products = new ObservableCollection<Product>();
    }

    public int ProductId (get; set;}
    public string Name {get; set;}
    public string Supplier {get; set;}
    public virtual ObservableCollection<Product> products {get; set;}
}

Now I wanted to bid this class to grid, so it automatically updates database when someone adds/edit row (or delete with context menu)
So in xaml there is ItemsSource = "{Binding}" (writing from memory, excuse small mistakes)
Then I've binded every column to exact property in the class Product.
OnLoad method uses database context and goes like this
Product product = new Produxt();
Datagrid1.DataContext = ctx.Product.products.ToList();

And it shows all the records properly, but then, if I add or edit records, it doesn't affect database :(
I've read that ToList breaks connection with EF, that's why I can't add/edit, but there wasn't any working fix for that. Any ideas?
By the way, where do I put methods for example ShowAllProductsForCustomer(int id)? Do I put them in Products class?
Answer: try this
ctx.Product.products.Load();
//create a bindings source on your form, then use it here
myBindingsSource.DataSource = ctx.Product.products.Local.ToBindingList();
//this can also be done in the properties of the grid on the form
Datagrid1.DataSource = myBindingsSource;

I'm doing something similar.
just have to execute the SaveChanges(); method of your context to update the db.
Answer: This is actually pretty simple, and if you want, you can bind the data very easily.
Try this:
    private void FillData()
    {
        var q = (from a in ctx.Product
                 select a).ToList();
        Datagrid1.ItemsSource = q;
    }

I have wrote this off the top of my head, but hopefully you get the gist of what you are trying to do.
Regards,
G.

Binding EF to DataGrid in WPF


Without using Spring ACL, implementing a method level security check based on "creator" of an entity

Question: Like many others have noted, the ACL seems like overkill for executing such a conceptually simple thing in a case like this.
I am looking for a simple implementation of the following scenario in Spring Security:
I have a method in a controller which handles a delete request for an event entity. I need the @PreAuthorize expression that will check to make sure that the ID of the user submitting the request matches the ID of the owner of the request. Perhaps through an Event.getOwner().getId() method.
How would this look? Thanks.
I'm thinking something like. The following method in the Event controller:
 @PreAuthorize("#event.getOwner().getId() == authentication.id")
 public void delete(@PathVariable("id") final Long id, @RequestBody final Event event) {
    repo.delete(id, event);
}

And if this is the correct use, where does #event come from? In other words, what is signified by the '#'? I ask because at this point we are in the controller, so, which Event is #event referring to?
Answer: Your idea is not safe. It requires that the event information including owner is sent as request body in the delete request. With this the client can spoof the owner to be of the current user instead of the actual owner.
Assuming that id is the unique id of an event, I would suggest something like the following as a minimal solution:
@RequestMapping(value="/{id}", method=RequestMethod.DELETE)
@PreAuthorize("@repo.getOwnerOfEvent(#id) == authentication.name")
public void delete(@PathVariable("id") final Long id) {
    repo.deleteEvent(id);
}

The above snippet requires a bean named "repo" that contains the method:
/**
 * Returns the owner username of the event with the specified id.
 */
String getOwnerOfEvent(long id);

Comment: @TylerDurden Yes, the important thing is to read the owner from the database. Regarding ACL:s you have pretty much already stated the pros and cons ...
Comment: So essentially, the database layer is the definitive gatekeeper in your scenario, because there is no direct entry point for a client to spoof the eventOwnerID upon sending the request. Instead, the eventOwnerID is definitively checked ONLY by the dto repo. Correct?
Comment: Also, I'd like to ask you a second question since you've just given me a great solution. What is your opinion on building with a setup like you've suggested vs. use of a full on ACL system (which seems to be the standard textbook option, very scalable, but obviously may be complicated overkill for such a simple check that will only be authorized against 3 or 4 methods at most)?
Comment: Hey @holmis83 could you check out another quest I have on ACL implementation? Thanks http://stackoverflow.com/q/43619171/7691083


Facebook PHP SDK retrieve current location of user

Question: So far I have tried:
$facebook->api('/me', 'get', array("fields"=>"location"));

Which returns:
Array ( [location] => Array ( [id] => 107847249250173 [name] => Cambridge, Cambridgeshire ) [id] => 1234567890 )

If I have the necessary permissions, how could I echo just the [name] bit (so the output is "Cambridge, Cambridgeshire") in a format that could be inserted into a database?
Comment: Why can't you just access that key in the array? `$loc_name = $output['location']['name'];`
Answer: $data = $facebook->api('/me', 'get', array("fields"=>"location"));
echo $data['location']['name'];

Comment: While the question does ask how to echo the location name, it says that the goal is to acquire the name in order to insert it into a database, so actually using `echo` here isn't entirely correct. Regardless, +1.
Comment: @Vulcan yes agreed with you.


How to calculate the size of a control without rendering it

Question: I wanna create a view not in xaml but in c# with vertical and horizontal options set and get its size without rendering it or adding it to a content page. I know that I can't calculate the size of a view unless we add it to a layout but that also doesn't work because It wasn't rendered.
In conclusion, Xamarin doesn't set the bounds of a view unless It's rendered.
Answer: You can MeasuredHeight property which can help you in your scenario.
<code>var textView = new TextView(this);
textView.Text = "Hello";
textView.Measure(0, 0);
int height =  textView.MeasuredHeight;
int width =  textView.MeasuredWidth;
</code>


VB Classic Windows Service says UNC file does not exist, works on 2nd server

Question: I have a VB Classic Windows service on two different 2008 Servers that access the same folder on a 2012 Server.  Both 2008 servers are configured the same (something's probably not) running the same application software.  One application can access the UNC files fine, the same application on the other server says the file doesn't exist and always returns false using objFSO.Exists(UNCfilename).  I can't see the difference in the servers and have exhausted places to look.  Here's some more background:

Both services running as administrator
Running services in VB as administrator, one fails one doesn't
UNC Folders on 2012 are shared with Everyone, full control
All servers on same subnet
All servers running workgroup not domain
All Firewalls are off
I can see UNC folder and files using Windows Explorer on both servers
C# services running as administrator on both servers see the files (no, converting the VB service to C# is not an option)
Dir(UNCfilename) doesn't work either on the one server, does on the other

There must be a difference in the two 2008 servers but I don't know what it could be.  What have I missed?
Comment: When you're checking in Windows Explorer are you certain you're using the same users & permissions as what the VB software is running as?
Comment: It might be something like https://support.microsoft.com/en-us/kb/3035277
Comment: That article had promise but it was already set to elevate without prompting.  I've logged on as administrator and am running the app in VB as administrator.  When it runs as a service, I've set the user to administrator.
Comment: The key thing I once learned from that article is how Windows tokens work. In the situation I was dealing with, running as admin actually gave the process LESS access - because the drive had been mapped as an ordinary user instead of as admin, and admin didn't "inherit" the map without the registry change. This seemed totally counter-intuitive until I understood it. Maybe it doesn't apply in your situation however.
Comment: At this point, ANYTHING is worth looking at.   Your comments make sense. But to the best of my knowledge, we don't use any mapped drives.  However, I will definitely take a look at that.
Answer: Well, I found the solution... don't exactly understand why this was the only fix I found, but after all this time, I don't much care!
DaveInCaz's comments about mapped drives led me in the right direction.  We didn't have any but I wondered what would happen if we did.  I added the following code to the program:
<code>remoteUser = "Administrator"
remoteServerName = "CADERed5" 'The name of the 2012 server
myUNCPath = "\\192.168.100.4\c\Program Files (x86)\..."

Set NetworkObject = CreateObject("WScript.Network")
NetworkObject.MapNetworkDrive "", myUNCPath, False, remoteServerName & "\" & remoteUser, remotePassword
If objFSO.FolderExists(myUNCPath) Then
...
</code>
I had to use the credentials of the target (2012) server's administrator prefixed by the server's name.  Basically, I became that server's admin and it allowed me to read the files.


A quicker way to approach the indefinite integral $\int{\frac{x^3dx}{1+x^5}}$

Question: Problem:   Evaluate the integral $$\int{\frac{x^3dx}{1+x^5}}$$
Source: Given to me as a challenge. I can't seem to find a valid substitution for the integral. Also the way should be quick enough to apply in a timed test. I don't know the answer and I have almost given up. I called the challenger and he said that I can ask for help but not look up on Wolfram or any such website as it won't be a proper solution. I don't think it is solvable though :p
My try: Well, I have tried to get around by using many substitutions which make the thing more complicated than it already is. Also I'm looking for the QUICKEST way to approach this problem in case  it happens to meet me on a test.
Comment: $$\int \frac{x^3}{1+x^5}dx=\int\frac{\frac{1}{x^2}}{\frac{1}{x^5}+1}dx$$ Now let $\frac 1x=t$. To covert it to $$-\int \frac{1}{t^5+1}$$This is the first thought came to me, I too don't know how to proceed further.
Comment: @YourAverageEuler lol it dosent deserve even an hour of yout life
Comment: Every rational function is integrable.
Comment: Nah I just phoned the guy and said I'm out...I already looked up the answer now and I was happy to see it...That guy just wasted 2 days of my life for this inhumane problem!
Comment: Are you able to integrate functions of the form $\frac{1}{\alpha-x}$? Well, then apply a partial fraction decomposition. The integrand function is a meromorphic function with simple poles at $-1$ and at the primitive tenth roots of unity.
Comment: With all due respect, I'm quite sorry to say that I didn't get a single thing you said..after all I'm a high school student!
Comment: The answer to this is an absolute nightmare. I'm not sure I could even figure out how to get the closed form solution.
Comment: @YourAverageEuler: in such a case, don't care about it. Something like that will not appear on your test.
Comment: Hope I could look it up...I think it would be a bunch of logarithms and inverse trig functions maybe $arcsin$
Comment: @YourAverageEuler: logarithms and arctangents, given by the primitives of $\frac{1}{x+1}$ or $\frac{1}{x^2+1}$ and similar objects. *Why* has been explained.
Comment: So should I just give up, gosh I would've won that cash! But for the love of math, we'll figure it out.
Comment: You will get a solution using partial fractions: http://www.wolframalpha.com/input/?i=x%C2%B3%2F(1%2Bx%E2%81%B5)+partial+fraction , but these things become messy to integrate, the first 2 terms will have an arctan primitive and the last term will have a logarithmic primitive. I don't think this is something to expect on a test, but as an exercise it might be worth it.
Comment: Partial fraction ... not sure this will be best ? https://www.wolframalpha.com/input/?i=partial+fractions((x%5E3)%2F(1%2Bx%5E5))
Comment: it's too much to calculate, isn't it? Another approach other than partials? Anyone?
Comment: there is no other Approach since the Integrand is a rational function
Comment: and we get a rational function again
Comment: So can we render this unsolvable for the average mathematician? I'll keep the post open for suggestions.
Comment: should i post the answer for you?
Comment: @YourAverageEuler Not too fast. At least wait for a day, even then if there isn't any simple answer, then come to this conclusion.
Comment: @YourAverageEuler  seems like you are a Indian JEE aspirant
Comment: Cf. the similar integral here: https://math.stackexchange.com/questions/3135455/evaluating-indefinite-integrals-of-the-form-int-fracx2-dxa-x5-b
Answer: Hint: $1+x^5$ factors as
$$(1+x)(1-x+x^2-x^3+x^4) = (1+x)(1 + ax + x^2)(1 + bx + x^2)$$
for appropriate $a, b$.  Then use partial fractions.
And this is NOT an appropriate question for a timed test.
Comment: With $a=-\phi$ and $b=\phi-1=\dfrac{1}{\phi}$ where $\phi$ is the golden ratio. Definitely not appropriate for a timed test. One can eliminate the $x^3$ in the numerator by the substitution $x=u^{-1}$.
Comment: Will use the approach when I'll have time. Thanks! And yeah it's tedious and boring actually, just mind bending calculations
Answer: Note that
\begin{align}
K(a)&= \int \frac{1-a t}{t^2-2a t+1}dx\\
&=-\frac a2 \ln(t^2-2a t+1)+\sqrt{1-a^2}\tan^{-1}\frac{t-a}{\sqrt{1-a^2}}
\end{align}
$$\frac5{t^5+1}=\frac1{t+1}+\frac{2(1-t\cos\frac\pi5)}{t^2-2 t\cos\frac\pi5+1}+ \frac{2(1-t\cos\frac{3\pi}5)}{t^2-2t \cos\frac{3\pi}5 +1}
$$
and
\begin{align}
\int \frac1{t^5+1}dt&= \frac15\ln(t+1) +\frac25K(\cos\frac \pi5) +\frac25K(\cos\frac {3\pi}5 )
\end{align}
Then, with $x=\frac1t$
$$\int \frac{x^3}{x^5+1}dx= -\int \frac1{t^5+1}dt
$$


How to clear Text in search box once the user selects other option

Question: I have created a view for to search my channels. But when user searches for a specific channel, and when he clicks any other option or on any other event,he redirects to other page but text in search box is not cleared,what i want is, the text in search box should get cleared once he clicks on other option.How can i do this??
Answer: I think you can do it in 2 ways:

You can use javascript to clear the value of textfield after
page load or on click.
You need to rewrite field or rebuild form when option changes.

It`s all that i can say without some code.
Answer: You can reset the value of search box with Javascript when page get ready. Create a simple custom module and create a js file in that module. Something like:
<code>//custom.js
(function($, Drupal, window, document, undefined) {
  $(document).ready(function(){
    $('SEARCH-FROM-INPUT').val('');
  });
})(jQuery, Drupal, this, this.document);
</code>
Attach this file to the pages those have that search form.
<code>function custom_form_alter(&$form, &$form_state, $form_id){
  if ($form_id == 'SERCH_FORM_ID') {
    $form['#attached']['js'] = array(
      drupal_get_path('module', 'custom') . '/custom.js' => array(
        'type' => 'file',
      ),
    );
  }
}
</code>
Update: updated code as per @Andy comment, adding js with '#attached' property
Comment: You should use [`#attached`](https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#attached) in this situation to add the JS to the form.
Comment: Also that JS won't necessarily play nicely with other modules (for example if you did anything AJAXy, the search query would suddenly disappear). You should write attach handlers such that they can be called multiple times (and you can't know when) without causing problems. Typically [`.once()`](https://www.drupal.org/node/756722#jquery-once) is used for this.
Comment: How to add JS to the form? Can you please edit the code?
Comment: @Tejaswini: I updated the code. You could do it yourself. Have a look at `#attached` form property. https://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7#attached
Comment: That how can i know. That is your views specific. Here `SEARCH-FORM-INPUT` is the jquery selector for your form's input field. And `SEARCH_FORM_ID` is your views exposed from id. Views exposed form id are in form of `views-exposed-form-VIEWS-MACHINE-NAME-VIEWS-DISPLAY-NAME`, Normally views machine name and views display name have `underscore(_)` in their name, remove those `underscore(_)` with `hyphen(-)`. Or use `dpm($form_id)` on first line in `hook_form_alter()` it will print the `form_id` of your exposed form.
Comment: I got SEARCH-FORM-INPUT for search form and module is working fine now.Thanks!


Extract object name as String from an object in JavaScript

Question: I have an object where its values are other objects
I would like to extract the name of the object by its parent key as a string, e.g., (input, expected output) = ('home', 'someObj), ('anotherOne', 'anotherObj').
So far I tried the following, but it returns [object Object].
I also tried JSON.stringify(data[key].key1) but does not return what I want. Is there a way to achieve this?

const someObj = {
  something: 'la'
}
const anotherObj = {
  something: 'be'
}

const data = {
  'home': {
    key1: someObj
  },
  'anotherOne': {
    key1: anotherObj
  }
}
console.log(data)

const key = 'home'
const output = `${data[key].key1}`

console.log(output) // expected output: 'someObj'
Comment: `someObj` is the name of the original variable, not the name of an object or anything else. That information isn't stored anywhere. This is probably an [XY problem](http://xyproblem.info/) so you might want to ask how to solve the actual problem instead.
Comment: No, that's not possible.
Comment: I think this might have a solution to your problem: https://stackoverflow.com/questions/4602141/variable-name-as-a-string-in-javascript
Comment: `Object.keys(data).flatMap(k=>[k, Object.values(data[k]])).join(',')`
Answer: Javascript objects don't have names. You'd have to take care yourself and probably add a 'name' field where you set an identifier on an object instance.
You hope, that the 'name' of the object could be like the name of the variable that you assign it to. But that's not true. There is zero connection between the object instance and the variable name.
Answer: The problem is that you are assigning the variable value and not its name. Because JS compiler will not keep track of the variable name that it used to assign values to
so,
const someObj = {
  something: 'la'
}
const anotherObj = {
  something: 'be'
}

const data = {
  'home': {
    key1: someObj
  },
  'anotherOne': {
    key1: anotherObj
  }
}

JS compiles it as
const data = {
  'home': {
    key1: {
     something: 'la' // Doesn't keep track of the original variable name used to assign value.
    }

  },
  'anotherOne': {
    key1: {
     something: 'be'
    }
  }
}

And when you fetch data[key].key1. it returns {something: 'la'} which is an object and when you use string template literal `${data[key].key1}`. It typecast it into string as
`${{}}` // Outputs "[object Object]"

So, you need to store the variable names as string
const someObj = {
  something: 'la'
}
const anotherObj = {
  something: 'be'
}

const data = {
  'home': {
    key1: 'someObj'
  },
  'anotherOne': {
    key1: 'anotherObj'
  }
}
console.log(data)

const key = 'home'
const output = `${data[key].key1}`

console.log(output) // output: 'someObj'

This code will work
You need to set the variable name as string.


Google App Engine — Allow customers to connect their domain to my website builder app

Question: I have a website builder on GAE which is successfully connected to my domain (example.com). A customer designs a website and connect it to his domain (customer.com). From programming side everything is alright (i.e. if customer.com hits my web application, the correct website displays).
But the problem is that GAE doesn't support static IP and I don't know how customers can set a DNS A record to point their domain to my application. Even CNAME doesn't work (i.e. landing.customer.com CNAME example.com outputs google's 404 error page).
So any solution for such a scenario?
Comment: The CNAME is the solution.
Comment: @womble - That is correct if the domain is verified by Google and the domain name is added to App Engine. Only specifying a CNAME will not work as the GFE (Google Frontend) will not know about the custom domain name mapping.
Answer: You will need to add the domain name as a verified domain and add the domain name to App Engine.
This article covers the steps in detail:
Mapping Custom Domains
If you skip the steps in the article and only add the A and CNAME records, the Google Frontend (GFE) will not know about the custom domain name mapping. The GFE uses the HTTP Host header to map domain names to App Engine services.
App Engine does support A and AAAA DNS resource records so that you can map the root domain to App Engine (example.com) and CNAME for subdomains (www.example.com).
Comment: The problem is that I want this process to be automatic or from DNS configuration as I can't repeat that process for 1000 domains (customers) who wants to link their domain to their website.
Comment: Your requirement does not change my answer. You can write your own software using Google APIs to do most of it. The validation of domain ownership must be done in the console. Therefore, your requirements are not supported by Google Cloud App Engine for custom domain mapping. Once you have verified domain ownership, you can do everything else via APIs.


Python not printing newline

Question: I have script that seems to have stopped working after my latest upgrade. To find the problem, I wrote a little script:
import subprocess

hdparm = subprocess.Popen(["xargs","echo"],
                stdin=subprocess.PIPE)

hdparm.stdin.write("Hello\n")
hdparm.stdin.write("\n")
hdparm.stdin.close()
hdparm.wait()
quit()

This just prints "Hello" and a new line, but I expect two newlines. What's causing this? (I am using 2.7.3 at the moment)
EDIT: Here is the problematic script (edited for clarity):
hdparm = subprocess.Popen(["hdparm", "--please-destroy-my-drive", "--trim-sector-ranges-stdin", "/dev/sda"],
               stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
hdparm_counter = 0
for rng in ranges_to_trim:
    hdparm.stdin.write("%d:%d\n" % (rng["begin"],rng["length"]))
    hdparm_counter += 1
    if hdparm_counter > 63:
         hdparm.stdin.write("\n")
         hdparm_counter = 0
if hdparm_counter != 0:
    hdparm.stdin.write("\n")
hdparm.stdin.close()
hdparm.wait()

EDIT: I believe the problem is with my script itself. I need to send EOF to hdparm to make it do whatever it is supposed to.
Answer: From the xargs man page:

This manual page documents the GNU version of xargs.  xargs reads items from the standard input, delimited by
  blanks (which can be protected with double or single quotes or a backslash) or  newlines,  and  executes  the
  command (default is /bin/echo) one or more times with any initial-arguments followed by items read from stan‐
  dard input.  Blank lines on the standard input are ignored.

(emphasis added).
Also, to add -- the newline you see is from echo itself.  xargs doesn't pass it along anyway.
Comment: The problem is that I actually pipe this to `hdparm --trim-sector-ranges-stdin` which has the same effect. Until recently, the newline character was piped correctly and everything worked. I did a system update, and now hdparm receives a huge line of ranges to trim that it cannot process.
Comment: It might be useful if you update the question with this information then so we can see what exactly you're doing for that case.
Comment: I added the script that is giving me trouble

Python not printing newline


How to infer a DateTime from a quarter string?

Question: I have the following dateframe column Time Period. In the column I have mixed time periods, with a unique list as follows, with the time initially recorded as quarterly and then switching to monthly.
Time Period
2018 Q1
2018 Q2
2018 Jul
2018 Aug
2018 Sep
2018 Oct
2018 Nov
2018 Dec

I am attempting to set the above to_datetime using the Pandas to_datetime function.
Code
 year_data['Time Period'] = pd.to_datetime(year_data['Time Period'])
However, 2018 Q1 and  2018 Q2 are producing the following error - valueError: ('Unknown string format:', '2018 Q1')
What I was hoping to achuieve is the following.
Time Period
01/03/2018
01/06/2018
01/07/2018
01/08/2018
01/09/2018
01/10/2018
01/11/2018
01/12/2018

Any help could be greatly appreciated.
Answer: Periods are by default parsing by first month, only necessary replace empty string to -:
year_data['Time Period'] = pd.to_datetime(year_data['Time Period'].str.replace(' ', '-'))
print (year_data)
  Time Period
0  2018-01-01
1  2018-04-01
2  2018-07-01
3  2018-08-01
4  2018-09-01
5  2018-10-01
6  2018-11-01
7  2018-12-01

But is possible add 2 months for values parsed from quarters:
m = year_data['Time Period'].str.contains('Q')
year_data['Time Period'] = pd.to_datetime(year_data['Time Period'].str.replace(' ', '-'))

year_data.loc[m, 'Time Period'] += pd.DateOffset(months=2)

Last for custom format in strings DD/MM/YYYY use Series.dt.strftime:
year_data['Time Period'] = year_data['Time Period'].dt.strftime('%d/%m/%Y')
print (year_data)
  Time Period
0  01/03/2018
1  01/06/2018
2  01/07/2018
3  01/08/2018
4  01/09/2018
5  01/10/2018
6  01/11/2018
7  01/12/2018

Comment: Nice solution, but OP wants `2018 Q1` to be `2018/03`.


How to I Add In Degree Symbols to Temperatures in a Javascript String?

Question: I have a string that was returned from an API, and I want to add in degree symbols from the temperatures that are included ("Tomorrow will be a high of 89F" → "Tomorrow will be a high of 89°F"). What would the Regex look like for my variable named forecastString?
Answer: This replace will work:
forecastString = forecastString.replace(/[0-9]{1,3}F/g, function addDegreeSymbol(x){return x.replace("F", "°F");});
forecastString = forecastString.replace(/[0-9]{1,3}C/g, function addDegreeSymbol(x){return x.replace("C", "°C");});

The Regex finds any numbers of 1-3 digits followed immediately by an F/C, and replaces the F/C with °F/°C
Answer: Why not
forecastString.replace(/\b(\d{1,3})(?=[FC]\b)/, "$1°");

? Are you sure about case insensitivity?
Comment: Was about to post the same, but I would add a `\b` in front of the numbers, otherwise the upper limit of 3 is useless. I think case sensitivity makes sense in this case, as the unit symbol is uppercase. On the other hand one might add a `\s*` behind the numbers to allow spaces.
Comment: The answer to "why not?" is because I'm a noob :)
Comment: @xd1936 I've updated the regex. I suggest you, if you want, the unicode symbols `℃` and `℉`.
Comment: @horcrux Man, this is why I posted here even though I thought I had a working solution. I had no idea there was a Unicode character for this! Awesome, thank you.
Comment: Ugh, please do not use the unicode character for this. `°` is part of of ascii (code `\xb0`) and pretty much guaranteed everywhere.
Comment: @naomik This string is eventually sent to Twitter. Can you think of a situation where a user is reading tweets on a device that isn't able to render `℃` and `℉`?
Comment: @xd1936 go crazy. I personally think the symbols look like garbage. And chances are, almost any font you use doesn't have a glyph defined for those code points.


Como atualizar/sincronizar o master do meu repositório no github com o master original

Question: Usando a linha de comando, como posso atualizar/sincronizar o meu master com o master original de onde fiz o fork.
Quais as maneiras diferentes e suas opções, qual a melhor, e de que maneira o histórico é afetado/registado.
Answer: O que eu costumo fazer é:
Primeiro, faço um fork do projeto original no Github (ex.: https://github.com/gatein/gatein-portal)
Depois, um clone do meu repositório no Github em minha máquina:
$ git clone firstname.lastname@example.com:jpkrohling/gatein-portal.git

Neste ponto, você tem um remoto chamado "origin". Então, adicione outro, chamado "upstream", que aponte para o original:
$ git remote add upstream firstname.lastname@example.com:gatein/gatein-portal.git

De tempos em tempos, sincronize:
$ git checkout master
$ git fetch upstream
$ git rebase upstream/master

Após fazer o rebase acima, meu master local fica exatamente igual ao master do upstream, precisando apenas atualizar a versão do github:
$ git push origin master

Eu tenho o costume de trabalhar apenas em tópicos (ie: a cada nova feature, um novo branch). Quando eu acabo o trabalho, envio este branch para o github:
$ git push

Então, do próprio github, eu faço um Pull Request dos commits no branch ao master do upstream. Meu master nunca recebe diretamente meus commits, o que facilita na sincronização, já que considero o master como um ponto de início para qualquer nova feature. Quando os commits do meu branch forem aceitos em upstream/master, eles chegam no meu master na próxima sincronização.
Comment: Muito boa a resposta, isso me ajudou muito.
Answer: Podes usar o Hub, Para executar uma pull request basta usar o comando:
git pull-request [-f] [-m MESSAGE|-F FILE|-i ISSUE|ISSUE-URL] [-bBASE] [-h HEAD]

Fonte: pull-request manpage:

Tambem podes usar o GitHub CLI
ghi pull-request [user] [branch]

Ou, usando o GitHub Gem:
gh pull-request [user] [branch]


How to compute the irreducible polynomial of a number

Question: Set $\alpha \in \mathbb{R}$ and $f=x^3+5x+1$ such that $f(\alpha)=0$. How could I compute the irreducible polynomial over $\mathbb{Q}$ of $\alpha ^2$? And of $\sqrt{3}\alpha$ ?
The problem is I am out of ideas since I don't know explicity $\alpha$.
Comment: You don't need to know explicitly $\alpha$. Note that $[\mathbb{Q}(\alpha):\mathbb{Q}(\alpha^2)] \leq 2$ (can you see why?) and that $[\mathbb{Q}(\alpha):\mathbb{Q}(\alpha^2)]$ divides $[\mathbb{Q}(\alpha):\mathbb{Q}]=3$ so it's one, and therefore the minimal polynomial of $\alpha^2$ has degree $3$. Now, just write $\alpha^4,\alpha^6$ in terms of lower powers of $\alpha$ and try to find a relation between them. Any relation will work.
Comment: What have you tried so far? Hint: you can use the fact that $\alpha^3+5\alpha+1=0$ to 'reduce' polynomials in $\alpha$. For instance, what can you say about $\alpha^6$?
Answer: We know that $\alpha^3+5\alpha+1=0$, so multiplying by $\alpha$ gives (letting $\alpha^2=b$) $b(b+5)=-\alpha$; squaring gives $b^2(b+5)^2=b$ or $b^3+10b^2+25b-1=0$. This is the minimal polynomial for $b$.
Now return to $f$ and multiply by $\sqrt3$ on both sides, giving (letting $\sqrt3\alpha=c$) $c^3/3+5c=-\sqrt3$. Again, squaring gives $c^6/9+10c^4/3+25c^2-3=0$, the minimal polynomial for $c$.
Answer: Hint: Let $\beta = \alpha^2$. Find the matrix of the map $x \mapsto \beta x$ in the basis $\{1,\alpha,\alpha^2\}$.
Comment: See also https://math.stackexchange.com/a/3860377/589


removing the 'title' field from custom content types

Question: I've created a content type to manage people, but in addition to the 'first name' and 'last name' fields that I've created, there's a 'title' field that seems to be present because its a Node module element.
Is there any way to, say, auto-fill it with something and hide it so that users who add content don't have to worry about it? It seems so redundant to have them fill out 'title' in addition to first name and last name.
Comment: can you please explain more on what you are trying do ?
Answer: You are looking for Exclude Node Title module

This module handles a very simple functionality, decide whatever to
  exclude a node title from full node page or node teasers. It provides
  a checkbox on node-edit pages for easier exclusion, or you can use the
  admin page to manually enter a list of node id's to exclude title.

Also provides the option to hide all titles of a certain Content type.
Answer: Looks like you need this automatic nodetitle. Please give a search in google before posting here.To prevent empty content title fields one can configure it to generate the title by a given pattern.


Counting TOTAL number of rows in the tables of a database

Question: I would like to know how to Count the TOTAL number of rows in the tables of a database. For example, I have 3 tables in a database called:
Table 1: 5 rows
Table 2: 4 rows
Table 3: 3 rows
So the output should be: 12 rows.
I know how to count rows in a specific table. Is there something to loop here?
Thanks.
Comment: https://dev.mysql.com/doc/refman/5.1/en/tables-table.html shows a schema table containing a rough count of the rows.  if you need an exact count, you could use data in the information schema to query each table and get the exact counts.
Comment: Thanks Rob. That worked out.
Answer: SELECT sum(cnt) AS overall_cnt
FROM (
    SELECT count(*) AS cnt FROM table1
    UNION ALL
    SELECT count(*) AS cnt FROM table2
    UNION ALL
    SELECT count(*) AS cnt FROM table3
) AS foo

Comment: No no. I mean what if I have like thousands of tables? Is there like a loop or something?
Comment: not in a regular query. you could build a stored procedure that queries the information schema tables and loop on those results.
Answer: SELECT sum(TABLE_ROWS)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME IN ('table1', 'table2', 'table3');

Answer: SELECT SUM(TABLE_ROWS)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'db_name';


Relatório de um objeto por vez com Jaspersoft Studio

Question: Tenho um sistema de notas avulso em jsf e primefaces. Eu consegui gerar um relatório conjunto de varias notas ao mesmo tempo, pesquisando através de dois parâmetros de entrada, data inicial e data final. Mas o que eu quero é gerar uma nota sem ter que informar nenhum parâmetro de entrada, o sistemas gera uma lista a partir de uma pesquisa das notas salvas e o usuário selecionar com o mouse a que ele que gerar e então é gerado o pdf.
Esse é o bean que gera o pdf
private Date dataInicial;
private Date dataFinal;`

@Inject
private LancamentoTributo lancamennto;
@Inject
private FacesContext facesContext;
@Inject
private HttpServletResponse response;
@Inject
private EntityManager manager;

public void emitir() {

    Map<String, Object> parametros = new HashMap<>();
    parametros.put("data_inicial", this.dataInicial );
    parametros.put("data_final", this.dataFinal );

    ExecutorRelatorio executor = new ExecutorRelatorio("/relatorios/nota_fiscal.jasper", response, parametros,
            "NTFSavemitida.pdf");

    Session session = manager.unwrap(Session.class);
    session.doWork(executor);

    if (executor.isRelatorioGerado()) {
        facesContext.responseComplete();
    } else {
        FacesUtil.addErrorMessage("Nenhuma nota emitida");
    }
}

@NotNull
public Date getDataInicial() {
    return dataInicial;
}

public void setDataInicial(Date dataInicial) {
    this.dataInicial = dataInicial;
}

@NotNull
public Date getDataFinal() {
    return dataFinal;
}

public void setDataFinal(Date dataFinal) {
    this.dataFinal = dataFinal;
}

public LancamentoTributo getLancamennto() {
    return lancamennto;
}

}

 Classe Executor

private String caminhoRelatorio;
private HttpServletResponse response;
private Map<String, Object>parametros;

private String nomeArquivoSaida;

private boolean relatorioGerado;

public ExecutorRelatorio(String caminhoRelatorio, HttpServletResponse
 response,Map<String, Object>parametros,
        String nomeArquivoSaida) {

    this.caminhoRelatorio = caminhoRelatorio;
    this.response = response;
    this.parametros = parametros;
    this.nomeArquivoSaida = nomeArquivoSaida;
    this.parametros.put(JRParameter.REPORT_LOCALE, new Locale("pt","BR"));
  }

@Override
public void execute(Connection connection) throws SQLException {

    try {
        InputStream relatorioStream = this.getClass().getResourceAsStream(this.caminhoRelatorio);

        JasperPrint print = JasperFillManager.fillReport(relatorioStream, this.parametros, connection);
        this.relatorioGerado = print.getPages().size() > 0;

        if (this.relatorioGerado) {
            Exporter<ExporterInput, PdfReportConfiguration, PdfExporterConfiguration,
            OutputStreamExporterOutput> exportador = new JRPdfExporter();
            exportador.setExporterInput(new SimpleExporterInput(print));
            exportador.setExporterOutput(new SimpleOutputStreamExporterOutput(response.getOutputStream()));

            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition", "attachment; filename=\""
            + this.nomeArquivoSaida + "\""); //Download automatico do pdf
            exportador.exportReport();
        }
    } catch (Exception e) {
        throw new SQLException("Erro ao executar relatorio " + this.caminhoRelatorio, e);
    }

 }

public boolean isRelatorioGerado() {
    return relatorioGerado;
}

Answer: Você pode utilizar JRBeanCollectionDataSource pasando a lista como parâmetro.
Ficaria mais ou menos assim:
InputStream relatorioStream = this.getClass().getResourceAsStream(this.caminhoRelatorio);
JRBeanCollectionDataSource ds = new JRBeanCollectionDataSource(suaLista);
JasperPrint print = JasperFillManager.fillReport(relatorioStream, this.parametros, connection, ds);
this.relatorioGerado = print.getPages().size() > 0;


Heartbleed testing tools do not recognize reissued certificates (PositiveSSL Wildcard + Amazon ELB)

Question: In response to the Heartbleed news, I have upgraded OpenSSL on my production server and am now trying to reissue the SSL certificate. I am using a PositiveSSL Wildcard certificate on an Amazon ELB.
I have followed the below instructions to reissue my certificate via Namecheap:
https://www.namecheap.com/support/knowledgebase/article.aspx/811
And have also added the new certificate credentials to my ELB:
http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/US_UpdatingLoadBalancerSSL.html
However, after doing this twice, the Heartbleed testing tools I'm using (http://possible.lv/tools/hb/, https://lastpass.com/heartbleed/) recognize that the upgrade has been made but continue to say that my certificate has not been re-issued and I may still be at risk.
Is there any additional work that needs to be done to make sure the reissued certificate is recognized?
I have tried deleting the original ELB and creating a new one from scratch with the new certificate, but no luck. I have noticed that the file modified date on the re-issued certificate file sent to me by Comodo has not changed from the date I purchased the certificate.
Thanks in advance.
Comment: It's probably Namecheap's fault. See [here](http://serverfault.com/a/587891/126632) and contact the issuer directly, bypassing them.
Comment: Are you sure you generated a new private key and CSR?
Comment: Yes, although I'm obviously missing something. Quick thought -- is the date of reissuance for an SSL cert public information? I can't seem to figure out what metric they're using to tell me the certs haven't been reissued. Would the expiration dates change?
Comment: Depends on your issuer. They could make it say whatever they want...
Comment: OK, thanks for your help. I have definitely followed the reissue process in the above links -- Comodo is the issuer via Namecheap. Really not sure where to go from here.
Comment: As a follow up -- Comodo insists the reissued certificates are correct and the testing tools I've been using are incorrect. We compared the modulus of the private key I generated and the newly signed certificate and they were equal, so I guess it's somewhere on the testing side.
Answer: This was my mistake. I misinterpreted the testing tool results. I confirmed this with the creator of the possible.lv tool, who has since revised the results for clarity.


Docker PHP-FPM Alpine with SQLSRV Driver Error

Question: I am getting this error when I try to connect to the sqlserver db:
Array ( [0] => Array ( [0] => IMSSP [SQLSTATE] => IMSSP [1] => -49 [code] => -49 [2] => This extension
requires the Microsoft ODBC Driver for SQL Server. Access the following URL to download the ODBC
Driver for SQL Server for x64: https://go.microsoft.com/fwlink/?LinkId=163712 [message] => This
extension requires the Microsoft ODBC Driver for SQL Server. Access the following URL to download the
ODBC Driver for SQL Server for x64: https://go.microsoft.com/fwlink/?LinkId=163712 ) )

My Dockerfile below:
FROM microsoft/mssql-tools as mssql
FROM php:7.2-fpm-alpine

COPY --from=mssql /opt/microsoft/ /opt/microsoft/
COPY --from=mssql /opt/mssql-tools/ /opt/mssql-tools/
COPY --from=mssql /usr/lib/libmsodbcsql-13.so /usr/lib/libmsodbcsql-13.so

RUN apk update \
&& apk add  --no-cache git mysql-client curl libmcrypt libmcrypt-dev openssh-client icu-dev
unixodbc-dev \
libxml2-dev freetype-dev libpng-dev libjpeg-turbo-dev g++ make autoconf \
&& docker-php-source extract \
&& pecl install xdebug redis \
&& docker-php-ext-enable xdebug redis \
&& docker-php-source delete \
&& docker-php-ext-install pdo_mysql soap intl zip \
&& pecl install \
    sqlsrv \
    pdo_sqlsrv \
&& docker-php-ext-enable --ini-name 30-sqlsrv.ini sqlsrv \
&& docker-php-ext-enable --ini-name 35-pdo_sqlsrv.ini pdo_sqlsrv \
&& echo "xdebug.remote_enable=on" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini \
&& echo "xdebug.remote_autostart=off" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini \
&& echo "xdebug.remote_port=10000" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini \
&& echo "xdebug.remote_handler=dbgp" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini \
&& echo "xdebug.remote_connect_back=0" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini \
#&& curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer \
&& rm -rf /tmp/*

CMD ["php-fpm", "-F"]

WORKDIR /var/www/cssp

EXPOSE 9000

It seems there is a problem with the installation of the driver
Has anyone tried this before? Please share. Thank you.
Answer: Try with below DockerFile
FROM microsoft/mssql-tools as mssql
FROM php:7.2-fpm-alpine

COPY --from=mssql /opt/microsoft/ /opt/microsoft/
COPY --from=mssql /opt/mssql-tools/ /opt/mssql-tools/
COPY --from=mssql /usr/lib/libmsodbcsql-13.so /usr/lib/libmsodbcsql-13.so

# Install language pack
ENV MUSL_LOCALE_DEPS cmake make musl-dev gcc gettext-dev libintl
ENV MUSL_LOCPATH /usr/share/i18n/locales/musl

RUN apk add --no-cache \
    $MUSL_LOCALE_DEPS \
    && wget https://gitlab.com/rilian-la-te/musl-locales/-/archive/master/musl-locales-master.zip \
    && unzip musl-locales-master.zip \
      && cd musl-locales-master \
      && cmake -DLOCALE_PROFILE=OFF -D CMAKE_INSTALL_PREFIX:PATH=/usr . && make && make install \
      && cd .. && rm -r musl-locales-master

# --- not show here---

# mssql odbc for dabase connection
RUN curl -O https://download.microsoft.com/download/e/4/e/e4e67866-dffd-428c-aac7-8d28ddafb39b/msodbcsql17_18.104.22.168-1_amd64.apk
RUN curl -O https://download.microsoft.com/download/e/4/e/e4e67866-dffd-428c-aac7-8d28ddafb39b/mssql-tools_188.8.131.52-1_amd64.apk
RUN apk add --allow-untrusted msodbcsql17_18.104.22.168-1_amd64.apk
RUN apk add --allow-untrusted mssql-tools_126.96.36.199-1_amd64.apk

RUN set -xe \
    && apk add --no-cache --virtual .persistent-deps freetds unixodbc \
    && apk add --no-cache --virtual .build-deps $PHPIZE_DEPS unixodbc-dev freetds-dev \
    && docker-php-source extract \
    && docker-php-ext-install pdo_dblib \
    && pecl install sqlsrv pdo_sqlsrv \
    && docker-php-ext-enable --ini-name 30-sqlsrv.ini sqlsrv \
    && docker-php-ext-enable --ini-name 35-pdo_sqlsrv.ini pdo_sqlsrv \
    && docker-php-source delete \
    && apk del .build-deps

Answer: If you're stuck with php 7.1 like I do now, here is the updated Dockerfile:
FROM mcr.microsoft.com/mssql-tools as mssql
FROM FROM php:7.1-fpm-alpine

ENV MUSL_LOCALE_DEPS cmake make musl-dev gcc gettext-dev libintl
ENV MUSL_LOCPATH /usr/share/i18n/locales/musl

COPY --from=mssql /opt/microsoft/ /opt/microsoft/
COPY --from=mssql /opt/mssql-tools/ /opt/mssql-tools/
COPY --from=mssql /usr/lib/libmsodbcsql-13.so /usr/lib/libmsodbcsql-13.so

RUN apk add --no-cache \
    $MUSL_LOCALE_DEPS \
    && wget https://gitlab.com/rilian-la-te/musl-locales/-/archive/master/musl-locales-master.zip \
    && unzip musl-locales-master.zip \
      && cd musl-locales-master \
      && cmake -DLOCALE_PROFILE=OFF -D CMAKE_INSTALL_PREFIX:PATH=/usr . && make && make install \
      && cd .. && rm -r musl-locales-master

# mssql odbc for dabase connection
RUN curl -O https://download.microsoft.com/download/e/4/e/e4e67866-dffd-428c-aac7-8d28ddafb39b/msodbcsql17_188.8.131.52-1_amd64.apk
RUN curl -O https://download.microsoft.com/download/e/4/e/e4e67866-dffd-428c-aac7-8d28ddafb39b/mssql-tools_188.8.131.52-1_amd64.apk
RUN apk add --allow-untrusted msodbcsql17_188.8.131.52-1_amd64.apk
RUN apk add --allow-untrusted mssql-tools_18.104.22.168-1_amd64.apk

RUN set -xe \
    && apk add --no-cache --virtual .persistent-deps freetds unixodbc \
    && apk add --no-cache --virtual .build-deps $PHPIZE_DEPS unixodbc-dev freetds-dev \
    && docker-php-source extract \
    && docker-php-ext-install pdo_dblib \
    && pecl install sqlsrv-5.6.1 pdo_sqlsrv-5.6.1 \
    && docker-php-ext-enable --ini-name 30-sqlsrv.ini sqlsrv \
    && docker-php-ext-enable --ini-name 35-pdo_sqlsrv.ini pdo_sqlsrv \
    && docker-php-source delete \
    && apk del .build-deps


Change style of single feature in mapbox gl

Question: The examples for highlighting polygons in mapbox gl use a second layer and a filter function. Is it not possible to change the color of a single feature/polygon in mapbox gl js, drawn from geojson source?
See https://www.mapbox.com/mapbox-gl-js/example/hover-styles/
Answer: It's possible to style a single feature using a data driven style that responds uniquely to an attribute of a single feature. For instance, if you have a point dataset with an id attribute and you want id 450 to be yellow instead of blue.
{
  "id": "mypoints",
  "type": "circle",
  "paint": {
    "fill-color": {
      "property": "id",
      "type": "category",
      "stops": [[450, "yellow"]],
      "default": "blue"
    }
  }
}

Caveat 1: the "default" feature is not publicly available yet.
Caveat 2: This only works for style properties that support data-driven functions.
Comment: The key part of my question is CHANGE the polygon style, not set the polygon style. I want to be able to change an individual feature/polygon on the fly, not when the style is initially created. Can I do that with this method?
Comment: yes, but how do you call that...layer.setStyle()? because there is nothing in the docs that shows how to update the style of a layer that I can find other than adding a new layer...I must be missing something here as this seems like a basic feature
Comment: Yes, that's what [data-driven styling](https://www.mapbox.com/blog/data-driven-styling/) is. You can leave the data the same, and update the style to highlight a different bit of it.
Comment: That changes/reloads the entire map, right? I am thinking more traditional GIS with a basemap as my map style, then layers on top. It looks like this works with map.setPaintProperty() with using stops function.
Comment: Not sure I understand you. `setStyle` changes one layer. `setPaintProperty` changes one property of one layer (as does `setLayoutProperty`). Both are potentially extremely quick - there's no "reloads the entire map".
Comment: Currently, the feature highlighting on click feels faster in my leaflet vector grid parcel viewer app compared to the mapbox gl js version, using the same vector tiles. I was trying to find a faster way to highlight an individual feature in mapbox gl js, but this does not seem possible. I'll provide examples soon.


How do lme4 in R and MixedModels.jl in Julia initialize model parameters for optimization?

Question: I'm curious about how lme4 in R and MixedModels.jl in Julia initialize model parameters for optimization.
From page 12 of this document

This template contains three types of elements: structural zeros (denoted by .), off- diagonal covariance parameters (initialized at 0), and diagonal variance parameters (initialized at 1).

it seems like this is how they do it: let's say the model has a random intercept and a random slope, then they would initialize the covariance matrix of the random effects using a 2 by 2 identify matrix. Question 1: Is my understanding correct?
By reading the Julia code, it seems like this is where they initialize. But it seems to me that it only initializes the random effects part, not the fixed effect parameters. Question 2: Did they just leave the fixed effect parameters uninitialized (so the starting point will be picked by the solver)? Or am I missing anything?
Answer: In linear mixed models, and if you have an estimate for the variance components ($V$ matrix below), the estimator for the fixed effects coefficients has a closed-form. This is why you do not need to initialize these parameters. Namely, if we let $\beta$ denote the fixed effects coefficients, $X$ the fixed-effects design matrix, and $y$ the outcome vector, then we (weighted least squares) estimator is:
$$\widehat \beta = \Biggl (\sum_{i = 1}^n X_i^\top V_i^{-1} X_i \Biggr)^{-1}\Biggl (\sum_{i = 1}^n X_i^\top V_i^{-1} y_i\Biggr),$$
where $i = 1, \ldots, n$ denotes the subjects, and $V_i = Z_i D Z_i^\top + \Sigma$, with $Z$ denoting the random effects design matrix, $D$ the variance-covariance matrix for the random effects, and $\Sigma$ the variance-covariance matrix for the error terms.
Comment: So they use REML to estimate V, and then calculate beta_hat using the WLS? But for maximum likelihood, don't they have to estimate beta_hat and V together? That's why I'm puzzled why they don't initialize beta.
Comment: @Xward The WLS for $\beta$ is also the ML estimator. Moreover, the estimators for $\beta$ and $V$ are orthogonal and can be obtained separately. You do not need to estimate them together.
Comment: Thanks for getting back. I believe they are orthogonal only if we use REML. For ML, since the log likelihood involves the term (y-X\beta)'V^{-1}(y-X\beta), I don't think one can estimate them separately.


What does "structural" mean in marginal structural models and structural nested models?

Question: Robins developed the marginal structural models and the structural nested models. An example of the structural nested models is
$$E[Y^a-Y^{a=0}\mid A=a, L]=\beta_1a + \beta_2aL,$$
where $Y^a$ is the counterfactual outcome, $A$ is the treatment, $L$ is the covariate vector.
I have a background in machine learning but I'm new to causal inference. To me, the structural nested model is simply a regression model. What does the word "structural" mean here? How it's different from a regression model?
Thanks!
Edit:
In section 2.1 of this paper "Simulating from marginal structural
models with time-dependent confounding", the authors say that "the term "structural" distinguished it as an interventional model, versus some observational marginal model $P(Y|A=a)$."
Comment: If you really want to study MSM, need to find/understand the difference between $pr[Y_{a_0}=1]$ and $pr[Y=1|A_0=a_0]$ in Section 3 on Robins paper "marginal structural models and causal inference in epidemiology" Epidemiology Sep 2000
Comment: Thanks. Yes, I understand the difference between $pr[Y_{a0}=1]$ and $pr[Y=1|A_0=a_0]$, the former is the true counterfactual distribution, and the latter is the observational distribution for the observational data collected by a specific policy. Did you mean that the difference between a regression model and an MSM is that a regression model is fitting $Y|A_0=a_0$ while the structural model is modeling $Y_{a0}$? Still, I don't get the point why the model is called structural? I'd appreciate it if you could share some insights about the meaning of the word "structural".
Comment: I have just started reading What if and found this model. What makes this model nested?
Answer: After reading more papers from Hernan, I found that the word "structural" simply has the meaning "causal".


const casting an int in a class vs outside a class

Question: I read on the wikipedia page for Null_pointer that Bjarne Stroustrup suggested defining NULL as
const int NULL = 0;
if "you feel you must define NULL." I instantly thought, hey.. wait a minute, what about const_cast?
After some experimenting, I found that
int main() {
    const int MyNull = 0;
    const int*  ToNull = &MyNull;
    int* myptr = const_cast<int*>(ToNull);
    *myptr = 5;
    printf("MyNull is %d\n", MyNull);
    return 0;
}

would print "MyNull is 0", but if I make the const int belong to a class:
class test {
public:
    test() : p(0) { }
    const int p;
};
int main() {
    test t;
    const int* pptr = &(t.p);
    int* myptr = const_cast<int*>(pptr);
    *myptr = 5;
    printf("t.p is %d\n", t.p);
    return 0;
}

then it prints "t.p is 5"!
Why is there a difference between the two? Why is "*myptr = 5;" silently failing in my first example, and what action is it performing, if any?
Comment: Relevant: when is const_cast safe: http://stackoverflow.com/questions/357600/is-const-cast-safe
Comment: That quote from Bjarne is from 2001 and I'm not entirely sure whether it's still what "is recommended". Personally I think it is a bad idea. Either use `0` or use `#define NULL 0`. I thought there are subtle differences between `0` and a `const int` set to zero.
Answer: First of all, you're invoking undefined behavior in both cases by trying to modify a constant variable.
In the first case the compiler sees that MyNull is declared as a constant and replaces all references to it within main() with a 0.
In the second case, since p is within a class the compiler is unable to determine that it can just replace all classInstance.p with 0, so you see the result of the modification.
Comment: @Mike Smith: `const_cast` exists to remove constness from *access paths* (pointers or references) that lead to *non-const* objects. For example: `int i = 0; const int *pi = &i *const_cast(pi) = 42;`. This is valid code with perfectly defined behavior. It uses `const_cast` to remove `const` from a pointer and thus gain write access to a *non-const* object. The key point here is that `i` is a *non-const object*. In your example you are attempting to modify *const* objects. This is always illegal.
Comment: If modifying a constant variable is undefined behavior, why does const_cast even exist?
Comment: @Mike Smith: Mainly to work with badly written APIs that do not follow [const correctness](http://en.wikipedia.org/wiki/Const-correctness). Say you have to use a function that wants you to pass it a pointer to a string that it simply wants to read, but the function is declared as `void foo(char *)`. `const_cast` comes to the rescue in cases like this.
Comment: @Mike Smith: Another common case is when you have two members `T& getFoo(); T const& getFoo() const;`. Forwarding one to another requires a `const_cast` on either `this` or the return value.
Answer: Firstly, what happens in the first case is that the compiler most likely translates your
printf("MyNull is %d\n", MyNull);

into the immediate
printf("MyNull is %d\n", 0);

because it knows that const objects never change in a valid program. Your attempts to change a const object leads to undefined behavior, which is exactly what you observe. So, ignoring the undefined behavior for a second, from the practical point of view it is quite possible that your *myptr = 5 successfully modified your Null. It is just that your program doesn't really care what you have in your Null now. It knows that Null is zero and will always be zero and acts accordingly.
Secondly, in order to define NULL per recommendation you were referring to, you have to define it specifically as an Integral Constant Expression (ICE). Your first variant is indeed an ICE. You second variant is not. Class member access is not allowed in ICE, meaning that your second variant is significantly different from the first. The second variant does not produce a viable definition for NULL, and you will not be able to initialize pointers with your test::p even though it is declared as const int and set to zero
SomeType *ptr1 = Null; // OK

test t;
SomeType *ptr2 = t.p; // ERROR: cannot use an `int` value to initialize a pointer

As for the different output in the second case... undefined behavior is undefined behavior. It is unpredictable. From the practical point of view, your second context is more complicated, so the compiler was unable to prefrom the above optimization. i.e. you are indeed succeeded in breaking through the language-level restrictions and modifying a const-qualified variable. Language specification does not make it easy (or possible) for the compilers to optimize out const members of the class, so at the physical level that p is just another member of the class that resides in memory, in each object of that class. Your hack simply modifies that memory. It doesn't make it legal though. The behavior si still undefined.
This all, of course, is a rather pointless exercise. It looks like it all began from the "what about const_cast" question. So, what about it? const_cast has never been intended to be used for that purpose. You are not allowed to modify const objects. With const_cast, or without const_cast - doesn't matter.
Answer: Your code is modifying a variable declared constant so anything can happen. Discussing why a certain thing happens instead of another one is completely pointless unless you are discussing about unportable compiler internals issues... from a C++ point of view that code simply doesn't have any sense.
About const_cast one important thing to understand is that const cast is not for messing about variables declared constant but about references and pointers declared constant.
In C++ a const int * is often understood to be a "pointer to a constant integer" while this description is completely wrong. For the compiler it's instead something quite different: a "pointer that cannot be used for writing to an integer object".
This may apparently seem a minor difference but indeed is a huge one because

The "constness" is a property of the pointer, not of the pointed-to object.
Nothing is said about the fact that the pointed to object is constant or not.
The word "constant" has nothing to do with the meaning (this is why I think that using const it was a bad naming choice). const int * is not talking about constness of anything but only about "read only" or "read/write".

const_cast allows you to convert between pointers and references that can be used for writing and pointer or references that cannot because they are "read only". The pointed to object is never part of this process and the standard simply says that it's legal to take a const pointer and using it for writing after "casting away" const-ness but only if the pointed to object has not been declared constant.
Constness of a pointer and a reference never affects the machine code that will be generated by a compiler (another common misconception is that a compiler can produce better code if const references and pointers are used, but this is total bogus... for the optimizer a const reference and a const pointer are just a reference and a pointer).
Constness of pointers and references has been introduced to help programmers, not optmizers (btw I think that this alleged help for programmers is also quite questionable, but that's another story).
const_cast is a weapon that helps programmers fighting with broken const-ness declarations of pointers and references (e.g. in libraries) and with the broken very concept of constness of references and pointers (before mutable for example casting away constness was the only reasonable solution in many real life programs).
Misunderstanding of what is a const reference is also at the base of a very common C++ antipattern (used even in the standard library) that says that passing a const reference is a smart way to pass a value. See this answer for more details.


Code in URLs despite clean URLs turned on

Question: The site I'm working on, shows the URL like this: http://www.sitename.com/page-name#.Uad4adKmjoY
It shows "#.Uad4adKmjoY" at the end of url, even though I've enabled the clean urls.
Anyone know why it is showing this? I've not come across this before.
Answer: According to this posting on StackOwerflow and this one on Drupal Answers, these appear if there is Javascript in place to add "AddThis" tracking to the website.  They do no harm, and if it's not your site, you should leave them alone.
(Note that this has nothing to do with clean URLs in Drupal.  Drupal's clean URLs changes things like example.com/?q=node/123 into  example.com/node/123.  It does nothing with hashmarks added to URLs.)


Probability of winning a competition K games best of series of N games

Question: Consider a 'best of 5' series in sports/competition where the first team to win 3 games wins the series. So N=5, K=3. Where  probability w = p(team A winning game) and l = p(team A losing game). Assume these probabilities do not change during the series.
When I first thought about this I mistakenly tried adding the individual probabilities of winning 3/3, 3/4, and 3/5 games:
wrong = function(w) {
  p = dbinom(3,3,w) + dbinom(3,4,w) + dbinom(3,5,w)
  return(p)
}

wrong(.9)
# 1.0935

Obviously, the issue is there is redundancy since 3 wins in a row, W-W-W renders any game 4 and 5 results obsolete. i.e. W-W-W-L-W and W-W-W-W-L aren't possible.
After removing redundancies these are the possible permutations:
win = function(w) {
  l = 1-w
  p = w*w*w +
    w*w*l*w + w*l*w*w + l*w*w*w +
    l*l*w*w*w+ l*w*l*w*w+ l*w*w*l*w+
    w*l*l*w*w+ w*l*w*l*w+
    w*w*l*l*w

  return(p)
}

win(.9)
# 0.99144

win(.9) + win(.1)
# 1

Manually typing the permutations gets out of hand quickly with longer series i.e. winning a N = 7 game series, 9 game series, etc. Generally, how does wrong() function need to be modified to get the correct probability?
Comment: See [existing questions on Math.SE on *probabiltiy win series*](https://math.stackexchange.com/search?q=probability+win+series+votes%3A5)
Comment: The methods presented in the answers at https://stats.stackexchange.com/questions/329521 make short work of this question, which is a simplified version of that one.
Answer: You can use the negative binomial distribution for this problem.
If X is distributed as NegBin(n, w), then X is the number of games the player loses before winning n of them, if the probability of winning any given game is w.
So, dnbinom(q = 2, size = 2, prob = w) is the probability that the player loses a total of 2 games before winning 2.
Then, pnbinom(q = 2, size = 3, prob = w) is the probability that the player loses 2 or less before they win 3 games. This is equal to the probability of winning a 3 out of 5 series.
In general, the probability of winning a best n-out-of-(2n-1) series can be calculated with pnbinom(q = n-1, size = n, prob = w).
## w is the probability of winning any individual game
## k is the number of wins needed to win the series (3 in a best 3 of 5 series)
win <- function(w, k){
  return (pnbinom(q = k - 1, size = k, prob = w))
}

win(0.9, 3)
## 0.99144

Comment: If `N` is even, then you need `ceiling((N+1)/2)` wins to win the serial, e.g., 4 out of 6. In this case, your generic function `win` in terms of `N` can be defined like `win <- function(w, N)  pnbinom(floor((N-1)/2), ceiling((N+1)/2), w)`, which can deal with either odd or even `N`
Comment: Nice solution using negative binomial distribution, +1! By the way, for generality, i.e.,even or odd `N`, applying `wins_needed <- ceiling((N+1)/2)` enables a generic function `win`
Comment: Thanks for the note @ThomasIsCoding - in this case, N should always be odd, since an even length series can end tied
Comment: I agree though that parameterizing `win` in terms of N opens the door to inputting an even length series. I've changed it to be in terms of k, the wins needed, to address that. Thanks again for the note
Answer: Actually you are almost there, but you should be aware of the cases with four and five games to win.
win <- function(w) dbinom(3,3,w)+w*dbinom(2,3,w) + w*dbinom(2,4,w)

or a compact solution
win <- function(w) w*sum(mapply(dbinom,2,2:4,w))

such that
> win(0.9)
[1] 0.99144

Explanation:
Given that the number of games needed to win the serial depends on the last win:

If 3 games are needed: the first two should both wins, such that the prob. is w**3 (equivalently dbinom(3,3,w) or dbinom(2,2,w)*w)
If 4 games are needed: among the previous three games there should be 2 wins and 1 loss, such that the prob. is choose(4,2)*w**2*(1-w)*w (equivalently dbinom(2,4,w)*w)
If 5 games are needed: among previous four games there should both 2 wins and 2 losses, such that the prob. is choose(4,2)*w**2*(1-w)**2*w (equivalently dbinom(2,4,w)*w)

Update: Generalization of win
With respect to any N (either even or odd), a generalized function win can be defined like below
win <- function(w, N) w*sum(mapply(dbinom,ceiling((N-1)/2),ceiling((N-1)/2):(N-1),w))

However, above is not as efficient for large Ns. Instead, the negative binomial distribution method mentioned by @RyanFrost is preferred for cases with large Ns, i.e.,
win <- function(w, N) pnbinom(floor((N-1)/2), ceiling((N+1)/2), w)

Example
> win(0.9,5) # needs at 3 wins out of 5 games
[1] 0.99144

> win(0.9,6) # needs at 4 wins out of 6 games
[1] 0.98415

Answer: This is interesting. Let's demonstrate using n = 3 where it takes 2 wins to be the winner. We can first determine which combinations are available
n = 3L
lst = replicate(n, 0:1, simplify = FALSE)
combos = do.call(expand.grid, lst)
combos

  Var1 Var2 Var3
1    0    0    0
2    1    0    0
3    0    1    0
4    1    1    0
5    0    0    1
6    1    0    1
7    0    1    1
8    1    1    1

As you noted, some of these combinations are not possible. We are specifically interested when the rowSums() are equal to 2. Using this we can figure out which combinations are actually possible.
possible_combos = combos[rowSums(combos) == ceiling(n / 2), ]
possible_combos

  Var1 Var2 Var3
4    1    1    0
6    1    0    1
7    0    1    1

Our last step is to calculate each contribution from our possible contributions. We know that w^2 will be in each calculation. The l part is more complicated. In our first possible combination, the l contributes nothing. We can use max.col(..., ties.method = "last") to figure how many ls occurred:
losses = max.col(possible_combos, ties.method = "last") - ceiling(n / 2)
losses
# [1] 0 1 1

w = 0.9
l = 1 - w
wins_p = w ^ ceiling(n / 2)
losses_p = ifelse(losses == 0L, 1, l ^ losses)

p = sum(wins_p * losses_p)
p
# [1] 0.972

To generalize this, we can use this as a function based on n and w:
right = function(n, w) {
  lst = replicate(n, 0:1, simplify = FALSE)
  combos = do.call(expand.grid, lst)
  possible_combos = combos[rowSums(combos) == ceiling(n / 2), ]
  losses = max.col(possible_combos, ties.method = "last") - ceiling(n / 2)

  l = 1 - w
  wins_p = w ^ ceiling(n / 2)
  losses_p = ifelse(losses == 0L, 1, l ^ losses)

  sum(wins_p * losses_p)
}

right(5, 0.9)
# [1] 0.99144
right(5, 0.9) + right(5, 0.1)
# [1] 1

Answer: It is a binomial distribution:
dbinom(3,5,0.9) + dbinom(4,5,0.9)+dbinom(5,5,0.9) = 0.99144

The reason goes like this, you just need to think about the total space,  even if there are already 3 wins or 4 wins, let's imagine the event goes on and we can write the possible events to include as:
w.w.w : w.w.w.w.k , w.w.w.k.k , w.w.w.k.w, w.w.w.w,w
w.w.l.w : w.w.l.w.l, w.w.w.l.w
l.w.w.w : l.w.w.w.1 , l.w.w.w.w

And so on..
And those that have written as containing 3 wins for example (w.w.l.w.l) will be part of 5 choose 3 in a binomial.
Out of the total space of W/L over 5 events, what we need are 3 wins, 4 wins and 5 wins to include all the events that can result in the team winning (even though in real life, the 4th or 5th match will not occur)
Comment: thanks for edit too !
Comment: yeah of course, pbinom would work. I just wrote the sum to be clear. Thanks for pointing it out.. I guess not a very good explanation anyway lol
Comment: This sum can also be written as `pbinom(5-3, 5, 1-0.9)` or `1 - pbinom(5-3, 5, 0.9)`
Answer: Here is a function win that computes the probability to win k out of n games with a probability to win each game w. It implements the idea of this Math.SE post.
win <- function(w, n = 5, k = 3){
  loose <- function(w, n, k){
    l <- 1 - w
    m <- n - k
    s <- seq_len(n - 1)[-seq_len(m - 1)]
    ch <- sapply(s, function(x) choose(x, m))
    w <- w^(seq_along(s) - 1)
    l^m * sum(w*ch)
  }
  if(k >= ceiling(n / 2)){
    1 - loose(w, n, k)*(1 - w)
  }else{
    stop("a minority cannot win.")
  }
}
win(0.9)
#[1] 0.99144

win(0.1)
#[1] 0.00856

win(0.9) + win(0.1)
#[1] 1

Answer: What your're asking is a simple math problem. I'll try to explain the math step by step then we'll write our codes with respect of that.
Math
Combination
In mathematics, a combination is a selection of items from a collection and is defined as follows.

 Where ! is the factorial operator. For example let's assume we have four rounds and you want to select three wins (or one loose). We have:

Which are: w-w-w-l, w-w-l-w, w-l-w-w, l-w-w-wBut as you mentioned, w-w-w-l is not acceptable because the game is done when 3 wins are accomplished! So take a good look at this point:

If our rounds takes more than 3 (best of 5), the last one must be win if winning probability calculation is desired!

So to correct my calculations I should first select the last round as a win and select 2 other spots (from remaining spots) for winning. Or

And if we show winning probability with w and loosing with l the probability of this state to be happened is

Javascript
Now that you know the concept, let's begin coding!
First I need a function to calculate factorial of n (n!).
let f = (n)=>
{
    let o = 1;
    for(i=1; i<=n; i++)
    {
        o *= i;
    }
    return o;
}

To understand the procedure better, I'll write my codes step by step. So the next step is to define the combination function.
let c = (n,r)=>
{
    return f(n)/(f(r) * f(n-r));
}

And now it's time to calculate r wins probability in a p round game with win probability of w.
let _w = (p,r,w)=>
{
    let o = 1;
    // Selection of win positions
    o *= c(1,1) * c(p-1,r-1);
    // Calculation probability
    o *= Math.pow(w, r) * Math.pow(1-w, p-r);

    return o;
}

Now we are ready to make the BO (Best Of) function with N rounds and K wins.
let BO = (N, K, w)=>
{
    // P is what we wish to find!
    let P = 0;
    for (j=K; j<=N; j++)
    {
        P += _w(j, K, w);
    }
    return P;
}

And some examples:
console.log(BO(5,3,0.9)); // 0.9914400000000001
console.log(BO(7,4,0.9)); // 0.997272
console.log(BO(9,5,0.9)); // 0.99910908


How to calculate how many standard deviations a number is from the mean

Question: I have 25 integers and I would like to find how many standard deviations each of them is from the mean. Apparently, normal distribution is not applicable here and therefore I have to move on with t-distribution. My problem is that I am not sure how to apply t-distribution. So, let's say that I have already computed t and s according to this link. What's the next step?
EDIT
here is a sample row:
array([  1.,   0.,   0.,   4.,   0.,   1.,   0.,   0.,   0.,   0.,   3.,
         0.,   2.,   1.,   0.,   0.,   3.,   0.,   3.,   0.,  14.,   0.,
         2.,   0.,   4.])

normally, values go from 0 to say 20. When I see unusual high numbers, I use to filter out the whole row. FYI, the following histogram shows how the really distribution looks like:

Answer: The question is puzzling.
(value $-$ mean) / SD is a descriptive calculation possible so long as SD is positive, which means usually. It doesn't require that data follow any specific probability distribution.
If you want to attach a probability, cumulative or otherwise, to it, then that will require a distribution assumption, but the possibilities aren't limited to normal or $t$ distributions. In fact, as your data are integers (and nothing more said) some quite different distribution may be more appropriate.
Comment: Hi, thank you very much for your reply. Can you please evolve a little bit more? What other sort of distributions do you believe I could apply? I have already tried this `>>> import scipy.stats as st
>>> st.mstats.zscore(arr, axis=1)`, but unfortunately the results I am getting are a bit skewed on the positive side. Any ideas?
Comment: You show us your data and I will try to add more. At present the flavour of "please tell me how to work with data I am not showing you" allows only advice like "choose an appropriate distribution". More generally, constraints on values such as possible minimum and maximum are crucial to advice here.
Comment: hi, I updated my original question. Please have a look :)
Comment: Your question now looks completely different. It seems that you know what the underlying distribution is, or should be (?), and that you are drawing one or more samples of size 25 (?). I don't think I want to add anything, as what you want is becoming increasingly unclear to me. I don't see how the t distribution enters at all.
Answer: t itself is the number of standard deviations a given value x lies away from the mean. The sign of t tells you in which direction x lies away from the mean.
Also look at its Wikipedia entry.


How to determine $x_0$ is whether a extremum point of smooth function $f(x)$ while $x_0$ is a zero of infinite multiplicity of $f'(x)$?

Question: How to determine $x_0$ is whether a extremum point of smooth function $f(x)$ while $x_0$ is a zero of infinite multiplicity of $f'(x)$?
I'm thinking about how to determine a stationary point of a smooth function $f\in C^\infty(\mathbb{R})$ is an extremum point or an inflection point. I think find the zeros of its derivative $f'(x)$ would be useful. If the multiplicity of the zero is finite, then the situation is easy to deal with.
But I have no idea when meeting the zero of infinite multiplicity. For example, consider the function:
\begin{equation}
f(x)=e^{-\frac{1}{x^2}},\ x\in\mathbb{R},
\end{equation}
which reaches $0$ at $x_0=0$ in supplement. Then $f(x)$ is a smooth function and $0$ is a zero of infinite multiplicity of $f'(x)$. It's trivial to see $0$ is a minimum point of $f(x)$, but I wonder if there are some methods to get the conclusion through derivative.
Answer: Oh, it seems that I think something wrong. It's always useful to consider the derivative $f'(x)$ around $x_0$ but not only $f'(x_0)$.


torch.CharStorage doesn't read data from a file when size isn't provided

Question: I'm trying to replicate the example provided here. In my case, though, when I do the torch.CharStorage('hello.txt') I get [torch.CharStorage of size 0]. Here's the full output
$ echo "Hello World" > hello.txt
$ th

   ______             __   |  Torch7
  /_  __/__  ________/ /   |  Scientific computing for Lua.
   / / / _ \/ __/ __/ _ \  |  Type ? for help
  /_/  \___/_/  \__/_//_/  |  https://github.com/torch
                           |  http://torch.ch

th> x = torch.CharStorage('hello.txt')
                                                                  [0.0001s]
th> x
[torch.CharStorage of size 0]

I also noticed that when I do torch.CharStorage('hello.txt', false, 11) the data is read correctly. However, in documentation the shared and size parameters are specified as optional. Is it the case that the documentation is not up to date or am I doing something wrong?
Answer: You appear to be running into distro bug #245, introduced by commit 6a35cd9. As stated in torch7 bug #1064, you can work around it by either updating your pkg/torch submodule to commit 89ede3b or newer, or rolling it back to commit 2186e41 or older.
Comment: Yes, my `pkg/torch` is currently between these two commits. Do you know if I will need to rerun the `torch/install.sh` script after updating to `89ede3b `?
Comment: @MaxShvets Yes, you will. But if you just run it as-is, it will undo your update. The quick/easy fix is to comment out [the line with `git submodule update --init --recursive`](https://github.com/torch/distro/blob/0219027e6c4644a0ba5c5bf137c989a0a8c9e01b/install.sh#L50) first.
Comment: I didn't get the chance to try out your suggestion yet, but I'm pretty sure that the reason for this problem is as you described. I'm going to accept your answer


What's the point of "Supported Device Orientation" in iOS application setting?

Question: In XCode4.2 + iOS5 SDK, I set "Supported Device Orientation" to be "Portrait" only. I expect that would make all views in the application to only support "Portrait" orientation. However, while I rotate the iPhone simulator, I found that other orientations still work.
It seems that the method shouldAutorotateToInterfaceOrientation in ViewController is the key to decide whether given orientation is supported. So, why bother to have "Supported Device Orientation"  setting in the application level if doesn't limit orientation?
Answer: Here's a quote from documentation for UISupportedInterfaceOrientations property:

UISupportedInterfaceOrientations (Array - iOS) specifies the interface orientations your application supports. The system uses this information (along with the current device orientation) to choose the initial orientation in which to launch your application. The value for this key is an array of strings.

E.g. this property determines possible orientations your application may be launched in (it's actually most used on iPad). The latter orientation changes are up to your ViewControllers.
Comment: So, UISupportedInterfaceOrientations is just to determine launch interface orientation, right?
Comment: Yes, it affects only initial orientation at launch.
Comment: Oon iOS6.0, it seems that this property actually does what you want i.e limite orientation of all the application.
Not working on iOS5.0...
Answer: Oon iOS6.0, it seems that this property actually does what you want i.e limite orientation of all the application. Not working on iOS5.0...
Comment: I have the same problem, is this normal?
Comment: not sure if it is normal, but I had to work arround this probleme.


What is theta in negative binomial distribution?

Question: https://www.rdocumentation.org/packages/MASS/versions/7.3-51.5/topics/theta.md
The above page says this.
Given the estimated mean vector, estimate theta of the Negative Binomial Distribution.

But it is not clear what the definition of theta is as there are different parameterization of NB. For example, wiki uses r and p.
https://en.wikipedia.org/wiki/Negative_binomial_distribution
I see this following is mentioned on https://data.library.virginia.edu/getting-started-with-negative-binomial-regression-modeling/
var(Y)=μ+μ^2/k

Is k here same as theta?
What is the relation between theta and r and p? Thanks.
Comment: hey this question has been asked before, maybe you can check this https://stats.stackexchange.com/questions/70619/dispersion-in-summary-glm/77594#77594
Comment: so to answer your question, theta is size in rnbinom(...) and is k in what you cited
Answer:
Is k here the same as theta?

I think so yes.

What is the relation between theta and r and p?

The major difference is how the negative binomial is written. Here the negative binomial is written as a Poisson mixture of gammas. See, e.g. here
for the derivation if you are unfamiliar with this notion.
Then write the mean of the gamma as $\mu$ and the variance of the gamma $\mu^2/\theta$. Recall the gamma mixes the Poisson rate parameter so that to get the marginal mean and variance of the Negative binomial, you need to integration out the gamma variations. To do this you can use conditional expectations, e.g.
$\mathbb{E}(y_i) = \mathbb{E}(\mathbb{E}(y_i | \lambda))$
where the inner expection is the Poisson, e.g.
$\mathbb{E}(y_i) = \mathbb{E}(\lambda) = \mu$
now the variance:
$$\mathbb{V}ar(y_i) = \mathbb{V}ar(\mathbb{E}(y_i | \lambda)) + \mathbb{E}(\mathbb{V}ar(y_i | \lambda))$$
now putting in the gamma values for the inner expectations and variances you see:
$$\mathbb{V}ar(y_i) = \mathbb{V}ar(\lambda) +  \mathbb{E}(\lambda)$$
and we may evaluate both the variance and the expectation on the right hand side as mean and variance of the gamma, to get:
$$\mathbb{V}ar(y_i) =\frac{\mu^2}{\theta} +  \mu$$
this is the parameterization that these packages appear to be using.
If you want to map this parameterization to the more common negative binomial parameters, write:
$p = \frac{\mu}{\mu + \theta}$ and $r=\theta$.


type transform by using constructor in c++ didn't work?

Question: My code can't run well, can anybody tell me what happened to my otest.cpp?
: ~$ g++ --version
g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

//filename: otest.cpp

#include <iostream>
using namespace std;
class Complex;   // declaration

class Victor
{
    private:
            int x, y;
    public:
            Victor(int xx = 0, int yy = 0) { x = xx;  y = yy; }
            friend ostream & operator <<(ostream & ostr, Victor & v);
//              operator Complex() { return Complex(x,y); }
            int getX() { return x;}
            int getY() { return y;}
            Victor(Complex & c) { x = c.getReal(); y = c.getImg(); }
};

class Complex
{
    private:
            int real, img;
    public:
            Complex(int re= 0, int im = 0) { real = re; img = im; }
            friend ostream & operator<<(ostream & ostr,Complex & c);
  //              operator Victor() { return Victor(real,img); }
            int getReal() { return  real;}
            int getImg() { return img; }
            Complex(Victor & v) { real = v.getX(); img = v.getY(); }
};

std::ostream& operator<< (std::ostream& ostr, Complex& c)
{       ostr << c.real << " + " <<c.img << " i";
    return ostr;
}

std::ostream& operator<< (std::ostream& ostr, Victor v)
{
    ostr << "( " << v.x << ", " << v.y << " )" ;
    return ostr;
}

int main()
{
    Victor v1(3,5);
    Victor v2;

    Complex c1(5,6);
    Complex c2;

    v2 = Victor(c1);
    cout << v2 << endl;
    cout << c1<<endl;

    c2 = Complex(v1);
    cout << c2 <<endl;
    cout << v1 <<endl;

    return 0;
}

Comment: Beeing named Victor myself, I assume you mean to name your class "Vector".
Comment: `Can't run well` does not adequately describe your problem
Comment: Do you get compilation errors? Then edit your question to include them all (unedited and complete). Does it crash when running? Then run in a debugger and at least get a backtrace and edit your question to include that.
Answer: The code shall not be compiled because in this point where constructor
Victor(Complex & c) { x = c.getReal(); y = c.getImg(); }

is defined the compiler knows nothing whether class Complex has methods getReal and getImg
You have only do declare the constructor in class Victor and define it only after the definition of class Complex.
Take into account that it would be better that some member functions and objects would have qualifier const. For example functions getReal and getImg could be declared with qualifier const. Also the parameter in the constructor above could be declared with  qualifier const.
Victor( cosnt Complex &c );

Or for example operator << could be declared like
friend std::ostream & operator <<( std::ostream &ostr, const Complex &c );

friend std::ostream & operator <<( std::ostream &ostr, const Victor &v );

Answer: Work through the errors in order, and fix each problem in turn.
First error:
test.cpp: In constructor 'Victor::Victor(Complex&)':
test.cpp:17:40: error: invalid use of incomplete type 'class Complex'
             Victor(Complex & c) { x = c.getReal(); y = c.getImg(); }

You can't use the Complex type here since it hasn't been defined yet. Just declare the function at this point:
Victor(const Complex &);

and define it after the definition of Complex
Victor::Victor(const Complex & c) { x = c.getReal(); y = c.getImg(); }

(I took the liberty of adding const since that's appropriate here. You might also want to rename the class Vector, since it appears to represent a vector not a victor.)
Second error:
test.cpp:10:17: error: 'int Victor::x' is private
test.cpp:43:23: error: within this context
    ostr << "( " << v.x << ", " << v.y << " )" ;

This is because you declare a function with one signature (taking its second argument by reference)
friend ostream & operator <<(ostream & ostr, Victor & v);

and define a different overload taking its argument by value:
std::ostream& operator<< (std::ostream& ostr, Victor v)

Make the both match; const Victor& is the most appropriate type. Alternatively, you could define the function within the class definition:
class Victor
{
    // ...
    friend ostream & operator <<(ostream & ostr, const Victor & v) {
        return ostr << "( " << v.x << ", " << v.y << " )" ;
    }
    // ...
};

Or you could implement the function using the public interface, with no need for a friend declaration:
std::ostream& operator<< (std::ostream& ostr, const Victor & v) {
    return ostr << "( " << v.getX() << ", " << v.getY() << " )" ;
}

After fixing those errors, the code compiles and produces sensible-looking output.
Comment: I need some time to digest what you said, but thanks, I am appreciate all of you. what a poor english,Haha!


Evaluating $\sum_{n=0}^\infty \frac{n}{3^n}$

Question: How can i prove that $ \sum\limits_{n=0}^\infty \frac{n}{3^n}=\frac{3}{4}$?
I tried to find some pattern but didn't succeed
Comment: Differentiate $\sum x^n$
Comment: $\sum_{n=0}^\infty \frac{n}{3^n} = \sum_{n=0} \sum_{m=1}^n \frac{1}{3^n}.$ Now rearrange this sum and use facts about geometric series. A picture might help on how to rearrange the sum.
Comment: @L.F. how differentiate helps here?
Answer: Another approach:  As the series converges, let L denote its limit.  Now you have $$L=\sum_{n=0}^\infty \frac{n}{3^n}=\sum_{n=1}^\infty  \frac{n}{3^n}= \frac{1}{3}\sum_{n=1}^\infty  \frac{n}{3^{n-1}}=  \frac{1}{3}\sum_{n=0}^\infty  \frac{n+1}{3^{n}}= \frac{1}{3}\left[\sum_{n=0}^\infty  \frac{n}{3^{n}}+\sum_{n=0}^\infty  \frac{1}{3^{n}}\right] =\frac{1}{3}\left[L+ \sum_{n=0}^\infty  \frac{1}{3^{n}}\right].$$
Now just use the usual formula for the limit of a geometric series, and solve algebraically for $L$.
Comment: It's.. it's beautiful
Comment: Both fantastically simple and simply fantastic.+1!