Remove Selected Spinner Item In Android

Question: I have spinner in my Activity which is set the item from JSON data and when i select any item from spinner and set into the spinner, and i have done all this things properly.But when i want to remove selected item from spinner i got exception:

E/AndroidRuntime(1022): java.lang.UnsupportedOperationException"

and

E/AndroidRuntime(1022):atandroid.widget.ArrayAdapter.remove(ArrayAdapter.java:212)

at the code line of

E/AndroidRuntime(1022):at com.spinnerdemo.SpinDemo$1.onItemSelected(SpinDemo.java:102)

Here is my code:
public class SpinDemo extends Activity {

    private static String strUrl = "http://192.168.1.61/jyoti/android_app/all_questions.php";
    private static String TAG_ID = "id";
    private static String TAG_CODE = "q_prefix";
    private static String TAG_CODE_ARR = "Questions";

    JSONArray jsonArray = null;
    Spinner codeSpinner, spinner2;
    EditText edTextSpinnerItem;
    String[] items;

    String strEdtext;
    String strid , strcode ;
    ArrayList<String> codeList;
    public  ArrayAdapter<String> adapter ;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        codeList = new ArrayList<String>();
        codeSpinner = (Spinner) findViewById(R.id.spinner2);

        JSONParser jParser = new JSONParser();
        JSONObject json = jParser.getJSONFromUrl(strUrl);
        try
        {
            jsonArray = json.getJSONArray(TAG_CODE_ARR);

             // looping through All Contacts
             final String[] items = new String[jsonArray.length()];

             for(int i = 0; i < jsonArray.length(); i++)
             {
                 JSONObject c = jsonArray.getJSONObject(i);

                // Storing each json item in variable

                    strid = c.getString(TAG_ID);
                    strcode = c.getString(TAG_CODE);
                    items[i] = c.getString(TAG_CODE);
                    System.out.println("Hello events " + items);

                    adapter = new ArrayAdapter<String>(this,
                            android.R.layout.simple_spinner_item,items);
                    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    codeSpinner.setAdapter(adapter);

             }
        }

        catch (JSONException e) {
            e.printStackTrace();
        }

        codeSpinner.setOnItemSelectedListener(new OnItemSelectedListener()
        {

            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                    int pos, long arg3)
            {
                // TODO Auto-generated method stub

                String anyvariable=String.valueOf(codeSpinner.getSelectedItem());
                System.out.println("anyvariable = " + anyvariable);
                edTextSpinnerItem=(EditText)findViewById(R.id.editText_SpinnerItem);
                edTextSpinnerItem.setText(anyvariable);
                System.out.println("edTextSpinnerItem " + edTextSpinnerItem);

                String t = adapter.getItem(pos);
                System.out.println("Get The Item Position From Adapter = " + t);

                adapter.remove(t);
                adapter.notifyDataSetChanged();
                codeSpinner.setAdapter(adapter);
                //mySpinner.setAdapter(m_adapterForSpinner);

                //adapter.remove((String)codeSpinner.getSelectedItem());
                //adapter.notifyDataSetChanged();
                //System.out.println("Item is Removed From The Spinner Drop Dwon List");

            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0)
            {
                // TODO Auto-generated method stub

            }
        });

    }

}

Answer: I think that the problem is caused from the deleting an element that is actual selected
Try to use a list instead of an Array for the items:
http://developer.android.com/reference/android/widget/ArrayAdapter.html#ArrayAdapter(android.content.Context,%20int,%20int,%20java.util.List)
Then in the on item selected use
items.remove(t);

Instead of:
adapter.remove(t);

With this change you remove the item from the ArrayList(List) and not from the adapter.
The adapter notifyDataSetChanged capture the change on the List and refresh the spinner
Comment: The application crash or not remove the object?
Comment: I,m getting all the items from JSON Data in spinner.The application crash and also not remove the object ,and got UnSupportedException.
Comment: Can possible for removing the selected item into the spinner which is getting data from JSON.
Answer: Try this..
1) Give spinner setadapter after for loop
2) If you need to remove any item. You need to use ArrayList it is the easy way.
I Posted code after some changes.
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        codeList = new ArrayList<String>();
        codeSpinner = (Spinner) findViewById(R.id.spinner2);

        JSONParser jParser = new JSONParser();
        JSONObject json = jParser.getJSONFromUrl(strUrl);
        try
        {
            jsonArray = json.getJSONArray(TAG_CODE_ARR);

             // looping through All Contacts
             final String[] items = new String[jsonArray.length()];

             for(int i = 0; i < jsonArray.length(); i++)
             {
                 JSONObject c = jsonArray.getJSONObject(i);

                // Storing each json item in variable

                    strid = c.getString(TAG_ID);
                    strcode = c.getString(TAG_CODE);
                    items[i] = c.getString(TAG_CODE);
                    System.out.println("Hello events " + items);
                    codeList.add(strcode);

             }

adapter = new ArrayAdapter<String>(this,
                            android.R.layout.simple_spinner_item,codeList);
                    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    codeSpinner.setAdapter(adapter);
        }

        catch (JSONException e) {
            e.printStackTrace();
        }

        codeSpinner.setOnItemSelectedListener(new OnItemSelectedListener()
        {

            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                    int pos, long arg3)
            {
                // TODO Auto-generated method stub

                String anyvariable=String.valueOf(codeSpinner.getSelectedItem());
                System.out.println("anyvariable = " + anyvariable);
                edTextSpinnerItem=(EditText)findViewById(R.id.editText_SpinnerItem);
                edTextSpinnerItem.setText(anyvariable);
                System.out.println("edTextSpinnerItem " + edTextSpinnerItem);

                String t = adapter.getItem(pos);
                System.out.println("Get The Item Position From Adapter = " + t);

                Object t2 = adapter.getItem(pos);
        Log.v("t2", ""+t2);
        codeList.remove(t2);
        adapter.notifyDataSetChanged();

            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0)
            {
                // TODO Auto-generated method stub

            }
        });

    }

Comment: What is aa = Object t = aa.getItem(position);
Comment: @tazeenmulani sorry `aa` is `adapter` change it.

Remove Selected Spinner Item In Android


Managing multiple Python environments

Question: I have some Python scripts that require different versions of Python, including but not limited to 2.4, 2.7, 3.2. I don't have the code ownership of the scripts, so the scripts can change by the next update. Therefore it's not an option to convert or adapter the scripts to a common Python version. Instead I want to manage environments with different versions of Python and different versions of the used modules. That's calling for Anaconda environments.
Running this command conda --name MyEnv python=2.4 in miniconda 2.7  failed with the message

Solving environment: failed
PackagesNotFoundError: The following packages are not available from current channels:

python=2.4

How can I install different Python versions on a set of Windows PCs and share environments to run the same scripts in the required environments?
Comment: _How can I install different Python versions on a set of Windows PCs and share environments to run the same scripts in the required environments?_ Is that related to the previous issue? What is the "main question" here?
Comment: Previous issue? I just described what I did before posting a question. The actual question is, how do manage different Python version and how do I manage that this will work also on different PCs if I copy the scripts to the other(s) PC(s)? Canda is obviously not the answer or I did something wrong.
Comment: Sorry if my comment wasn't clear, by previous issue I am referring to the whole `PackagesNotFoundError` situation. _The actual question is, how do manage different Python version and how do I manage that this will work also on different PCs if I copy the scripts to the other(s) PC(s)?_ I'm confused, the accepted answer is mostly focused on the issue of Python 2.4.
Comment: _Canda is obviously not the answer or I did something wrong._ I'm confused even further now. I would not consider the availability of a package for Python 2.4 to be a significant aspect when comparing tools/methods for managing multiple Python installations/environments.
Answer: Python 2.4 is very old and Anaconda does not support it.
It seems like PyEnv supports managing different versions of Python environments including 2.4 and other versions you need. Here's a tutorial that might be useful. (I haven't tried it.)
Another option is virtualenv, but you'll still need to use an older version of it because they stopped supporting Python 2.4. Here's a pointer.

Managing multiple Python environments


XMLHttpRequest - How to trap situation where an HTML error page is returned instead of data

Question: Javascript: Using XMLHttpRequest to get a small amount of data which is echo'd to it by a specific php routine on a webserver. Async with callback function. Or synchronous, makes no odds.
The issue arises if the php file is absent or inaccessible. Instead of returning an error flag, the responseText property returns the HTML content of a server 404 error page.
The 404 page content will vary from server to server so it's virtually impossible to trap this situation by any string test. Is there any way to flag the fact that an error has happened and return null instead?
 // envvars is set previously
 AjaxRequest.open('post','handler.php?nocache='+nocache,true);
 AjaxRequest.setRequestHeader("User-Agent",'Firefox');
 AjaxRequest.onreadystatechange = aCallback;
 AjaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
 AjaxRequest.setRequestHeader("Content-length", envvars.length);
 AjaxRequest.setRequestHeader("Connection", "close");
 AjaxRequest.send(envvars);
}

function aCallback() {
 if(AjaxRequest.readyState == 4){
   var response = AjaxRequest.responseText;
   if(response == 0){
     // It is useless to test for failure here because a complete 404 page is returned,
     // instead of a null or -1 response.
     document.ajax.response.value="Fail";
    } else {
     document.ajax.response.value=response;
   }
 }
}

// handler.php:
if ($_POST["request"]=="countbananas"):
  echo "bananas=43" ;
endif;

ps I know jQuery will be mentioned but I'd rather avoid that route.
Comment: Can't you detect if the HTTP status code is 404?
Comment: Think I've found the answer. The AjaxRequest.status property will be 200 if OK. Looks like the guy who wrote the sample I based my code on used didn't know how to trap the error properly. Took a while to discover that this property exists, very few examples mention it.  Thx anyway.
Answer: You can read the status property of the XMLHttpRequest object to get the HTTP response code:
function aCallback() {
 if(AjaxRequest.readyState == 4){
   if(AjaxRequest.status !== 200){
     // something went wrong
     document.ajax.response.value="Fail";
    } else {
     var response = AjaxRequest.responseText;
     document.ajax.response.value=response;
   }
 }
}

This of course assumes, that your source is returning proper HTTP code, such as "404 File not found".
Answer: Can't you use the HTTP status code returned by the XMLHttpRequest?
if ( AjaxRequest.status + "" == "404" ) {
  // Error page
}

Or:
// 4xx status code
if ( (AjaxRequest.status + "").substr(0,1) == "4" ) {
  // Error page
}

Comment: Yes, thanks, we've figured out that the sample I used had an incorrect error handling method. That is the right way.


How to sample a total variation prior?

Question: I am interested in drawing samples from a total variation prior:
$$\pi_{\mathrm{pr}}(\boldsymbol{x})=\left(\frac{\alpha}{2}\right)^n\exp\left(-\alpha\sum_{j=0}^{n-1}\vert x_{j+1}-x_{j}\vert\right)=\left(\frac{\alpha}{2}\right)^n\exp\left(-\alpha\Vert\mathbf{L}\boldsymbol{x}\Vert_1\right)=\mathrm{Laplace}(\Vert\mathbf{L}\boldsymbol{x}\Vert_1;0,\alpha^{-1}),$$ where $\mathbf{L}$ is a difference matrix and $\alpha$ is the inverse of the scale parameter of a Laplace distribution.
My initial guess was to generate sample paths of a process such that: (i) it starts at 0, (ii) the increments are independent, and (iii) the increments are distributed according to $\mathrm{Laplace}(\cdot;0,\alpha^{-1})$. Is this procedure correct? Or is there any other way to generate samples from such distribution (other than MCMC)?
Thanks in advance!
Comment: But after doing so, I guess one still end up using MCMC (component-wise MH or Gibbs)
Answer: The joint density
$$\pi(\boldsymbol{x})=\overbrace{\left(\frac{\alpha}{2}\right)^n}^{\substack{  \text{correct}\\ \text{constant}}}\exp\left(-\alpha\sum_{j=0}^{n}\vert x_{j+1}-x_{j}\vert\right)$$
assuming $\boldsymbol{x}=(x_1,\ldots,x_n)$ writes as
$$\pi(\boldsymbol{x})=\frac{\alpha}{2}\exp\left(-\alpha\vert x_{1}-x_{0}\vert\right)\frac{\alpha}{2}\exp\left(-\alpha\vert x_{2}-x_{1}\vert\right)\cdots\frac{\alpha}{2}\exp\left(-\alpha\vert x_{n}-x_{n-1}\vert\right)$$
and can be expressed as a product of conditional Laplace densities
$$\pi(\boldsymbol{x})=f_\alpha(x_1|x_0)f_\alpha(x_2|x_1)\cdots f_\alpha(x_n|x_{n-1})$$meaning it can be simulated as

