Can the Autocomplete delay be lowered in forms?

Question: I have seen that the autocomplete widget in Forms API is started when I finish typing, or when there is a delay between one key hitting and the next one. Could it be configured so it is launched as soon as I press a key, like in Google Autosuggest or other search boxes?
Comment: That delay is the time it takes the AJAX request to come back from the server (plus maybe a nominal delay for UX)
Comment: I have to disagree with my esteemed colleague @Clive here, as the delay from the UX is not nominal and is built into the Drupal autocomplete functionality.
Comment: I knew there was one in there @MPD, didn't realise it was as large as 300ms. Can see why they did it
Comment: I think that the behaviour is intentional. Also there seems to be a higher delay when the user doesn't stop typing, which seems intentional. If he/she is typing with no pause, probably knows perfectly what she is searching and doesn't want to be bothered with suggestions. I find the speed now good, if I have this in mind. ITOH, the time lapse of 300ms reminds me of another timelapse in PhoneGap, which is similar, and is also built in into the system, with ways of circumventing it. It might be a matter of preference.
Answer: As Clive suggested in a comment major part of the delay is because of the time taken by your server to populate the dropdown list. This generally happens because Drupal has to load all the enabled modules and do a complete Drupal bootstrapping.
In special cases like Autocomplete responses that may not be necessary. Hence you can load only what is required and do a minimal Bootstrapping.
You can check out the details of how this is done on this page.
Note : This involves custom coding and will not to perform any access checks unless you manually do it.
Comment: Yes, this is what I needed, to reduce almost x10 the time consumed. I was seeing all the data returned via AJAX and almost dismayed. Maybe with this approach it will be easier.
Answer: As others have suggested, there is a delay with AJAX autocomplete due to the server round trip.  However, there is a delay baked into Drupal itself.
In misc/autocomplete.js, there is this section of code
Drupal.ACDB = function (uri) {
  this.uri = uri;
  this.delay = 300;
  this.cache = {};
};

The delay property is used in Drupal.ACDB.prototype.search to debounce the search requests when a user is typing, so that the input has to be stable for 300ms before triggering the autocomplete callback.
You can get around this by monkey patching, and providing your own version of Drupal.ACDB that uses a different delay.
Comment: @Cesar Also keep in mind a search against a single character can produce a huge result set in some instances.  It's all a balancing act.
Comment: I edited that value, but didn't see any speed gain. Also I found this misleading: when I start typing, no indication of suggestions appear. Stop typing & suggestion appear, and from then, different keys offer different suggestions. Maybe what I called _delay_ is the normal behaviour?
Comment: @Cesar That is the way this is supposed to work.  The delay is from the last keystroke to the AJAX callback so you don't do wasted calls while the user is still typing.  It sounds like your problem is with the actual AJAX callback.
Comment: Well, in fact I didn't presume that it was a malfunction or something. In my question, last sentence, I only ask for another way of working which is found elsewhere on the net: `Could it be configured so it is launched as soon as I press a key, like in Google Autosuggest or other search boxes?`  I only wanted to know if this behaviour could be imitated. Another thing is the delay, and even the lots-of-data that the server sends back, which may slow down the process in certain cases, but seems to be necessary for security - and other - reasons.
Comment: @Cesar Sorry for the confusion.  Yes, this would be possible, but it would require a pretty big rewrite of the standard autocomplete system, as you would not have multiple simultaneous callbacks which you need to handle.    The best way to accomplish this is to clone autocomplete.hs, and then hook_js_alter() in your own version.  You are trading latency for additional system load (for processing requests that don't get used because the user is still typing).
Comment: Yes, you have made me change my mind. I will let the default behaviour, I think the functionality has been carefully designed. Sites like Google can offer such functionality, but for a normal site it is better to restrict it a little.
Answer: Try with Autocomplete Deluxe Module.
Refer How to use autocomplete deluxe programatically
May be this will help you.
Comment: I used Autocomplete Deluxe for other part of the project (highlight suggestions) and didn't convince me. I opted to modify the PHP autosuggestion code to get the highlight myself.


Weird gibberish characters appearing on bottom of Drupal 7 pages

Question: What are some reasons to why there would be weird gibberish characters appearing on the bottom of a Drupal 7 site? I work in a linux environment, but sometimes I copy the files over from windows. I'm not sure if that is the culprit, but how would one even debug something like this?
Comment: I believe this is the result of some resource compression issue; what you're seeing is the embedding of some gzipped resource. I couldn't find a good resource on the topic, but you should look at cache clearing and investigating your Apache/PHP/Drupal compression setting and how that might be affected by what you're doing.
Comment: This almost looks like the contents of an image or video file are sent to the screen in plain text. What is your `dialog-playlist-container` supposed to contain? Is it some misbehaving lightbox? Try to disable any module that provides a pop-up modal that is supposed to contain images. If this only happens occasionally, perhaps the image is corrupted? This is not normal Drupal behavior and without more details there is unfortunately not much we can do.
Comment: does switching to a Drupal 7 default theme change anything?
Comment: @ShawnConn I believe you are right. Perhaps disabling page compresson can fix this, $conf['page_compression'] = FALSE; in settings.php
Comment: it only pops up sometimes. i'll give those a try, but for something random like this its hard to say.
Answer: Since these characters appearing within certain section of the website, you need to identify the source of it and which rendering element is responsible for it (either template file or some function).
The easiest way would be to track it down by enabling theme_debug variable in your settings file which enable you to debug the output of the rendering engine.
So please add this line into your settings file:
$conf['theme_debug'] = TRUE;

then refresh the page and check the source code to see which rendering element is outputting this.

For more advanced solution, use PHP debugger such as phpdbg (in PHP >=5.6 core) or XDebug (which allows you to generate a trace file and find the source of the problem). Here is sample xdebug.ini config, so in your scenario you just need to enable xdebug.auto_trace, generate a trace file for single page load, then disable the setting (since it hugely impacts the overall performance). Then open a generated trace file, look for gibberish where they've started to appear and find out which code is generating it.
Comment: is phpdbg better than xdebug without needing to recompile php with xdebug?
Comment: For XDebug, you don't need to recompile your PHP, you just need to install PHP module. In most of systems it's just one-liner to install XDebug (like `brew install php5-xdebug` on Mac or `sudo apt-get install php5-xdebug` on Linux).
Comment: Another thing i just read was that xdebug causes a performance hit while phpdbg doesnt. Is this true from your experience? thx
Comment: It's true, but I haven't used phpdbg to tell the difference. Mainly I'm using XDebug. If you don't have `auto_trace`/`profiler_enable` enabled by default, the performance difference is really small. Having stacktraces shown on errors (`xdebug.default_enable`) gives more benefits in terms of troubleshooting issues which may overcome the actual speed difference, especially when you're using just for your local/dev environment.


Decrypt AES-CBC-256 Mcrypt_RIJNDAEL encrypted in PHP decrypt on GOLang

Question: I try to rewrite some old code made in php5.6 (CodeIgniter) in go, but I'm banging my head with decryption on go. I managed to decode MCRYPT_RIJNDAEL_128 from php to go, where the iv size is 16 characters, but I can't do it on 256 - iv is 32. I don't want to use go_mcrypt because that's strict on libcrypt headers, so I tried using go classic encrypt libs AES cipher with CBC mode, but on 256 it complains about IV length... The php IV has 32 characters not 16 as expected..
The php part works well...
private $CIPHER_KEY = "12345678901234567890123456789012";

    private function Encrypt($toEncrypt=null){
        $iv_size = $this->ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
        $iv = $this->ivKey = mcrypt_create_iv($iv_size, MCRYPT_RAND);
        $this->B64IV = base64_encode($iv);
        return base64_encode($iv . mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->CIPHER_KEY, $toEncrypt, MCRYPT_MODE_CBC, $iv));
    }

this is the PHP result:
KEY: 12345678901234567890123456789012
IV: Egu4tSySXluBLi5dcMzHbZHVSOS7jdNwUKUFlZ8dL1w=
ENC: Egu4tSySXluBLi5dcMzHbZHVSOS7jdNwUKUFlZ8dL1yATFjg26/Nav7cWtlJJL3djhUCND6KV8r/JL7owboKFA==
IV Size: 32

IV is included in the encrypted text... (and has 32 chars)
mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC); return 32

func main(){
   key := []byte("12345678901234567890123456789012")

   iv,_ := base64.StdEncoding.DecodeString("Egu4tSySXluBLi5dcMzHbZHVSOS7jdNwUKUFlZ8dL1w=")
   encText,_  := base64.StdEncoding.DecodeString("Egu4tSySXluBLi5dcMzHbZHVSOS7jdNwUKUFlZ8dL1yATFjg26/Nav7cWtlJJL3djhUCND6KV8r/JL7owboKFA==")
//   iv := encText[:32] // also tried to get the iv from encoded string

   fmt.Printf("Key Len: %d\nIV  Len: %d\nENC Len: %d\n",len(key),len(iv),len(encText))

    block, err := aes.NewCipher(key)
    if err != nil {
        panic(err)
    }

    if len(encText) < aes.BlockSize {
        panic("cipherText too short")
    }

    cipherText := encText[32:]
    if len(cipherText)%aes.BlockSize != 0 {
        panic("cipherText is not a multiple of the block size")
    }

    mode := cipher.NewCBCDecrypter(block, iv)
    mode.CryptBlocks(cipherText, cipherText)

    cipherText, _ = pkcs7.Unpad(cipherText, aes.BlockSize)

   fmt.Printf("Dec: %s\n",cipherText)

}

Key Len: 32
IV  Len: 32
ENC Len: 64
panic: cipher.NewCBCDecrypter: IV length must equal block size
goroutine 1 [running]:
crypto/cipher.NewCBCDecrypter(0x10e7c20, 0xc00009a030, 0xc00008a000, 0x20, 0x42, 0x0, 0x0)
IV size is 32 but the block size is 16.
Comment: OK - I re-re-read the documentation and AES-256 is using only 128 bytes IV (16 chars)..
AES is a variant of Rijndael that has a fixed block size of 128 bits, and a key size of 128, 192, or 256 bits.
The Rijndael documentation specifiy with block and key sizes multiple of 32 bits, with a minimum of 128 and a maximum of 256 bits, hence the confusion AES is not RIJNDAEL - only a variant.

I guess the only solution is to decrypt the sensitive data in php and encrypt it using 128 bytes IV.

Anyone know another library - compatible with RIJNDAEL 250 that works with IV of 256 bytes (32 chars)?
Answer: This works in Linux - for anyone courious how to decode with IV 32 characters

apt install libmcrypt-dev
go get "github.com/tblyler/go-mcrypt"

import (
  "fmt"
  "github.com/tblyler/go-mcrypt"
  "encoding/base64"
)

const (
   KEY = "12345678901234567890123456789012"
   ENC = "Egu4tSySXluBLi5dcMzHbZHVSOS7jdNwUKUFlZ8dL1yATFjg26/Nav7cWtlJJL3djhUCND6KV8r/JL7owboKFA=="
)

