Show that $E_Q[Y]=E_P[XY]$

Question: I was trying to solve an exercise which asks me to prove
Show that $E_Q[Y]=E_P[XY]$ where $P$ is a probability measure on $(\Omega,\mathcal{A})$ and $X$ is a r.v such that $P[X>0]=1$ and $E[X]=1 $
$Q:\mathcal{A} \to R$ is a probability measure such that
$Q(A)=E[X\mathrm{1}_A]$
I managed to prove it using the standard technique where I first prove it for simple functions, then pass to positive functions via Beppo-Levi but nowhere in the proof do I use that $\{X>0\}$ has measure one(all I need is $X\ge 0$ almost surely). Where exactly is almost sure strict positivity used. Is it even required?
Answer: It's not required; all you need for what you wish to prove is that $X \ge 0$ almost surely. However, the fact that $X > 0$ a.s. does guarantee that $P$ and $Q$ are equivalent measures. That is, they are mutually absolutely continuous, which is to say that $P \ll Q$ and $Q \ll P$. (It might be useful to think through why this is true.)
This then means that you also have that for each $A \in \mathcal A$, $$P(A) = E_Q \left[\frac 1X 1_A\right],$$ so that, for every $P$-integrable $Y$, $$ E_P[Y] = E_Q \left[ \frac YX \right]. $$

Show that $E_Q[Y]=E_P[XY]$


Print de um valor realizado dentro de uma função bugado

Question: Estou tentando criar um programa que calcule o método da bisecção.
Gostaria que o usuário inserisse a equação desejada e os valores de a, b e a tolerância, porém não estou conseguindo fazer com que o input da equação seja lida corretamente.
Também não sei se existe uma biblioteca que faça a leitura correta de uma equação. Além disso, criei uma função para me retornar um valor, porém ela está me retorna algo estranho:
def funcao_soma(x,y):
    soma = x+y
    return soma

funcao_soma(1,5)
print("A soma foi {}".format(funcao_soma))

Ele me retorna:
A soma foi <function funcao_soma at 0x000001BC6E8EFF78>

Ao invés do valor 6.
Answer: O resultado da sua função não está sendo salvo em nenhuma variável (linha 5). Deveria ser, por exemplo:
resultado = funcao_soma(1,5)
print("A soma foi {}".format(resultado))

ou caso não queira usar uma variável intermediária:
print("A soma foi {}".format(funcao_soma(1,5)))

Comment: Obrigado, deu certo!
Comment: Poderia marcar a resposta como solução, por gentileza?


pydrive: Losing file content during upload()

Question: I currently have a 34x22 .xlsx spreadsheet.  I am downloading it via pydrive, filling in some of the blank values, and uploading the file back via pydrive.  When I upload the file back, all cells with formulas are blank (any cell that starts with =).  I have a local copy of the file I want to upload, and it looks fine so I'm pretty sure the issue must be with pydrive.
My code:
def upload_r1masterfile(filename='temp.xlsx'):
        """
        Upload a given file to drive as our master file
        :param filename: name of local file to upload
        :return:
        """
        # Get the file we want
        master_file = find_r1masterfile()
        try:
            master_file.SetContentFile(filename)
            master_file.Upload()
            print 'Master file updated. ' + str(datetime.datetime.now())
        except Exception, e:
            print "Warning: Something wrong with file R1 Master File."
            print str(e)
            return e

The only hint I have is that if I add the param={'convert': True} tag to Upload, then there is no loss.  However, that means I am now working in google sheets format, and I would rather not do that.  Not only because it's not the performed format to work with here, but also because if I try to master_file.GetContentFile(filename) I get the error: No downloadLink/exportLinks for mimetype found in metadata
Any hints?  Is there another attribute on upload that I am not aware of?
Thanks!
Answer: Robin was able to help me answer this question at the github repository.  Both suggested solutions worked:

1) When you upload the file, did you close Excel first? IIRC MS Office writes a lot of the content to a temporary file, so that may explain why some parts are missing. If you tried the non converting upload first, the full file may have been saved to disk between the two tries, and thus the second converting upload attempt worked.
2) GetContentFile takes a second argument called mimetype, which should allow you to download the file. Could you try .GetContentFile(filename, mimetype="application/vnd.ms-excel")? If that mimetype doesn't work as anticipated, there is a great StackOverflow post here which lists a bunch of different types you can try.

Thanks again Robin!


Como definir focus no jhtmlarea?

Question: Estou obtendo erro ao usar o plugin JHtmlArea:

An invalid form control with name='descricao' is not focusable.

HTML

Descrição do assunto

    <textarea name="descricao" id="descricao" cols="60" rows="15"></textarea>

jQuery:
$(document).ready(function() {

  $("#descricao").htmlarea();

  $("#contato").on("submit", function (){
      if($("iframe").val().trim() == "")   {
          alert("Preencha a descrição do e-mail");
          $("#descricao").prop("required",true);
      } else {
          $("#descricao").prop("required",false);
      }
  });

Onde estou errando?
A jhtmlarea esta funcionando, mas não consigo barrar o envio com o campo descrição vazio nem colocar o foco nela para preenchimento.
Onde estou errando?
Vale lembra que o plugin cria um iframe e torna a textarea display: none.
Comment: adicionar required ao plugin. esse é o problema. Já coloquei o link d plugin.
Comment: Não, é falta de atenção mesmo. Mas corrigi aqui. Mas ainda não consigo colocar o focus() no jhtmlarea.
Comment: Voce está tendo problema para fazer a validação ou somente para jogar o focu no campo
Comment: Os dois. Na verdade, quando o plugin entra em cena, ele esconde o textarea e mostra um iframe por cima. Só que, se não tiver nada preenchido eu não consigo enviar um alerta e nesse caso não mostra erro nem nada para o usuario, apenas não submete o form
Comment: Conseguiu resolver o problema?
Comment: Achei que tinha conseguido conforme resposta que dei abaixo. Mas nã deu certo não!
Answer: Se um input estiver como "required", o form será inválido e não conseguirá enviar. O caso do foco, se o input estiver oculto, não conseguirá colocar foco.
Comment: O colega, desculpa. Enquanto você respondia estava editando a pergunta, Dá uma olhada de novo fazendo favor!
Comment: Agora que vi.
Se um input estiver como "required", o form será inválido e não conseguirá enviar.
O caso do foco, se o input estiver oculto, não conseguirá colocar foco.
Comment: O campo não esta oculto e nem tem required no campo pois não sei em quem colocar o required, se no textarea ou no jhtmlarea. Mas em nenhum funcionou.
Comment: o required deve ser colocado no textarea.
Comment: sim. Isso é um plugin que fornece ferramentas do word para edição do texto. Tipo, negrito, itálico, sublinhado. Essas coisas.
Comment: veja esse link referente ao foco: http://stackoverflow.com/questions/1615861/set-focus-to-jhtmlarea-jquery-plugin
Comment: Já tinha visto esse link não é isso não. Preciso é colocar o focou em um iframe que o plugin cria para sobrepor a textarea e coloca display none nela. dá pra ver em: http://www.dinamicaimoveis.com.br/novo/ no formulário de contato que tem no final da página
Comment: Ainda não consegui!
Answer: Isso funcionou para mim.
Criei um .js com esse código e importei onde tivesse jhtmlarea
  $("#contato").on("submit", function (){
    if($('#descricao').val() == "")   {     //verifica apena o texto
        alert("Descrição não está preenchida!");
        $('#descricao').siblings().each(function(){
          if ($(this).children('iframe').length){
             var iframe=$(this).children('iframe')[0];
             iframe.contentWindow.focus();
          }
       });
       return false;
    }
  });

Porém ainda não consigo ao invés de validar o iframe com JScript, validar com html5 tratando a propriedade require com true e evitar a famosa janelinha popup do JScript.
Comment: doce ilusão: funcionou! Mas parou o restante do JQuery. Alguma saída?
Answer: O campo que quer validar é
<textarea name="descricao" id="descricao" cols="60" rows="15"></textarea>

Por isso deverá validar a textarea e não o iframe que a biblioteca cria.
$("#contato").on("submit", function (){
  if($("#descricao").val() == "")   {
      alert("Descrição não está preenchida!");
  } else {
      alert("Obrigado pela descrição");
  }
});

Não funciona porque a maioria dos casos porque basta ter um entar e ficará com o seguinte valor

Portanto não é vazio logo é valido.
Para voce conseguir dar focus é o seguinte codigo.:
$('#descricao').siblings().each(function(){
    if ($(this).children('iframe').length){
        var iframe=$(this).children('iframe')[0];
        iframe.contentWindow.focus();
    }
});

O que sugiro é.:
$("#contato").on("submit", function (){
  var a=document.createElement('div'); //cria uma div temporaria
  $(a).html($('#descricao').val());    //insere o html na div
  if($(a).text().trim() == "")   {     //verifica apena o texto
      alert("Descrição não está preenchida!");
      $("#descricao")
         .val('')
         .prop("required",true)
      ;
      $('#descricao').siblings().each(function(){
        if ($(this).children('iframe').length){
           var iframe=$(this).children('iframe')[0];
           iframe.contentWindow.focus();
        }
     });
  } else {
      alert("Obrigado pela descrição");
  }
});

Comment: Entendi. Mas ai surgem dois problemas 1) Os outros campos do formulário estão sendo validados com htm5 validate e não com JavaScript. Logo, estou colocando $("#descricao").prop("required",true); mas como o plugin faz display: none com a textarea, logo não é possivel colocar o foco na textarea.
Comment: Editei a resposta. Já está tudo ok?
Comment: Olha, reduzi sua solução e obtive o mesmo resultado. Porém ainda não consigo ao invés de validar o iframe com JScript, validar com html5 tratando a propriedade require com true e evitar a famosa janelinha popup do JScript. Veja a solução que reduzi na minha resposta à pergunta logo abaixo! Vê se tem como me ajudar mais!
Comment: Voce apagou codigo importante. Com o codigo completo. Não funcionou?
Comment: dá esse erro: An invalid form control with name='descricao' is not focusable. O plugin jHtmlArea faz display: none ao textarea e nesse caso, não adianta fazer required pois dará erro. Não conheço outra maneira.
Answer: Uma forma prática e funcional é criar uma função para verificar se o campo <textarea> com o plugin jHtmlArea está vazio e focar nele:
function checa(){
    var a = document.createElement('div');
    $(a).html($('#descricao').val());
    if($(a).text().trim() == ""){
        alert("Vazio");
        $('#descricao').siblings().each(function(){
            if($(this).children('iframe').length){
                var iframe=$(this).children('iframe')[0];
                iframe.contentWindow.focus();
            }
        });
        return false;
    }
}

E coloca no seu <form> o onsubmit="return checa()".

Como definir focus no jhtmlarea?


How to hook into an attachment?

Question: I have a field loading hidden in an attachment view and I need to hook into that attachment to alter the output of the field.
It involves PHP and I'd rather hook into template.php rather than download some PHP module to store PHP code in my database.
I've tried hooking into theme_views_pre_render but I can't find my attachment, I can only modify the $view->attachment_before output.
That, plus I can't actually obtain the field values in this hook?
So how can I hook into a field value in an attachment?
Answer: An attachment is just like any other view (except that it is attached to other views), and so can be manipulated as such:
In template.php:
<code>function THEMENAME_preprocess_views_view_fields(&$vars) {
  if (isset($vars['view']->name) && $vars['view']->name == 'VIEW_NAME' && $vars['view']->current_display == 'ATTACHMENT_NAME') {
    foreach ($vars['fields'] as $id => $field) {
      if ($id == 'FIELD_NAME') {
        $vars['fields'][$id]->content = 'new value';
      }
    }
  }
}
</code>
Remember to clear your cache.

How to hook into an attachment?


What is the purpose of the "Menu language" widget?

Question: When the Content Translation module is enabled, a "Menu language" widget appears in the form for editing menus:

What is the purpose of this widget?  What does it do?
It does not seem to affect my site at all when I change the dropdown to a different language, or to "Not specified" or "Not applicable."
Answer: This is the original language for the label and the description. After saving the menu in the original language you can click on the tab above (admin/structure/menu/manage/main/translate) and translate the two text fields into other languages.
Comment: I tried visiting /structure/menu/manage/main/translate and also /admin/structure/menu/manage/main/translate and I get "page not found."  So I am wondering if there are cases when the Menu Language widget is totally irrelevant to the site but Drupal still presents the widget.
Comment: You could use the tab "Translate menu" directly above the screenshot in the question. This is the standard translation for all config objects and is not menu-specific. I don't know whether the translation of the two fields is relevant to your site, but it looks better in UI if the two fields are translated.
Comment: "original language for the label and the description."  Do you mean the Title and Administrative Summary of the menu itself?  If so, for clarity's sake, should we edit your answer to use the same language used in the UI?
Comment: Yes, but when you translate the fields they are called label and description, which is also used to store the fields in config.


How to find the text insertion point position in an NSTextView in Swift?

Question: In an NSTextView, I would like to find where the caret, or the start of a selection has been placed as a integer. How could I do that?
I tried with this statement:
@IBOutlet var mainTextField: NSTextView!

let theSelectedRange = mainTextField.selectedRange
cursorPosition = mainTextField.offset(from: mainTextField.beginningOfDocument, to: theSelectedRange.start)

but I get the error:

Value of type 'NSTextView' has no member 'offset'

I saw this question but I can't translate the solution in Swift due my little experience.
Comment: https://stackoverflow.com/a/34247107/2303865
Answer: let selectedRange = self.textViewIn.selectedRanges.last
print(selectedRange ?? "No Selected")

Output: NSRange: {0, 3})
Answer: let insertionPointIndex = myTextView.selectedRanges.first?.rangeValue.location