simulate $X_1\sim \mathfrak{L}(x_0,\alpha)$
simulate $X_2|X_1=x_1\sim \mathfrak{L}(x_1,\alpha)$
$\qquad\vdots$
simulate $X_n|X_{n-1}=x_{n-1}\sim \mathfrak{L}(x_{n-1},\alpha)$

How to sample a total variation prior?


How to get user.field value in node--teaser.twig

Question: That's how I getting user.field value for node--full.twig but this code does not work for node--teaser.twig
function MYTHEME_preprocess_node(&$variables) {
    if ($node = \Drupal::routeMatch()->getParameter('node')) {
              $variables['author'] = $node->getOwner()->field_name->value;
    }
}

}
Any ideas?
Answer: This bit's the problem:
$node = \Drupal::routeMatch()->getParameter('node')

Even if that returned a value, it would probably be the wrong one; it's not common to render the node as a teaser on its own view page.
As it happens, you don't need to load it yourself for any of the view modes. The node is already in $variables:
function MYTHEME_preprocess_node(&$variables) {
  $variables['author'] = $variables['node']->getOwner()->field_name->value;
}

You may need to add a further check of $variables['node']->getType() if the field is only available to certain content types.
Comment: I take my words back. Everything works perfectly! Thank you!
Comment: Thank you for your answer. `$variables['author'] = $variables['node']->getOwner()->field_name->value;` and `$variables['author'] = $variables['node']->getType()->$variables['node']->getOwner()->field_name->value;` not works.


How to seed database with JSON in ASP.NET MVC

Question: So I have a json file with these values:

and I have to make a MSSQL database for it using ASP.NET MVC and Entity framework. My question would be of two parts.

How do I seed the database with this JSON?
How should my model look or be written? I'm particularly curious about the specs and image part.

[Edit]
Seed Method
        using (StreamReader jsonData = new StreamReader(System.Web.HttpContext.Current.Server.MapPath("~/Resources/products.json")))
        {
            List<Product> products = JsonConvert.DeserializeObject<List<Product>>(jsonData.ReadToEnd());
            products.ForEach(s => context.Products.AddOrUpdate(s));
            context.SaveChanges();
        }

[Edit]
My model:
    public class Product
{
    public int id { get; set; }

    public string name { get; set; }

    public double price { get; set; }

    public string specsmanufacturer { get; set; }

    public int specsstorage { get; set; }

    public string specsos { get; set; }

    public int specscamera { get; set; }

    public string imagesmall { get; set; }

    public string imagelarge { get; set; }
}

Comment: Sorry I only read it once, apologies for not reading it multiple times, I didn't know that was required. :-) Anyway...we don't know the business requirements which might inform the structure, we don't know if any of these values are fixed items to be chosen from a list of pre-defined values- we don't know a lot of detail, in fact. But just based on that one small snippet of data, you could in theory place all of those values into separate columns in one single table. Maybe that suits your overall requirements, maybe not. Difficult to know.
Comment: For 1, you can use Json.Net to deserailize your json into entities. For you canjust store the path like that or refine the path before storing it into your database.
Comment: you mean how to insert it into the database? It depends on the table structure. Have you designed one? Or do you just want to place the JSON into a single field? It's not really clear what you mean, or what your issue is. What have you tried so far? As for a model structure (your second point), specs and image would be objects which are properties of the main object, just like they are in the Json. Probably they'd each be of a different type to the main object. Or you could just serialise to a flattened object, if that has no value.
Comment: @ADyson if you would've read the question a few times you would clearly see I haven't designed one, I'm just asking for the best way to do this and how to post it into database :)
Comment: This is an assignment I have to do and literally I have given all the information I know, so that's it, If I knew more, I wouldn't have asked a question, youre missing the point.
Comment: So this is homework? Have you tried anything yet? The best way to learn is by doing. We can spoon feed you an answer which might or might not be what your course tutor had in mind, but no-one gains much from that. I've given you some hints though. You can find more about the specifics of doing this kind of task via EF Code First online through tutorials and documentation (and previous answers on here) already. Do you also have to deserialise this JSON from somewhere as part of this? Again that process is quite easy to research on google.
Comment: Basically the "right" answer to this is whatever is simplest, works correctly and best suits all the available requirements. If you've given us all the possible info, then unless this bit of the course is supposed to be about studying some particular topic around data structures which you're supposed to be taking into account and using some arbitrary technique or design pattern, then probably a flat table structure will be sufficient, or three tables as suggested in the answer would work too. It's really up to you, do what works.
Comment: I'm sorry to say again but youre missing the point. No, this is not homework. this is not for university/school/anything. but this is an assignment. That's not the point. the point is the question. and the question asks not "DO THE TASK FOR ME" but "what is the best way to do the task".
Comment: "This is an assignment"...what's an assignment if it's not homework? Anyway as I've just mentioned, "best" is entirely subjective in this situation, if there are no further requirements to take into account. Do the simplest thing which works.
Comment: maybe it's using Json.net maybe its creating 3 models, maybe its creating one model and in the specs field doing some kind of magic (I dont know what). That's what Im asking.
Comment: Oh my god, please, If you dont have an answer, just leave, I am not going to talk about what is this for, its not part of the question.
Comment: I don't have an answer because there is no "best" way to do it, there are only ways which succeed in meeting the requirements, and ways which don't, especially since the requirements are utterly trivial
Comment: There is a best way to do it, there's always is, you and I just probably dont know it. Thats why I asked.
Comment: Well what exactly would your definition of "best" be, then? What criteria do you attach to that, other than "it works"? Performance? Minimal amount of code? Shortest development cycle? Most testable? Somehow re-usable? Maintainability? Using some specific design or architectural principles? Uses least amount of external libraries? People's definition of good code, beyond "meets the basic requirements" varies enormously.
Answer: You could either flatten your model (1 class 1 table) or store the entities in their respective tables (3 classes 3 tables).
Edit: flat class model.
public class Thingy
{
   [Key]
   public int ID{get;set;}
   public string Name{get;set;}
   public decimal Price{get;set;}
   public string SpecsManufacturer{get;set;}
   public int SpecsStorage{get;set;}
   public string SpecsOS{get;set;}
   //etc
}

If you are using Code-first and have a Configuration.cs in your Migrations folder then you can override the Seed method:
protected override void Seed(DataContext context)
{
   //Populate using whatever method you want.
}

The Seed method runs every time you run the command update-database against your database.
Comment: if I were to do it as 1 table, how would the specs part look? a list or something like that?
Comment: I edited my answer. You would have to handle the mapping from JSON to object manually as I doubt it's smart enough to flatten the structure for you.
Comment: I'm seeding the data like in my example (see edit), but I get this error "Object reference not set to an instance of an object"
Comment: Which of your objects is null?
Comment: It was because of the Web.Server. I changed it to a regular directory and now it works better, my problem now is that it adds the name id and price values but others arent added. maybe know why @Wurd
Comment: You can't deserialize an object into a class that doesn't match it without doing manual mapping. Get your deserialized class http://json2csharp.com/ then map it to your database class manually or using automapper or something like that.


Implementando o conceito de herança em banco de dados

Question: Por quê o atributo PessoaJuridicaId não é gerado?

Essa é a classe base Pessoa:
public class Pessoa
{
    public Pessoa()
    {
        DataCadastro = DateTime.Now;
    }
    public int PessoaId { get; set; }
    public DateTime DataCadastro { get; set; }
    public string Observacao { get; set; }
    public bool Ativo { get; set; }
}

Essa é a classe PessoaJuridica que herda da classe Pessoa:
public class PessoaJuridica: Pessoa
{
    public int PessoaJuridicaId { get; set; }
    public string RazaoSocial { get; set; }
    public string NomeComercial { get; set; }
    public string CNPJ { get; set; }
    public string IE { get; set; }
    public string IM { get; set; }
    public string CCM { get; set; }
    public DateTime? DataAbertura { get; set; }
}

Esta é a classe Repositório:
public void Salvar(PessoaJuridica pessoaJuridica)
{
    _repositorio.PessoaJuridica.Add(pessoaJuridica);
    _repositorio.SaveChanges();
}

Comment: Como assim "não é gerado"? A segunda coluna da segunda tabela  tem nome **PessoaJuridicaId**.
Comment: Porque a chave primária é `PessoaId` e não `PessoaJuridicaId`. Você pode usar uma chave composta se achar necessário. Particularmente, eu acho errado usar herança pra fazer isso no EF.
Comment: Essa é minha dúvida, no meu entender essa coluna PessoaJuridicaId deveria ser atribuido um valor auto-incremento e não foi gerado valor nenhum, por quê ? Estou conceituando errado ? Essa coluna PessoaJuridicaId não deve existir ?
Comment: E como tornar `PessoaJuridicaId` **primária** ? Uma vez que a classe **base** é `Pessoa` e `PessoaId` é a chave dessa classe ?
Answer: Ia só comentar, mas ficou longo e acho que no fundo o erro é conceitual.
Onde está escrito que deveria ser autoincrementado? Qual o critério para gerar um identificador autoincrementado? Isto não ocorrerá sozinho. Sozinho o Entity Framework só consegue fazer com o primeiro campo, no caso ele fez com PessoaID que é o primeiro já herdado. Na verdade, ele fez certo, se quer herança mesmo.
Eu acho estranho ter identificadores diferentes nas duas tabelas e ter uma relação de herança. Isto só ocorre quando há algum tipo de composição, associação ou agregação, não de herança. Se é herança então pessoa jurídica é o mesmo que pessoa, elas não existem separadamente, por que eles deveriam ter identificadores diferentes? Eu acho que o EF fez certo, o seu modelo que está adicionando algo desnecessário: PessoaJuridicaId.
Em geral eu prefiro fazer, no máximo, uma herança lógica, mas concretamente ter apenas as tabelas dos subtipos com os dados replicados, que é o que acontece concretamente na memória quando usamos herança em uma linguagem, o objeto é único, não existem dois da classe base e da derivada.
Pra falar a verdade esse modelo de ter fisicamente uma tabela base e suas derivadas separadas gera uma composição e não uma herança de fato. Herança é algo lógico para reusar código, não é para reusar dados. Em geral ter essa composição de tabelas não traz benefício algum e traz até malefícios, então não tem porque usar. Claro que pode ter algum caso que pode valer a pena. Mas precisa conceituar certo, entender todas as implicações. Não pode fazer por fazer, fazer porque "funcionou", tem que fazer o certo.
Não sou muito fã de herança em banco de dados porque quase todo mundo faz errado. Eu mesmo não sei se sei fazer certo, mas sei que a maioria faz errado :) Orientação a objeto já é complicado demais na memória e as pessoas acham que não, em banco de dados mais ainda. Sabe a estória de que morre afogado aquela pessoa que acha que sabe nadar. Quem não sabe nadar não morre porque não tenta. Quem sabe nadar mesmo não morre porque sabe. O problema é quando a pessoa acha que sabe nadar e não sabe.
Tem algumas perguntas sobre o assunto:

Herança correta no Entity Framework
Herança no Entity Framework
Herança X Composição - MySQL C# Entity
EF com herança TPT e campos de auditoria
Como configurar Mapeamento Entity Framework 1:N usando herança
EF 6, Mapeamento com Fluent Api em classes com herança
Herança com Repository Pattern

Coloquei no GitHub para referência futura.
Comment: Achei esse ponto do seu comentário esclarecedor: _"...esse modelo de ter fisicamente uma tabela base e suas derivadas separadas gera uma associação e não um herança de fato"_  vou rever como fazer essa implementação e repensar o ponto onde diz: _"Em geral eu prefiro fazer, no máximo, uma herança lógica"_.