func main(){
    encText, _ := base64.StdEncoding.DecodeString(ENC)

    iv := encText[:32]
    toDecrypt := encText[32:]

    fmt.Printf("Key Len: %d\n",len(KEY))
    fmt.Printf("IV  Len: %d\n",len(iv))

    decText, err := mcrypt.Decrypt([]byte(KEY),iv,[]byte(toDecrypt))
    if err != nil { panic(err) }

    fmt.Printf("%s\n",decText)
}

Answer: I've been playing with a similar issue, when transporting code from php 5.6 to php 7.3. The easiest and most reliable way I have found is just to decrypt all the values with php 5.6 and then recrypt with the new format that works well. It's a one time thing to do when moving over, but it saves a lot of headaches.
Answer: I just test it from my MacOS, the above code is working from Mohave 10.14.5.
I used MacPorts to install libmcrypt

sudo port install libmcrypt
mkdir mcrypt
curl -o mcrypt/mcrypt.go https://raw.githubusercontent.com/tblyler/go-mcrypt/master/mcrypt.go

or copy it from your own src/github.com/tblyler/go-mcrypt to project mcrypt folder
now edit mcrypt.go and add the C flags:
package mcrypt

/*
#cgo LDFLAGS: -L/opt/local/lib -lmcrypt
#cgo CFLAGS: -I/opt/local/include
#include <stdlib.h>
...

modify import from above example to import mcrypt version locally, and run it...
package main

import (
  "fmt"
//"github.com/tblyler/go-mcrypt"
  "./mcrypt"
  "encoding/base64"
)

when running the code it adds a warning about linking
ld: warning: building for macOS, but linking in object file (/var/folders/xz/7ng416ds5611ypt12c96g1_40000gn/T/go-link-754294955/go.o) built for
Key Len: 32
IV  Len: 32
Abra Cadabra


How to add marker on specific location longitude and latitude as input field?

Question: I am trying to add marker on location based on html input field longitude and latitude. After providing input and click on search button which is calling function goToLocation the result should show marker on that location, but after executing this function only location is zoom but no marker is visible. I am using open layer 4.5 version and Here is my code with the function:
function goToLocation() {

    vectorSource.clear();
    var f = "{ \"type\": \"Feature\",\"geometry\": { \"type\": \"Point\", \"coordinates\": [" + $('#input-longitude').val() + "," + $('#input-latitude').val() + "]}}";
    //  var f2 = "{ \"type\": \"Feature\",\"geometry\": { \"type\": \"Point\", \"coordinates\": [" + $('#input-longitude').val() + "," + $('#input-latitude').val() + "]}}";

    var iconStyle = new ol.style.Style({
        image: new ol.style.Icon(/** @type {olx.style.IconOptions} */({
            anchor: [0.5, 46],
            anchorXUnits: 'fraction',
            anchorYUnits: 'pixels',
            opacity: 0.75,
            src: 'img/marker.png'

        }))
    });

    var myFeature = (new ol.format.GeoJSON()).readFeature(f);
    myFeature.setStyle(iconStyle);

    vectorSource.addFeature(myFeature);

    map.getView().fit(vectorSource.getExtent(), map.getSize());
    map.getView().fit(vectorSource.getExtent(), map.getSize());

    map.getView().setZoom(12);
}

Answer: OL is sensible to the input type. Sometimes you can use a string for the coordinates, and sometimes not, it must be a float.
The solution is to parse the coordinates
parseFloat($('#input-longitude').val())

Also make sure that the user used a . to separate the decimals, not a ,
PS: that being said, you don't need to construct a GeoJson and to re-parse it again.
myVectorSource.addFeature(
   new Feature( {geometry: new Point([parseFloat($('#input-longitude').text()),
                                      parseFloat($('#input-longitude').text())]),
                name: String($('#input-myname').text()),
                }));

Comment: first thank you for your reply but I can't define myVectorSource as new feature because it is giving me undefined of new Feature that because I am using in another script.js. The problem is I see myfeature with all elements that I need while I am debugging and also I am not receiving any error but I am not able to see on the map? any suggestions or help? thank you in advance
Comment: I tried but it's not working as you can read from my question above the location is working and zooming without parsing the values. But not showing marker on the specific longitude and latitude
Comment: If you are using full build the syntax is `new ol.Feature` and `new ol.geom.Point`


How to get all cookies of the new firefox browser instance

Question: Am using the following to create a firefox driver
profile = Selenium::WebDriver::Firefox::Profile.new
profile['general.useragent.override'] = agent
browser = Watir::Browser.new :firefox, profile: profile

Making request:-
browser.goto "http://3454kdf.blogspot.com/"