Exibir texto original, com quebras de linhas, dentro da tag

Question: Estou tentando colocar um texto com mais de um paragrafo como link, mas a exibição dentro da tag  remove as quebras de linhas que há no texto. Estou fazendo da seguinte forma:
<a style="cursor: pointer;" onclick="wpquery_link_filter(' <?= preg_replace('/\s+/', ' ', $value) ?> ', <?= $property['id'] ?>)">
    <?= $value ?>

Estou obtendo algo assim:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer sem magna, eleifend id hendrerit vel, imperdiet sit amet ligula. Cras eleifend quam vel ex fringilla fringilla. Phasellus at nibh eget lorem ullamcorper faucibus tristique eu purus. Donec quis turpis porta, posuere mauris quis, elementum urna. Nunc maximus neque feugiat, pretium eros egestas, varius justo. Proin accumsan fringilla sapien ut varius. Cras non finibus nisi, eu pretium lacus. Pellentesque elementum maximus erat ut posuere. Vivamus elementum mauris et nisl ullamcorper, quis suscipit ipsum tempor. Proin sit amet dolor quam. Cras mattis malesuada dui. Morbi ac massa a odio facilisis vehicula. Sed a diam sed nisl egestas fermentum. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Vestibulum varius nec nibh at hendrerit. Quisque augue urna, lobortis ut cursus sed, bibendum sed orci. Donec maximus, erat ut elementum porttitor, erat elit fringilla enim, at imperdiet odio urna nec lorem. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Ut vitae sem dignissim, consequat metus non, vehicula augue. Donec quis nisl sit amet erat auctor tempus. Proin at sollicitudin turpis, sit amet vestibulum leo. Nunc tellus erat, consectetur a posuere non, aliquet id sem.
Como posso fazer que a exibição permaneça como o texto original?
Answer: O problema ocorre que as quebras de linha no texto não são renderizadas como quebra de linha no html, para isso existe a tag
. O que você precisa fazer é converter as quebras de linha da variável $value para a tag
.
Como o texto vem de uma variável PHP, exite a função nativa nl2br que faz exatamente isso. Você confere a documentação desta função aqui, e o seu código com a função logo abaixo:
<a style="cursor: pointer;" onclick="wpquery_link_filter(' <?= preg_replace('/\s+/', ' ', $value) ?> ', <?= $property['id'] ?>)">
    <?= nl2br($value) ?>

Comment: na verdade, ele pode usar a tag  com o link dentro
Comment: Valeu pela dica, depois de pesquisar mais eu encontrei uma forma de fazer utilizando uma propriedade CSS. Propriedade `white-space: pre-wrap`, mas a sua solução também funcionaria.


AVAudioSourceNode not working in swift playgrounds

Question: I am trying to run a simple oscillator using the new AVAudioSourceNode Apple introduced in the latest release. The code is excerpt from the example code Apple released, available here.
However, whenever I run this in a Swift playground, the callback is fired but no sound is emitted. When I move this code to an iOS app, it works fine. Any idea what's happening? AFAIK other audio nodes work well in Playgrounds, so I'm not sure why this specific one fails. See code below. Ran using Xcode 11 and macOS 10.15.
import AVFoundation
import PlaygroundSupport

let audioEngine = AVAudioEngine()
let mainMixerNode = audioEngine.mainMixerNode
let outputNode = audioEngine.outputNode
let format = outputNode.inputFormat(forBus: 0)
let incrementAmount = 1.0 / Float(format.sampleRate)
var time: Float = 0.0

func sineWave(time: Float) -> Float {
    return sin(2.0 * Float.pi * 440.0 * time)
}

let sourceNode = AVAudioSourceNode { (_, _, frameCount, audioBufferList) -> OSStatus in
    let bufferListPointer = UnsafeMutableAudioBufferListPointer(audioBufferList)
    for frameIndex in 0..<Int(frameCount) {
        let sample = sineWave(time: time)

        time += incrementAmount

        for buffer in bufferListPointer {
            let buf: UnsafeMutableBufferPointer<Float> = UnsafeMutableBufferPointer(buffer)
            buf[frameIndex] = sample
        }
    }
    return noErr
}

audioEngine.attach(sourceNode)

audioEngine.connect(sourceNode, to: mainMixerNode, format: format)
audioEngine.connect(mainMixerNode, to: outputNode, format: nil)

mainMixerNode.outputVolume = 0.5

audioEngine.prepare()
do {
    try audioEngine.start()
} catch {
    print(error.localizedDescription)
}

PlaygroundPage.current.needsIndefiniteExecution = true

Answer: It seems that Playground printing really ruins the performance of real time processing blocks. I had the same problem and then I moved the AVAudioSourceNode code to a different .swift file in the Sources folder, as suggested here


É possível omitir os números dos argumentos de formatação do "String.Format" em C#?

Question: Eu estava vendo que em Python é possível formatar uma string sem numerar os argumentos.
Exemplo:
#mensagem = "Meu nome é {0} e minha idade é {1}";

mensagem = "Meu nome é {} e minha idade é {}".format("Wallace", 27)

print(mensagem);

Existe alguma forma em Csharp de definir os argumentos da formatação de maneira posicional (isto é, omitindo o número, da mesma forma que no Python)?
Edit
Eu preciso de algo parecido no C#. Seria muito útil em um cenário onde eu preciso concatenar strings que precisarão ser formatadas, porém as numerações dos argumentos precisaria ser dinâmica.
Exemplo:
  var parameters = new Dictionary<string, string>() {
          {"AND [a] = {0} ", TB_A.Text},
          {"AND [b] LIKE '%{1}%' ", TB_B.Text},
          {"AND [c] = '{2}' ", TB_C.Text},
          {"AND [d] = '{3}' ", TB_D.Text}
    };

    foreach (var parameter in parameters)
    {
        // Se o valor for vazio, pula
        // Isso quebra a sequência?
        if (parameter.Value.Length > 0)
        {
            retorno += parameter.Key;
        }
    }

    DataSource.FilterExpression = retorno;

    DataSource.FilterParameters.Clear();

    DataSource.FilterParameters.Add("A", TB_A.Text);
    DataSource.FilterParameters.Add("B", TB_B.Text);
    DataSource.FilterParameters.Add("C", TB_C.Text);
    DataSource.FilterParameters.Add("D", TB_D.Text);

Dessa forma atualmente, quando eu tenho {1}, mas não tenho {0}, a "formatação" para o valor de {1} está sendo ignorada. Fiz uns testes e percebi que, se ele obedecer a uma ordem posicional certinha (ex: 0,1,2,3), funciona perfeitamente.
Comment: Acho que sua dúvida deveria ser voltada para o problema específico. Da forma atual tá bem com cara de duplicada da que eu apontei.
Comment: @WallaceMaxters Era isso? Precisa mais?
Comment: @WallaceMaxters Era isso? Precisa mais?
Comment: Depois de marcar como duplicada eu percebi que talvez não seja. O que você acha, AP?
Comment: Não acho que seja. Eu preciso por exemplo de montar uma string mais ou menos com concatenação, porém não dá pra "advininhar" qual condição será aceita ou não pra concatentar. Por isso a ideia era concatenar com  "AND x = {}" para depois usar o `DS_Grid.FilterParameters.Add` com o número de argumentos certos (pois jogando como qualquer número tá dando erro).
Comment: @LINQ de qualquer forma, a pergunta referência da duplicação não responde a respeito do "argumento posicional dinâmico", no sentido de ela ignorar o número e pegar pela primeira ocorrência em diante do `{}`. De toda forma, o "não" do Maniero já respondeu.
Answer: Não, mas pode fazer interpolação:
mensagem = $"Meu nome é {("Wallace")} e minha idade é {27}";

Claro que se não for variável ou alguma expressão que envolva variável, não faz sentido.
Respondendo à edição:
public class Program { public static void Main() => System.Console.WriteLine("{0}, {2}, {3}", 1, null, "teste", 23.5); }

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Ainda acho esta solução horrível, não deveria montar queries assim. Anos de gambiarra em PHP dá nisso :P
Aprender fazer MCVE é bom :P
Comment: Os valores foram só um exemplo, mas a ideia era a variável mesmo. E no meu caso, o problema é que a classe que faz o controle da formatação é o `ParameterCollection` do `SqlDataSource`. Mas o "não" já ajuda a saber que vou ter que ir por outro caminho, kkkkkk


404 errors for pages other than homepage when uploaded to web-server

Question: I and new to php and I got started with drupal and this is my demo site http://sugandha.net63.net/ Yea and it works but when I try to click on any link it throws 404error message. What might be the problem? It works fine in localhost.
My setting is as follows :
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'a2256974_drupal',
      'username' => 'username',
      'password' => 'pwd',
      'host' => 'mysql1.000webhost.com',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

This is my database setting and
 # $base_url = 'http://www.example.com';  // NO trailing slash!

Answer:
Do you have an .htaccess file in your root of your installation?
Its one of the most common problems because its a hidden file and people keep missing uploading it to their web server

if you have the .htaccess file then its got to be your base url..change it like Jorge Córdoba said...