Touch event on ipad

Question: Do you know how I can run the touch event on ipad? I have a small problem on closing a submenu.
For example, if my sub-menu is unfolded and I aillor click, it automatically closes. My code below works fine, but not on the ipad.
Would you have an idea for it to work on ipad?
<code>var navigation = $('.l-navigation');

$(document.body).click(function(e) {

    // Si le clic n'est pas sur la navigation

    if( !$(e.target).is(navigation) && !$.contains(navigation[0],e.target) ) {

            navigation.find('.submenu').slideUp(); // Alors on cache le sous-menu

    }

});
</code>
Thank you very much!
Answer: You can use jQuery UI Touch Punch plugin for touch events on touch devices. Give a try.

Touch event on ipad


Convert Ninject DI to Unity DI

Question: How Do I convert the following Ninject DI to Unity? I'm having trouble understanding the correct syntax.
///
    /// Load your modules or register your services here!
    ///
    /// <param name="kernel">The kernel.</param>
    private static void RegisterServices(IKernel kernel)
    {
        Database.SetInitializer(new MigrateDatabaseToLatestVersion<DefaultMembershipRebootDatabase, BrockAllen.MembershipReboot.Ef.Migrations.Configuration>());

        var config = MembershipRebootConfig.Create();
        kernel.Bind<MembershipRebootConfiguration>().ToConstant(config);
        kernel.Bind<UserAccountService>().ToSelf();
        kernel.Bind<AuthenticationService>().To<SamAuthenticationService>();
        kernel.Bind<IUserAccountQuery>().To<DefaultUserAccountRepository>().InRequestScope();
        kernel.Bind<IUserAccountRepository>().To<DefaultUserAccountRepository>().InRequestScope();
    }

Answer:
Registering a single instance is done using the RegisterInstance method.
Registering types as 'self' is done using the RegisterType<T>() method.
Registering types with a request lifestyle is done using the HierarchicalLifetimeManager.

Convert Ninject DI to Unity DI


Putting instantiated objects in arrays

Question:
Below is all the code for the program I am writing for my programming class. My main problem is that when I invoke AddPerson() it skips the position [0] in _people[] and places the object created in [1] of _More[]. How can i prevent this from happening while also adding newly created objects to the array?
Also, i need to at the end display all of the data in the array in ordered form. I believe I have the proper code in the DisplayAllPeople() method in the GroupOfPeople class.

I'm hoping I have most of this correct. Can anyone help me please?
*There is one class called IOHelper that was provided to us (the students) by our teacher but I did not include it as it is only static methods.
//Main Program//
public class Program
    {
        public static void Main(string[] args)
        {
            GroupOfPeople group = new GroupOfPeople();
        while (IOHelper.AskYesNoQuestion("Do you want to add another person to the array? "))
        {
            Console.Write("Name?   :");
            string name = Console.ReadLine();
            Console.Write("Age?    :");
            int age = int.Parse(Console.ReadLine());
            Person newPerson = new Person(name, age);

            group.AddPerson(newPerson);

        }

        Console.WriteLine("Here are your entries:");

        group.DisplayAllPeople();

        Console.Write("Press any key to end the program... ");
        Console.ReadKey();
    }

 }

//Person Class//
public class Person
    {
        private string _name { get; set; }
        private int _age { get; set; }
    public Person(string name, int age)
    {
        _name = name;
        _age = age;
    }

    public void Display()
    {
        Console.Write("Name : " + _name);
        Console.Write("Age  : " + _age);
        Console.WriteLine();
    }
}

//GroupOfPeople Class//
public class GroupOfPeople
    {
        private Person[] _people;
    public GroupOfPeople()
    {
        _people = new Person[0];
    }

    public void AddPerson(Person newPerson)
    {

        Person[] _More= new Person[_people.Length +1];
        _More[_people.Length] = newPerson;
        _people = _More;

    }

    public void DisplayAllPeople()
    {
        foreach (Person newPerson in _people)
        {
            newPerson.Display();
        }

    }
}

Answer: The way you have this coded right now, each time you add a person you are creating a new array and only saving the last added person:
   Person[] _More= new Person[_people.Length +1];
   _More[_people.Length] = newPerson;
   _people = _More;

If you want to re-size the array each time you add an entry to it, you should copy the already existing elements to the newly created array.
Also, if you're re-sizing the array, a better approach is to pre-alocate more space than you need and each time increase the size by a certain amount, proportional to the current size of the array (this could be 1/2 of the array size, of 3/4, or some other proprotion). This way you're not incurring the cost of resizing (copying the previous elements of the array) each time you add an element.
Or you could use a generic List<Person> which uses an array backing store, if your programming assignment will allow it.
Answer: You need to copy references from old to new array:
public void AddPerson(Person newPerson)
{
    Person[] _More= new Person[_people.Length +1];
    Array.Copy(_people, _More, _people.Length);
    _More[_people.Length] = newPerson;
    _people = _More;

}

Comment: This worked like a charm! I actually had that in there before, and when I was trying to make it all work i accidentally took it out and forgot to put it back in. Thanks for the help!!

Putting instantiated objects in arrays


Statistical test for power law samples