Its redirecting to amazon site and getting cookie value from amazon site.
But i want to get the cookies of this page(http://3454kdf.blogspot.com/) which is loaded. How can i get it.
To get cookies, am use the following:-
browser.cookies.to_a

browser.driver.manage.all_cookies

If am making request with three different url using firefox profile. Then i want to get all  the cookies stored in browser. How can i get it?
Comment: Are you saying that the code is not doing what you want or are you answering your own question within the question?
Comment: @JustinKo browser.cookies getting current url cookies only not all browser cookies(cookies stored already by other requests)
Answer: If you want to get the name of all the cookies on the page, use the all_cookies method:
driver.manage.all_cookies.each do |cookie|
    puts cookie[:name]
end

Comment: I want to get all cookies stored in browser not cookies in current page.
Comment: Not sure why you would need to do that, but ok.
Answer: For security reasons, you can access the cookies only set by your site/current page. You can not access all the cookies stored in the browser.
Comment: Is there any way to store all request details and cookie details in local file and fetch from it.


Is absolute value of the difference of two vectors associated with its standard deviation (variance)?

Question: Suppose there are two random variables that are independent with each other. Is there any relationship between the absolute value of the difference of these two variables and variance of the two variables?
u1 <- rnorm(100, 0, sd=0.2)
u2 <- rnorm(100, 0, sd=0.8)
abs(u2-u1)

It will give something like

0.8553218366 0.1559001753 0.3589231965 0.1126236494
1.1591884681 1.0089059851 0.6116833748 0.1552008638...

If I look for the mean of absolute value of the difference,
mean(abs(u2-u1))

It will give me 0.66..
I am wondering, this abs(u2-u1) could have any mean association with sd (0.2 or 0.8)? In other words, how can I approximate the abs(u2-u1) given the sd(0.2 or 0.8)?
Answer: Mathematically, the expectation of abs(u2-u1) should be
> sqrt(0.2**2 + 0.8**2)*sqrt(2/pi)
[1] 0.6579525

abs(u2-u1) actually follows the folded normal distribution, and you will find more information from this link
Comment: Thanks for the answer!
Answer: Yes, there is a meaning behind this combination. As you can find here, the difference of two normal random variables has the following distribution:
$$
U_1-U_2 \sim\ U_1 + a U_2\ \sim\ \mathcal{N}\big( \mu_{U_1} + a\mu_{U_2},\ \sqrt{\sigma_{U_1}^2 + a^2\sigma_{U_2}^2} \big) = \mathcal{N}\big( \mu_{U_1} - \mu_{U_2},\ \sqrt{\sigma_{U_1}^2 +  \sigma_{U_2}^2} \big)
$$
Hence, the difference of these two comes from a normal distribution $\mathcal{N}(0, \sqrt{(0.2)^2 + (0.8)^2}) \sim \mathcal{N}(0, 0.82)$.
For the difference you can use the folded normal distribution. Hence, $|U_1 - U_2|$ has the mean like following (see this link for more details which $Y = |U_1 - U_2|$ in our case):

So, expected value of the distribution of absolute difference of two normal variables $U_1$ and $U_2$ is $0.82 \times \sqrt{\frac{2}{\pi}}$ (because $\mu = 0$ in distribution of $U1 - U_2$).
Finally, as the average of $n$ instance ($n = 100$) from the same distribution (i.i.d.) is an estimation of the mean of the distribution we can say mean(abs(u1 - u2)) = 0.82 * (\sqrt(2/pi))  ~ 0.657952.
Comment: Thanks very much! Very detailed answer.


Is the covariance matrix almost always postive definite?

Question: I understand a covariance matrix is always positive semi-definite, but it seems that the covariance matrix would almost always be positive definite (although theoretically is only guaranteed to be positive semi-definite).
For example, $\det [A] \geq 0$ if $A$ is positive semi-definite, and $\det [A] > 0$ if $A$ is positive definite. Since the product of eigenvalues is the determinant, the implication of $\det [A] > 0$ is that no eigenvalue is zero. In other words, if a covariance matrix is positive definite, variability exists on all variables no matter how we transform the data.
Is this reasoning correct? Is this not almost always the case since data is never perfect? If so, are most covariance matrices actually positive definite?
Comment: "Most" may be in the eye of the beholder.  It's possible that "most" users of statistical software use redundant variables, in which case they will frequently have singular covariance matrices.
Answer: As @whuber said, as soon as we step into a multivariate setting, it is likely we have features that they reflect similar sources of variability. As we aggregate additional features in our analysis it becomes more likely we have collinearities and thus end up with PSD matrices.
I think the flaw in the presenting reasoning stems from your point that "variability exists on all variables no matter how we transform the data."
We can have variability in all of our data features but the crux is that this variability is potentially reflecting identical information.
For example see the R code below:
set.seed(123)
x1 = runif(4)
x2 = runif(3)
A  = x1 %*% t(x2) # Obviously a rank-deficient matrix // Rank-1 matrix

While the data matrix A is of rank 1 (i.e. it has a single non-zero eigenvalue), every feature of the matrix A is having some variability.
apply(A, 2, var)
# [1] 0.08313244 0.33252977 0.74819198

The point is that all columns are perfectly correlated with each other so the covariance matrix is singular.
cor(A)
#      [,1] [,2] [,3]
# [1,]    1    1    1
# [2,]    1    1    1
# [3,]    1    1    1

Comment: In your example, variability only exists along a single dimension because they are collinear (of course only after applying a transformation). I guess I wan't clear with my wording "no matter how we transform the data". Edit: Nevertheless, I see your point.


Helper para escrever HtmlHelpers

Question: Estou tentando escrever um HtmlHelper e vendo alguns exemplos básicos achei um com a classe TagBuilder que já ajuda:
namespace MyNamespace
{
    public static class MyHeleprs
    {
        public static MvcHtmlString Image(this HtmlHelper htmlHelper,
        string source, string alternativeText)
        {
            //declare the html helper
            var builder = new TagBuilder("image");
            //hook the properties and add any required logic
            builder.MergeAttribute("src", source);
            builder.MergeAttribute("alt", alternativeText);
            //create the helper with a self closing capability
            return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
        }
    }
}

Só que eu desejo criar um facilitador maior, para no fim manipular um valor que vai ser exibido, algumas classes css etc. Logo, não gostaria de ter que reescrever todo um helper que já existe como o TextBoxFor ou o EditorFor.
Partindo dessa vontade, então pensei em poder reaproveitar esses helpers e adicionar minhas manipulações.
Estava pensando em fazer o seguinte:
public static MvcHtmlString FieldFor<TModel, TProperty>(
    this HtmlHelper<TModel> htmlHelper,
    Expression<Func<TModel, TProperty>> expression,
    string cssClass = "",
    bool placeHolder = false,
    bool autoFocus = false,
    object htmlAttributes = null)
{
    var builder = new TagBuilder(
        htmlHelper.TextBoxFor(expression, htmlAttributes).ToString());

    // value attribute
    ...
    builder.Attributes["type"] = "text";
    builder.Attributes["value"] = value;

    // autofocus
    if (autoFocus)
        builder.Attributes.Add("autofocus", "autofocus");

    // css
    builder.AddCssClass(cssClass);

    // placeholder
    ...
    return new MvcHtmlString(builder.ToString(TagRenderMode.SelfClosing));
}

Enfim, destacando o que eu pensei:
var builder = new TagBuilder(htmlHelper.TextBoxFor(expression, htmlAttributes).ToString());

Mas o TagBuilder não funciona assim.
Manipular algo já pronto ajuda por não ter que ficar reescrevendo coisas que o framework já faz, como gerar a Id e o Name do elemento entre outros.
Como posso resolver isso? Qual seria um caminho mais prático?
Answer: Exemplo:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
namespace System.Web.Mvc
{
    public static class Methods
    {
        public static String ControllerName(this HtmlHelper HtmlHelper)
        {
            return HtmlHelper.ViewContext.RequestContext.RouteData.Values["controller"].ToString();
        }
        public static String ControllerName(this AjaxHelper AjaxHelper)
        {
            return AjaxHelper.ViewContext.RequestContext.RouteData.Values["controller"].ToString();
        }
        public static String ActionName(this HtmlHelper HtmlHelper)
        {
            return HtmlHelper.ViewContext.RequestContext.RouteData.Values["action"].ToString();
        }
        public static String ActionName(this AjaxHelper AjaxHelper)
        {
            return AjaxHelper.ViewContext.RequestContext.RouteData.Values["action"].ToString();
        }
        public static IHtmlString FieldFor<TModel, TProperty>(
            this HtmlHelper<TModel> htmlHelper,
            Expression<Func<TModel, TProperty>> expression,
            string cssClass = "",
            string placeHolder = "",
            bool autoFocus = false,
            object htmlAttributes = null)
        {
            IDictionary<string, object> htmlAttributesList = new Dictionary<string, object>();
            if (htmlAttributes != null)
            {
                foreach (PropertyInfo prop in htmlAttributes.GetType().GetProperties())
                {
                    htmlAttributesList.Add(prop.Name, prop.GetValue(htmlAttributes));
                }
            }
            if (!String.IsNullOrEmpty(cssClass))
            {
                htmlAttributesList.Add("css", cssClass);
            }
            if (!String.IsNullOrEmpty(placeHolder))
            {
                htmlAttributesList.Add("placeholder", placeHolder);
            }
            if (autoFocus)
            {
                htmlAttributesList.Add("autofocus", "autofocus");
            }
            return new MvcHtmlString(htmlHelper.TextBoxFor(expression, htmlAttributesList).ToHtmlString());
        }
    }
}

Obs: Existem além do que você tinha alguns métodos a mais que geralmente eu uso para montar alguma coisa padrão, mas, a sua dúvida seria assim a maneira de se fazer, sem a TagBuilder.
Como usar:
@Html.FieldFor(a => a.Nome);
@Html.FieldFor(a => a.Nome, htmlAttributes: new { id="Nome" })
@Html.FieldFor(a => a.Nome, cssClass: "", placeHolder: "", autoFocus: false, htmlAttributes: null)
@Html.FieldFor(a => a.Nome, "form-control", "Digite o seu nome", true, null)

Comment: Só lembrando que esse código ta testado e funcionou pelo menos nos meus testes não sei se passou algo qualquer coisa mantenha informado... vlw @TiagoSilva

Helper para escrever HtmlHelpers


monitor IO to tmpfs partition?

Question: How can I monitor the write speed to a tmpfs partition. It does not appear in the output of vmstat or iostat.
I am running several python processes that are writing heavily to tmpfs and contributing to load. The load is high but the CPU, memory, disk IO, etc is all nominal. The load seems to be taking this heavy tmpfs IO into account indirectly somehow. I'd love to know the write speed to have an idea of upper limits per host. I'm running blind any help would be appreciated.
Comment: Actually the softirq handling in Linux has very sophisticated locking capabilities and multicore friendly handling, see http://www.wil.cx/matthew/lca2003/paper.pdf But it could still be that there is some sort of contention here.
Comment: It's not really IO since it is all in RAM and as Janne said correctly,  no block-layer seems to be involved. It seems to me that it's more an allocator/pageing or locking problem. Check the percentage values in the "Cpu(s)" line of top (3rd line). One of these percentages should have a high value.
Comment: @AndreasM the software interrupts on one CPU is at ~35%. IOwait and all other lines are quite low. Is that level of soft ints enough to cause this load?
Comment: yes I think so. I'm not a kernel developer, but I guess the same interrupt handler is (probably) difficult to execute several times in parallel, that would require very fine locking IMHO. I suspect your python processes are communicating/sharing data via tmpfs and are hitting a limit. Maybe you can contact the developer(s) of that application about it to find other ways (shared mem, some sort of message queue etc)
Answer: tmpfs is not a block device, so ordinary I/O monitoring tools are no good for you.
One way to monitor write speed would be to use pv command. pv, Pipe Viewer allows you to see statistics about current process in situations you normally would be blackboxed, such as during compressing a huge log file or creating a tar ball.
Typical use cases of pv include stuff like this:
pv /path/to/your/log | gzip >/logarchivedir/log.gz
tar cvfz - /your/directory | pv >/outputdir/yourdir.tar.gz

I hope this helps you; you didn't tell us anything detailed.
Comment: I can't really modify the program or pipe the output in anyway, so I'm not sure this would be useful.  This is a good tool to keep in mind though so thanks!
Comment: Running PV adds its own bottlenecks, usually invisible at disk speeds, but they will be significant at RAM speeds.  Beware.
Comment: Why would tools such as `iotop` not work with non-block devices? This seems to be indeed correct; I mounted `tmpfs` on a folder, created a big file with `dd`, but `iotop` did not measure at all the writing speed, a rate of about 2 GB/sec.
Answer: I had the same monitoring desire - it occurs to me /dev/shm could be mounted to a loop device (ie. /dev/loop0) and that loop device can be monitored [1]. The problem is a loop device would need a static file that is formatted with it's own filesystem and that defeats the point of the speed with tmpfs.
But note while tmpfs cannot be easily monitored, /dev/ram0 etc. can be by default.
Perhaps a linux expert can comment if tmpfs can be mounted to a loop device directly, I am uncertain.
[1] iostat does not seem to report statistics on loop devices (tested on linux 3.14.27/fedora 19).

monitor IO to tmpfs partition?


Is "access administration pages" a valid access argument?

Question: In Drupal 7, it appears that access administration pages is a VALID access argument. Is this the case?
How can I determine all the correct access arguments?
Answer: That permission is defined from system_permission().
The access arguments that an access callback uses can be any value, as any access callback can define its own access arguments in the implementation of hook_menu().
If you are referring to the access arguments accepted from user_access(), which is normally the access callback used from most of the menus defined from Drupal modules, then the access arguments are just the string for the permission the user needs to have to access that menu. The "access administration pages" string is just a possible value, and third-party modules can extend the permissions adding new ones to the ones already defined from Drupal core modules.
To get all the permissions defined from the installed modules, and assigned to one of the roles used in your site, you can use the following snippet (it requires the Devel module):
$cache = array();
$result = db_query("SELECT rid, permission FROM {role_permission}");

foreach ($result as $row) {
  $cache[] = $row->permission;
}

dsm(array_unique($cache));

To get any permission defined from the modules enabled in your site, you can use the following snippet:
$permissions = module_invoke_all('permission');
dsm($permissions);

The difference between the snippets is that the first one can return also the permissions defined from a module that you disabled, as long as the permission has been assigned to a role; the second only returns the permissions defined from currently enabled modules. If you have temporary disabled a module, the second snippet will not return its permissions.


Early stopping using tensorflow tf.estimator ?

Question: I am using tensorflow v1.4. I want to use early stopping using the validation set with a patience of 5 epochs.
I have searched on the web and found out that there used to be a function called ValidationMonitor but it is depreciated now. So is there a way to achieve this  ?
Answer: There doesn't seem to be a good way of doing this, unfortunately. One method to consider is to save checkpoints quite often during training, and then later iterate over them and evaluating them. Then you can discard the checkpoints that does not have the best eval performance. This doesn't help you in saving time during training, but at least the resulting model you are left with is an early stopping model.
Comment: Thank you, for  the answer :) . What you suggested is an obvious solution, I'm using it right now. It would be nice to save the training time.
Answer: Recently I have come across this function in tensorflow API.
tf.keras.callbacks.EarlyStopping. tf version is r1.9.
Arguments:

monitor: quantity to be monitored
min_delta: minimum change in the monitored quantity to qualify as an improvement, i.e. an absolute change of less than min_delta, will count as no improvement.
patience: number of epochs with no improvement after which training
will be stopped.
verbose: verbosity mode.
mode: one of {auto, min, max}. In min mode, training will stop when
the quantity monitored has stopped decreasing; in max mode it will
stop when the quantity monitored has stopped increasing; in auto
mode, the direction is automatically inferred from the name of the
monitored quantity.
Comment: Can it be used in combination with estimators?
Comment: As far as I know, it can't be used with estimator. `tf.keras` is `Keras API` that can be used in tensorflow. This answer solved my problem but it can not be used with estimators.


Statistically group chemical batches

Question: I have 80 chemical batches, each of which has 8 associated measurements like pH, viscosity, etc.  Is there a way to use Principal Components Analysis or Factor Analysis to group the similar batches together?  I know I can use cluster analysis, but I want to have a different visual representation of batch groups other than the dendogram.  I'd like to have a bi-plot.  I tried to perform a PCA, but got an error message that there cannot be more variables than observations.  My matrix has the 80 batches as the column names, and the 8 measurements as the row names.  When this matrix is transposed, PCA just groups the like measurements, not the batches.
Comment: transpose your data. You sample 8 measurements and the each batch is an element in your sample. In this case PCA expects batches in rows and measurements in the columns.
Comment: Which software are you working with?
Answer: You'll be hard-pressed to show an 8-D representation of sets of similar batches using anything but a dreary table.  But, along the lines of Bill's point I think, if you're willing to select the 3 most interesting or most discriminating dimensions, you could show where each batch falls within a cube defined by those 3.  Perhaps better is to first do a cluster analysis and then show where each cluster falls within such a cube.  Some software (such as SPSS) will allow you to assign each batch a color or a symbol according to its cluster, and you could draw spikes from each point to its cluster's centroid to create a nice, vivid effect.
Answer:
As already stated (by @mpiktas), in order to do PCA, you need to transpose your data so that chemical batches are rows and "measurements" are columns.
You can then run a PCA on the data and plot the 80 chemical batches on axes derived from the first two components.
Here's an example on Quick-R of doing this in R.
Also a small supplementary suggestion, you might want to have a look at Chernoff faces.
They present a face where each of your eight variables would represent a feature on the face. The size or shape of the feature indicates something about the variable. Flowing data has a  tutorial in R with images.
Answer: You need to be more specific about what you mean by "similar", and provide some type of example.   Maybe the following will help as an example of 8 batches with 3 measurements.    Feel free to change it if you think it will help.
<code>texinp <- "
Batch M1 M2 M3
1  0.01  14  -123
2  0.03  23    30
3  0.02  12    23
4  0.01  18  -107
5  0.04  49   110
6  0.01   8  -101
7  0.02  11    11
8  0.01  14  -115"