Uncomment (remove #) and change example.com...Like this:
# $base_url = 'http://www.example.com';  // NO trailing slash!
to
$base_url = 'http://sugandha.net63.net';  // NO trailing slash!

if it still doesn't work:

try using ?q= before the relative url..eg:
http://sugandha.net63.net/admin to http://sugandha.net63.net/?q=admin
if that works then you have to disable clean urls on the online installation
Comment: u have to trick drupal:P go here: `http://sugandha.net63.net/?q=user/login` and enter you username/pass.it will throw 404 but you will be logged in if you go to your homepage,after that.then just use the link above to disable clean url
Comment: it's not hidden and i uploaded it :)
Comment: if you changed base url and .htaccess is there then i have no clue:P
maybe you should try reinstalling
Comment: and your website is under review so i cant check it online:P
i ll check later once the check is over if i get a clue^^
Comment: yea I don't know it was working :D just recently Is all free webhosting same
Comment: ok,its online and i can see the problem....you dont have clean urls enabled on the web-server...eg http://sugandha.net63.net/node/4 throws 404 but if you go with the normal drupal urls it works...eg `http://sugandha.net63.net/?q=node/4`...you have to disable clean urls from `http://sugandha.net63.net/?q=admin/config/search/clean-urls`
Comment: The clean url might be the reason but can't log in through admin :(
Comment: you are great :D Thanks for advice . Ha Ha Great Trick.
Answer: Check the settings for your site, most probably your host string is defined to "localhost" and therefore any links in the site are directed to "localhost/whatever" instead of the actual location.
You need to edit the "$base_url" variable in your settings.php file which can be found in sites/default for single site drupal instalations.
Comment: when you put "example.com" ... you do have your actual url there right?
Comment: where can I change the host string
Comment: I was about to post that :)
Comment: Could not get the setting done :( is that because base_url is not configured
Comment: nope :D I did not change it
Answer: Another possibility: If it's a new server, make sure that Apache has mod_rewrite installed. Happened to me.


Ruby on Rails - Call a method for each subclass from the parent class

Question: I'm using Ruby on Rails with the following class structure:
class Parent
  def self.parse
    self.subclasses.each(&:parse) # how to fix this?
  end
end

class Child1 < Parent
  def self.parse
    # ...
  end
end

class Child2 < Parent
  def self.parse
    # ...
  end
end

I'd like to do something like:
Parent.parse
=> Child1.parse and Child2.parse

But actually the child classes are not loaded and so the subclasses methods give empty array.
Is there a easy way to do this very common task?
Comment: What you're trying to acomplish? Parent class doesn't have access to the Child's. Maybe what you need can be done in another way. See http://stackoverflow.com/questions/11074175/how-to-return-new-instance-of-subclass-while-initializing-parent-class
Answer: This happens because rails autoloads classes: Parent doesn't know about its subclasses until they used somewhere or required.
Just require them all manually from the Parent class:
# parent.rb
require 'child1'
require 'child2'

class Parent
  def self.parse
    self.subclasses.each(&:parse) # how to fix this?
  end
end

Comment: Absolutely right that it's the auto loading causing the problem (you can turn this off if you need to in `config/development.rb`) but I'm not sure the right place to require them is the parent class. Wouldn't it be better to do it in application.rb, or an initializer, or in config/development.rb if that's the only environment the problem will occur in.
Comment: @Shadwell, yeah you are right that there is may be a better place. This is just how I feel about the class readability. I'd put this into the `parent` class since it makes clear at first glance that this class doesn't rely on rails autoload feature.


Python2: Should I use Pickle or cPickle?

Question: Python 2 has both the pickle and cPickle modules for serialization.
cPickle has an obvious advantage over pickle: speed. What, if any, advantage does pickle have over cPickle?
Comment: you may take look at this page. This will give you a proper direction about your confusion
https://docs.python.org/2/library/pickle.html
Answer: The pickle module implements an algorithm for turning an arbitrary Python object into a series of bytes. This process is also called serializing" the object. The byte stream representing the object can then be transmitted or stored, and later reconstructed to create a new object with the same characteristics.
The cPickle module implements the same algorithm, in C instead of Python. It is many times faster than the Python implementation, but does not allow the user to subclass from Pickle. If subclassing is not important for your use, you probably want to use cPickle.
Source of above information.
Comment: For those searching for pickle / cPickle use in Python3, [this SO answer](https://stackoverflow.com/a/37138791/6340496) might be helpful.
Comment: From the link above, @Martijn Pieters: "In Python 3 the accelerated version has been integrated and there is simply no reason to use anything other than import pickle."
Answer: I found this regarding pickle and cPickle:
"The pickle module implements an algorithm for turning an arbitrary Python object into a series of bytes....
The cPickle module implements the same algorithm, in C instead of Python. It is many times faster than the Python implementation, but does not allow the user to subclass from Pickle.
If subclassing is not important for your use, you probably want to use cPickle."
Source: https://pymotw.com/2/pickle/


How do I alter myuserpoints table?

Question: I am using the Userpoints module. Using that, when I click the "My Score" link I am viewing a table with list of points.
There are 6 headers and 6 rows displaying. In that table, I need only 3 headers and 3 rows to display.
As of now, the module shows the following headers:

Points
Approved
Date
Operation
Category
Description

What I need to display is the following headers:

Points
Date
Description

How can I achieve this?
Answer: Here is the way:

hook_menu_alter()

<code>/**
 *Implemantation of hook_menu_alter()
 */
function your_module_menu_alter(&$items) {
  $items['myuserpoints']['page callback'] = 'userpoints_list_my_userpoints_custom';
}
</code>
By using menu alter write your custom function and change the table structure as per your need. And it's done :)

How do I alter myuserpoints table?


Large sample with low R² and high RMSE; or Small aggregated sample with high R² and low RMSE?

Question: I have 45 independent variables and 50 (US) state controls.
I have a sample of about 100,000 county-level observations. With this sample, I run my regression (observations weighted by population) and I find that my R² is 0.3851, while my RMSE is 443.24. (The mean of the dependent variable is 556.)
Using this exact same sample, I aggregate these 100,000 county-level observations into roughly 2,000 state-level observations (the aggregation is weighted by population). I run an analogous regression, but now my R² is 0.8691 and my RMSE is 139.60.
The estimates of the slope coefficients are broadly similar, but naturally they do not exactly coincide.
Which set of results should I prefer? What are some considerations?
Also, why might the R² and RMSE for the larger sample fare more poorly? F(  25, 47) =   .
Linear  regression  Number  of  obs =   100851
    F(  25, 47) =   .
    Prob    >   F   =   .
    R-squared   =   0.3851
    Root    MSE =   443.24

    (Std.   Err.    adjusted    for 48  clusters    in  state)
----------------------------------------------------------------------------------
    |   Robust
    depVar  |   Coef.   Std.    Err.    t   P>|t|   [95%    Conf.   Interval]
-----------------+----------------------------------------------------------------
    year    |   16.02798    2.789082    5.75    0   10.41707    21.63889
1   indepVar1   |   -458.473    183.6673    -2.5    0.016   -827.964    -88.982
2   indepVar2   |   205.6476    45.68145    4.5 0   113.7483    297.5468
3   indepVar3   |   233.3758    60.4131 3.86    0   111.8404    354.9113
4   indepVar4   |   177.3645    95.08196    1.87    0.068   -13.91579   368.6447
5   indepVar5   |   -948.498    550.6482    -1.72   0.092   -2056.259   159.2632
6   indepVar6   |   -992.7274   756.5457    -1.31   0.196   -2514.701   529.2463
7   indepVar7   |   982.5164    755.8617    1.3 0.2 -538.0813   2503.114
8   indepVar8   |   151.0235    165.765 0.91    0.367   -182.4526   484.4996
9   indepVar9   |   -379.7011   272.9085    -1.39   0.171   -928.7223   169.32
10  indepVar10  |   -93.88511   136.5604    -0.69   0.495   -368.6093   180.839
11  indepVar11  |   28.98643    26.16698    1.11    0.274   -23.65474   81.6276
12  indepVar12  |   240.7211    193.3436    1.25    0.219   -148.236    629.6781
13  indepVar13  |   -6.526805   74.67645    -0.09   0.931   -156.7564   143.7028
14  indepVar14  |   193.1296    221.9745    0.87    0.389   -253.4254   639.6847
15  indepVar15  |   -11.20702   102.6446    -0.11   0.914   -217.7014   195.2874
16  indepVar16  |   51.82138    102.8591    0.5 0.617   -155.1045   258.7472
17  indepVar17  |   -124.7794   123.8627    -1.01   0.319   -373.9591   124.4002
18  indepVar18  |   340.7428    105.5859    3.23    0.002   128.3314    553.1543
19  indepVar19  |   1777.38 1135.562    1.57    0.124   -507.0753   4061.835
20  indepVar20  |   -191.8244   115.5749    -1.66   0.104   -424.3311   40.68239
21  indepVar21  |   1390.434    779.4091    1.78    0.081   -177.5352   2958.403
22  indepVar22  |   254.1712    88.50643    2.87    0.006   76.11923    432.2232
23  indepVar23  |   -346.1083   325.8941    -1.06   0.294   -1001.723   309.506
24  indepVar24  |   171.7473    45.03025    3.81    0   81.15817    262.3365
25  indepVar25  |   -76.53413   95.20126    -0.8    0.425   -268.0544   114.9861
26  indepVar26  |   -197.4632   81.29256    -2.43   0.019   -361.0028   -33.92371
27  indepVar27  |   -1060.178   571.7728    -1.85   0.07    -2210.436   90.08107
28  indepVar28  |   -69.41351   91.52206    -0.76   0.452   -253.5321   114.7051
29  indepVar29  |   32.38332    265.625 0.12    0.903   -501.9853   566.7519
30  indepVar30  |   -125.3714   263.3725    -0.48   0.636   -655.2085   404.4657
31  indepVar31  |   159.1979    343.29  0.46    0.645   -531.4124   849.8083
32  indepVar32  |   336.8044    382.4105    0.88    0.383   -432.5063   1106.115
33  indepVar33  |   324.824 277.9695    1.17    0.248   -234.3785   884.0266
34  indepVar34  |   -577.9178   286.0078    -2.02   0.049   -1153.291   -2.544465
35  indepVar35  |   -171.3952   334.1503    -0.51   0.61    -843.619    500.8286
36  indepVar36  |   523.0878    329.1718    1.59    0.119   -139.1206   1185.296
37  indepVar37  |   -191.6111   70.98143    -2.7    0.01    -334.4073   -48.8149
38  indepVar38  |   11.59451    40.05563    0.29    0.774   -68.98701   92.17604
39  indepVar39  |   75.86873    97.55217    0.78    0.441   -120.3809   272.1184
40  indepVar40  |   -11.92264   729.6524    -0.02   0.987   -1479.794   1455.949
41  indepVar41  |   22.75141    242.714 0.09    0.926   -465.5262   511.029
42  indepVar42  |   -58.7689    171.3043    -0.34   0.733   -403.3887   285.8509
43  indepVar43  |   -402.7508   188.6756    -2.13   0.038   -782.3171   -23.18449
44  indepVar44  |   -140.292    45.70826    -3.07   0.004   -232.2451   -48.33883
    _Istate_2   |   4.68108 677.5097    0.01    0.995   -1358.293   1367.655
    _Istate_3   |   -415.3851   549.4083    -0.76   0.453   -1520.652   689.8818
    _Istate_4   |   -212.9707   688.97  -0.31   0.759   -1598.999   1173.058
    _Istate_5   |   111.7194    689.2478    0.16    0.872   -1274.868   1498.307
    _Istate_6   |   -920.1566   666.3922    -1.38   0.174   -2260.765   420.4515
    _Istate_7   |   -1147.931   822.0788    -1.4    0.169   -2801.74    505.8783
    _Istate_8   |   0   (omitted)
    _Istate_9   |   -334.1907   556.992 -0.6    0.551   -1454.714   786.3326
    _Istate_10  |   -875.1989   356.2245    -2.46   0.018   -1591.83    -158.5677
    _Istate_11  |   -523.8942   891.2408    -0.59   0.559   -2316.839   1269.051
    _Istate_12  |   -638.8514   677.2967    -0.94   0.35    -2001.397   723.6938
    _Istate_13  |   0   (omitted)
    _Istate_14  |   -243.9082   634.2313    -0.38   0.702   -1519.817   1032.001
    _Istate_15  |   -416.1645   623.6256    -0.67   0.508   -1670.737   838.4084
    _Istate_16  |   -1141.161   677.5166    -1.68   0.099   -2504.149   221.8263
    _Istate_17  |   -3470.225   1734.007    -2  0.051   -6958.598   18.14813
    _Istate_18  |   -731.1899   719.8711    -1.02   0.315   -2179.384   717.0041
    _Istate_19  |   -755.1031   649.8175    -1.16   0.251   -2062.367   552.161
    _Istate_20  |   176.8451    1040.597    0.17    0.866   -1916.567   2270.257
    _Istate_21  |   -1216.53    653.1755    -1.86   0.069   -2530.549   97.48979
    _Istate_22  |   -827.732    610.1264    -1.36   0.181   -2055.148   399.684
    _Istate_23  |   -955.0581   553.2604    -1.73   0.091   -2068.075   157.9584
    _Istate_24  |   276.0788    183.6137    1.5 0.139   -93.30428   645.4618
    _Istate_25  |   -455.0858   720.1046    -0.63   0.53    -1903.749   993.5778
    _Istate_26  |   -257.604    872.7705    -0.3    0.769   -2013.392   1498.184
    _Istate_27  |   -902.1086   609.1673    -1.48   0.145   -2127.595   323.378
    _Istate_28  |   -186.9086   641.4881    -0.29   0.772   -1477.416   1103.599
    _Istate_29  |   -2021.791   866.2154    -2.33   0.024   -3764.392   -279.1904
    _Istate_30  |   288.9218    1036.67 0.28    0.782   -1796.588   2374.432
    _Istate_31  |   -653.2965   699.3336    -0.93   0.355   -2060.174   753.5812
    _Istate_32  |   -169.1177   972.8816    -0.17   0.863   -2126.303   1788.068
    _Istate_33  |   -3.528485   1064.729    0   0.997   -2145.487   2138.43
    _Istate_34  |   -595.7262   699.0201    -0.85   0.398   -2001.973   810.5209
    _Istate_35  |   -915.5309   589.8294    -1.55   0.127   -2102.115   271.0527
    _Istate_36  |   -97.34604   801.2839    -0.12   0.904   -1709.321   1514.629
    _Istate_37  |   -136.5235   556.0349    -0.25   0.807   -1255.121   982.0744
    _Istate_38  |   -1086.956   448.4446    -2.42   0.019   -1989.11    -184.8022
    _Istate_39  |   899.9832    639.4759    1.41    0.166   -386.4764   2186.443
    _Istate_40  |   -1029.878   533.3683    -1.93   0.06    -2102.876   43.12109
    _Istate_41  |   -424.9372   709.2462    -0.6    0.552   -1851.756   1001.882
    _Istate_42  |   -650.9319   565.2988    -1.15   0.255   -1788.166   486.3025
    _Istate_43  |   -362.5626   462.3638    -0.78   0.437   -1292.719   567.5934
    _Istate_44  |   105.9245    533.5528    0.2 0.843   -967.4452   1179.294
    _Istate_45  |   -696.8787   573.4762    -1.22   0.23    -1850.564   456.8067
    _Istate_46  |   444.2534    965.5209    0.46    0.648   -1498.124   2386.631
    _Istate_47  |   -453.4677   946.4425    -0.48   0.634   -2357.464   1450.529
    _Istate_48  |   155.548 1004.649    0.15    0.878   -1865.545   2176.641
    _Istate_49  |   -1901.979   644.8006    -2.95   0.005   -3199.151   -604.8077
    _Istate_50  |   -455.9132   649.3263    -0.7    0.486   -1762.189   850.3627
    _cons   |   -29004.39   5391.158    -5.38   0   -39850  -18158.77

State level
Linear  regression  Number  of  obs =   1920
    F(  30, 49) =   .
    Prob    >   F   =   .
    R-squared   =   0.8691
    Root    MSE =   139.6

    (Std.   Err.    adjusted    for 50  clusters    in  state)
----------------------------------------------------------------------------------
    |   Robust
    cdr |   Coef.   Std.    Err.    t   P>|t|   [95%    Conf.   Interval]
-----------------+----------------------------------------------------------------
    year    |   15.93609    2.797954    5.7 0   10.31339    21.55879
    indepVar1   |   -462.6864   187.8189    -2.46   0.017   -840.1226   -85.25021
    indepVar2   |   204.1425    45.82676    4.45    0   112.0501    296.2348
    indepVar3   |   231.3854    60.60526    3.82    0   109.5945    353.1762
    indepVar4   |   170.1259    93.77893    1.81    0.076   -18.3299    358.5817
    indepVar5   |   318.636 495.8839    0.64    0.524   -677.8801   1315.152
    indepVar6   |   -41.4763    410.9076    -0.1    0.92    -867.2261   784.2735
    indepVar7   |   74.56288    419.5127    0.18    0.86    -768.4795   917.6052
    indepVar8   |   148.87  169.4261    0.88    0.384   -191.6044   489.3445
    indepVar9   |   -322.1897   297.0613    -1.08   0.283   -919.1568   274.7774
    indepVar10  |   -132.2453   144.1476    -0.92   0.363   -421.9207   157.4301
    indepVar11  |   19.46477    24.23743    0.8 0.426   -29.24216   68.1717
    indepVar12  |   270.2618    197.9292    1.37    0.178   -127.4919   668.0155
    indepVar13  |   -7.056924   75.70485    -0.09   0.926   -159.1915   145.0777
    indepVar14  |   115.9848    230.2678    0.5 0.617   -346.7556   578.7252
    indepVar15  |   50.12875    99.16391    0.51    0.615   -149.1486   249.4061
    indepVar16  |   67.80731    107.6611    0.63    0.532   -148.5458   284.1604
    indepVar17  |   -126.4316   126.5776    -1  0.323   -380.7987   127.9355
    indepVar18  |   262.0144    79.06571    3.31    0.002   103.126 420.9029
    indepVar19  |   346.017 584.5286    0.59    0.557   -828.6372   1520.671
    indepVar20  |   -49.34303   59.68256    -0.83   0.412   -169.2796   70.59357
    indepVar21  |   424.2462    408.4819    1.04    0.304   -396.629    1245.121
    indepVar22  |   269.7198    86.80823    3.11    0.003   95.2721 444.1674
    indepVar23  |   -1004.421   354.4545    -2.83   0.007   -1716.724   -292.1185
    indepVar24  |   170.2637    45.17349    3.77    0   79.48418    261.0432
    indepVar25  |   -74.82832   99.6722 -0.75   0.456   -275.1271   125.4705
    indepVar26  |   -206.8909   86.18732    -2.4    0.02    -380.0908   -33.69103
    indepVar27  |   315.7434    353.4699    0.89    0.376   -394.5811   1026.068
    indepVar28  |   -81.04575   88.4054 -0.92   0.364   -258.703    96.61155
    indepVar29  |   -12.19315   285.1077    -0.04   0.966   -585.1385   560.7522
    indepVar30  |   -76.08443   286.5407    -0.27   0.792   -651.9095   499.7406
    indepVar31  |   176.6186    371.1519    0.48    0.636   -569.2391   922.4762
    indepVar32  |   -34.44861   576.5569    -0.06   0.953   -1193.083   1124.186
    indepVar33  |   353.2545    286.057 1.23    0.223   -221.5985   928.1075
    indepVar34  |   49.13409    251.1301    0.2 0.846   -455.5307   553.7989
    indepVar35  |   -768.7232   457.9258    -1.68   0.1 -1688.959   151.5131
    indepVar36  |   463.5527    355.4124    1.3 0.198   -250.6753   1177.781
    indepVar37  |   -180.4985   70.34141    -2.57   0.013   -321.8548   -39.14209
    indepVar38  |   4.988007    42.14908    0.12    0.906   -79.71374   89.68976
    indepVar39  |   72.58692    102.0223    0.71    0.48    -132.4345   277.6084
    indepVar40  |   395.4613    612.4864    0.65    0.522   -835.3763   1626.299
    indepVar41  |   -115.897    203.7209    -0.57   0.572   -525.2895   293.4956
    indepVar42  |   -213.2643   140.9771    -1.51   0.137   -496.5683   70.03972
    indepVar43  |   -161.1463   164.0912    -0.98   0.331   -490.9  168.6075
    indepVar44  |   -143.5427   46.51919    -3.09   0.003   -237.0265   -50.05888
    _Istate_2   |   1316.494    487.8308    2.7 0.01    336.1608    2296.826
    _Istate_3   |   817.3253    543.4823    1.5 0.139   -274.8432   1909.494
    _Istate_4   |   1619.078    610.0062    2.65    0.011   393.2245    2844.931
    _Istate_5   |   1377.191    428.3966    3.21    0.002   516.296 2238.086
    _Istate_6   |   474.6932    396.4474    1.2 0.237   -321.9978   1271.384
    _Istate_7   |   692.2386    542.2445    1.28    0.208   -397.4425   1781.92
    _Istate_8   |   461.9138    216.6741    2.13    0.038   26.49081    897.3368
    _Istate_9   |   293.6877    473.3727    0.62    0.538   -657.5904   1244.966
    _Istate_10  |   -354.8723   465.1904    -0.76   0.449   -1289.707   579.9628
    _Istate_11  |   1383.923    607.3632    2.28    0.027   163.3811    2604.465
    _Istate_12  |   625.1371    444.8335    1.41    0.166   -268.7894   1519.063
    _Istate_13  |   1284.684    669.603 1.92    0.061   -60.93324   2630.302
    _Istate_14  |   1020.459    384.4732    2.65    0.011   247.8313    1793.087
    _Istate_15  |   879.3303    378.8966    2.32    0.025   117.909 1640.752
    _Istate_16  |   651.6313    632.8723    1.03    0.308   -620.1732   1923.436
    _Istate_17  |   287.9311    1245.841    0.23    0.818   -2215.68    2791.542
    _Istate_18  |   456.5379    370.9701    1.23    0.224   -288.9545   1202.03
    _Istate_19  |   604.1628    488.2987    1.24    0.222   -377.1102   1585.436
    _Istate_20  |   618.5926    284.0822    2.18    0.034   47.70796    1189.477
    _Istate_21  |   218.2797    466.5063    0.47    0.642   -719.1998   1155.759
    _Istate_22  |   575.3536    497.0401    1.16    0.253   -423.4859   1574.193
    _Istate_23  |   330.1886    352.4509    0.94    0.353   -378.0881   1038.465
    _Istate_24  |   189.497 171.7207    1.1 0.275   -155.5887   534.5828
    _Istate_25  |   807.9892    495.9669    1.63    0.11    -188.6935   1804.672
    _Istate_26  |   1652.076    578.7392    2.85    0.006   489.056 2815.096
    _Istate_27  |   494.7572    519.676 0.95    0.346   -549.5709   1539.085
    _Istate_28  |   1092.352    394.7797    2.77    0.008   299.0125    1885.691
    _Istate_29  |   239.8971    701.5776    0.34    0.734   -1169.976   1649.77
    _Istate_30  |   49.01292    477.8495    0.1 0.919   -911.2615   1009.287
    _Istate_31  |   696.6968    488.8129    1.43    0.16    -285.6096   1679.003
    _Istate_32  |   201.85  206.5152    0.98    0.333   -213.1578   616.8578
    _Istate_33  |   369.3282    248.6358    1.49    0.144   -130.3241   868.9805
    _Istate_34  |   1251.643    635.0245    1.97    0.054   -24.48705   2527.772
    _Istate_35  |   468.8939    469.3269    1   0.323   -474.2539   1412.042
    _Istate_36  |   1697.119    670.0581    2.53    0.015   350.5869    3043.651
    _Istate_37  |   1140.92 369.6134    3.09    0.003   398.1538    1883.686
    _Istate_38  |   226.659 495.361 0.46    0.649   -768.8062   1222.124
    _Istate_39  |   -366.5443   564.3341    -0.65   0.519   -1500.616   767.5275
    _Istate_40  |   268.0867    435.2812    0.62    0.541   -606.6436   1142.817
    _Istate_41  |   1421.221    633.4396    2.24    0.029   148.2767    2694.166
    _Istate_42  |   739.0075    447.7915    1.65    0.105   -160.8632   1638.878
    _Istate_43  |   959.5551    477.1847    2.01    0.05    0.6165694   1918.494
    _Istate_44  |   1403.917    512.9851    2.74    0.009   373.0345    2434.799
    _Istate_45  |   707.8354    572.4191    1.24    0.222   -442.4839   1858.155
    _Istate_46  |   826.5462    488.0049    1.69    0.097   -154.1364   1807.229
    _Istate_47  |   1570.959    780.5679    2.01    0.05    2.34885 3139.569
    _Istate_48  |   585.7089    284.5396    2.06    0.045   13.90527    1157.513
    _Istate_49  |   173.9831    636.3534    0.27    0.786   -1104.817   1452.783
    _Istate_50  |   870.1673    475.0868    1.83    0.073   -84.55542   1824.89
    _cons   |   -30153.08   5185.637    -5.81   0   -40574.01   -19732.15

Comment: This is the archetypal example of the [ecological fallacy](http://stats.stackexchange.com/search?q=ecological+fallacy) in regression.
Comment: If possible, Could you please add your output in this question as you got from software that you use ? I meant the portion that you are referring here. It would be helpful to understand better. Thanks !
Comment: @Learner: Great suggestion, I've done just that.
Answer: As @whuber pointed out, this is an example of the ecological fallacy. More specifically as to why this might be the case: it is likely because your county level data is more variable than your aggregated data. This make sense, since in general, the sample average of some set of random variables will be less variable than the random variables themselves. (Think about the central limit theorem.)
For example, say you have three counties: one is poor and rural, one is rich and rural, one is neither poor nor rich, but urban. You average them together and you'll have something that looks (numerically) middle income and suburban. You've completely ignored the variability among the three counties (not to mention the variability among the people within those counties).
Now is the part of the answer that strays from what you have directly asked. I really hope that you have given serious thought to issues of multicolinearity with those 45 independent variables. Reducing that set of independent variables may be a good modelling strategy. Think seriously also about what you want to model as fixed versus a random effect.
Comment: I suppose which one you should prefer depends on your objectives. But that is a much more in-depth question and answer session to figure out. You need to figure out what your goals are for this model and maybe at what level inferences from this model will affect decisions. I tend to models that incorporate information at the finest grain and aggregates within the model using all the data, but I could see going a different route for a different set of objectives.
Comment: So, which should I prefer? And why?


A variation of Cesaro means

Question: It follows from the Cesaro means that
$$\lim_{n\rightarrow\infty}\frac{1}{n}\sum_{k=1}^n g(k)=c~~~{\rm if}~~~\lim_{k\rightarrow\infty}g(k)=c.$$
Instead, let us consider a sequence $\{f_n\}$ such that $f_n\rightarrow f$ (uniformly or pointwise).
I'd like to show that
$$\lim_{n\rightarrow\infty}\frac{1}{n}\sum_{k=1}^n f_n(k)=c~~~{\rm if}~~~\lim_{k\rightarrow\infty}f(k)=c.$$
Can anybody help me prove this?
Answer: This is trivial if $f_n\to f$ uniformly. Given $\epsilon>0$, if $n$ is large enough then $$\left|\frac1n\sum_{k=1}^nf_n(k)-\frac1n\sum_{k=1}^nf(k)\right|<\frac1n\sum_{k=1}^n\epsilon=\epsilon$$
and
$$\left|c-\frac1n\sum_{k=1}^nf(k)\right|<\epsilon.$$
Answer: This is not true pointwise, at least without further assumptions. Take $f=0$ (constant function) and $(f_n)_n$ defined by
$$
f_n(x) = \begin{cases} n& \text{ if } x=n\\ 0& \text{ o.w.}\end{cases}
$$
Then, for any $n$, $\frac{1}{n}\sum_{k=1}^n f_n(k) = \frac{1}{n}f_n(n) = 1$, and yet

$(f_n)_n$ converges pointwise to $f=0$;
$\lim_{k\to\infty} f(k) = 0$.
Comment: I'll think about it later (it's early morning here), but please do not edit your question that way -- adding a "Edit:" to mention you are now specifically interested in the uniform convergence is fine, but removing the original question about pointwise is not... if anything, it makes this answer totally irrelevant to the new question, while it was not to the previous.
Comment: Thank you so much!! What if $f_n\rightarrow f$ uniformly? The identity seems to hold in many practical cases.
Comment: It makes sense. I re-edited the question like the previous one. Thanks again.

A variation of Cesaro means


How to programmatically copy Webform handler config?

Question: I would like to copy the Webform handler from 1 Webform into another. I can get hold of Webform settings via:
/** @var \Drupal\webform\WebformInterface $webform */
$webform = \Drupal::entityTypeManager()->getStorage('webform')->load('example_webform_id');
$webform->getSettings();
=> [
     "ajax" => false,
     "ajax_scroll_top" => "",
     "ajax_progress_type" => "",
     "ajax_effect" => "",
     ...

However that doesn't include the handler config that I would need and a way to save its new config as well.
I also tried it via the handler object itself:
/** @var \Drupal\webform\Plugin\WebformHandlerInterface[] $handlers */
$handlers = $webform->getHandlers('example_webform_handler_id');
$handler = $handlers->getIterator()->current();
$handler->setConfiguration($new_handler_config)->save();

for which it appears that there is no save() operation in the handler class:

Error: Call to undefined method ::save()

Any way I can do this programmatically that you may know of?
Answer: Ended up using the ConfigFactory service, which I believe is fine to do:
$config = \Drupal::configFactory()->getEditable('webform.webform.' . $webform->id());
$config_key = 'handlers.' . $webform_handler_id;
$config->set($config_key, $new_handler_config)->save();


How much RAM does data take up?

Question: How does one go about (asides from trail and error) to determine the amount of RAM required to store one's dataset?
I know this is a super general question, so, hopefully this example can narrow down what I am trying to understand:
I have a data file, the data file contains characters[A-Z] and numbers (no special symbols). I want to read the data into RAM (using python), then I store the data in a dictionary. I have a lot of data and computer with only 2 gigs of RAM, so I'd like to know ahead of time whether the data would fit into RAM as this could change the way I load the file with Python and handle the data downstream.  I recognize that all the data may not all fit into RAM - but that's another problem, I just want to know how much RAM the data would take up and what I  need to consider to make this determination.
So knowing the content of my file, it's initial size, and the downstream data structure I want to use, how can I figure out the amount of RAM the data will take-up?
Comment: Check out http://stackoverflow.com/questions/110259/which-python-memory-profiler-is-recommended - more specifically, heapy
Comment: @user4673 the data type does matter, and can save you space as you point out (for instance a factor of 4 between 32bit and 8bit integers. You might want to have a look at using a numpy array if part of your dataset is purely numeric (obviously you have some strings, but perhaps not every entry is a string?) numpy will likely be faster when you come to access/analyse the data too. Perhaps you could provide a sample or your dataset in the question?
Comment: @user4673: Python doesn't have 8-bit ints or 32-bit ints; it has arbitary-length ints that take up anywhere from 16 bits to 128Gbits depending on how big they are. More importantly, every Python object, including an integer, is "boxed", with a header that's dozens of bytes long. On the other hand, Python can also collapse immutable built-in types, so if you have 1000000 copies of the number `1`, you probably only _really_ have 1 copy of the number `1` (and 1000000 references to it, but a reference is only the same of a pointer).
Comment: Will it be a single dictionary or multiple dictionaries? I think it shouldn't be far from the file size.
Comment: if you read the whole file into RAM, you need at least N bytes, if N is the size of the file. Then, when you build the dictionary, you should know how python implements them, so you may know the O function of n in memory usage, if it's known. It's an estimate of course, and likely rather broad.
Comment: @ShinTakezou does it matter at the nature of the data stored? For example if I were to store 32-bit ints, or 8-bit ints for my numeric data? I know python's typing is dynamic, but if I could specify it, as one would in other languages more rountinely, how much of a difference does that make?
Comment: Data sets I typically work with are something called fastq files: http://en.wikipedia.org/wiki/FASTQ_format   I know there are optimized methods for such data as well. I typically store each read (with its ID, sequence and quality) as a class and make a dictionary of type read. Eventually, that will run out of memory when I analyze something large enough.
Comment: Anyway, if you need to mix numerical data and string data, take a look at Pandas, which sits on top of NumPy (the library @three_pineapples recommended).
Comment: Finally, do you really need all of the data in RAM, or do you just need it to act like an in-RAM `dict`? Because you can get the latter with, e.g., the `dbm` or `shelve` modules without using up all of your memory.
Comment: "I store the data in a dictionary". That's not really enough detail. If you mean that you read the whole file into a `bytes` object, then create a dictionary `{ 'data' : my_bytes_object }`, then it takes an amount of RAM equal to the file size, plus a negligible amount for the dictionary. If you mean something different from that, then the amount of RAM used depends what you mean. Because of per-object overheads, it matters how many objects you chop your data into (and of course the types of those objects). The overheads vary between versions of Python and 32 vs 64 bit...
Comment: @abarnert If things get to large, I will need it to act like an in-RAM dict ideally. Thank you for the module recommendations.
Comment: ... for example in Python 3.2 your string data will be double the size if stored in `str` compared with storing it in `bytes`. Python 3.3 introduces variably-encoded `str` objects, so provided your data is all `A-Z` that difference disappears.
Answer: The best thing to do here is not to try to guess, or to read the source code and write up a rigorous proof, but to do some tests. There are a lot of complexities that make these things hard to predict. For example, if you have 100K copies of the same string, will Python store 100K copies of the actual string data, or just 1? It depends on your Python interpreter and version, and all kinds of other things.
The documentation for sys.getsizeof has a link to a recursive sizeof recipe. And that's exactly what you need to measure how much storage your data structure is using.
So load in, say, the first 1% of your data and see how much memory it uses. Then load in 5% and make sure it's about 5x as big. If so, you can guess that your full data will be 20x as big again.
(Obviously this doesn't work for all conceivable data—there are some objects that have more cross-links the farther you get into the file, others—like numbers—that might just get larger, etc. But it will work for a lot of realistic kinds of data. And if you're really worried, you can always test the last 5% against the first 5% and see how they differ, right?)
You can also test at a higher level by using modules like Heapy, or completely externally by just watching with Process Manager/Activity Monitor/etc., to double-check the results. One thing to keep in mind is that many of these external measures will show you the peak memory usage of your program, not the current memory usage. And it's not even clear what you'd want to call "current memory usage" anyway. (Python rarely releases memory back to the OS. If it leaves memory unused, it will likely get paged out of physical memory by the OS, but the VM size won't come down. Does that count as in-use to you, or not?)

How much RAM does data take up?


Use Rules to Change Field Value By Clicking URL

Question: I am creating a simple internal ticketing system which emails customers when the status of their ticket changes (Open -> Waiting on parts). I have set up rules to do this and I haven't had any issues with it. However, I would like to create a way for customers to "unsubscribe" from the emails. I have created a checkbox field named "allow emails" which determines if customers will or will not get an email as a condition for the rule.
I would also like to include a link at the end that if clicked the customer would set the field to "no" or "off".
Note:Customers aren't actual users on the site but are nodes within a "customer" content type. The users are our internal staff that would log in to use the website.
Can rules do this by itself or do I need a separate module?
Thanks
Answer: I'm not sure I understand exactly what you need, but the great module Rules Link (https://www.drupal.org/project/rules_link) provides a link that can be attached to any content type or entity, and can also be accessed in Views as a special Rules Link field. When you click the link a preset Rule is triggered. The link passes the node or entity as a parameter to the Rule. There is also the option of using a "Javascript" link that invokes the Rule via AJAX (without reloading the whole node) - I've never used that option, but I suspect that it may help your needs.
Comment: Basically I would like to create an "unsubscribe" URL when I send out certain emails. When the customer opens the email and clicks on the URL, it will uncheck the "allow emails" checkbox which will stop any further emails from being sent to the customer since my Rules checks to make sure that it is checked before it will fire the send mail action.

Thank you for your response, I will look into that module.
Comment: Check this patch that someone created in order to be able include a working Rules Link URL in an email: https://www.drupal.org/node/2356717 . You can also refer to JamesWilson's answer if you need help creating the actual Rule Action that changes the "allow emails" field.  If this answers your question, please mark my answer as a correct one.
Comment: @argiepiano : I keep wondering what the pros/cons are about rules_link versus using the flag module. Do you think that would be a good question for me to post? What I mostly wonder: if I can achieve the same with Flag, I can probably reuse that module in much more occasions as compared to rules_link, unless there are other cases where the opposite is true. Please let me know ...
Comment: @Pierre.Vrains : While I've seen the Flag module in many answers (and from the description it looks like a powerful module), I have never used it - I have used Rules Link many times. It'd be great to have a question on this to see what people think. Thanks
Answer: You can definitely set the field value of a node with a Rules action assuming the referenced node is passed into the Rule.
Also, remember that in order to set a field value in a Rule, you have to first check to see that the field exists using a Rules condition (there is a specific condition for this).
Related question:
How to change a field value with a Rules Action?
Answer: Perhaps try Rules Argument.
https://www.drupal.org/project/rules_url_argument
Compose your URL using token field values and then check for these values in the path when the user clicks through (you may need the Path Rules module). IMO the path handling would be better done with a menu callback in a custom module, but if you want to use Rules, you should be able to use the above mods.
As a security measure, you may want to create a custom token so that a malicious 'user' can't unsubscribe another 'user' by guessing path vars.
Comment: Thank you for your response. I am trying to keep the site as "maintenance free" as possible. Just in case if I leave, someone else can pick it up without having to go over PHP. The learning curve for Drupal is high so I don't want to throw "oh and you have to know the Drupal 7 API as well".
Comment: :) fair enough. I guess if the logic is all sitting in one place it's easier to maintain.


How to do dependency injection on complex classes like when extending WidgetBase

Question: Since the Drupal sniffer whines at you if you call \Drupal::service() in your code, I have been trying to figure out how to use dependency injection on a widget  I've been working on. Here's what I've currently arrived at:
<?php

use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\xois\SicsService;
use Symfony\Component\DependencyInjection\ContainerInterface;

class XoisSicSelect extends WidgetBase {

  /**
  * SICs service.
  *
  * @var \Drupal\xois\SicsService
  */
  protected $sicsService;

  /**
  * {@inheritdoc}
  */
  public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, array $third_party_settings, SicsService $sicsService) {
    parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $third_party_settings);
    $this->sicsService = $sicsService;
  }

  /**
  * {@inheritdoc}
  */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('xois.sics')
    );
  }

}