Question: What is the t-test analog for testing against the null hypothesis that two samples come from the same distribution, if the two samples are distributed according to power law and have different number of elements.
Comment: You might find the framework described in papers [here](http://tuvalu.santafe.edu/~aaronc/powerlaws/) useful.  There's an accompanying python package described [here](http://arxiv.org/abs/1305.0215). Otherwise maybe just fall back to a suitable generative model and some likelihood ratio tests.
Comment: Do you mean a plain Pareto with common lower bound at 1? Or something else? Can you be more precise about the assumptions here?
Comment: Do you have any idea what distribution the data is drawn from?  Power law distributions lack a sufficient statistic and this creates other limitations you may not intend.  You could use Bayesian model selection with one of your hypothesis being that they are drawn from the same model.
Answer: I do not believe there is a simple answer to your question without more details about the distribution. Power law distributions can have infinite variance, in which cases the large sample guarantees from the CLT will not apply.
If you know the variance of the distribution is finite (which can be guaranteed for certain parameter values) you can use something like the Wilcoxin ranked test detailed in
https://www.stat.auckland.ac.nz/~wild/ChanceEnc/Ch10.wilcoxon.pdf
I would not rely on these tests completely without some simple checks based on the Berry-Essen theorem (https://en.wikipedia.org/wiki/Berry%E2%80%93Esseen_theorem)
Essentially, you need some insights into the ratio of the third to the second moments of the distribution. This again, will depend on the nature of the exponential distribution under consideration
Answer: If your distribution is a Pareto distribution, you can apply $\log$ to the values and you will get an exponential distribution. Then you can perform a t-test
Comment: The t-test only compares *arithmetic means*; the mean log is actually the *geometric mean* of the original data. Now if you have in mind a one-parameter "power law" ([which is not the only possibility](http://en.wikipedia.org/wiki/Power_law#Power-law_probability_distributions)) this would still be fine, but why would the t-test be applicable to exponentially-distributed variables, which tend to be extremely skew?

Statistical test for power law samples


Como obter a instância do objeto superior/pai em uma function javascript?

Question: Estou implementando uma biblioteca de extensão de métodos do prototype, e se faço da forma simples tudo funciona perfeitamente como podem verificar no simples exemplo a seguir:

String.prototype.append = function(value) {
  // aqui o this é a instancia da String. Ok!
  return this.toString() + value;
};

document.getElementById('result').textContent = "Concatena com ".append("isto!");

Mas para evitar sobrescrever métodos do prototype, criei um objeto dentro do prototype para registrar esses métodos, mas com isso o escopo do método se modifica e o this não é mais uma referencia para a String, como pode ser verificado no exemplo a seguir:

String.prototype.extencion = {
  append: function(value) {
    // aqui o this não é mas uma instancia da String. Fail =(!
    // Como pegar a instancia do objecto pai?
    return this.toString() + value;
  }
};

document.getElementById('result').textContent = "Concatena com ".extencion.append("isto!");

Pergunta
É possível recuperar a instância do objeto pai em uma function no objeto filho?
Answer: Infelizmente isso que você quer não é possível. O objeto que você criou é um membro do protótipo de String, então o máximo que você poderia (embora eu acredite que nem isso seja possível) seria obter uma referência a esse protótipo - mas não à string que originou o acesso a ele. Pois uma vez que se subiu a cadeia de protótipos no acesso ao campo:
"Concatena com ".extencion

Já se perdeu a referência pra string original para sempre...
No caso dos métodos a referência ainda existe na forma do this, mas não no acesso a campos, de modo que eu costumo usar closures quando preciso fazer algo desse tipo (embora não saiba se é uma boa ideia mesmo fazer isso ou não). Exemplo:

String.prototype.extencion = function() {
  return {
    append: (function(value) {
      return this.toString() + value;
    }).bind(this) // aqui o this é amarrado com o objeto original
  };
};

document.getElementById('result').textContent = "Concatena com ".extencion().append("isto!");

Uma desvantagem desse método é que ele cria um objeto novo a cada invocação de função... Você poderia salvá-la para cada instância, mas aí há um desperdício de memória que pode se tornar significativo (dependendo do modo como se usa). Por isso disse não saber se é uma boa ideia. Um meio termo - não tão conveniente, mas sem os problemas citados acima - é fazer no "estilo jQuery":

var extensoesString = {
  append: function(_, value) {
    return this.toString() + value;
  }
};

String.prototype.extencion = function(funcao) {
  return extensoesString[funcao].apply(this, arguments);
};

document.getElementById('result').textContent = "Concatena com ".extencion("append", "isto!");

Comment: Essa ultima edição matou a minha resposta :P  agora vou ter de inventar outra abordagem :) `+1`
Comment: @EProgrammerNotFound Chrome, FF, Opera, Safari e IE9+ pelo menos ([há um *polyfill* pros que não suportam](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind)). O que é "edge" e "godzilla"?
Comment: Edge é o novo browser da microsoft (Pelo visto você ainda não instalou o Windows 10). [Godzila](https://br.answers.yahoo.com/question/index?qid=20130921200023AAdqRGa) é o mozzila firefox
Comment: @mgibsonbr, a respeito do `innerText` para `textContent`, alterei na pergunta também, assim fica coerente com a resposta e funciona no FF, não tinha reparado isto!
Comment: @Fernando hehe você pode tentar usar a criatividade, tipo criar uma cache (principalmente agora que os principais *browsers* [começaram a dar suporte ao `WeakMap`](https://kangax.github.io/compat-table/es6/#test-WeakMap)) e só criar uma instância se ela não existir ainda, etc. Se compensa ou não, não sei, eu já me acostumei com o "jeito jQuery" rsrs.
Comment: Acho que em ES6 acho que daria para usar um [Proxy](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Proxy), e interceptar a busca do método no objeto no momento da chamada.
Comment: Eu preciso pesquisar pra ver como faz, se der certo eu posto depois. Também não tenho certeza se não sofreria dos mesmos problemas que você citou.
Comment: bind functionará para todos os browser majoritários ? ie, chrome, edge, opera, safari, godzilla ? Em alguns casos teria que criar no início do script não? veja [aqui](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind)
Comment: @Fernando Eu queria apenas chamar atenção ao nome da função: O correto seria extension se estiver em inglês
Comment: @mgibsonbr, são boas formas de se fazer +1! Mas a primeira forma com _closures_ como você citou irá criar uma nova instância a cada chamada, o que não é bom, já a segunda a chamada se torna pouco intuitiva, ainda mais para uma biblioteca de extensão! Vou reanalisar meu problema!
Comment: @EProgrammerNotFound, foi um erro de digitação, vou corrigir em meu projeto! Mas na pergunta vou deixar assim mesmo para não causar incoerência com a resposta! Obrigado!
Comment: @Fernando Recriar o objeto é irrelevante na maioria dos casos. Não se preocupe em otimizações a não ser que tenha um gargalo nessa parte. Eu faria o mais simples e legível, primeiro. Até onde sei, concatenar a string também cria uma nova instâcia, não ?
Comment: @EProgrammerNotFound Em tese eu concordo com você (em particular se o compilador for esperto, e o coletor de lixo for generacional, o *overhead* da criação do objeto será mínimo), na prática, só testando... :)
Comment: @bfavaretto De fato, mas pelo que eu entendi essa solução sofreria dos mesmos problemas do meu primeiro exemplo (além do óbvio inconveniente de se ter que criar o Proxy). A menos que eu tenha entendido errado, é claro, não quer postar uma resposta com sua sugestão?
Comment: @bfavaretto, interessante sua sugestão, apesar de ser "_futurística_" =D, [já que até o momento somente o Firefox e o Edge tem isso implementado](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Proxy#Browser_compatibility). Não consegui assimilar bem como isso iria ser implementado com [Proxy](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Proxy), mas parece algo no minimo interessante. Se conseguir implementar um exemplo simplório de sua ideia seria agregador. (fiquei curioso =D)
Comment: @mgibsonbr, acabei implementando sua solução numero 1 (apesar de seus problemas, hehe), então vou aceitar está como resposta, pelo menos até ter solução melhor, talvez o [Proxy](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Proxy) que o bfavaretto citou, mas possivelmente vai demorar para ser compatível e usual, já que nem há um _**Polyfill**_ para ele. hehe
Answer: Podes criar um Type paralelo (superString no exemplo em baixo) e colocar os teus métodos alí. Para isso copias o prototype de String e passas as tuas strings pelo novo Type que crias-te. A ideia é assim:
var superString = (function () {
    // constructor
    function MyString(str) {
        this._str = str;
    }

    // criar uma cópia para não escrever métodos na String nativa
    MyString.prototype = Object.create(String.prototype);

    // funcionalidade "append"
    MyString.prototype.append = function (value) {
        return this.toString() + value;
    };

    // é preciso sobreescrever estes métodos...
    MyString.prototype.toString = function () {
        return this._str;
    };

    MyString.prototype.valueOf = function () {
        return this._str;
    };

    Object.defineProperty(MyString.prototype, 'comprimento', {
        get: function () {
            return this._str.length;
        }
    });
    return MyString;
})();

var str = new superString('Concatena com ');

document.getElementById('result').textContent = str.append('isto!');
console.log(str.comprimento); // 14

jsFiddle: http://jsfiddle.net/f2gzm6dx/
Algumas notas:

Tive de re-escrever os métodos nativos .valueOf () e .toString () para funcionar senão dava erro.
para re-criar uma propriedade tipo .length é teoréticamente possivel, mas o Chrome entra num loop infinito, assim criei uma propriedade comprimento com um getter para dar o que é esperado.

Outra solução usando a mesma ideia, sem importar o prototype de String já permitiria a propriedade .length e seria mais simples:
var superString = (function () {
    // constructor
    function MyString(str) {
        this._str = str;
    }

    // funcionalidade "append"
    MyString.prototype.append = function (value) {
        return this._str.toString() + value;
    };

    Object.defineProperty(MyString.prototype, 'length', {
        get: function () {
            return this._str.length;
        }
    });
    return MyString;
})();

var str = new superString('Concatena com ');

document.getElementById('result').textContent = str.append('isto!');
console.log(str.length); // 14

jsFiddle: http://jsfiddle.net/93xc49Lm/
Comment: Boa e inteligente alternativa @Sergio. Ainda mais pelo fato de não sobrescrever nada diretamente na `String` nativa. +1
Comment: Gostei da abordagem +1, mas francamente não a usaria.


Downloading a .csv file from the web (with redirects) in python

Question: Let me start by saying that I know there are a few  topics discussing problems similar to mine, but the suggested solutions do not seem to work for me for some reason.
Also, I am new to downloading files from the internet using scripts. Up until now I have mostly used python as a Matlab replacement (using numpy/scipy).
My goal:
I want to download a lot of .csv files from an internet database (http://dna.korea.ac.kr/vhot/) automatically using python. I want to do this because it is too cumbersome to download the 1000+ csv files I require by hand. The database can only be accessed using a UI, where you have to select several options from a drop down menu to finally end up with links to .csv files after some steps.
I have figured out that the url you get after filling out the drop down menus and pressing 'search' contains all the parameters of the drop-down menu. This means I can just change those instead of using the drop down menu, which helps a lot.
An example url from this website is (lets call it url1):
url1 = http://dna.korea.ac.kr/vhot/search.php?species=Human&selector=drop&mirname=&mirname_drop=hbv-miR-B2RC&pita=on&set=and&miranda_th=-5&rh_th=-10&ts_th=0&mt_th=7.3&pt_th=99999&gene=
On this page I can select 5 csv-files, one example directs me to the following url:
url2 = http://dna.korea.ac.kr/vhot/download.php?mirname=hbv-miR-B2RC&species_filter=species_id+%3D+9606&set=and&gene_filter=&method=pita&m_th=-5&rh_th=-10&ts_th=0&mt_th=7.3&pt_th=99999&targetscan=&miranda=&rnahybrid=&microt=&pita=on
However, this doesn't contain the csv file directly, but appears to be a 'redirect' (a new term for me, that I found by googeling, so correct me if I am wrong).
One strange thing. I appear to have to load url1 in my browser before I can access url2 (I do not know if it has to be the same day, or hour. url2 didn't work for me today and it did yesterday. Only after after accessing url1 did it work again...). If I do not access url1 before url2 I get "no results" instead of my csv file from my browser. Does anyone know what is going on here?
However, my main problem is that I cannot save the csv files from python.
I have tried using the packages urllib, urllib2 and request but I cannot get it to work.
From what i understand the Requests package should take care of redirects, but I haven't been able to make it work.
The solutions from the following web pages do not appear to work for me (or I am messing up):
stackoverflow.com/questions/7603044/how-to-download-a-file-returned-indirectly-from-html-form-submission-pyt
stackoverflow.com/questions/9419162/python-download-returned-zip-file-from-url
techniqal.com/blog/2008/07/31/python-file-read-write-with-urllib2/
Some of the things I have tried include:
import urllib2
import csv
import sys

url = 'http://dna.korea.ac.kr/vhot/download.php?mirname=hbv-miR-B2RC&species_filter=species_id+%3D+9606&set=or&gene_filter=&method=targetscan&m_th=-5&rh_th=-10&ts_th=0&mt_th=7.3&pt_th=-10&targetscan=on&miranda=&rnahybrid=&microt=&pita='

#1
u = urllib2.urlopen(url)
localFile = open('file.csv', 'w')
localFile.write(u.read())
localFile.close()

#2
req = urllib2.Request(url)
res = urllib2.urlopen(req)
finalurl = res.geturl()
pass
# finalurl = 'http://dna.korea.ac.kr/vhot/download.php?mirname=hbv-miR-B2RC&species_filter=species_id+%3D+9606&set=or&gene_filter=&method=targetscan&m_th=-5&rh_th=-10&ts_th=0&mt_th=7.3&pt_th=-10&targetscan=on&miranda=&rnahybrid=&microt=&pita='

#3
import requests
r = requests.get(url)
r.content
pass
#r.content =  "< s c r i p t > location.replace('download_send.php?name=qgN9Th&type=targetscan'); < / s c r i p t >"

#4
import requests
r = requests.get(url,
allow_redirects=True,
data={'download_open': 'Download', 'format_open': '.csv'})
print r.content
# r.content = "

#5
import urllib
test1 = urllib.urlretrieve(url, "test.csv")
test2 = urllib.urlopen(url)
pass

For #2, #3 and #4 the outputs are displayed after the code.
For #1 and #5 I  just get a .csv file with </script>'
Option #3 just gives me a new redirect I think, can this help me?
Can anybody help me with my problem?
Answer: The page does not send a HTTP Redirect, instead the redirect is done via JavaScript.
urllib and requests do not process javascript, so they cannot follow to the download url.
You have to extract the final download url by yourself, and then open it, using any of the methods.
You could extract the URL using the re module with a regex like r'location.replace\((.*?)\)'
Comment: `.*` matches any characters, `?` makes it `non-greedy`, so the group delimited by the inner parentheses matches anything inside the argument parentheses of `location.replace` - which happens to be the url javascript is redirecting to.
Comment: An explanation of `r'location.replace\((.*?)\)'` would help
Answer: Based on the response from ch3ka, I think I got it to work. From the source code I get the java redirect, and from this redirect I can get the data.
#Find source code
redirect = requests.get(url).content

#Search for the java redirect (find it in the source code)
# --> based on answer ch3ka
m = re.search(r"location.replace\(\'(.*?)\'\)", redirect).group(1)

# Now you need to create url from this redirect, and using this url get the data
data = requests.get(new_url).content


Invalid cast exception was unhandled when saving gridview to a file

Question: okay I am totally stuck.
I have been getting some help off and on throughout this project and am anxious to get this problem solved so I can continue on with the rest of this project.
I have a gridview that is set to save to a file, and has the option to import into excel.
I keep getting an error of this:
Invalid cast exception was unhandled.
At least one element in the source array could not be cast down to the destination array type.
Can anyone tell me in layman easy to understand what this error is speaking of?
This is the code I am trying to use:
<code>Dim fileName As String = ""
    Dim dlgSave As New SaveFileDialog
    dlgSave.Filter = "Text files (*.txt)|*.txt|CSV Files (*.csv)|*.csv"
    dlgSave.AddExtension = True
    dlgSave.DefaultExt = "txt"
    If dlgSave.ShowDialog = Windows.Forms.DialogResult.OK Then
        fileName = dlgSave.FileName
        SaveToFile(fileName)
    End If
End Sub
Private Sub SaveToFile(ByVal fileName As String)
    If DataGridView1.RowCount > 0 AndAlso DataGridView1.Rows(0).Cells(0) IsNot Nothing Then
        Dim stream As New System.IO.FileStream(fileName, IO.FileMode.Append, IO.FileAccess.Write)
        Dim sw As New System.IO.StreamWriter(stream)
        For Each row As DataGridViewRow In DataGridView1.Rows
            Dim arrLine(9) As String
            Dim line As String
            **row.Cells.CopyTo(arrLine, 0)**
            line = arrLine(0)
            line &= ";" & arrLine(1)
            line &= ";" & arrLine(2)
            line &= ";" & arrLine(3)
            line &= ";" & arrLine(4)
            line &= ";" & arrLine(5)
            line &= ";" & arrLine(6)
            line &= ";" & arrLine(7)
            line &= ";" & arrLine(8)
            sw.WriteLine(line)
        Next
        sw.Flush()
        sw.Close()

    End If
</code>
I bolded the line where it shows in debug, and I really dont see what all the fuss is about LOL
Comment: That's got to be the worst question title ever..
Comment: You should make your question title more specific so that people will actually view this post.
Answer: If we assume you only want the value of the cell, then your method is incorrect, as it will try to copy the entire cell to the array.
Would this work for you?
<code>        //**row.Cells.CopyTo(arrLine, 0)**
        line = row.Cells[0].Value.ToString()
        line &= ";" & row.Cells[1].Value.ToString()
        line &= ";" & row.Cells[2].Value.ToString()
        line &= ";" & row.Cells[3].Value.ToString()
        line &= ";" & row.Cells[4].Value.ToString()
        line &= ";" & row.Cells[5].Value.ToString()
        line &= ";" & row.Cells[6].Value.ToString()
        line &= ";" & row.Cells[7].Value.ToString()
        line &= ";" & row.Cells[8].Value.ToString()
        sw.WriteLine(line)
</code>
Comment: This is what you want.  Looks like DataGridViewRowCollection.CopyTo is expecting an array of DataGridViewRow objects, not an array of strings.

http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewrowcollection.copyto.aspx
Comment: That didnt work :( it gave me the same error as before ..but thank you for the effort!
Comment: @Dcurvez The only reason you would be getting the same error ("At least one element in the source array could not be cast down to the destination array type.") is if you did not comment out the line row.Cells[0].CopyTo(arrLine,0).  Unless you have another Array.CopyTo somewhere else.  Did you do this?
Comment: Jesus Matthew, I dont know. what I have so far....it has changed from previous because at this point I am reaching for straws.

    Dim arrLine(9) As String                Dim line As String                row.Cells.CopyTo(DirectCast(arrLine, Array), 0)                line = arrLine(0)                line &= ";" & arrLine(1)                line &= ";" & arrLine(2)                 sw.WriteLine(line)

this one gives me the cast down error
Comment: this one gives error stating arrLine is not declared:

    Dim arrLines As Array = New String() {}                Dim line As String                row.Cells.CopyTo(DirectCast(arrLine, Array), 0)                line = arrLine(0)                line &= ";" & arrLine(1)                line &= ";" & arrLine(2)
Comment: @Dcurvez The problem is the CopyTo function.  What happens if you comment out the line involving that function?
Comment: removing that line and running debug gave me an out of bounds error
on the line under it :  line = arrLine(0)
says Index out of range exception was unhandled,Index was out of bounds of the array.
Comment: @Dcurvez Good. Let's try this. Leave the line commented and replace everything from that line to the sw.WriteLine function with my answer. Does that change anything?
Comment: no Matthew it didnt work :(

it gave me errors on all the lines at the point of line = row.Cells[0].Value.ToString()on these lines it is not happy with the numbers in the brackets. It tells me Identifier is expected.

and the lines at the point of :

line &= ";" & row.Cells[2].Value.ToString()

it is telling me on this that Operator '&' is not defined for types 'string'and 'system.windows.forms.DataGridViewCellCollection'

maybe if I replace the numbers with the actual column names?
Answer: I generally try to avoid VisualBasic (the syntax always seems opposite to me), but from a little bit of Googling at the VB docs, I'd hazard a guess that you have a type mismatch between your string array (arrLine) and what row.Cells is trying to copy into it.
Comment: well, i am sorry for the bad title. didnt really give it much thought.

I tried the alterations above and ended p with the same error :(

Kitsune seems to strike a point as it was the first thought that came to mind, however I do not know how to fix this.


adjust container width by absolutely positioned inner element or vertical align bottom

Question: Also a fiddle.
How can I get the container of an absolute element, adjust its width automatically based on the width of the absolutely positioned element inside it.
Alternatively, the positioning can be removed but it's impossible to get the element (img) be vertically aligned to bottom.
ul {}
ul li {min-width:120px;height:200px;border:1px solid;float:left;margin:5px;position:relative;}
ul li img {position:absolute;bottom:0;display:block;}
ul li a {}

Andrew

Splog

Image below.
Comment: I don't think you can, the parent will not respond to an absolutely positioned child, unless of course you use js, or are willing to make the child positioned relative
Comment: Your HTML is aweful. Ewwww!
Comment: @andrewk, what I need is your credit card number :P. The closing `` should be after the closing ``, not after.
Comment: Yes that is right, I missed it. Sorry about that, I thought you were just trolling and passing bye.
Comment: I hope the answer below was helpful.
Answer: <!doctype html>

        <title></title>

Andrew

Splog

The magic is in the display: table, display: table-cell, and vertical-align: bottom. You also have to remove the absolute positioning from the image.
Also notice I changed all occurences of ul li to li? Yes, that's because all lis are inside uls!
Comment: This is not what the OP asked for, you are removing the absolute positioning on the image
Comment: @JustinBicknell, you read too fast that you did not get this line in the question "Alternatively, the positioning can be removed but it's impossible to get the element (img) be vertically aligned to bottom."
Comment: @Kizer it does get the job done. :) Goodluck in the Cup of Nations.
Answer: This Javascript code (jQuery) will do the trick if you run it after the images have loaded:
http://jsfiddle.net/turiyag/KA2F5/5/
$.each($("ul li"),function(idx,item) {
    var maxWidth = 0;
    var liElement = $(this);
    $.each(liElement.find("img"),function(idx2,imgelem) {
        if($(this).width() > maxWidth) maxWidth = $(this).width();
        liElement.css("width",maxWidth + "px");
    });

});


Modify a method annotation parameter at runtime

Question: I found this thread: How to change annotation value at runtime using reflection?
And I'm trying to change method annotation, but java.lang.reflect.Method does not contain any map-field like "annotations" or method like "getDeclaredAnnotationMap"
There is only private byte[] annotations but what can I do with this byte array?
So, how to modify annotation of method?
EDIT:
I created that: http://pastebin.com/T2rewcwU
But that only edit this instance of method, if you uncomment 33 line of code then value will reset.
Comment: Are you sure? http://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Method.html#getDeclaredAnnotations--
Comment: "map-field", and "getDeclaredAnnotation**Map**", that only copied array with annotations, nothing will change if you edit it.
Comment: Oops, too late for me. I stopped reading after the JavaDocs "The caller of this method is free to modify the returned array".
Comment: ok, I created that: http://pastebin.com/T2rewcwU , but this only edit current instance of Method class.
Answer: I wrote a class AnnotationUtil to resolve the seris requirements.
It can add/remove/change annotation value on class/field/method instance.
Note that use ReflectUtil to get root field/method when add/remove annotation.
See it on github:
AnnotationUtil
ReflectUtil
Comment: I don't even remember why I needed this now, and I already know that trick (as I was only missing that root instance) but forgot about this question.
Note that it will not work in next java versions, as they don't allow anymore for reflection between modules - additional jvm arguments will need to be used - or agent+instrumentation/unsafe/native code.
I will accept this answer tho.
Comment: @JayD https://github.com/XDean/Java-EX/blob/master/src/test/java/cn/xdean/jex/reflect/AnnotationUtilTest.java
Comment: @GotoFinal …and in case of class annotations, they're held by a `SoftReference`, which allows garbage collecting the cached data and effectively revert your manipulations.
Comment: this is truly a last resort, but i learned a lot going through your utils :)
Comment: Links are broken :(
Comment: @PaulPraet Link is back. Enjoy!  :)
Comment: @DeanXu can you kindly please provide working example for using addAnnotation method for class methods, specifically the Annotation type parameter passed into the method
Comment: @DeanXu cheers man, guess I didn't looked close enough


How to put variable from map function into Apollo mutation variables?

Question:  {data.devices.payload.map(device => (

                      <Card className="card">
                        <CardContent>
                          <TextField
                            id="outlined-bare"
                            defaultValue={device.name}
                            margin="normal"
                            variant="outlined"
                            variables={{device.id}}
                            onChange={e => this.setState({ name: e.target.value })}
                          />
                          <Typography>
                            Status: {device.isOn === true ? "WŁĄCZONY" : "WYŁĄCZONY"}
                          </Typography>
                        </CardContent>

                        <CardActions>

                              <Mutation
                                mutation={device.isOn === true ? SETOFF_MUTATION : SETON_MUTATION}
                                variables={{ device.id  }}>
                                {mutation => (

                                    <Button variant="contained" color={device.isOn === true ? "secondary" : "primary"} onClick={mutation}>
                                      {device.isOn === true ? "WYŁĄCZ" : "WŁĄCZ"}
                                      <PowerSettingsNewIcon className="rightIcon" />
                                    </Button>

                                )}
                              </Mutation>

I just want to pass my device.id from map function into Apollo Mutation. I can other values like device.name. Why i can't pass device.id?
Answer: Look at your code again do you really mean variables={{device.id}} or you wanted to type variables={device.id} or are you trying pass in an object with a property id which should be variables={{id:device.id}}


Display a Menu and Submenu as tabs

Question: I have a simple 2 level menu like this:
<code>Category1
   Link1a
   Link1b
   Link1c
Category2
   Link2a
   Link2b
   Link2c
</code>
I'd like to create a tabbed Menu/Submenu for this: When Category1 or any of it's sublinks are selected (clicked) Category1 is "active" and its links are shown. Category2 is visible but its links are not:
tabbed menu http://xooplate.com/assets/template/9845/p16qeq63ber8n2agm6hf8p2kb9-details.jpg
(random example from the web)
Can anybody point me in the right direction?
Answer: Simply use the quick tab module. It exactly do same thing.

Display a Menu and Submenu as tabs


Completing Cayley table for a group

Question: The task is to complete the following Cayley table

for a given group. $e$ is of course the identity element. Together with group axioms and the fact that every Cayley table of a group must be a latin square, I arrived at

Is it correct? I know there is only one possible table and it sure looks like a latin square but I would appreciate if someone could confirm it's correct or not!
Comment: Being a latin square does not imply itself that it is correct, but your answer is correct.
Comment: lol yes I did, I checked that it was a Sudoku (or rather a latin square) but does that make it correct? Just wanting to make sure!
Comment: Yeah for sure, there exist latin squares which do not represent groups, hence the question. Thanks!
Comment: Think Sudoku!  =)
Answer: I agree with your answer.
Completing the Cayley table of order $6$ (if $pq=e$, it must be $qp=e$, etc.), you get a non commutative ($pr\ne rp$) magma, with identity element $e$.
Each element of it has unique inverse (each one is inverse of itself, but $p$ and $q$ mutually inverses).
Finally, if you relabel $e,p,q,r,s,t$ as $1,2,3,4,5,6$, you get the table
$$\begin{array}{c|cccccc}
\cdot & 1 & 2 & 3 & 4 & 5 & 6\\
\hline
1 & \color{green}{1} & \color{red}{2} & \color{red}{3} & \color{blue}{4} & \color{blue}{5} & \color{blue}{6}\\
2 & \color{red}{2} & \color{red}{3} & \color{green}{1} & \color{blue}{5} & \color{blue}{6} & \color{blue}{4}\\
3 & \color{red}{3} & \color{green}{1} & \color{red}{2} & \color{blue}{6} & \color{blue}{4} & \color{blue}{5}\\
4 & \color{blue}{4} & \color{blue}{6} & \color{blue}{5} & \color{green}{1} & \color{red}{3} & \color{red}{2}\\
5 & \color{blue}{5} & \color{blue}{4} & \color{blue}{6} & \color{red}{2} & \color{green}{1} & \color{red}{3}\\
6 & \color{blue}{6} & \color{blue}{5} & \color{blue}{4} & \color{red}{3} & \color{red}{2} & \color{green}{1}
\end{array}$$
that you can check to be associative by using this brute-force Matlab script.
On the other hand, the above is a quasigroup since the Cayley table is a latin square and an associative quasigroup has identity element too.
Answer: I will try to construct the table in a systematic way. We know that in a group table each element appears exactly one in each row and each line. Also there must be an element where the corresponding row and line contains the same elements as the header row and line.
\begin{array}{c|cccccc}
\cdot & e & p & q & r & s & t\\
\hline
e & e & p & q & r & s & t\\
p & p & q & e & s &  & \\
q & q & &  &  &  & \\
r & r &  & & e &  & p\\
s & s &  & &  &  & \\
t & t &  &  &  &  &
\end{array}
To complete the $p$-line we use that a letter must appear exactly once in each line and each row. So we have $p t=r$ and $p  s=t$, and we get
\begin{array}{c|cccccc}
\cdot & e & p & q & r & s & t\\
\hline
e & e & p & q & r & s & t\\
p & p & q & e & s & t & r \\
q & q & &  &  &  & \\
r & r &  & & e &  & p\\
s & s &  & &  &  & \\
t & t &  &  &  &  &
\end{array}
$$p p=q \implies q  x = (p  p)  x = p  (p   x)$$
so we can calculate the $q$-line.
\begin{array}{c|cccccc}
\cdot & e & p & q & r & s & t\\
\hline
e & e & p & q & r & s & t\\
p & p & q & e & s & t & r \\
q & q & e & p & t & r & s\\
r & r &  & & e &  & p\\
s & s &  & &  &  & \\
t & t &  &  &  &  &
\end{array}
We have $p =r  t = \implies rp =r(rt)=(rr)t=et=t $ and so
\begin{array}{c|cccccc}
\cdot & e & p & q & r & s & t\\
\hline
e & e & p & q & r & s & t\\
p & p & q & e & s & t & r \\
q & q & e & p & t & r & s\\
r & r & t & & e &  & p\\
s & s &  & &  &  & \\
t & t &  &  &  &  &
\end{array}
and from this we get the position of $s$ and $q$ because of the uniqueness of an element in a row and in a line
\begin{array}{c|cccccc}
\cdot & e & p & q & r & s & t\\
\hline
e & e & p & q & r & s & t\\
p & p & q & e & s & t & r \\
q & q & e & p & t & r & s\\
r & r & t & s & e & q & p\\
s & s &  & &  &  & \\
t & t &  &  &  &  &
\end{array}
We have $rq=s$, and so $sx=r(q(x))$, so the $s$-line can be generated from the $r$-line and the $q$-line, similar to the $q$-line. It should not be a problem to create the final line now. Either by the fact that $t=sq$, or by the fact the elements are exactly once in each row and column. So we end up with
\begin{array}{c|cccccc}
\cdot & e & p & q & r & s & t\\
\hline
e & e & p & q & r & s & t\\
p & p & q & e & s & t & r \\
q & q & e & p & t & r & s\\
r & r & t & s & e & q & p\\
s & s & r & t & p & e & q\\
t & t & s & r & q & p & e
\end{array}
Now you still have to prove the associativity.
But this is the group $D_3$, the Dihedral Group, which is the group of symmetry group of the equilateral triangle. It is also the group $S_3$, the group of permutation of three elements. We see this if we compare the Cayley Table. So we know that it will be associative.
But of course we want to prove associativity without referencing wiki. I think the simplest way to do this is to create the Cayley table of the symmetric operations of the equilateral triangle. This can be done rather quick.

The reflection $r,s,t$ and the (counterclockwise) rotations $p,q$ are drawn in the sketch. The identity transformation is not shown. You have to check all 36 combinations. As an example we calculate $r\circ s$, to reflexions, will result in a rotation. Wich one?  $s$ does not change $C$, but $r$ transforms $C$ to $B$, $q$ also transforms $C$ to $B$, so $r\circ s = q$. Doing this for the whole table we see that the table represents the binary operation $x\circ y$, where $\circ$ is the composition of function. We know that the composition of function is an associative operation, so our table is associative.

There are other ways to test associativity.
To test associativity you usually have to check all $6^3$ triples $a,b,c$ if $a(bc)=(ab)c$ holds.
There are algorithms that may or may not reduce the number of checks
(e.g. Light's associativity test
There are some special kind of tables where it is easy to prove associativity.
So the subgroup of the elements $\{e,p,q\}$ defines  such a special table. It is symmetric about the main diagonal therefore the operation is commutative.
We have $q=p^2, e=p^3$ and so it is a cyclic group generated by $p$ and a cyclic group is always associative because of the properties of the exponents.
Note that because of the commutativity of the operator the expression $p^3$ is not ambiguous, $(p^2)p$ and $p(p^2)$ give the same result.
In our case we also can prove the associativity with less then $6^3=216$ checks.
First we have to prove the following simple variants of the associativity law.
$$p^k p^n=p^{k-1}p^{n+1}                       \tag{1a}$$
$$(rp^k) p^n=(rp^{k-1})p^{n+1}                   \tag{1b}$$
$$p^k  (p^nr)=p^{k-1}(p^{n+1} r)                  \tag{1c}$$
$$(rp^k) (p^nr)=(rp^{k-1}) (p^{n+1}r)   \tag{1d}$$
$$r(rp^k)=p^k   \tag{2}$$
and also the following
$$rp^k=p^{-k}r  \tag{3}$$
Note that by induction follows
$$p^k p^n=p^{k+n}                       \tag{1'a}$$
$$(rp^k) p^n=rp^{k+n}                   \tag{1'b}$$
$$p^k  (p^nr)=p^{k+n}r                  \tag{1'c}$$
$$(rp^k) (p^nr)=(rp^{k+n})r=r(p^{k+n}r)   \tag{1'd}$$
Also note that the exponent $n$ is a number modulo $3$, so $-1$ is actually $2$ and $4$ is actually $1$.
How many checks do we have to do?
To check statements $81a)$ we actually have nothing to check because this is the law of exponents we already mentioned befor.
To check $(1b)$ we have to check $k=1,\ldots,3$ and $n=1,\ldots,3$, these are $9$ pairs of values. The same is true for $(1c)$ and $(1d)$.
For $(2)$ and $3$ we have to check for $k=1,\ldots,3$. So all in all we have to do $33$ checks.
I leave these checks up to you.
Now we will prove the following $8$ equations.
$$(rp^k)((rp^m)(rp^n))=((rp^k)(rp^m))(rp^n) \tag{4a}$$
$$(p^k)((rp^m)(rp^n))=((p^k)(rp^m))(rp^n) \tag{4b}$$
$$(rp^k)((p^m)(rp^n))=((rp^k)(p^m))(rp^n) \tag{4c}$$
$$(rp^k)((rp^m)(p^n))=((rp^k)(rp^m))(p^n) \tag{4d}$$
$$(p^k)((p^m)(rp^n))=((p^k)(p^m))(rp^n) \tag{4e}$$
$$(p^k)((rp^m)(p^n))=((p^k)(rp^m))(p^n) \tag{4f}$$
$$(rp^k)((p^m)(p^n))=((rp^k)(p^m))(p^n) \tag{4g}$$
$$(p^k)((p^m)(p^n))=((p^k)(p^m))(p^n) \tag{4h}$$
Let's start with the prove of $(4a)$
$$(rp^k)((rp^m)(rp^n))=\text{(3)}\\
=(rp^k)((rp^m)(p^{-n}r))=\text{(1'd)}\\
=(rp^k)(r(p^{m-n}r))=\text{(3')}\\
=(rp^k)(r(rp^{n-m}))=\text{(2')}\\
=(rp^k)(p^{n-m})=\text{(1'b)}\\
=rp^{k-m+n}$$
In a similar manner
$$((rp^k)(rp^m))(rp^n)\\=rp^{k-m+n}$$
can be shown. This completes the proof of $(4a)$.
The equations $(4b)$ to $(4g)$ can be proven in a similar manner. For $(4h)$ no proof is needed.
Now we have proven the associativity law
$$a(bc)=((ab)c$$
for every $a,b,c$, because $a,b,c$ are in $\{p^0, p^1, p^2, rp^0,rp^1,rp^2\}$

Completing Cayley table for a group


How do I add repeating dates programmatically?

Question: I have some JSON data I'm using to populate Drupal 7 database. This involves creating nodes with repeating dates.
This is a sample of the data.
<code> [field_event_date] => Array
    (
        [0] => stdClass Object
            (
                [value] => 2012-12-14 10:00:00
                [value2] => 2012-12-14 12:00:00
                [rrule] => RRULE:FREQ=WEEKLY;INTERVAL=1;UNTIL=20160422T215959Z;WKST=MO
EXDATE:20121221T000000,20130125T000000,20130222T000000,20130329T000000,20130426T000000,20130531T000000,20130628T000000,20130726T000000,20130830T000000,20130927T000000,20131025T000000,20131129T000000,20131220T000000,20140131T000000,20140228T000000,20140328T000000,20140425T000000
                [timezone] => Europe/London
                [timezone_db] => Europe/London
                [date_type] => datetime
            )

        [1] => stdClass Object
            (
                [value] => 2012-12-28 10:00:00
                [value2] => 2012-12-28 12:00:00
                [rrule] => RRULE:FREQ=WEEKLY;INTERVAL=1;UNTIL=20160422T215959Z;WKST=MO
EXDATE:20121221T000000,20130125T000000,20130222T000000,20130329T000000,20130426T000000,20130531T000000,20130628T000000,20130726T000000,20130830T000000,20130927T000000,20131025T000000,20131129T000000,20131220T000000,20140131T000000,20140228T000000,20140328T000000,20140425T000000
                [timezone] => Europe/London
                [timezone_db] => Europe/London
                [date_type] => datetime
            )
    )
</code>
How could I enter this data into the table which stores the date for this node type?
Answer: Add [] to the end of the data field.
eg.
<code>    foreach($vals->field_event_date as $fed){
        //notice the []!
        $node->field_date_of_event['und'][]= array(
            'data1' => $fed->data1,
            'data2' => $fed->data2
        )
    }
</code>


How to set Textarea maximum number of rows

Question: I have a Textarea that I use to display content only.
How do I set it it's maximum number of rows to 4, regardless of the string length.
Or is there a way to calculate amount of text that can fit in 4 rows on any device? I can use this to extract part of the string and set the text on the Textarea to this substring.
I have tried textarea.setRows(4);, but this seems to work only if I have to type in the text.
Comment: Codenameone Gui Builder https://www.codenameone.com, Cross-platform mobile application tool.
Answer: Try something like this:
textarea.setGrowLimit(4);
textarea.setRows(4);
textarea.setGrowByContent(false);

I'm not sure if grow limit is necessary once grow by content is disabled.
Comment: Thanks, both works individually. Is there a way to remove the constraint at runtime? I'm trying to simulate growShrink() when user tap `more`
Comment: I think setting grow by content to be true should work and setting grow limit to -1 should too.
Comment: I did that earlier, but `growShrink(200)` and `revalidate()` didn't work, only `forceRevalidate()` was effective.


If a theory $A$ can prove $B$ consistent relative to $A$, and $A$ is consistent, does $B$ have to be consistent?

Question: Let's say we have two sets of axioms $A$ and $B$ such that $\mathsf{ZF} \subseteq A \subseteq B$, and from $A$ we can prove that if $A$ is consistent, then $B$ is consistent as well (that is, $A \vdash \text{Con}(A) \rightarrow \text{Con}(B)$).
Now, if $A$ is consistent ($A \not\vdash \bot$), does it follow that $B$ is consistent ($B \not\vdash \bot$)?
My approach: I think the answer is "no":
Suppose $\mathsf{ZF}$ is consistent. Since $\mathsf{ZF} \not\vdash \text{Con}(\mathsf{ZF})$ (by the second incompleteness theorem), $A = \mathsf{ZF} + \lnot\text{Con}(\mathsf{ZF})$ is consistent as well. Since we have $A \vdash \lnot \text{Con}(\mathsf{ZF})$, we also have $A \vdash \lnot \text{Con}(A)$, and thus $A \vdash \text{Con}(A) \rightarrow \text{Con}(B)$ for any $B$.
Now, let $B = A + \bot$. Then $B$ is obviously inconsistent, so $A$ and $B$ are a counterexample to my "rule".
Does this look correct? Can one also give a counterexample without assuming the consistency of $\mathsf{ZF}$?

The philosophical reason why I think that this might be important is the following:
As far as I know, one important reason for accepting the axiom of choice is the following: Gödel proved (using $\mathsf{ZF}$) that if $\mathsf{ZF}$ is consistent, then so is $\mathsf{ZFC}$. So if $\mathsf{ZF}$ is usable, then so is $\mathsf{ZFC}$.
But if the answer to my question is "no", that argument is flawed: Suppose tomorrow somebody proves a contradiction from $\mathsf{ZFC}$. Then of course, from the contrapositive of Gödel's theorem, we can prove $\mathsf{ZF}$ inconsistent. But $\mathsf{ZF}$ might still be a perfectly usable, since we haven't proven a contradiction from it!
(If one takes the perspective of "believing" in $\mathsf{ZF}$ then this paradoxical situation looks as follows: one "knows" that a proof of a contradiction is "out there", but one can't find that proof, and that proof might have some nonstandard length, so that no mathematicians will ever be able to write it down!)
This is probably too vague for this site, but if anybody spots some holes in that argumentation, feel free to point them out!
Comment: I disagree with the vote to close - I think this is an appropriate question for this site.
Comment: If there is a proof of a contradiction from $\mathsf{ZFC}$, then there is a proof of a contradiction from $\mathsf{ZF}$.
Answer: You are correct that, if $A$ proves "$Con(A)\rightarrow Con(B)$" and $A$ is consistent, this in general tells us nothing about whether $B$ is consistent.
However, your criticism of the argument that ZFC is consistent if ZF is, is flawed: the proof of "$Con(ZF)\rightarrow Con(ZFC)$" takes place in a much weaker theory (Peano Arithmetic is enough). So as long as we believe that $PA$ is true (or merely correct about $\Sigma_1$ sentences), then that's enough.
Comment: Also, note that even if full ZF were needed to prove this, the effect of a contradiction in ZFC would still be felt in ZF: namely, ZF would have to prove "I am inconsistent!" Now ZF might still be *consistent*, but I'm not sure ZF would be *usable* - surely we (most of the time :P) only care about set theories which don't prove plainly false $\Sigma_1$ facts!
Comment: @dankness If ZF is in fact consistent, then "ZF is inconsistent" is false; that's all I meant (presumably if we're using ZF, we believe ZF is consistent, in which case we believe "ZF is inconsistent" is false). Meanwhile, $\Sigma_1$ is a notation used to refer to part of the **Levy hierarchy**: basically, a sentence is $\Sigma_1$ if it has the form $\exists x_0, x_1, . . ., x_n\varphi$," where $\varphi$ uses only *bounded* quantifiers (e.g. quantifiers of the form $\forall x<y$ or $\exists x<y$). Inconsistency statements are of this form.
Comment: @NoahSchweber No, no. Using Gödel's arguments you get in the real world with actual true numbers an explicit procedure that transforms a proof of an inconsistency in one theory into a proof of an inconsistency in another theory. As soon as you formalize this procedure into a (meta)theory, naturally we need to assume its $\Sigma_1$-soundness.
Comment: Uhm, where can I look up $\Sigma_1$ facts, and why is "I am inconsistent!" plainly false?
Comment: @Noah. It may be worth adding that if $\mathsf{ZFC}$ is inconsistent, the proof that ${\rm Con}(\mathsf{ZF})\to{\rm Con}(\mathsf{ZFC})$ gives more than a proof of $\lnot{\rm Con}(\mathsf{ZF})$ from $\mathsf{ZF}$: It actually gives a proof of the inconsistency of $\mathsf{ZF}$. Your comments address what happens when $\mathsf{ZF}$ is actually consistent, and yet it proves the inconsistency of $\mathsf{ZFC}$, which is a slightly different thing. I point this out because the difference is subtle and may be worth making it explicit to the OP.
Comment: @AndrésE.Caicedo Well, strictly speaking, it only does that *if* we believe that PA (well, much less) is correct about $\Sigma_1$ sentences.


Given $f(i, j) = f(i − 1, j − 1) + f(i, j − 1)$, find the value of $f(1009, 2019)$

Question:
Let $f:(\mathbb{N}\ \cup \{0\})^2$ $\rightarrow\mathbb{N}\ \cup\{0\}$ be such that $f(0, x) = f(x, 0) = 1$ for all x $\in$ $\mathbb{N}\ \cup$ {$0$}.
Also for all $i, j \in\ \mathbb{N}$ we have $f(i, j) = f(i − 1, j − 1) + f(i, j − 1)$. Find $f(1009, 2019)$.

What I've tried:
I took two cases: $i>=j$ and $i<j$.
As $j$ is reduced by $1$ in both $f(i-1,j-1)$ and $f(i,j-1)$, if $j<=i$, then $j$ will reach $0$ first irrespective of $i$. So the value of $f(i,j)$ is $2^{j}$. Here's a branch diagram to illustrate what I meant
So $f(3,2)=2^2=4$
However I'm stuck at finding the pattern for the other case ($j>i$). Example for $f(i,j)$ where $i<j$:
$f(2,3)=7$
I do recognize that I can stop evaluating once I reach a point where $i=j$ but I can't find at which places and how many times they reach that point. It would be highly helpful If you would help me find the pattern. Also, am I going in the right direction? Is there any other way to solve this problem(a formula or something)? Help would be highly appreciable!
Comment: Pascal's triangle :)
Comment: Did you mean $f:(\mathbb{N}\ \cup \{0\})^2 \rightarrow\mathbb{N}\ \cup\{0\}$?
Comment: @CyclotomicField yes, I will edit it
Comment: @jlammy Pascal's triangle would work when $j<i$. But when $i<j$ some of the branches would stop when they reach $(0,x)$ or $(x,0)$. Am I right? How do we account for that?
Comment: The connection to Pascal's triangle / binomial coefficients may be clearer if you write out a table of small values for $f(i,j)$. (It won't be as simple as $f(i,j)=\binom{i+j}{i}$, but the pattern may yet be apparent.)
Answer: I programmed the sequence to see if there is any pattern.
Below is the $13 \times 13$ matrix including enough initial values to notice the pattern to be proven by induction after all:
<code>[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
[1, 2, 4, 7, 11, 16, 22, 29, 37, 46, 56, 67, 79]
[1, 2, 4, 8, 15, 26, 42, 64, 93, 130, 176, 232, 299]
[1, 2, 4, 8, 16, 31, 57, 99, 163, 256, 386, 562, 794]
[1, 2, 4, 8, 16, 32, 63, 120, 219, 382, 638, 1024, 1586]
[1, 2, 4, 8, 16, 32, 64, 127, 247, 466, 848, 1486, 2510]
[1, 2, 4, 8, 16, 32, 64, 128, 255, 502, 968, 1816, 3302]
[1, 2, 4, 8, 16, 32, 64, 128, 256, 511, 1013, 1981, 3797]
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1023, 2036, 4017]
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2047, 4083]
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4095]
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096]
</code>
So, the pattern I noticed is as follows:
$$f(m,n) = \begin{cases} \displaystyle\sum\limits_{k=0}^{m} {n \choose k},\ \  m < n \\[1mm] 2^n, \qquad \ \ \ \ ~ m\ge n \end{cases}$$
Next, we should prove it by induction.

The case $m < n$ (which is more interesting since $1009 < 2019$):

$\square$ We have enough information for the base case (see the table above). Now assume that
$$f(m-1,n-1) = \sum_{k=0}^{m-1}{n-1 \choose k} $$ and $$ f(m,n-1) = \sum_{k=0}^{m}{n-1 \choose k}$$ are true.
We should show that $f(m-1,n-1) + f(m,n-1) = f(m,n)$ is found by the same formula; that is, we are to prove
$$\sum_{k=0}^{m-1}{n-1 \choose k} + \sum_{k=0}^{m}{n-1 \choose k} = \sum_{k=0}^{m} {n \choose k}$$
Indeed,
$$
\begin{align}
\sum_{k=0}^{m-1}{n-1 \choose k} + \sum_{k=0}^{m}{n-1 \choose k}
&= \sum_{k=1}^{m}{n-1 \choose k-1} + {n-1\choose 0} + \sum_{k=1}^{m}{n-1 \choose k} \\[1mm]
&=  {n-1\choose 0} +  \sum_{k=1}^{m}\left[{n-1 \choose k-1} +{n-1 \choose k}\right] \\[1mm]
&\overset*= {n\choose 0} + \sum_{k=1}^{m}{n\choose k} \\[1mm]
&= \sum_{k=0}^m {n\choose k}
\end{align}
$$
where (*) denotes the Pascal's formula. $\blacksquare$

The case $m \ge n$:

$\square$ The base case and the induction hypothesis are analogous and the induction step is trivially proven by noting that
$$\underbrace{2^{n-1}}_{f(m-1,n-1)}+\underbrace{2^{n-1}}_{f(m,n-1)} = \underbrace{2^n}_{f(m,n)}. \ \ \blacksquare$$

Finally, we note that $$\boxed{f(1009, 2019) = \sum_{k=0}^{1009}{2019 \choose k}}$$
Comment: One interesting remark from WolframAlpha: For the case of $n=2m+1$, one has $f(m,2m+1)=\sum_{k=0}^m \binom{2m+1}{k}=4^m$ ([source](https://www.wolframalpha.com/input/?i=Sum%5BBinomial%5B2m%2B1%2Ck%5D%2C%7Bk%2C0%2Cm%7D%5D)). This includes $f(1009,2019)$ as the $m=1009$ case.
Comment: Upon reflection, this is simple: $$\sum_{k=0}^{m} \binom{2m+1}{k}=\sum_{k=m+1}^{2m+1} \binom{2m+1}{k}=\frac12 \sum_{k=0}^{2m+1}\binom{2m+1}{k}=2^{2m}.$$
Comment: 1) One has $f(1,1)=f(0,0)+f(1,0)=2$ but $m=n=1$ in your sum formula gives $\sum_{k=0}^0 \binom{1}{k} = \binom{1}{0}=1$. This doesn't occur if the upper limit if $m$ rather than $m-1$, so you may wish to recheck this.
2) If you look along and below the diagonal, you seem to have powers of 2. In other words, $f(m,n)=2^m$ if $m\geq n$.
Comment: @VIVID Do you mean$$\sum_{k=1}^{m}\left[{n-1 \choose k-1} +{n-1 \choose k}\right]$$ in the last but third line? Also thank you for your help!
Comment: @Semiclassical 1) I seem to confuse the indexing. In my indexing $f(2,2) = f(1,1) + f(2,1) = 2$. 2) I thought that sum formula would deal with the powers of two as well.
Comment: The problem states that $f(x,0)=f(0,x)=1$, so I think it's just an index shift by 1. As for the powers---yes, it'll include it, but it seems worth saying so explicitly.
Comment: @Semiclassical Yes, I fixed the indexing. Now, I will try to do the induction step and include the powers of two as you suggest. Thank you.
Comment: @Semiclassical Yes, that is interesting! Thanks.
Comment: @basilisk Yes, that was a typo. Glad that it helps $\ddot\smile$
Answer: Here is a generating function approach. We consider the recurrence relation
\begin{align*}
f(i,j)&=f(i-1,j-1)+f(i,j-1)\qquad\qquad i,j\geq 1\tag{1}\\
f(i,0)&=f(0,j)=1\qquad\qquad\qquad\qquad\qquad\quad i,j\geq 0
\end{align*}

We set
\begin{align*}
\color{blue}{F(x,y)=\sum_{i=0}^\infty\sum_{j=0}^\infty f(i,j)x^iy^j}
\end{align*}
and use guided from (1) the Ansatz
\begin{align*}
\sum_{i=1}^\infty\sum_{j=1}^\infty f(i,j) x^iy^j=\sum_{i=1}^\infty\sum_{j=1}^\infty f(i-1,j-1) x^iy^j+\sum_{i=1}^\infty\sum_{j=1}^\infty f(i,j-1) x^iy^j\tag{2}
\end{align*}

Left-hand side of (2):
We obtain
\begin{align*}
\sum_{i=1}^\infty&\sum_{j=1}^\infty f(i,j) x^iy^j\\
&=\sum_{i=0}^\infty\sum_{j=0}^\infty f(i,j) x^iy^j-\sum_{i=0}^\infty f(i,0)x^i-\sum_{j=0}^\infty f(0,j)y^j+f(0,0)\\
&=F(x,y)-\frac{1}{1-x}-\frac{1}{1-y}+1\tag{3}
\end{align*}
Right-hand side of (2):
We obtain
\begin{align*}
\sum_{i=1}^\infty&\sum_{j=1}^\infty f(i-1,j-1) x^iy^j+\sum_{i=1}^\infty\sum_{j=1}^\infty f(i,j-1) x^iy^j\\
&=\sum_{i=0}^\infty\sum_{j=0}^\infty f(i,j) x^{i+1}y^{j+1}+\sum_{i=1}^\infty\sum_{j=0}^\infty f(i,j) x^{i}y^{j+1}\\
&=xyF(x,y)+yF(x,y)-\sum_{j=0}^\infty f(0,j)y^{y+1}\\
&=xyF(x,y)+yF(x,y)-\frac{y}{1-y}\tag{4}
\end{align*}
From (3) and (4) we get:

\begin{align*}
F(x,y)-\frac{1}{1-x}-\frac{1}{1-y}+1&=xyF(x,y)+yF(x,y)-\frac{y}{1-y}\\
F(x,y)(1-y(1+x))&=\frac{1}{1-x}\\
\color{blue}{F(x,y)}&\color{blue}{=\frac{1}{1-x}\,\frac{1}{1-y(1+x)}}\tag{5}
\end{align*}

The final step is to extract $f(i,j)=[x^iy^j]F(x,y)$ where we use the coefficient of operator $[x^i]$ to denote the coefficient of $x^i$ of a series.

We obtain from (5) for $i,j\geq 0$:
\begin{align*}
\color{blue}{f(i,j)}&=[x^iy^j]\frac{1}{1-x}\,\frac{1}{1-y(1+x)}\\
&=[x^iy^j]\sum_{k=0}^\infty y^k(1+x)^k\,\frac{1}{1-x}\tag{6}\\
&=[x^i](1+x)^j\,\frac{1}{1-x}\tag{7}\\
&=[x^i](1+x)^j\sum_{k=0}^\infty x^k\tag{8}\\
&=\sum_{k=0}^i[x^{i-k}](1+x)^j\tag{9}\\
&=\sum_{k=0}^i\binom{j}{i-k}\tag{10}\\
&\color{blue}{=\begin{cases}
\sum_{k=0}^i\binom{j}{k}&\qquad j>i\\
2^j&\qquad j\leq i
\end{cases}}\tag{11}
\end{align*}
Comment:

In (6) we use the geometric series expansion.

In (7) we select the coefficient of $y^j$.

In (8) we expand $\frac{1}{1-x}$.

In (9) we use the linearity of the coefficient of operator and apply the rule $[x^{p-q}]A(x)=[x^p]x^qA(x)$. We also set the upper limit of the series to $i$ since other terms do not contribute.

In (10) we selet the coefficient of $x^{i-k}$.

In (11) we change the order of summation $k\to i-k$ and we use the binomial identity $\sum_{k=0}^j\binom{j}{k}=2^j$ as well as $\binom{j}{k}=0$ if $k>j$.
Comment: Happy to see someone take the g.f. approach. (+1)
Comment: @Semiclassical: Many thanks for your nice comment and the credit. :-)
Answer: A slightly simpler solution based on VIVID's work (it's essentially the same).
If we utilize the generalized binomial coefficients where $$\binom{n}{k} = 0, n, k \in \mathbb Z, k > n \text { or } k<0$$ then VIVID's formula becomes $$f(m,n) = \sum_{k=0}^m \binom{n}{k} \tag 1$$
We also know the following recursive relation is true for these generalized coefficients as well:
$$\binom{n}{k} = \binom{n-1}{k} + \binom{n-1}{k-1} \tag 2$$
Then, since $f$ is uniquely determined by $$f(0,x)=f(x,0)=1 \tag 3$$ and $$f(i, j) = f(i − 1, j − 1) + f(i, j − 1) \tag 4$$
we only need to show $(3)$ and $(4)$ are true when we plug in VIVID's formula $(1)$. Now, $(3)$ is obviously true. For $(4)$, indeed we have (via $(2)$)
$$f(i,j) = \sum_{k=0}^i \binom{j}{k} = \sum_{k=0}^i \binom{j-1}{k-1} + \sum_{k=0}^i \binom{j-1}{k}  \\
= \sum_{k=1}^i \binom{j-1}{k-1} + f(i,j-1)\\
= \sum_{k=0}^{i-1} \binom{j-1}{k} + f(i,j-1)\\
= f(i-1,j-1) + f(i,j-1).\blacksquare $$


Get HEX of Color constants in Android

Question: I searched and wasn't able to find the answer. What I am looking for is the HEX corresponding value for Color constants in Android.
For example:
Color.BLACK = #000000
Color.WHITE = #FFFFFF

So what would be the HEX values for the following constants:
    Color.CYAN
    Color.DKGRAY
    Color.GRAY
    Color.GREEN
    Color.LTGRAY
    Color.MAGENTA
    Color.RED
    Color.YELLOW
    Color.BLUE

Comment: You can also press `F3` on that code, that will display code of that value. :)
Comment: In xml use @android:color/black
Comment: [Google it](http://cloford.com/resources/colours/500col.htm). These are everywhere, hex values for color are used in web design too.
Comment: Check the [Android Color documentation](http://developer.android.com/reference/android/graphics/Color.html)
Comment: Or better yet how do I add the background using XML. What is the XML version of Color.BLACK (e.g.)
Comment: Just google it. You'll get what you want. Check this link: http://www.rapidtables.com/web/color/index.htm
Comment: Nice question.. But I have only one doubt, I have a color constant for ex : 17170449 which I need to convert into the hexa decimal code. is it possible? Thanks in advance @shree202
Answer: See http://developer.android.com/reference/android/graphics/Color.html#BLACK

public static final int CYAN

Constant Value: -16711681 (0xff00ffff)

public static final int DKGRAY

Constant Value: -12303292 (0xff444444)
public static final int GRAY

Constant Value: -7829368 (0xff888888)

public static final int GREEN

Constant Value: -16711936 (0xff00ff00)

public static final int LTGRAY

Constant Value: -3355444 (0xffcccccc)

public static final int MAGENTA

Constant Value: -65281 (0xffff00ff)

public static final int RED

Constant Value: -65536 (0xffff0000)
Comment: Accepted your answer.
Answer: If you need to do it in your program code, then you can use the Color class.
Color.BLACK.getRGB();

Otherwise, just google it I suppose.

Get HEX of Color constants in Android


Are there scales and chord progressions particularly used in Rag music?

Question: I am interested in the underlying scale and chord structures of ragtime music . For example, I was reading in my book Jazzology last night that ii-V-I progressions are frequently used in Jazz. I am interested in the corresponding ones for ragtime music.
Are there scales and chord progressions particularly used in Rag music?
Comment: Ragtime is basically a march but with characteristic syncopated rhythms. Rhythm, not scale or chord patterns, define Ragtime.
Answer: Structurally ragtime harmony is pretty much classical tonal harmony, but there are some idiomatic specificities that give ragtime its characteristic sound.
One progression very characteristic of ragtime is the so called... ragtime progression (although it was used before, even in classical music, it was mostly popularized in ragtime). It's made of a succession of "piggybacked" secondary dominants in a succession of rising 4th intervals onto the tonic, e.g., in C, in its full extension:
C - E - A - D - G - C   (in this instance I find chord note names easier to use than the roman numeral analysis that would be required)
Usually, all chords are dominant 7th chords. The progression may start in any of the secondary dominants, the most common case being a 4 step progression (starting on A for a piece in C).
Another variation superimposes a ii-V-I progression by making one of chords minor (also usually 7th)
C - A7 - D-7 - G7 - C
There is also a lot of chromatic substitutions, usually dictated by voice leading (i.e. chords changing by step intervals, mostly half tones) thus creating a lot of full and half diminished (7th) chords.
Just to give an example, at the end of the B part Scott Joplin's Maple Leaf Rag (Ab major), the progression is:

Notice how the first chord of the "ragtime progression", F in this case, is approached chromatically in a quite seamless way. Then the progression follows pretty much plainly (no no-chord-tones for two bars).
In bar 4, at the point marked with *, Bb- is replaced by Bb7add9 both providing harmonic interest and smoothing voice leading: notice how the uppermost and lower "treble" voices move stepwise.

Regarding scales, my understanding is that structurally they are mostly diatonic, I don't think that pentatonic or blues scales are inherently used, although sometimes a "bluesy" sound may occur by means of the harmony. Melody is not a strong component of ragtime anyway, many ragtimes almost have no melody as such, or melody is built practically with arpeggiated chords and a lot of chromatic passing tones (Mapleleaf Rag a case in point).
Answer: I'm going to tell you what I observe in very layman's terms without music theory terms.
Let's for simplicity we're in the key of C.
A lot of them have this progression: (F F#° or Ab7 /) C/G A7 D7 G7 C especially towards the end of a section.
A possible "verse" (very common) is
C / / / | / / / / | F / / / | C / / /
C / G/B / | Am / Am7/G / | D7 / / / | G / / /
C / / / | / / / / | F / / / | (C or E7) / / /
F / F#° / | C/G / A7 / | D7 / G7 / | C / / /
There are lots of C6s and F6s scattered throughout, especially when you get to the "second section", and that second section (quite often) starts with G.
There may be a few diminished chords, usually C->C#°->D, D->D#°->C/E, F->F#°-C/G, A#°->G/B, for example.
In quite a few of them, there is the trio section, which is going to be in a key a perfect 4th from your starting key. In this case, that trio section will be in F.
My apologies for my dilettante approach to this.


How to hide not translated menu items

Question: I have a multilanguage site. Now i'm running in the issue that some pages don't have translations. So i would like to hide that from the navigation.
I already tried to manipulate it with that hook:
mytheme_preprocess_menu_local_task
But it seems that it does not have an affect. I also don't find any other hook which i could use for that.
Any suggestion?
Answer: Use hook_node_access() to deny access to the not translated nodes and this will automatically hide the corresponding menu items:
mymodule.module:
use Drupal\Core\Access\AccessResult;
use Drupal\node\NodeInterface;
use Drupal\Core\Session\AccountInterface;

  /**
   * Implements hook_node_access().
   */
  function mymodule_node_access(NodeInterface $node, $op, AccountInterface $account) {
    $langcode = \Drupal::languageManager()->getCurrentLanguage()->getId();
    if (!$node->hasTranslation($langcode)) {
      $access = AccessResult::forbidden();
    }
    else {
      $access = AccessResult::neutral();
    }
    $access->addCacheableDependency($node);
    return $access;
  }

You can be more specific, hide not translated nodes of specific content types. Or for specific user roles, which you probably need to do if other users than the admin wants to edit the nodes. Or you have to be specific about the operation $op. And test this with different user roles, as admin you won't see a difference, because this account passes all access checks.
Comment: Thanks. But it seems that it does not have an effect. Do i need active or install a module for node access? Cause even when i make dump inside the function is it not executed.
Comment: Yes, you need a custom module and install it.
Comment: yes that i've done but it does not work. i ment another core module or something. but ok i will check why it does not work
Comment: great it works!! Thanks a lot!! sorry i overread your "as admin you won't see a difference"
Comment: now i have another thing. i redirected previously user to startpage of selected language if they switch language on an non translated node. now that doesn't work anymore cause it does not go into my mytheme_preprocess_node function and inside the new function i'm not able to do unless to get too many redirects. Do you have any hints?
Comment: Use an event subscriber for redirecting. Either to a REQUEST event after routing to check the node object in the matched route or to an EXCEPTION event to catch the 403.

How to hide not translated menu items


Derivate $y(x) = y_0 +\int^{x}_{x_0}F(t,y(t))dt$

Question: Let $\frac{dy}{dx} = F(x,y)$ be a bounded, continuously differentiable function which satisfies a Lipscitz condition. And let $y(x_0) = y_0$
I want to derivate the following
$$y(x) = y_0 +\int^{x}_{x_0}F(t,y(t))dt$$
to obtain the original function. How to do this?
The left hand side is of course just $\frac{dy}{dx}$ but what about the right hand side?
$\frac{d}{dx}( y_0 +\int^{x}_{x_0}F(t,y(t))dt) = \frac{d}{dx}y_0 +\frac{d}{dx}\int^{x}_{x_0}F(t,y(t))dt = 0 +  \frac{d}{dx}\int^{x}_{x_0}F(t,y(t))dt = $
$\frac{d}{dx} (F'(x,y(x)) - F'(x_0,y(x_0)))  $ Where $F'(t,y(t))$ is the primitive function of $F(t,y(t))  $ with respect to $t$
I think that $F'(x_0,y(x_0)) \in \mathbb{R}$ so $\frac{d}{dx} (F'(x,y(x)) - F'(x_0,y(x_0))) = \frac{d}{dx} F'(x,y(x)) -\frac{d}{dx}F'(x_0,y(x_0)) = \frac{d}{dx} F'(x,y(x))  - 0 = \frac{d}{dx} F'(x,y(x))$
I'm not sure how to show that
$$\frac{d}{dx} F'(x,y(x)) = F(x,y)$$
This is how far I got and I'm not even sure above steps are correct. Can anyone please help me solve this?
Comment: You're correct, $F'(x_0,y(x_0))$ is indeed a number. All above steps seem right too.
Comment: You can apply Differentiation under the integral sign (see http://en.wikipedia.org/wiki/Differentiation_under_the_integral_sign ), to get the conclusion much easier, witout primitives of $F$.
Comment: @cjferes Thats at least a start. Thank you! :) To the person downvoting me would you mind commenting on why you downvoted? Is there anything wrong with my question?
Answer: By the fundamental theorem of calculus
$$
\frac{d}{dx}\int_{x_0}^xF(t,y(t))\,dt=F(x,y(x)).
$$