#Read the data into a data frame
df <- read.table(textConnection(texinp), header=TRUE)
df

#Plot some stuff
plot(df$M1, df$M2)
plot(df$M2, df$M3)
plot(df$M1, df$M3)
</code>
If you're not using R, show the example in whatever you're using.
Answer: I'm not pretty sure, but i think that if you more variable than observation  the Partial Least Square (PLS) regression is the right tool for you, and it's commonly used by chemometrician.
As you know this site is R biased and i use R too, so i'll recommend to take a look at pls package package which can also do principal component regression, and it also have a biplot.mvr (S3 method for biplot) function to make a biplot.
A good starting point can be http://mevik.net/work/software/pls.html , is the website of package's author and have some useful link like the journal of statistical software article about the R package pls.

Statistically group chemical batches


Why is server FIN'ing after starting TLS session?

Question: TLS server is doing something I don't understand.

TCP handshake executes normally.
SSL Client Hello executes normally.
SSL Server Hello seems normal.  Provides certificate, says Server Hello Done.
Dissection shows client issues "Client Key Exchange, Change Cipher Spec, Encrypted Handshake Message"
Dissection shows server issues "Change Cipher Spec" then "Encrypted Handshake Message"

Client now ACKs, starts to send data.  But server ACKs then sends an "Encrypted Alert" and FIN's out.
This has happened just after swapping out certs.  The cert presented in the SSL handshake is the new key.
Clue, anyone?
Comment: It sounds like there might have been a protocol violation somewhere, or there is a problem with the new certificate... dig a bit using openssl perhaps?  Especially, try using openssl s_client?
Answer: Its probably due to an SNI issue with either the client or some device in the middle, like a load balancer.  The load balancing device must be able to present the server name to the backend host as part of the initial Client Hello.   see https://en.m.wikipedia.org/wiki/Server_Name_Indication
Answer: The most important packet is the "Encrypted Alert" as it contains the reason why the connection is closed.
It seems to be a validation error. This means that the certificate is not trusted, or invalid. But the real reason is send via the TLS Alert protocol
Comment: Its not a validation error on the cert side or you wouldn't get "change cipher spec" and handshake, which leaves only SNI - very good point about TLS alert- which would of course provide the definitive answer.
Comment: TLS alert shows in hex 15 03 01 00 12 e1 54 de 28 35 56 9d d6 d1 1e 25 e7 6e 00 dc bd a7 e5. I think this means 0x15 == alert, 03 01 == TLS 1.0, 0x0012 == length of 18, and then we should see level and description, but I can't understand what it is telling me.
Comment: Use Wireshark. It has a protocol dissector for TLS. If it doesn't recognize the stream as SSL/TLS, you can change this with: "Decode As..." from the context menu of a SSL/TLS packet.
Answer: I've run into a similar issue with pure-ftpd in explicit TLS mode (FTPS server).
In my case though, there was no Encrypted Alert sent from server; it just Fin'd immediately after key exchange (Change Cipher Spec, Finished message from server → FIN from server). Next, the client sent the Encrypted alert, level 1 code 0 Close Notify (which is expected — unlike the server FIN).
This happened only with one single specific client (a device firmware), and didn't reproduce with other ftps clients.
I haven't dig up the root of the issue, but I suspect we hit a server bug. pure-ftpd uses apache-like fork-per-connection model; and I observed the child process crashing in gdb (exiting with code -1) — which of course leads to the OS closing the socket FD and sending FIN.
One more reason to say its a server bug in my case — the behavior stopped reproducing as soon as we swapped out the ftps server for a different implementation, proftpd.

I don't think this matches the OP case — there, server ends the connection in TLS-appropriate way, with Encrypted Alert — but nevertheless, something to consider for anyone hitting this page.


Finding the number of teams

Question: I played in a online tournament of a game of some sorts, and I want to know how many teams they were.
I have the following informations :

The team who finished in first place were on the Top 0.001%
The team who finished in 9501th place were on the Top 0.287%
The team who finished in 10000th place were on the Top 0.302%

Thank you math genius that you are!
Answer:
The team who finished in 10000th place were on the Top 0.302%

In other words 10,000 teams make up 0.302% of the entire pool.
Then 20,000 teams make up 0.604% (since $2*10,000=20,000$ and $2*0.302\% = 0.604\%$)
and  30,000 teams make up 0.906% (since $3*10,000=30,000$ and $3*0.302\% = 0.906\%$)
...
and  3,310,000 teams make up 100% (since $331*10,000 = 3,310,000$ and $331*0.302\% \approx 100\%$)
Comment: try using this template to figure out the solution and report back where it gets you
Comment: Thanks!! Bonus question, was that ways about our rank in we were in the 38% ?

Finding the number of teams


Unable to install the Cloudinary Integration module

Question: I downloaded the Cloudinary Integration module and installed it.
The module appears in the module list, but I cannot enable it. The modules page shows this message after the description of the module.

Requires: Cloudinary Stream Wrapper (disabled), Cloudinary SDK (disabled), Libraries (missing)
Answer: You haven't installed the dependencies.
They're listed on the module page:

Requirements

Libraries
Cloudinary SDK for PHP
Cloudinary API Account

Download each of those as well, then try again.
Comment: where to put those folders?
Comment: They're all modules - same place as you put the other one
Comment: I kept those libraries, cloudinary, cloudinary php master folders in Myproject/sites/all/modules.. Is that correct? Still there are some errors  in Myproject/admin/config/media/cloudinary.  *"Please make sure the Cloudinary SDK library is installed in the libraries directory.
The Cloudinary SDK for PHP library could not be found."*


Linux head and tail equivalent command in MySQL

Question: In Linux, it's easy to get first few data from top or bottom with head and tail command.
wolf@linux:~$ cat db.txt
| information_schema |
| database_name      |
| mysql              |
| opencart           |
| wordpress          |
| performance_schema |
| sys                |
wolf@linux:~$

top 2
wolf@linux:~$ cat db.txt | head -2
| information_schema |
| database_name      |
wolf@linux:~$

Last 2
wolf@linux:~$ cat db.txt | tail -2
| performance_schema |
| sys                |
wolf@linux:~$

Is there any similar command in MySQL?
All databases
mysql> SHOW DATABASES;
+--------------------+
|     Databases      |
+--------------------+
| information_schema |
| database_name      |
| mysql              |
| opencart           |
| wordpress          |
| performance_schema |
| sys                |
+--------------------+

7 rows in set (0.00 sec)
mysql>

Desired Output: Top 2 database
mysql> <mysql command here>
+--------------------+
|     Databases      |
+--------------------+
| information_schema |
| database_name      |

Desired Output: Last 2 database
mysql> <mysql command here>
| performance_schema |
| sys                |
+--------------------+

Comment: Why would you do this? Its probably going to break at some point as you can't rely on ordering of result to an SQL query unless you specify a field to order on.
Comment: For the commandline mysql tool, see `pager`.  For your two examples:  `pager head -5` and `pager tail -4` would get those outputs.
Answer: In MySQL there is no command that would resemble head or tail.
The easiest way would be to execute a mysql query on the shell using mysql -e and then piping the result to head or tail, e.g.
$ sudo mysql -e "SHOW DATABASES" --defaults-file=/etc/mysql/debian.cnf | tail -2
performance_schema
sys

If you want to do this from within the mysql shell you'd need to query the information_schema database like this:
mysql> (SELECT `SCHEMA_NAME` FROM `information_schema`.`SCHEMATA`
ORDER BY `SCHEMA_NAME` DESC LIMIT 2) ORDER BY `SCHEMA_NAME`;
+--------------------+
| SCHEMA_NAME        |
+--------------------+
| performance_schema |
| sys                |
+--------------------+
2 rows in set (0,00 sec)

where you use LIMIT to restrict the result set to the number of desired rows.


onTapGesure not registering for background of ScrollView

Question: For some reason, the .onTapGesture event won't fire for the background of the ScrollView, but it does fire correctly when applied to the background of a nested VStack view:
    var body: some View {
        ScrollView {
            VStack {...}
            .background(
                Rectangle()
                    .fill(.red)
                    .onTapGesture {
                        print("!!!CLICKED!!!")
                    }
            )
        }
        .background(
            Rectangle()
                .fill(.green)
                .onTapGesture {
                    print("!!!CLICKED!!!")
                }
        )
    }

So when I click the red area, I'm able to see "!!!CLICKED!!!" printed, but when I click the green area, nothing is printed:
ViewLayout image
Answer: To trigger the action on the background of the ScrollView, just move the .onTapGesture() modifier to the bottom of the ScrollView itself, instead of the .background().
Here below, you will see a sample code that works (I added a couple of variables to notice the effect directly on the screen):
@State private var clicked = "Nothing"  // For testing purposes only
@State private var alternate = true     // For testing purposes only

var body: some View {
    ScrollView {
        VStack {
            Text("One")
            Text("Two")
            Text("Three")

            Text(clicked)  // For testing purposes: see what was clicked on the screen
                .padding()
            Text(alternate ? "Clicked" : "... and again")  // See the effect after each click
        }
        .background(
            Rectangle()
                .fill(.red)
                .onTapGesture {
                    clicked = "Clicked red"
                    alternate.toggle()
                    print("!!!CLICKED RED!!!")
                }
        )
    }

    // Here is where the modifier should be to trigger the action on the background of the ScrollView
    .onTapGesture {
        clicked = "Clicked green"
        alternate.toggle()
        print("!!!CLICKED GREEN!!!")
    }
    .background(
        Rectangle()
            .fill(.green)
    )
}

Comment: Awesome! Can't believe I didn't think of that. Works like a charm, thanks @HunterLion!


Jazz Theory Prerequisites