Pretty much the standard DI pattern, no? Only difference is that WidgetBase takes a whole load of construct parameters already.
Problem is, it doesn't work. When run, it gives this delightful error:
The website encountered an unexpected error. Please try again later.
Recoverable fatal error: Argument 6 passed to Drupal\xois\Plugin\Field\FieldWidget\XoisSicSelect::__construct() must be an instance of Drupal\xois\SicsService, none given, called in /var/www/docroot/core/lib/Drupal/Core/Field/WidgetPluginManager.php on line 125 and defined in Drupal\xois\Plugin\Field\FieldWidget\XoisSicSelect->__construct() (line 35 of modules/xois/src/Plugin/Field/FieldWidget/XoisSicSelect.php).

Anyone got an idea on how to accomplish this?
Answer: You will need to implement ContainerFactoryPluginInterface in order to use dependency injection in your class.
Include use Drupal\Core\Plugin\ContainerFactoryPluginInterface; and implement the interface so it looks like:
class XoisSicSelect extends WidgetBase implements ContainerFactoryPluginInterface {

    ....

}

You will also need to make sure your __construct() and create() methods contain the correct parameters.
If you look at ContainerFactoryPluginInterface.php, you will see the parameters the create() method takes in:
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition);

Thus, your final code should look like:

use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\xois\SicsService;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;