Question: What topics should I master on music theory before I move on to jazz guitar? Is it necessary to learn blues guitar? I have basic knowledge of music theory, like major and minor chords.
Comment: How about practice, what can you do in practice? Why do you think you need more theoretical knowledge on topics? :) Can you play songs by ear? Can you identify chords by ear? Do you know what a chord will sound like before you play it? Can you improvise new chord progressions for melodies? :) Can you play songs in different keys?
Comment: If I did, I would have posted a link to it. Anyway, find the melody and chords to Twinkle Twinkle Little Star by ear and play it in different keys. Then Let It Be.
Comment: @NewGuitarMan, any list will be partly a matter of taste.  But there is a history to Jazz and Jazz guitar that cannot be denied.  As for learning guitar, get your hands on Mel Bay or William Levitt's beginner books and work through them, preferably with an instructor.  As for simple melodies.  Miles Davis was as gifted as Mozart when it came to writing memorable melodies.  Give the following a listen, Kind of Blue and Birth of Cool.  Specifically,  Four, All Blues, So What.
Comment: Don't look at a real book or other anthology.  That will be utterly meaningless w/o context.  Listen to Kenny Burrell's debut album, specifically Don't Cry Baby.  You are, after all, a guitarist and Kenny is a great.  Listen to Wes Montgomery's Debut album, specifically 4 on 6, West Coast Blues.  Also try Ah Um and The Clown by Mingus.  In Be Bop land, Parker and Diz, look up A night in Tunisia, Ornithology, Donna Lee, Groovin' High.  Just listen, don't play.  Ask yourself if you like it and want to learn it.  These are oldies but still goodies.
Comment: I totally forgot the Latin influence!  Jobim, Brazilian Jazz, listen to Wave (brilliantly beautiful), there is a live recording of him playing with his son and Herbie Hancock at the Brazilian Jazz fest early 2000's.  It's a great rendition.
Comment: Thanks to everybody who answered. To your question i cannot play songs by ear or identify chords ear. So How could i learn it?
Comment: The most important step is to start. Simple melodies, simple chords, simple songs. Happy Birthday, Twinkle Twinkle Little Star, that sort of thing. Play them in different keys. Let It Be? Yesterday? Smile? I Just Called to Say I Love You? Careless Whisper? Almost any "old" pop song will most probably contain some new thing to learn. It would be great to have a big catalogue of songs classified by difficulty in various aspects. With such a list all you'd have to do is learn each song by ear, and the list ordering would guarantee there's only one new thing to learn.
Comment: Do you know any such list :)?
Answer: You should not master anything as a prerequisite for learning Jazz guitar.  There is no hierarchy of styles.  If you like Jazz start with Jazz.  I would say the only real prerequisite is that you actually like Jazz as a style of music.  If you don't you will never enjoy learning it and never play it well.  Start by LISTENING.  That is what music is, experiencing sound.  Listen to the greats starting with Eddie Lang, Charlie Christian, Django Reinhardt, Wes, Joe Pass, Pat Martino, Grant Green, George Benson, John Scofield, Pat Metheny, Allan Holdsworth, Al Dimeola, Ronnie Jordan, and on and on, picking what you like from the list and dropping the rest.  A key to great musicianship is being a good listener in every respect.  So, listen to people you like, start transcribing their licks by ear if you can, get your hands on transcriptions or TAB as needed.  Take lessons.
Some folks might start throwing a list of music theory prerequisites but this is really misleading.  Theory comes after practice!
Also, listen to other instruments.  Coltrane, Davis, Parker, Dizzy, Bill Evans, Mingus, Monk, Duke, Count, etc.  Jazz is a culture not an exercise.
Comment: Don't know if you have to be a jazz fan to enjoy those amazing artists though. That moment when you learn that Django actually has a disability and STILL shreds like that, priceless.
Comment: I agree, great music and musicians should transcend style.  But some people just dont respond the same way.
Comment: +1 for "If you like Jazz, start with Jazz."  I once liked the idea of learning to play Jazz, because Jazz musicians generally understand what they're doing when they play.  The problem was that I don't care to listen to Jazz.  I changed my focus to learning to play the songs that I love, as well as try to understand the theory.  If there's an occasional jazzy chord, then great.  I will occasionally read about Jazz theory, and talk to my teacher about it.
Answer: Don't worry about 'theory', unless by that you mean basic musical literacy - reading notes and rhythms.  That always comes in useful!
And beware.  There's a lot of half-assed 'theory' in the jazz guitar world. Listen, read, copy.  Look at WHAT various books and other forms of instruction tell you to play.  Don't get too hung up on their WHY explanations though.
Answer: If you don't know more than basic majors and minors you're going to struggle.
Theory wise, the need to know what it is that makes a chord that chord is pretty important. being ablee to play in every key , so knowing what that entails, is paramount, as is knowing your instrument really well, and being able to hear something and repeat it, pretty well note for note - good ears. that's a  start.

Jazz Theory Prerequisites


How to make Image change to show it is being pressed?

Question: I am working on a project for a mobile bidding system. I am designing the front end of it and ran into a problem with the two buttons that I am using. There are two buttons: 1) raise bid; 2) bid.
Now that being said here is my code
<input class="btnraise" type="image" src="bidraise.png" onclick="raiseBid();"/>
<input class="btnbid" type="image" src="mobilebid.png" onclick="Bid();"/

That works fine. Except the CEO wanted the buttons to kind of wrap around each other. The raise button is a triangle with a concave bottom where a round circle bid button fits up almost touching the concave bottom of the triangle. (not sure if this makes sense) Almost like a golf ball sitting on a tee upside down. This is the CSS I am using to make them almost touch:
.btnbid{
width:250px;
position:relative;
top:-79px;
}

.btnraise{
width:230px;
}

Anyway, I need to make these buttons change (like they are indented) when they are pressed. So I did this:
<input class="btnraise" type="image" src="bidraise-up.png" onmousedown="this.src='bidraise-down.png'" onmouseup="this.src='bidraise-up.png'" onclick="raiseBid();"/>
<input class="btnbid" type="image" src="mobilebid-up.png" onmousedown="this.src='mobilebid-down.png'" onmouseup="this.src='mobilebid-up.png'" onclick="Bid();"/>

That worked just fine on a PC..... But It doesn't work well on a mobile device. The device I have access to is a 3rd or 4th gen iPod Touch. It doesn't change because there is no mouse... I didn't think that one through did I?
So I googled around and found some things that might work. Things like changing the input type from image to button but then they don't line up right. I lose the round bid image sitting inside the concave part of the triangle. So I was thinking that if I just added both events inside of the onclick event then it would work, so I tried this:
<input class="btnbid" type="image" src="mobilebid-up.png" onclick="this.src='mobilebid-down.png'; Bid();this.src='mobilebid-up.png';"/>

This didn't change the image for the mobile. Any ideas? Do I need to take a different approach to this or is there something different for effects on a mobile site?
Answer:
This is what I did:
1) Added id="btnbid"
2) Added ontouchstart event
3) Added ontouchend event
<input id="btnbid" class="btnbid" type="image" src="mobilebid-up.png" ontouchstart="touchStart()" ontouchend="touchEnd()"/>

Then I put this in the script tag:
var btnbid = document.getElementById('btnbid');
btnbid.addEventListener('touchstart', toucchStart, false);
btnbid.addEventListener('touchend', touchEnd, false);

function touchStart( event ) {
document.getElementById("btnbid").src="mobilebid-down.png";
 return false;
}
function touchEnd( event ) {
document.getElementById("btnbid").src="mobilebid-up.png";
return false;
}

This gave me the desired effect!!!
Answer: You should try onTouch() instead of onclick
Comment: This is an answer. He is using onclick which works with PCs but not with mobiles. He wants it to work with mobiles. My answer of ontouch() is correct and would resolve this issue. This isn't a comment or an opinion.
Comment: Thanks so much! I am on the right track. The image changes now. Is there a way I can capture or display the image while it's being touched and then change when it's not?
Comment: Glad i could be of some help


Retorno de um List Da View para o Controller - Asp.Net Core

Question: Possuo uma viewmodel chamada Perfil, nesta viewmodel há uma propriedade List de ItensPerfil e uma string - título.
public class PerfilViewModel
{
    [Key]
    [DisplayName("Código")]
    public int Id { get; set; }

    [Required(ErrorMessage = "O campo {0} é obrigatório")]
    [StringLength(50, ErrorMessage = "O campo {0} deve ter no mímino {1} caracteres")]
    [DisplayName("Título")]
    public string Titulo { get; set; }

    public IEnumerable<PerfilItens> ItensPerfil { get; set; }
}

Os atributos da classe ItensPerfil são boleanos: visualizar, criar, editar e excluir e mais um, inteiro (id) que indica o Perfil deste ItensPerfil.
Crio minha view desta forma:
var viewModel = new PerfilViewModel();
var itens = Bootstrap._listaPerfil;

viewModel.ItensPerfil = itens.Select(x => new PerfilItensViewModel
{
    ItemMenu = x.ItemMenu,
    Criar = x.Criar,
    Visualizar = x.Visualizar,
    Excluir = x.Excluir,
    Editar = x.Editar
});

return View(viewModel);

A função Bootstrap._listaPerfil() apenas carrega os itens de perfil que devem ser criados.
A view aparece perfeitamente, através de um for ou foreach consigo gerar para o usuário dos os itens do perfil, ele só precisa inserir um título e marcar ou não, via checkbox, os itens.
    <form asp-action="Create">

            <input asp-for="Descricao" class="form-control" />

        @foreach (var item in Model.ItensPerfil)
        {

                @item.ItemMenu

                <input type="checkbox" asp-for="@item.Visualizar" checked="@item.Visualizar" />

                <input type="checkbox" asp-for="@item.Editar" checked="@item.Editar" />

                <input type="checkbox" asp-for="@item.Criar" checked="@item.Criar" />

                <input type="checkbox" asp-for="@item.Excluir" checked="@item.Excluir" />

        }

            <input type="submit" value="Create" class="btn btn-default" />

    </form>

Agora vamos ao problema, quando retorna para a função Create por Post o Perfil vem corretamente, o título aparece certinho, mas os itensPerfil retorna como null.
Alguma solução para isto?
Comment: No método onde você seleciona os dados, você está dando `Include` dos `ItensPerfil`. Poste também o código do método de seleção..
Comment: Coloque o código na pergunta.
Answer: Barbetta, seria isso que vc queria ver?
public class Bootstrap
{
    public static List<PerfilGenerico> _listaPerfil { get; private set; }

    public static void Configuracao(IServiceCollection services)
    {
        SetListaPerfil();

        services.AddScoped<IAmbiente, AmbienteRepositorio>();
        services.AddScoped<IAmbienteApp, AmbienteApp>();

        services.AddScoped<ICidade, CidadeRepositorio>();
        services.AddScoped<ICidadeApp, CidadeApp>();

        services.AddScoped<IEstado, EstadoRepositorio>();
        services.AddScoped<IEstadoApp, EstadoApp>();

        services.AddScoped<IPerfil, PerfilRepositorio>();
        services.AddScoped<IPerfilApp, PerfilApp>();

        services.AddScoped<IPerfilItens, PerfilItensRepositorio>();
        services.AddScoped<IPerfilItensApp, PerfilItensApp>();
    }

    private static void SetListaPerfil()
    {
        _listaPerfil = new List<PerfilGenerico>
        {
            new PerfilGenerico { Classe = "Ambiente" },
            new PerfilGenerico { Classe = "Cidade" }
        };
    }
}

 public class PerfilGenerico
{
    public string Classe { get; set; }
    public bool Visualizar { get; set; }
    public bool Criar { get; set; }
    public bool Editar { get; set; }
    public bool Excluir { get; set; }
}

Answer: Resolvido. Neste caso não se pode utilizar List porque no HTML os IDs nos inputs dentro do loop se repetem e causam o problema, deve-se utilizar vetor.
Comment: Não se esqueça de marcar como respondida a pergunta. https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/1079#1079


Maior espaço entre os itens do spinner

Question: Estou criando um app que possui spinner, porem ao abrir os itens estão sempre colados uns nos outros, gostaria de saber se apenas por custom spinner eu consigo dar espaço ou existe algum style/tema que ja possua esses espaços...as classe e tudo ja está criado só falta o layout funcional ao abrir o spinner
Comment: Aleff, como está montando o layout dos seus itens? em geral basta adicionar um padding para dar um espaçamento...
Answer: Você pode mudar a aparência do seu spinner mudando o adaptador que foi usado para o mesmo com o seguinte comando:
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

O simple_spinner_dropdown_item é o layout padrão para spinners. Creio que seja isso que procuras. Se preferires podes também criar um estilo customizado.
Answer: Crie o seu próprio adapter, assim você pode customizar da forma que preferir.
Exemplo:
public class ListAdapter extends ArrayAdapter {
public ListAdapter(Context context, int textViewResourceId) {
    super(context, R.id.campotexto);
}

public ListAdapter(Context context, int resource, List<Item> items) {
    super(context, resource, items);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    View v = convertView;

    if (v == null) {
        LayoutInflater vi;
        vi = LayoutInflater.from(getContext());
        v = vi.inflate(R.layout.linhacustomizada, null);
    }

    Item p = getItem(position);

    if (p != null) {
        TextView tt1 = (TextView) v.findViewById(R.id.id);
        TextView tt2 = (TextView) v.findViewById(R.id.categoryId);
        TextView tt3 = (TextView) v.findViewById(R.id.description);

        if (tt1 != null) {
            tt1.setText(p.getId());
        }

        if (tt2 != null) {
            tt2.setText(p.getCategory().getId());
        }

        if (tt3 != null) {
            tt3.setText(p.getDescription());
        }
    }

    return v;
}

}

Maior espaço entre os itens do spinner


Applications of the Little and Great Theorems of Picard

Question: I have completed the two famous theorems of Picard, presenting their proofs in a graduate course of Complex Analysis, but I have not managed to discover a good number interesting applications.
List of applications (rather straight-forward though):

If a meromorphic function on $\mathbb C$ misses three values, then it is constant.
The equation $f^3+g^3=1$ has non-trivial meromorphic in $\mathbb C$ solutions
only if $n\le 3$.
If $f$ is entire and one-to-one, then it is linear.
If $f,g$ are entire and $g'=f(g)$, then $f$ is linear or $g$ is constant.

Could you provide any interesting applications of these theorem?
Comment: [Another one posted here](https://math.stackexchange.com/q/2718167/551819)
Comment: You probably mean $f^n+ g^n = 1$ at no 2.
Comment: Could you provide a source/proof for claim 4 in the question? I am not able to prove it.
Answer: An interesting consequence is that if $X = \mathbf{P}^1(\mathbb C)-\{p_1, \dots, p_n\}$ is the Riemann sphere with $n$ punctures, then $\widetilde X$, the universal covering space of $X$, is the upper-half plane for $n\geq 3$. Indeed, $\widetilde X$ must be simply-connected, and by Riemann's theorem it is either $\mathbf{P^1}(\mathbb C)$, $\mathbb C$, or the upper-half plane $\mathfrak h$. It cannot be $\mathbf{P^1}(\mathbb C)$ because $X$ is not compact; it cannot be $\mathbb C$ by Picard's theorem; therefore it is $\mathfrak h$.
Corollary: For each $n \geq 3$, $\text{PSL}_2(\mathbb R)$ contains a copy of $F_n$, the free group on $n$ generators (and therefore also for $n=2$).
Indeed this follows from the theory of covering spaces; the group of deck transformation of $\widetilde X \to X$ is $\pi_1(X)\cong F_n$. On the other hand, $\text{Aut}(\mathfrak h) \cong \text{PSL}_2(\mathbb R)$.
Comment: Can you explain something to me Bruno? It seems as though what you're using is the Uniformization Theorem (the classification of simply connected Riemann surfaces). How does that follow from the big/small Picard theorems? The proof I know uses Green's functions/differential geometry.
Comment: He assumes the uniformization theorem and then uses the fact that an analytic function from $\tilde{X}$ will omit too many values unless it's constant.  But yes, the majority of the strength is from uniformization.

I'm not sure about an alternate proof of the uniformization theorem, but classifying admissible analytic maps between spherical/flat/hyperbolic complex surfaces can be done using some normal families and dynamics (esp. hyperbolic compactness theorem).  So just exhibit the hyperbolicity of a 2+ punctured sphere directly.

Lee's Topological Manifolds takes a stab at this.
Answer: In general, a Holomorphic map from $\mathbb C\to \mathbb C $ does not have a fixed point. But using the Little Picard theorem, we can prove that even though $f$ does not have a fixed point, $f\circ f$ does have a fixed point until unless $f$ is translation function.
More precisely, the statement is as follows:
Theorem: Let $f: \mathbb{C} \rightarrow \mathbb{C}$ be holomorphic. Then $f \circ f: \mathbb{C} \rightarrow \mathbb{C}$ always has a fixed point unless $f$ is a translation $z \mapsto z+b, b \neq 0$.
Proof. Suppose $f \circ f$ has no fixed points. Then $f$ also has no fixed points (if it has then that also fixed point of $f \circ f$), and it follows that $$g(z):=\left.\frac{f(f(z))-z} {f(z)-z}\right. $$ is entire function. This function omits the values $0$ and $1$ ( If it does then that implies flex point) ; hence, by Picard, there exists a $c \in \mathbb{C} \backslash\{0,1\}$ with
$$
f(f(z))-z=c(f(z)-z), \quad z \in \mathbb{C}
$$
By differentiation and rearranging terms gives $$f^{\prime}(z)\left[f^{\prime}(f(z))-c\right]=1-c .$$ Since $c \neq 1$ (if equals to 1 then it implies fixed point), $f^{\prime}$ has no zeros and $f^{\prime}(f(z))$ is never equal to $c$. Thus $f^{\prime} \circ f$ omits the values 0 and $c \neq 0$ by Picard, $f^{\prime} \circ f$ is therefore constant. It follows that $f^{\prime}=$ constant, hence that $f(z)=a z+b .$ Since $f$ has no fixed points, $a=1$ and $b \neq 0$
So we have proved that when $f\circ f$ has no fixed point, then $f$ is translation.


Redirect URL with parameters in web2py controller

Question: I am trying to redirect to a URL('form','results') from forminput.html with parameters (in my case, it's a huge dictionary i.e. output). But when the web page is redirected to results.html, all the parameters are also included in the web Url itself, which what we don't want for two reasons, security and lenthy type of urls.
Can you help me in this scenario ?
Thanks in advance
Here is the sample of URL.
http://127.0.0.1:8000/AWS/form/results?csp=&ibx=&metro=&o=%7B%22se1.sv1%22%3A+%7B%22xe-0%2F2%2F1%22%3A+%7B%22Util%22%3A+66%2C%22c_name%22%3A+%22dxcon-fh26tz6s%22%2C%22c_serial%22%3A+%2215563580-A%22%7D%2C%22xe-2%2F1%2F3%22%3A+%7B%22Util%22%3A+31%2C%22c_name%22%3A+%22dxcon-fgptdigg%22%2C%22c_serial%22%3A+%2220130277-A%22%7D%2C%22xe-3%2F0%2F3%22%3A+%7B%22Util%22%3A+0%2C%22c_name%22%3A+%22SFDC-SV3-CX-SEC-01%22%2C%22c_serial%22%3A+%2220375541-A%22%7D%2C%22xe-3%2F1%2F2%22%3A+%7B%22Util%22%3A+0%2C%22c_name%22%3A+%22dxcon-ffj66n3f%22%2C%22c_serial%22%3A+%2220347645-A%22%7D%2C%22xe-3%2F2%2F3%22%3A+%7B%22Util%22%3A+0%2C%22c_name%22%3A+%22dxcon-fgsmxuat%22%2C%22c_serial%22%3A+%2220366330-A%22%7D%7D%7D#
<code>/*this my controller, form.py*/

my_funct():
    out_dict=dict()  // out_dict is a huge dictionary with 100 of keys and values
    return out_dict

define forminput():
    outout=my_funct()
    redirect(URL('form','results', vars= dict(out=output)))

define results():
    data=request.vars['out']
</code>
Answer: You can instead store the data in the session (which remains on the server):
<code>define forminput():
    session.data = my_funct()
    redirect(URL('form', 'results'))

define results():
    data = session.data
</code>
Comment: Thanks a lot, Anthony. It worked for me. This is what exactly I wanted.


Parse error: syntax error, unexpected end of file, expecting elseif (T_ELSEIF) or else (T_ELSE) or endif (T_ENDIF)

Question: Hello dear i want to create a customer blade which provides users to import and export excel file.
My customers_blade.php looks like this;
@extends('layouts.app')

@section('content')

Import and Export Data Into Excel File

    {!! Form::open(array('route'=>'customer.import','method'=>'POST','files'=>'true')) !!}

            @if(Session::has('success'))

                    {{Session :: get('message')}}

                @if(Session::has(warning))

                    {{Session::get('message')}}

                @endif

                    {!! Form::label('sample_file','Select File to Import:',['class'=>'col-md-3']) !!}

                        {!! Form::file('customers',array('class'=>'form-control')) !!}
                        {!! $error->first('products','
:message'btn btn-success']) !!}

    {!! Form::close() !!}

@endsection

But when i go to page this error occurs. How can i edit it. Can you please help me?
Parse error: syntax error, unexpected end of file, expecting elseif (T_ELSEIF) or else (T_ELSE) or endif (T_ENDIF) (View: /home/vagrant/code/excel/resources/views/customers.blade.php)
Answer: If you notice in your blade file you will find that you are missing @endif
                    @if(Session::has('success'))

                            {{Session :: get('message')}}

                    @endif

In the above section  @if(Session::has('success')) this If was not ending anywhere.
@extends('layouts.app')

@section('content')

Import and Export Data Into Excel File

    {!!

    Form::open(array('route'=>'customer.import','method'=>'POST','files'=>'true')) !!}

                @if(Session::has('success'))

                        {{Session :: get('message')}}

                @endif
                    @if(Session::has(warning))

                        {{Session::get('message')}}

                    @endif

                        {!! Form::label('sample_file','Select File to Import:',['class'=>'col-md-3']) !!}

                            {!! Form::file('customers',array('class'=>'form-control')) !!}
                            {!! $error->first('products','
:message'btn btn-success']) !!}

        {!! Form::close() !!}

    @endsection

Hope this helps