class XoisSicSelect extends WidgetBase implements ContainerFactoryPluginInterface {
  /**
   * SICs service.
   *
   * @var \Drupal\xois\SicsService
   */
  protected $sicsService;

  /**
   * {@inheritdoc}
   */
  public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, array $third_party_settings, SicsService $sicsService) {
    parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $third_party_settings);
    $this->sicsService = $sicsService;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $plugin_id,
      $plugin_definition,
      $configuration['field_definition'],
      $configuration['settings'],
      $configuration['third_party_settings'],
      $container->get('xois.sics')
    );
  }
}

Answer: This was a difficult one for myself as well. How I figured out to resolve it was to go to the documentation page for the class (ex WidgetBase), and look for  the __construct() method (ex WidgetBase::__construct()). Click on that, and you'll see a section for "X methods override CLASSNAME::__construct()". For example, DateRangeDefaultWidget::__construct overrides WidgetBase::__construct(). Click on the override, and you'll an example of what the __construct() override should look like:
public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, array $third_party_settings, EntityStorageInterface $date_storage) {
  parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $third_party_settings);

  $this->dateStorage = $date_storage;
}

And if you look at the class page (ex DateRangeDefaultWidget), you can find what the create() method should look like: DateRangeDefaultWidget::create):
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
  return new static(
  $plugin_id,
  $plugin_definition,
  $configuration['field_definition'],
  $configuration['settings'],
  $configuration['third_party_settings'],
  $container->get('entity_type.manager')->getStorage('date_format')
  );
}