Converting FuzzykMeans to SphericalFuzzyKMeans?

Question: I grabbed an implementation of FuzzyKMeans (FuzzyCMeans) from the nightly build of the Apache Commons Math library, but I now realize I need to use Cosine Similarity instead of the Euclidean Distance. Of course, just plugging in Cosine Similarity caused the algorithm to end up in an infinite loop (I tested it just in case, by some miracle, it would work).
I've looked into the differences between KMeans and SphericalKMeans to try and see how I should change FuzzyKMeans to become SphericalFuzzyKMeans, but I'm very inexperienced with clustering and am having trouble distilling any practical information from theoretical papers.
So, what I'm looking for is a practical explanation of the differences between FuzzyKMeans and SphericalFuzzyKMeans, not just a theoretical one.
Any pointers would be EXTREMELY helpful, even if you can't say exactly what needs to be changed in the following code. Even what you suspect should be changed would go a long way in helping me.
Here's the implementation of FuzzyKMeans (FuzzyCMeans) that I have:
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.commons.math3.ml.clustering;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import org.apache.commons.math3.exception.MathIllegalArgumentException;
import org.apache.commons.math3.exception.MathIllegalStateException;
import org.apache.commons.math3.exception.NumberIsTooSmallException;
import org.apache.commons.math3.linear.MatrixUtils;
import org.apache.commons.math3.linear.RealMatrix;
import org.apache.commons.math3.ml.distance.DistanceMeasure;
import org.apache.commons.math3.ml.distance.EuclideanDistance;
import org.apache.commons.math3.random.JDKRandomGenerator;
import org.apache.commons.math3.random.RandomGenerator;
import org.apache.commons.math3.util.FastMath;
import org.apache.commons.math3.util.MathArrays;
import org.apache.commons.math3.util.MathUtils;

/**
 * Fuzzy K-Means clustering algorithm.
 *

 * The Fuzzy K-Means algorithm is a variation of the classical K-Means algorithm, with the
 * major difference that a single data point is not uniquely assigned to a single cluster.
 * Instead, each point i has a set of weights uij which indicate the degree of membership
 * to the cluster j.
 *

 * The algorithm then tries to minimize the objective function:
 *

 * J = ∑i=1..C∑k=1..N uikmdik2
 *

 * with dik being the distance between data point i and the cluster center k.
 *

 * The algorithm requires two parameters:
 *

 *
k: the number of clusters
 *
fuzziness: determines the level of cluster fuzziness, larger values lead to fuzzier clusters
 *

 * Additional, optional parameters:
 *

 *
maxIterations: the maximum number of iterations
 *
epsilon: the convergence criteria, default is 1e-3
 *

 *

 * The fuzzy variant of the K-Means algorithm is more robust with regard to the selection
 * of the initial cluster centers.
 *
 * @param <T> type of the points to cluster
 * @version $Id: FuzzyKMeansClusterer.java 1512043 2013-08-08 21:27:57Z tn $
 * @since 3.3
 */
public class FuzzyKMeansClusterer<T extends Clusterable> extends Clusterer<T> {

    /** The default value for the convergence criteria. */
    private static final double DEFAULT_EPSILON = 1e-3;

    /** The number of clusters. */
    private final int k;

    /** The maximum number of iterations. */
    private final int maxIterations;

    /** The fuzziness factor. */
    private final double fuzziness;

    /** The convergence criteria. */
    private final double epsilon;

    /** Random generator for choosing initial centers. */
    private final RandomGenerator random;

    /** The membership matrix. */
    private double[][] membershipMatrix;

    /** The list of points used in the last call to {@link #cluster(Collection)}. */
    private List<T> points;

    /** The list of clusters resulting from the last call to {@link #cluster(Collection)}. */
    private List<CentroidCluster<T>> clusters;

    /**
     * Creates a new instance of a FuzzyKMeansClusterer.
     *

     * The euclidean distance will be used as default distance measure.
     *
     * @param k the number of clusters to split the data into
     * @param fuzziness the fuzziness factor, must be > 1.0
     * @throws NumberIsTooSmallException if {@code fuzziness <= 1.0}
     */
    public FuzzyKMeansClusterer(final int k, final double fuzziness) throws NumberIsTooSmallException {
        this(k, fuzziness, -1, new EuclideanDistance());
    }

    /**
     * Creates a new instance of a FuzzyKMeansClusterer.
     *
     * @param k the number of clusters to split the data into
     * @param fuzziness the fuzziness factor, must be > 1.0
     * @param maxIterations the maximum number of iterations to run the algorithm for.
     *   If negative, no maximum will be used.
     * @param measure the distance measure to use
     * @throws NumberIsTooSmallException if {@code fuzziness <= 1.0}
     */
    public FuzzyKMeansClusterer(final int k, final double fuzziness,
                                final int maxIterations, final DistanceMeasure measure)
            throws NumberIsTooSmallException {
        this(k, fuzziness, maxIterations, measure, DEFAULT_EPSILON, new JDKRandomGenerator());
    }

    /**
     * Creates a new instance of a FuzzyKMeansClusterer.
     *
     * @param k the number of clusters to split the data into
     * @param fuzziness the fuzziness factor, must be > 1.0
     * @param maxIterations the maximum number of iterations to run the algorithm for.
     *   If negative, no maximum will be used.
     * @param measure the distance measure to use
     * @param epsilon the convergence criteria (default is 1e-3)
     * @param random random generator to use for choosing initial centers
     * @throws NumberIsTooSmallException if {@code fuzziness <= 1.0}
     */
    public FuzzyKMeansClusterer(final int k, final double fuzziness,
                                final int maxIterations, final DistanceMeasure measure,
                                final double epsilon, final RandomGenerator random)
            throws NumberIsTooSmallException {

        super(measure);

        if (fuzziness <= 1.0d) {
            throw new NumberIsTooSmallException(fuzziness, 1.0, false);
        }
        this.k = k;
        this.fuzziness = fuzziness;
        this.maxIterations = maxIterations;
        this.epsilon = epsilon;
        this.random = random;

        this.membershipMatrix = null;
        this.points = null;
        this.clusters = null;
    }

    /**
     * Return the number of clusters this instance will use.
     * @return the number of clusters
     */
    public int getK() {
        return k;
    }

    /**
     * Returns the fuzziness factor used by this instance.
     * @return the fuzziness factor
     */
    public double getFuzziness() {
        return fuzziness;
    }

    /**
     * Returns the maximum number of iterations this instance will use.
     * @return the maximum number of iterations, or -1 if no maximum is set
     */
    public int getMaxIterations() {
        return maxIterations;
    }

    /**
     * Returns the convergence criteria used by this instance.
     * @return the convergence criteria
     */
    public double getEpsilon() {
        return epsilon;
    }

    /**
     * Returns the random generator this instance will use.
     * @return the random generator
     */
    public RandomGenerator getRandomGenerator() {
        return random;
    }

    /**
     * Returns the {@code nxk} membership matrix, where {@code n} is the number
     * of data points and {@code k} the number of clusters.
     *

     * The element Ui,j represents the membership value for data point {@code i}
     * to cluster {@code j}.
     *
     * @return the membership matrix
     * @throws MathIllegalStateException if {@link #cluster(Collection)} has not been called before
     */
    public RealMatrix getMembershipMatrix() {
        if (membershipMatrix == null) {
            throw new MathIllegalStateException();
        }
        return MatrixUtils.createRealMatrix(membershipMatrix);
    }

    /**
     * Returns an unmodifiable list of the data points used in the last
     * call to {@link #cluster(Collection)}.
     * @return the list of data points, or {@code null} if {@link #cluster(Collection)} has
     *   not been called before.
     */
    public List<T> getDataPoints() {
        return points;
    }

    /**
     * Returns the list of clusters resulting from the last call to {@link #cluster(Collection)}.
     * @return the list of clusters, or {@code null} if {@link #cluster(Collection)} has
     *   not been called before.
     */
    public List<CentroidCluster<T>> getClusters() {
        return clusters;
    }

    /**
     * Get the value of the objective function.
     * @return the objective function evaluation as double value
     * @throws MathIllegalStateException if {@link #cluster(Collection)} has not been called before
     */
    public double getObjectiveFunctionValue() {
        if (points == null || clusters == null) {
            throw new MathIllegalStateException();
        }

        int i = 0;
        double objFunction = 0.0;
        for (final T point : points) {
            int j = 0;
            for (final CentroidCluster<T> cluster : clusters) {
                final double dist = distance(point, cluster.getCenter());
                objFunction += (dist * dist) * FastMath.pow(membershipMatrix[i][j], fuzziness);
                j++;
            }
            i++;
        }
        return objFunction;
    }

    /**
     * Performs Fuzzy K-Means cluster analysis.
     *
     * @param dataPoints the points to cluster
     * @return the list of clusters
     * @throws MathIllegalArgumentException if the data points are null or the number
     *     of clusters is larger than the number of data points
     */
    @Override
    public List<CentroidCluster<T>> cluster(final Collection<T> dataPoints)
            throws MathIllegalArgumentException {

        // sanity checks
        MathUtils.checkNotNull(dataPoints);

        final int size = dataPoints.size();

        // number of clusters has to be smaller or equal the number of data points
        if (size < k) {
            throw new NumberIsTooSmallException(size, k, false);
        }

        // copy the input collection to an unmodifiable list with indexed access
        points = Collections.unmodifiableList(new ArrayList<T>(dataPoints));
        clusters = new ArrayList<CentroidCluster<T>>();
        membershipMatrix = new double[size][k];
        final double[][] oldMatrix = new double[size][k];

        // if no points are provided, return an empty list of clusters
        if (size == 0) {
            return clusters;
        }

        initializeMembershipMatrix();

        // there is at least one point
        final int pointDimension = points.get(0).getPoint().length;
        for (int i = 0; i < k; i++) {
            clusters.add(new CentroidCluster<T>(new DoublePoint(new double[pointDimension])));
        }

        int iteration = 0;
        final int max = (maxIterations < 0) ? Integer.MAX_VALUE : maxIterations;
        double difference = 0.0;

        do {
            saveMembershipMatrix(oldMatrix);
            updateClusterCenters();
            updateMembershipMatrix();
            difference = calculateMaxMembershipChange(oldMatrix);
        } while (difference > epsilon && ++iteration < max);

        return clusters;
    }

    /**
     * Update the cluster centers.
     */
    private void updateClusterCenters() {
        int j = 0;
        final List<CentroidCluster<T>> newClusters = new ArrayList<CentroidCluster<T>>(k);
        for (final CentroidCluster<T> cluster : clusters) {
            final Clusterable center = cluster.getCenter();
            int i = 0;
            double[] arr = new double[center.getPoint().length];
            double sum = 0.0;
            for (final T point : points) {
                final double u = FastMath.pow(membershipMatrix[i][j], fuzziness);
                final double[] pointArr = point.getPoint();
                for (int idx = 0; idx < arr.length; idx++) {
                    arr[idx] += u * pointArr[idx];
                }
                sum += u;
                i++;
            }
            MathArrays.scaleInPlace(1.0 / sum, arr);
            newClusters.add(new CentroidCluster<T>(new DoublePoint(arr)));
            j++;
        }
        clusters.clear();
        clusters = newClusters;
    }

    /**
     * Updates the membership matrix and assigns the points to the cluster with
     * the highest membership.
     */
    private void updateMembershipMatrix() {
        for (int i = 0; i < points.size(); i++) {
            final T point = points.get(i);
            double maxMembership = 0.0;
            int newCluster = -1;
            for (int j = 0; j < clusters.size(); j++) {
                System.out.println("CYCLE");
                double sum = 0.0;
                final double distA = FastMath.abs(distance(point, clusters.get(j).getCenter()));

                for (final CentroidCluster<T> c : clusters) {
                    final double distB = FastMath.abs(distance(point, c.getCenter()));
                    System.out.println(distA/distB + " RAISED TO: " + (2.0/(fuzziness - 1.0)));
                    sum += FastMath.pow(distA / distB, 2.0 / (fuzziness - 1.0));
                }

                membershipMatrix[i][j] = 1.0 / sum;
                System.out.println("MEM MAT: " + membershipMatrix[i][j] + " FROM: " + sum);
                if (membershipMatrix[i][j] > maxMembership) {
                    maxMembership = membershipMatrix[i][j];
                    newCluster = j;
                }
            }
            System.out.println("CLUSTER SIZE: " + clusters.size());
            clusters.get(newCluster).addPoint(point);
        }
    }

    /**
     * Initialize the membership matrix with random values.
     */
    private void initializeMembershipMatrix() {
        for (int i = 0; i < points.size(); i++) {
            for (int j = 0; j < k; j++) {
                membershipMatrix[i][j] = random.nextDouble();
            }
            membershipMatrix[i] = MathArrays.normalizeArray(membershipMatrix[i], 1.0);
        }
    }

    /**
     * Calculate the maximum element-by-element change of the membership matrix
     * for the current iteration.
     *
     * @param matrix the membership matrix of the previous iteration
     * @return the maximum membership matrix change
     */
    private double calculateMaxMembershipChange(final double[][] matrix) {
        double maxMembership = 0.0;
        for (int i = 0; i < points.size(); i++) {
            for (int j = 0; j < clusters.size(); j++) {
                double v = FastMath.abs(membershipMatrix[i][j] - matrix[i][j]);
                maxMembership = FastMath.max(v, maxMembership);
            }
        }
        return maxMembership;
    }

    /**
     * Copy the membership matrix into the provided matrix.
     *
     * @param matrix the place to store the membership matrix
     */
    private void saveMembershipMatrix(final double[][] matrix) {
        for (int i = 0; i < points.size(); i++) {
            System.arraycopy(membershipMatrix[i], 0, matrix[i], 0, clusters.size());
        }
    }

}

Answer: Based on this question, which was, by accident, posted in the wrong StackExchange, I believe that the only changes I need to make are as follows:

Normalize all vectors
Change the distance measure to cosine dis-similarity.


Bayesian updating - coin tossing example

Question: I have a question about Bayesian updating. In general Bayesian updating refers to the process of getting the posterior from a prior belief distribution.
Alternatively one could understand the term as using the posterior of the first step as prior input for further calculation.
The below is a simple calculation example. Method a is the standard calculation. Method b uses the posterior output as input prior to calculate the next posterior.
Using method a, we get P(F|HH) = 0.2. Using method b, gives P(F|HH) = 0.05.
My question is as to how far method b is a valid approach ?

Problem: You toss a coin twice, get 2 Heads. What is the probability that the coin is fair, i.e. $Pr(Fair\ coin| HH)$?
Now for the first toss:
$Pr(Fair\ coin| H) = \frac{Pr(Head|Fair)\cdot P(Fair)}{Pr(Head|Fair) \cdot P(Fair)+Pr(Head|Biased) \cdot P(Biased)} = \frac{Pr(H|F)\cdot P(F)}{P(H)}  \quad\quad (1)$
Assuming starting prior belief P(Fair) = 0.5, want to find P(F|H) for the first toss
Below are the calculation for the intermediate steps:
$P(H|F)= {n \choose x} \theta^{x}(1-\theta)^{n-x} = {1 \choose 1} 0.5^{1}(0.5)^{0}= 0.5$
$P(H)= P(H|F) \cdot P(F)+ P(H|Biased) \cdot P(Biased)=(0.5 \cdot 0.5) +(1 \cdot 0.5) = 0.75$
(Note: P(H|Biased) = 1 because assuming an extreme example with Heads on both sides of the coin, the probability of getting Heads with a biased coin = 1 (makes calculation easy))
Hence, plugging into (1), we get :
$Pr(F| H) =\frac{Pr(H|F)\cdot P(F)}{P(H)} = \frac{0.5 \cdot 0.5}{0.75} = 0.33$

Now, we toss the coin again and get another H. To calculate $Pr(F| HH) $
, we
a) continue using P(Fair)=0.5
$Pr(F|HH) = \frac{Pr(HH|F)\cdot P(F)}{Pr(HH|F) \cdot P(F)+Pr(HH|Biased) \cdot P(Biased)} = \frac{Pr(HH|F)\cdot P(F)}{P(HH)}  \quad\quad (2)$
$P(HH|F)= {n \choose x} \theta^{x}(1-\theta)^{n-x} = {2 \choose 2} 0.5^{2}(0.5)^{0}= 0.25$
$P(HH)= P(HH|F) \cdot P(F)+ P(HH|Biased) \cdot P(Biased)=(0.25 \cdot 0.5) +(1 \cdot 0.5) = 0.625$
Hence, plugging into (2),
$Pr(F|HH) =\frac{Pr(HH|F)\cdot P(F)}{P(HH)} = \frac{0.25 \cdot 0.5}{0.625} = 0.2$

Alternatively, what if we calculate $Pr(F| HH) $ by using
b) our updated belief P(Fair)=0.33 which we got from Pr(F|H) in the first step
In this case,
$P(HH|F)= {n \choose x} \theta^{x}(1-\theta)^{n-x} = {2 \choose 2} 0.33^{2}(1-0.33)^{0}= 0.1089$
$P(HH)= P(HH|F) \cdot P(F)+ P(HH|Biased) \cdot P(Biased)=(0.1089 \cdot 0.33) +(1 \cdot 0.67) = 0.705937$
Hence, plugging into (2),
$Pr(F|HH) =\frac{Pr(HH|F)\cdot P(F)}{P(HH)} = \frac{0.1089 \cdot 0.33}{0.705937} = 0.05091$

Using method a, we get P(F|HH) = 0.2. Using method b, gives P(F|HH) = 0.05.
My question is as to how far method b is a valid approach ?
Comment: Usually a biased coin just means that it's not fair, but it could have any bias.  You should make it clear in your question that you're only considering the possibilities that either the coin is perfectly fair, or else it always comes up heads.  You might want to recast this as an urn problem since that's not a very realistic coin.
Comment: "Indeed, a coin is either totally fair or totally biased." — Not really.  There are very very few coins that either totally fair or "totally biased".
Comment: both sides heads
Comment: How did you reason that the probability of getting heads given a biased coin is 1?  Anyway, no matter how many times you flip the coin, the probability that it is fair is zero.
Comment: If the coin is biased and we see a Head it means the coin has Head on both sides. We will always see Head, so probability of getting Head with a biased coin=1.
Comment: Indeed, a coin is either totally fair or totally biased. If it was a dice, there would be different scenarios of bias. For a coin, there's only 1 option.
Comment: Are you pointing to the option that although there's Heads on one side and tails on the other, the metal on one side is heavier than the other and hence tends to fall more on a particular side? Fine, I'm happy with an alternate calculation for the P(H|Biased). However, the focus of the question is about using  priors recursively from previous posterior results. It's widely used from what I see.
Comment: Most coins have a bias, some number, like 0.56.  That's a biased coin.  It falls head 56% of the time and tails 44% of the time.  Your biased coin falls heads 100% of the time.  How would design a coin like that anyway?
Comment: Fair enough.  But that's not what people usually mean when they say "biased coin".
Comment: No problem. The focus of the question is about using priors recursively from previous posterior results. It's widely used from what I see.
Comment: Yes, I see.  If you do this in log-odds space, then the updates are additive and this is much easier.  Your first approach seems right: 1:1 after no observations, then 2:1, then 4:1, etc.  Something's wrong with your second approach.  Good luck.
Comment: Interesting, Thanks. Yes, the first approach is standard and not updating the prior. It just seems inefficient not to make use of the updated information from the first toss.
Answer: Your approach b) is wrong: both the single step updating, in which all data are used together to update the prior and arrive at the posterior, and the Bayesian sequential (also called recursive) updating, in which data are used one at a time to obtain a posterior which becomes the prior of the successive iteration, must give exactly the same result.  This is one of the pillars of Bayesian statistics: consistency.
Your error is simple: once you updated the prior with the first sample (the first "Head"), you only have one remaining sample to include in your likelihood in order to update the new prior. In formulas:
$$P(F|HH) =\frac{P(H|H,F)P(F|H)}{P(H|H)} $$
This formula is just Bayes' theorem, applied after the first event "Head" has already happened: since conditional probabilities are probabilities themselves, Bayes' theorem is valid also for probabilities conditioned to the event "Head", and there's nothing more to prove really . However, I found that some times people don't find this result self-evident, thus I give a slightly long-winded proof.
$$P(F|HH) =\frac{P(HH|F)P(F)}{P(HH)}= \frac{P(H|H,F)P(H|F)P(F)}{P(HH)}$$
by the chain rule of conditional probabilities. Then, multiplying numerator and denominator by $P(H)$, you get
$$\frac{P(H|H,F)P(H|F)P(F)}{P(HH)}=\frac{P(H|H,F)P(H|F)P(F)P(H)}{P(HH)P(H)}=\frac{P(H|H,F)P(H)}{P(HH)}\frac{P(H|F)P(F)}{P(H)}=\frac{P(H|H,F)}{P(H|H)}\frac{P(H|F)P(F)}{P(H)}=\frac{P(H|H,F)P(F|H)}{P(H|H)}$$
where in the last step I just applied Bayes' theorem. Now:
$$P(H|H,F)= P(H|F)=0.5$$
This is obvious: conditionally on the coin being fair (or biased), we are modelling the coin tosses as i.i.d.. Applying this same idea to the denominator, we get:
$$P(H|H)= P(H|F,H)P(F|H)+P(H|B,H)P(B|H)=P(H|F)P(F|H)+P(H|B)P(B|H)=0.5\cdot0.\bar{3}+1\cdot0.\bar{6}$$
Finally:
$$P(F|HH) =\frac{P(H|H,F)P(F|H)}{P(H|H)}=\frac{0.5\cdot0.\bar{3}}{0.5\cdot0.\bar{3}+1\cdot0.\bar{6}}=0.2$$
QED

That's it: have fun using Bayesian sequential updating, it's very useful in a lot of situations! If you want to know more, there are many resources on the Internet: this is quite good.