So it takes a bit of detective work, but once you figure out the method of detecting, it's actually fairly straightforward for any classes.
Comment: Your IDE/code editor should be able to help with this. For example, when a method is being overridden Netbeans looks up the parent and displays a clickable marker next to the line number. Clicking on the marker will open the file with the parent method and take you to it.
Comment: Depends on the editor. Mine doesn't do this.
Comment: It's a handy feature. Obviously the whole Drupal codebase needs to be part of the same project for this to work.
Answer: You need to copy the create() method and add your argument, not replace it.
There's no magic involved, it's just a plain static PHP method that contructs an object, including all its arguments.


Autocompleting line-item fields in Drupal commerce

Question: First off all I'm rather new with Drupal & Drupal Commerce. I'm going to do my best to describe what I have done and tried.
I'm developing a website where people can register (buy) a place in event. One of the things is that on the "add to cart" page they should be able to give some information like name, club, etc.
I added some fields to the line item "Product" like for example a textfield name Club and where I selected the option "Include this field on Add to Cart forms for line items of this type" so that it is shows in my add to cart form.
The problem I now have, is that I want (for a start) autocomplete that line-item field Club using #ajax and a ajax callback.
I started off with a hook_form_alter. I dumped (after checking the form id) the $form variable (with dpm()) to look for the Club #textfield so that I can modify it to include #ajax or #autcomplete_path, but I can't find that element.
The only thing I see is an array line_item_fields containing field_club, field_name (my fields that I attached to the line item) of the type #container (and I looked for a #texfield node within it, but didn't find it). I tried adding #ajax to it but that didn't work.
To be honest I'm totally stuck now as I don't know how to proceed further with this. Is it even possible to attach #ajax or any other attributes to a line-item field visible in the add to cart form ?
Answer: If you change the field from a simple text field into an entity reference field, you can create the different clubs as nodes (seems to make sense, since you could then write info about each club on your site). Entity reference comes with a built in autocomplete.
You could also use taxonmy terms and taxonomy reference field instead if you don't want to create a node for each club. Either way should work just fine, as both have autocomplete built in.


Algorithm to extract number of varying length from title of file

Question: I have a list of 400,000 file names (column in excel) of the format

xxx.Number.Date.zzz.txt

and I want to extract the Number from the string
Normally I would just set it to take the 5th through 9th character in that string, but the numbers vary in length (2 - 4 digits) and I am not sure how to design an algorithm that can tell how long the number is.
Using python3 if anyone is interested, but really I just need help with the pseudocode
I looked at this previous question, but it did not really answer the question in terms that I can use since it seems like it is using bash functions or I did not understand the explanation:
Extract number of variable length from string
Answer: You can use a regular expression (available in most languages):
.*?\.(\d+)\.

which matches the number between the first two dots:
import re
re.match('.*?\.(\d+)\.', 'xxx.12345.Date.zzz.txt').group(1)
#'12345'

An explanation on regex101.

This can also be done in pure Python (easily translatable to other languages):
s = 'xxx.12345.Date.zzz.txt'
out = ''
in_num = False
for c in s:
    if in_num:
        if c == '.':
            break
        out += c
    elif c == '.':
        in_num = True

giving out as: '12345'.
Note that with this second method, we do not verify that the characters between the first fullstops are digits.
Answer: If the format of the file is always xxx.Number.Date.zzz.txt, and we only care about Number, then you could convert the string into a list, and then extract the 1st element of that list. Example:
file = "xxx.4432.Date.zzz.txt"
num = file.split(".")[1]
print(num) # prints 4432

You could write this in a loop to go through your Excel column (check out openpyxl if you haven't yet).


Git Submodule inside a folder with folders and files to be ignored

Question: I have encountered a situation that a git submodule is inside a folder which containing other folders that to be ignored. The structure is like the following:
lib/
  submodule-folder/
  other-folder/       # This is folder should be ignored

My question is that can I just add lib/ to .gitignore to achieve the goal of other-folder being ignored while the submodule still working as normal? Or should I exclude the submodule pattern in .gitignore such as
lib/*
!lib/submodule-folder/

I have tried the first way and the submodule seems to work well when using command like git submodule update, but is still not sure if this is correct since I cannot find reference for explaining that. Does anyone run into a situation like that?
Answer: If the submodule is already tracked (meaning its root folder lib/submodule-folder/ is already part of the Git history as a gitlink), then yes, you can add lib/ to a .gitignore.
That will ignore everything else within the lib/ folder.
To double-check the submodule folder is not ignored by any .gitignore rule, check that the following command does return nothing:
git check-ignore -v -- lib/submodule-folder

(no trailing slash in this instance)
Comment: Many thanks on your comment! This indeed give me much help


Trying to render a custom date format with Twig

Question: I'm in the process of porting one of my contrib themes to Drupal 8. For custom date formats on nodes, I have something like this in a node_preprocess function in the theme's template.php file in the Drupal 7 version:
$vars['thedate'] = format_date($node->created, "custom", "j");
$vars['themonth'] = format_date($node->created, "custom", "M");
$vars['theyear'] = format_date($node->created, "custom", "Y");

I render it with the following code.
  <?php print $thedate; ?> / <?php print $themonth; ?> / <?php print $theyear; ?>

In my Drupal 8 port, I've tried a similar approach in the theme's .theme file and then try to render them in node.html.twig as {{{ thedate }} / {{ themonth }} / {{ theyear }}}, but I'm getting a nasty error.

Twig_Error_Runtime: An exception has been thrown during the rendering of a template ("The timestamp must be numeric.") in themes/mytheme/templates/page.html.twig
          at line 210. in Twig_Template->displayWithErrorHandling()
          (line 279 of /site/core/vendor/twig/twig/lib/Twig/Template.php).

I looked to Twig date formats, and it seems you should simply attach a variable, such as {{ display_submitted |date("m/d/Y") }}. I tried that without a preprocess function but what outputs is 12/31/1969, which is not the date the node was created so I'm a bit lost here.
Comment: Note that this has nothing to do with Twig (apart from the unhelpful error handling), but I'm leaving the question as it is, as someone else might search for this. I'll expect we'll see a few similar ones, this isn't obvious if you're coming from 7.x.
Answer: Here is an approach that uses just Twig (no preprocess functions needed):

{{ node.createdtime | date("d F Y") }}

Comment: Excellent, the more I have been using Twig, the more I discover that preprocess functions are needed far less.
Answer: $node->created is a FieldItemList object.
You need to use either one of these.
$vars['thedate'] = format_date($node->created->value, "custom", "j");
$vars['thedate'] = format_date($node->getCreatedTime(), "custom", "j");

All node base fields (and most other entity types, some are still being worked on) have methods now, that are defined in NodeInterface.
Comment: Changed TypedData to FieldItemList and made the documentation link a bit more specific.
Comment: Very interesting! Both of those work fine so thanks for that. I'm one of those who will be really struggling to wrap my arms around Drupal 8 (self taught, no CS degree) so I'm trying to start early to unravel some of this. The jury is still out whether I'll be up tot he task or not so I appreciate the help.
Comment: Just curious, for comments, if I use `$vars['created'] = format_date($comment->getCreatedTime(), "custom", "m / j / y");`, that does not work, I need to use `$vars['created'] = format_date($comment->created->value, "custom", "m / j / y");` so it seems inconsistent...
Comment: Comment::getCreatedTime() will work eventually, see https://drupal.org/node/2028025
Answer: For people who need a little more help understanding this, add the following to YOURTHEMENAME.theme file:
/**
 * Implements template_preprocess_comment()
 */
function YOURTHEMENAME_preprocess_comment(&$variables) {
  $comment = $variables['elements']['#comment'];
  $variables['YOUR_DATE_NAME'] = format_date($comment->created->value, "custom", "m / j / y");
}

Then in your theme, update the twig template (such as templates/comment.html.twig) to use the variable like so:
{{ YOUR_DATE_NAME }}


Show that in a neighborhood of $(u_0, v_0, x_0, y_0)=(0,0,1,1), (u,v)$ can be written as differentiable functions of $x$ and $y$

Question: I have the following problem:
Considerate the following system:
$$x=\cos(u)+\sin(v) $$
$$y=\sin(u)+\cos(v)$$
Show that in a neighborhood of $(u_0, v_0, x_0, y_0)=(0,0,1,1), (u,v)$ can be written as differentiable functions of $x$ and $y$. Furthermore,
$$\left(\frac {\partial u}{\partial x}\right)^2 +\left(\frac {\partial u}{\partial y}\right)^2=\left(\frac {\partial v}{\partial x}\right)^2+\left(\frac {\partial v}{\partial y}\right)^2$$
I made some attempts however I did not succeed in the second part. But related to that , I will try again. I would appreciate any hints in the first part, which I believe is an application of implicit function theorem.
Thanks in advance.
Answer: PART $1$
We just need to apply the Implicit Function Theorem. Consider the mapping $F : \mathbb{R}^4 \to \mathbb{R}^2$ given by $F(x,y,u,v) = (\cos u + \sin v-x, \cos v + \sin u-y)$. The set of $(x,y,u,v) \in \mathbb{R}^4$ such that $F(x,y,u,v) = (0,0)$ is the surface you're interested in. Calculating the Jacobian Matrix of $F$:
$$J_F = \left[ \begin{array}{cccc} -1 & 0 & -\sin u & \cos v \\ 0 & -1 & \cos u & -\sin v \end{array} \right] . $$
Clearly the rank of $J_F$ is maximal, i.e. equal to two, for all $x,y,u$ and $v.$ It follows that $F$ has no critical values and that $(0,0)$ must be a regular value. This means that the surface is a smooth parametrisable surface in a neighbourhood of each of its points.
Moreover, at $(x,y,u,v) = (0,0,1,1)$ we see that the last two columns form an invertible two-by-two matrix. By the IFT, we can write $u$ and $v$ as smooth functions of $x$ and $y$. (Notice that this hold for all $u$ and $v$ with $\cos(u+v) \neq 0.$)
PART $2$
Assume that $u$ and $v$ are functions of $x$ and $y$, i.e. $u = u(x,y)$ and $v=v(x,y).$ Consider the equation $x = \cos u + \sin v.$ Differentiating with respect to $x$ gives $1 = -u_x\sin u + v_x\cos v.$ Differentiating with respect to $y$ gives $0 = -u_y\sin u + v_y\cos v.$ Applying a similar process to $y = \sin u + \cos v$ gives $0 = u_x\cos u -v_x\sin v$ and $1 = u_y\cos u - v_y\sin v.$ We get:
$$\left[ \begin{array}{cc} -\sin u & \cos v \\ \cos u & -\sin v \end{array} \right]\left[ \begin{array}{cc} u_x & u_y \\ v_x & v_y\end{array}\right] = \left[ \begin{array}{cc} 1 & 0 \\ 0 & 1\end{array} \right] $$
Assuming that $\sin u \sin v - \cos u \cos v \neq 0$ we can rearrange this to give:
$$\left[ \begin{array}{cc} u_x & u_y \\ v_x & v_y\end{array}\right] = \frac{1}{\cos(u+v)}\left[ \begin{array}{cc} \sin v & \cos v \\ \cos u & \sin u \end{array} \right].$$
It follows that:
$$u_x^2+u_y^2 = v_x^2 + v_y^2 \iff  \frac{\sin^2v}{\cos^2(u+v)} + \frac{\cos^2v}{\cos^2(u+v)} = \frac{\cos^2u}{\cos^2(u+v)} + \frac{\sin^2u}{\cos^2(u+v)} \, . $$
Using the fact that $\cos^2\theta + \sin^2\theta = 1$ for all $\theta$, we see that this last statement is indeed true. (Assuming $\cos(u+v) \neq 0.$)
Answer: Working off the definition of the implicit function theorem on Wikipedia, let $\textbf{f}(x,y,u,v)=(x-\cos u-\sin v,y-\sin u-\cos v)$. Then there is some function $\textbf{g}(x,y)=(u(x,y),v(x,y))$ whose graph is the level set $\mathbf{f}(x,y,u,v)=\mathbf{0}$ in the vicinity of a point $(x_0,y_0,u_0,v_0)=(1,1,0,0)$ if the matrix of partial derivatives $\frac{\partial\mathbf{f}}{\partial(u,v)}(x_0,y_0,u_0,v_0)$ is nonsingular. But $\frac{\partial\mathbf{f}}{\partial(u,v)}(1,1,0,0)=\left[\begin{matrix}
 0&1\\1&0\end{matrix}\right]$, so it is invertible and all is well.
Answer: Let $\phi: \mathbb{R}^2 \times \mathbb{R}^2 \to \mathbb{R}^2$ be given by $\phi(w,z) = \begin{bmatrix} \cos w_1 + \sin w_2 -z_1 \\ \sin w_1 + \cos w_2 - z_2 \end{bmatrix}$. The system above is equivalent to $\phi(w,z) = 0$, and we have $\phi((0,0),(1,1)) = 0$.
A quick computation gives $\frac{\partial \phi(w,z)}{\partial w} = \begin{bmatrix} -\sin w_1 & \cos w_2 \\ \cos w_1 & -\sin w_2\end{bmatrix}$, $\frac{\partial \phi(w,z)}{\partial z} = -I$. Since $\frac{\partial \phi((0,0),(1,1))}{\partial w} = \begin{bmatrix} 0 & 1 \\ 1 & 0\end{bmatrix}$ is invertible and $\frac{\partial \phi}{\partial w}$ is continuous, we see that it is invertible in a neighborhood of $((0,0),(1,1))$.
Then the implicit function says that there are neighborhoods $U$ of $(1,1)$ and $V$ of $(0,0)$, and a unique differentiable function $\omega:U \to V$ such that $\phi(\omega(z),z) = 0$ for all $z \in U$. (In the question's notation, this can be written as $(u(x,y),v(x,y)) = \omega((x,y))$. Also, note that uniqueness implies $\omega((1,1)) = (0,0)$.) This is the solution to the first part.
The second part is just computation, differentiating $\phi(\omega(z),z) = 0$ using the chain rule gives
$\frac{\partial \phi(\omega(z),z)}{\partial w} \frac{\partial \omega(z)}{\partial z}+\frac{\partial \phi(\omega(z),z)}{\partial z} = 0$, from which is follows that $\frac{\partial \omega(z)}{\partial z} = - \frac{\partial \phi(\omega(z),z)}{\partial w}^{-1} \frac{\partial \phi(\omega(z),z)}{\partial z}$. Doing the computation shows that $\frac{\partial \omega(z)}{\partial z} = \frac{1}{\sin w_1 \sin w_2 - \cos w_1 \cos w_2} \begin{bmatrix} -\sin w_2 & -\cos w_2 \\ -\cos w_1 & -\sin w_1\end{bmatrix}$. Since we have $\frac{\partial \omega((x,y))}{\partial z} = \begin{bmatrix} \frac{\partial u(x,y)}{\partial x} & \frac{\partial u(x,y)}{\partial y} \\ \frac{\partial v(x,y)}{\partial x} & \frac{\partial v(x,y)}{\partial y} \end{bmatrix}$, the desired result follows from the identity $(\cos x)^2 + (\sin x)^2 = 1$.


Can I invoke an ancestor's method from a child's overloaded method?

Question: I am trying to design my (Java) classes and I am not sure what this is called-- essential it goes something like this:
MediaPlayer // contains play(String filePath) method

OtherPlayer // extends MediaPlayer and inherits play(String filePath)

MyObject  // extends OtherPlayer

The problem is-- I want MyObject to call play without passing the string in. MyObject contains a private member and I want to simply call,
myobject.play();

Can I have MyObject overload play() but somehow call play(String filePath) using its private string?
Edit:
I want to avoid doing this:
myobject.play(myobject.getFilePath());

Comment: Is play declared in any of the ancestors?
Comment: play(String filePath) is in all other ancestors, but there is no play()
Answer: Assuming play(String) is public/protected, then simply:
class MyObject extends OtherPlayer {
    ...

    public void play() {
        play(myString);
    }

    private String myString;
}

Comment: So even though the new play() overloads the old play, the old play(string name) is still valid? Gah I feel dumb!
Comment: Dont' feel dumb @Google you have all the answers :)
Answer: If you mean something like
class MyObject extends OtherPlayer {

    private String myString;

    public void play(){
       play( myString );
    }

}

Then that's perfectly fine. You won't be overloading play() though, just creating a new method (different signatures means different methods).
Answer: Try this:
private void play() {
    super.play(myfilename); // calls the inherited method
}

private someMethod() {
    play(); // call your method like this
}


gamm4 what does s() do?

Question: say we have the following:
library(gamm4)
    set.seed(0)
    dat <- gamSim(1,n=400,scale=2) ## simulate 4 term additive truth
    ## Now add 20 level random effect fac...
    dat$fac <- fac <- as.factor(sample(1:20,400,replace=TRUE))
        dat$y <- dat$y + model.matrix(~fac-1)%*%rnorm(20)*.5
gamm4 5
    br <- gamm4(y~s(x0)+x1+s(x2),data=dat,random=~(1|fac))

What does the s() do in this model?
Comment: it just mean you only estimate the intercept and not the slope>?
Comment: it is a function used in the definition of smooth terms within gam(m) model formulae. See `?mgcv::s`
Answer: library(gamm4)
    set.seed(0)
    dat <- gamSim(1,n=400,scale=2) ## simulate 4 term additive truth
    ## Now add 20 level random effect fac...
    dat$fac <- fac <- as.factor(sample(1:20,400,replace=TRUE))
            dat$y <- dat$y + model.matrix(~fac-1)%*%rnorm(20)*.5
    #gamm4 5
        br <- gamm4(y~s(x0)+x1+s(x2),data=dat,random=~(1|fac))
    plot(br$gam,pages=1,all=TRUE)
    br <- gamm4(y~x0+x1+x2,data=dat,random=~(1|fac))
plot(br$gam,pages=1,all=TRUE)

s() terms are represented as penalized splines.  You might read Simon Wood's 2006 textbook for more on what that is.  The code above illustrates the difference with and without.

gamm4 what does s() do?


Redirecionamento 301 protocolo https para http

Question: Gostaria de fazer um redirecionamento 301 (por meio do .htaccess) apenas em 1 link que eu tenho https para http sem alterar qualquer outro link do servidor ou protocolo.
Link https:
https://meudominio.com/blog/tag/dengue-mata/
Redirecionar Para:
http://meudominio.com/blog/tag/dengue-mata/
OBS: Repare que o link é o mesmo só muda o protocolo https para http;
Obrigado!
Comment: Tentei todas as formas abaixo e não funcionou... Acho que existe uma outra forma de funcionar... Como eu faço para todos meus links que tiver "https://" forem redirecionados para o mesmo link sem o www ? por ex: https: // www. meudominio.com/teste ser redirecionado para https:// meudominio.com/teste
Comment: Se nao funcionou da forma abaixo, alguma outra coisa está errada na sua configuração. Inclusive eu testei todas pra ver quais davam loop e quais não. Tem certeza que seu .htaccess está sendo lido e que está com as permissões necessárias? o mod rewrite está habilitado?
Answer: Para os casos em que tudo o que é HTTPS deve ser direccionado para HTTP:
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Comment: Zull, Obrigado mas ainda não funcionou cara, ele continua indo para o HTTPS (Eu ja mudei o .htaccess da raiz e tbn do /blog, mas não funcionou).
Comment: Viste a resposta do @Bacco ?
Comment: vi sim! Mas como esta escrito la em cima.. ela vai entrar em loop infinito.. pois o link das 2 são iguais.. o que muda é só o https. Tem como vc me add no face para eu explicar melhor? Muito obrigado! https://www.facebook.com/israelvitorino
Answer: Baseado na resposta do @Zuul, segue a versão para seu caso específico,
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule blog/tag/dengue-mata/ http://meudominio.com/blog/tag/dengue-mata/ [R=301,L]

Se pretende usar parâmetros ou algum dado extra depois da barra, pode fazer assim:
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule blog/tag/dengue-mata(.*) http://meudominio.com/blog/tag/dengue-mata$1  [R=301,L]

Notar que omiti a barra final, para contemplar URLs sem a barra também. Ajuste conforme a necessidade.

Importante: se seu domínio não estiver com o certificado correto, ao acessar por https://, a mensagem de erro aparecerá antes do redirect de qualquer forma. Isto é da natureza do protocolo, que primeiro faz a conexão segura, para depois solicitar o caminho.

Cuidado com redirect puro:
O redirect é excelente, mas quando você só troca o protocolo, e o caminho é o mesmo, pode entrar em loop infinito, como neste caso:
Redirect 301 /blog/tag/dengue-mata/ http://meudominio.com/blog/tag/dengue-mata/

Answer: Tente isso
# Permanent URL redirect
Redirect 301 /blog/tag/dengue-mata/ http://meudominio.com/blog/tag/dengue-mata/

Comment: Você criou um loop infinito.
Comment: Leandro, mas e o https ? dessa forma que vc pos vai entrar em loop infinito
Answer:          var url      = window.location.href;     // Retorna a url completa

        console.log(url);

        var array = url.split(":");  // separa antes e após os :

        console.log(array[0]);

        if(array[0] == "http"){  // faz a comparação

            var trocado = url.replace("http", "https");  // faz a troca

            console.log(trocado);

            window.location.href = trocado;  // redireciona
        }


How to add more than one tags for content?

Question: For example, I want to create two tag, one is "new", the other is "test",Now tags is "new test"
Screenshot:
Comment: Add tags separated by comma ,
Comment: @Bipin K helpful!!!
Answer: You already seem to have 1 field for this content type that is a term reference, whereas the corresponding taxonomy has at least 2 terms (i.e. "test" en "new").
Solution 1:
Allow "multiple" or "unlimited" values for the term reference you're already using, which is an option with the field settings of your existing term reference. Which you'll find at /admin/structure/types/manage/mycontenttype/fields/field_term_ref, assuming field_term_ref is the machine name of your term reference, and mycontenttype is the machine name of your content type.
Solution 2:
Create an additional term reference field for this content type, and add one of those 2 terms to the new field, and delete it from the term reference field you already have.
Note: Which solution to choose depends a bit on your use case:

If the terms are somehow "related", then solution 1 is what you should use. E.g.: Target audience with terms like visitors, members, editors, administrators.
If the terms are not at all "related", then go for solution 2. E.g. Topic and Target audience.
Comment: There is no need to have two fields to have two different tags.
Comment: I was just adding the 2nd "option" ... And wanted to already do a temporary save ...
Answer: I know this is a bit old but the final and ultimate solution is simply setting the Widget type  to Auto Complete in the widget setting

Set up number of values to unlimited in the field setting of the Taxonomy term/ tag of interest.
Then Use a comer to separate the tags as you in put them. eg Drupal, modules, etc.


Can you run multiple clr instances on a windows server?

Question: I hear that on the other side, Java folks run multiple jvm instances on their servers and load balance not just the servers but also instances. How is this possible in asp.net? pools?
Answer: If you are referring to ASP.NET on IIS, then yes, each application pool can have its own version of the CLR, because they are individual processes.  This doesn't particularly help for load balancing however- IIS takes care of that on it's own.  I'm pretty sure you'd just be hampering it.


Property of nilpotent square matrix, $2\times 2$

Question: Let A be matrix $2\times 2$ and take integer $k \geq 2$. Show that if $A^k = 0$ then we must have that $A^2 = 0$
Comment: Have you any thoughts of your own on this?
Comment: Do you know what the minimal polynomial of a matrix is (+ some elementary properties of this polynomial)?
Answer: Suppose that $A$ has an inverse matrix. Then, multiplying the both sides of
$$A^k=O$$
by $\left(A^{-1}\right)^k$ gives us $I=O$ where $I$ is the identity matrix, which is a contradiction.
Hence, if we set $A=\begin{pmatrix} a&b\\c&d\end{pmatrix}$, then we have $ad-bc=0$. So, by the Cayley–Hamilton theorem, we have
$$A^2=(a+d)A-(ad-bc)I=(a+d)A.\tag1$$
Hence, we have
$$A^3=(a+d)^2A,\ \ A^4=(a+d)^3A,\cdots, A^k=(a+d)^{k-1}A.$$
Since $A^k=O$, we have
$$a+d=0\ \ \ \text{or}\ \ \ A=O.$$
From $(1)$, in either case, we have $A^2=O$.
Answer: Here is a laboured way of explaining a more general case (you have $k=2$). But it relies on more general theory.
Presumably it is a matrix over a field $\mathbb F$. Once a basis is chosen for a vector space $V$ of dimension $k$ over $\mathbb F$, a $k\times k$ matrix $M$ represents a linear map on $V=\mathbb F^k$.
Let $I_n$ be the image of $V$ under $M^n$ with $I_0=V$. Note that for $n\ge 1$we have $M^{n+1}V=M^n(MV)$. Because $MV\subset V$ we then have $I_{n+1}\subset I_n$.
Now suppose $\dim I_n=\dim I_{n+1}\gt 0$. Since the dimensions are equal, and $I_{n+1}\subset I_n$ we have $I_{n+1}=I_n$, and $MI_n=I_n\neq 0$. This implies that $M^rI_n=I_n\neq 0$ for all positive integers $r$, which contradicts the fact that $M$ is nilpotent.
We therefore have $\dim I_n \leq \max(\dim V-n,0)$ and in particular $\dim I_k=0$ whence $M^k=0$


Laravel 5.6 validate required_without multiple

Question: I use laravel 5.6 and I try to use validate to check my input.
But I have an issue with required_without.
I have 4 input : heure_bureau / heure_supp_bureau / heure_terrain / heure_supp_terrain
I must fill one input at least. So if I fill heure_bureau, the others aren't necessary.
So I use this code :
<code>        $validator = \Validator::make($request->all(), [
        'heures_bureau'    => 'nullable|date_format:"H\hi"|required_without:heures_supp_bureau,heures_terrain,heures_supp_terrain|before:07h45',
        'heures_supp_bureau'    => 'nullable|date_format:"H\hi"|required_without:heures_bureau,heures_terrain,heures_supp_terrain|before:13h15',
        'heures_terrain'    => 'nullable|date_format:"H\hi"|required_without:heures_bureau,heures_supp_bureau,heures_supp_terrain|before:07h45',
        'heures_supp_terrain'    => 'nullable|date_format:"H\hi"|required_without:heures_bureau,heures_supp_bureau,heures_terrain|before:13h15'
    ], $messages);
</code>
But it doesn't work. I have an error for each other input when I fill one.
If I use requried_without with only one input, it work well but not when I use it with multiple inputs.
Where am I wrong ?
Thank for your help !
Answer: try this:
<code> $validator = \Validator::make($request->all(), [
    'heures_bureau'    => 'nullable|date_format:"H\hi"|required_without_all:heures_supp_bureau,heures_terrain,heures_supp_terrain|before:07h45',
    'heures_supp_bureau'    => 'nullable|date_format:"H\hi"|required_without_all:heures_bureau,heures_terrain,heures_supp_terrain|before:13h15',
    'heures_terrain'    => 'nullable|date_format:"H\hi"|required_without_all:heures_bureau,heures_supp_bureau,heures_supp_terrain|before:07h45',
    'heures_supp_terrain'    => 'nullable|date_format:"H\hi"|required_without_all:heures_bureau,heures_supp_bureau,heures_terrain|before:13h15'
], $messages);
</code>
Comment: Is it possible to combine required_if and required_without ?


Como exibir resultados caso meu select dê falso?

Question: E estou tendo o seguinte problema, existem duas tabelas POSTS e TOPICOS, um topico tem vários posts, e eu estou exibindo os topicos ordenando pela data mais atual do post do topico, só que ao criar um novo topico ele não exibe na tela porque não tem post, e se eu postar no topico ele exibe na tela porque tem post, e eu queria saber como posso exibir os topicos que não tem posts?
Como eu consigo listar os topicos que não tem posts? Porque o meu JOINN só está trazendo os topicos que tem posts relacionados
<code>$sqlTopicos = mysqli_query($conexao,
        "SELECT topico.titulo, posts.idTopico, slug, posts.dataPost, usuario.usuario, visualizacoes, qtdPosts
         FROM (SELECT * FROM posts ORDER BY dataPost DESC) posts
         INNER JOIN topico
            ON posts.idTopico = topico.idTopico
         INNER JOIN usuario
            ON topico.idUsuario = usuario.idUsuario
         WHERE posts.idArea = '$idArea' GROUP BY titulo ORDER BY posts.dataPost DESC");
</code>
Answer: Faça um Left Join entre as tabelas: http://www.w3schools.com/sql/sql_join_left.asp. Ele irá trazer os resultados de Topicos mesmo que não existam Posts associados.
Exemplo:
<code>SELECT * FROM Topicos t
LEFT JOIN Posts p
ON t.TopicoID=p.TopicoID
ORDER BY t.DataCriacao;
</code>
Comment: Consegui da seguinte maneira:
Comment: Não apareceu a sua solução, posta novamente.