Simple python web-crawler

Question: I have been searching for a simple, working, and web-crawler (also know as a spider) and have not been able to find one. Could anyone help me with this problem? I would like it to simply get all the links from a specified url as well as all the links from each of the urls it scanned.
Answer: You can use the scrapy module.
Alternatively, you can write your own crawlers, using a combination of a module for fetching data (i.e. requests, urllib2, or selenium) and some HTML parser (BeautifulSoup or selenium's built-in parser).
Answer: I have not tried making a webcrawler before. However, I imagine it shouldn't be too complicated. I will give you a couple resources you can use.
I do not know any module that will simply fetch all the links for you, so you will have to probably go through the process yourself.
First, get the HTML from you link with urllib2. Then, parse the HTML and find the links with BeautifulSoup. There is even a section on the page that describes how to get all the links from a webpage.
This is really all the "difficult" code. You can then append all the links you got to a list, go through each link, repeat the same process as above, and then add the resulting links to the list again, and recursively repeat this process for however long you want. That should make a basic web crawler for you.
Answer: You can use this as a web crawler but I am not sure if it will work or not because it gives me some errors but you might have another python path installed
<code>import requests
from bs4 import BeautifulSoup

    def trade_spider(max_pages):
    page = 1
    while page <= max_pages:
    url = "https://buckysroom.org/trade/search.php?page=" + str(page)
    source_code = requests.get(url)
    # just get the code, no headers or anything
    plain_text = source_code.text
    # BeautifulSoup objects can be sorted through easy
    soup = BeautifulSoup(plain_text)
    for link in soup.findAll('a', {'class': 'item-name'}):
        href = "https://buckysroom.org" + link.get('href')
        title = link.string  # just the text, not the HTML
        print(href)
        print(title)
        # get_single_item_data(href)
    page += 1

def get_single_item_data(item_url):
source_code = requests.get(item_url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text)
# if you want to gather information from that page
for item_name in soup.findAll('div', {'class': 'i-name'}):
    print(item_name.string)
 # if you want to gather links for a web crawler
 for link in soup.findAll('a'):
    href = "https://buckysroom.org" + link.get('href')
    print(href)

trade_spider(1)
</code>

Simple python web-crawler


Else if evaluates bool incorrectly

Question: Here is my code:
if (addNewRecord == false)
        { MessageBox.Show("No action selected. \nSave cancelled."); }
else if (editCurrentRecord == false)
        { MessageBox.Show("No action selected. \nSave cancelled."); }
else{.....}

addNewRecord and editCurrentRecord are both bools that I have checked have a true value. When I do as above the messageboxes will still show as if the bools were false. However, if I only comment out the ELSE IF it will continue with the ELSE as intended. Am I missing something fundamental here? Thanks for any input.
EDIT: Both of the messageboxes don't show just one. I am checking the values of both bools before the IF statement with MessageBox.Show(addNewRecord.ToString());and the same for the other bool. They are working as intended. The problem only happens when I try to evaluate both of the bools, either with else if or with an OR statement.
Here is all the relevant code:
namespace E_Z_Rent
{
public partial class Bookings : Form
{
    bool addNewRecord = false;
    bool editCurrentRecord = false;

    public Bookings()
    {
        InitializeComponent();
    }

    private void bookingsBindingNavigatorSaveItem_Click(object sender, EventArgs e)
    {
        MessageBox.Show(addNewRecord.ToString());
        MessageBox.Show(editCurrentRecord.ToString());
        if (addNewRecord == false)
        { MessageBox.Show("No action selected. \nSave cancelled."); }
        else if (editCurrentRecord == false)
        { MessageBox.Show("No action selected. \nSave cancelled."); }
        else
        {
            MessageBox.Show("OK");
        }
    }

    private void EditFieldsCheckBox_CheckedChanged(object sender, EventArgs e)
    {
        if (EditFieldsCheckBox.Checked == true)
        {
            editCurrentRecord = true;
        }
        else
        {
            editCurrentRecord = false;
        }
    }

    private void bindingNavigatorAddNewItem_Click(object sender, EventArgs e)
    {
        addNewRecord = true;
    }
}
}

I have got it working as intended by doing:
   if (addNewRecord == true || editCurrentRecord == true){
          MessageBox.Show("OK");
      }
      else
      {
          MessageBox.Show("No action selected. \nSave cancelled.");
      }

I am still puzzeled by this so if anyone else can say why this happened I will be checking back. Thanks for all the suggestions everyone.
Comment: I don't believe that both the bools are false. Prove it with a self-contained testcase. Otherwise, look for race conditions, checking the wrong variable, etc.
Comment: What you are saying is impossible.
Comment: Try refactor to if (!addNewRecord || !editCurrentRecord)) { MessageBox.show(...); } else { .... }
Comment: Are you saying that _both_ messageboxes are showing?
Comment: In any case, I recommend changing the messages so they are different. "(1) No action selected. \nSave cancelled." and "(2) No action selected. \nSave cancelled." will suffice, for debugging purposes.
Comment: @DanielDaranas is right and then take some time , be easy and then give it a look.
Comment: It seems my guess was right alhough down votes :(
Comment: When do you execute that code, and when did you checked ?
Comment: When the program enters inside IF or ELSE IF blocks it will not enter ELSE block. You can rewrite IF and ELSE IF blocks into one IF.
Comment: Not impossible, I've seen it happen, unfortunately. Very unlikely however, because there were a lot of things going on that were causing it to mess up like that. (Compiling as 32-bit fixed it in that specific case)
Comment: First you check if (editCurrentRecord == false) and check if that fails
Comment: Do these bools have get accessors that change the state of anything?  Equality overridden?
Comment: Another recommendation. You say you check that the bools are true with "MessageBox.Show(addNewRecord.ToString());". This is a strange way to check that a bool is true. Try this one instead: "Debug.Assert(addNewRecord);"
Answer: It seems you want to do this;
if (addNewRecord == false || editCurrentRecord == false)
        { MessageBox.Show("No action selected. \nSave cancelled."); }
else{.....}

Comment: Don't you mean `||` and not `&&`?
Comment: At first I wrote || but when downwoted I advised && . As others stated I thik we are talking about a misunderstanding of a problem.
Answer: Your algorithm is wrong.
You will go to the final else case only if both addNewRecord AND editCurrentRecord are true.
If any one is wrong, you will pop the "No action selected" message.

Else if evaluates bool incorrectly


Setting up subdomains, confused on "Settings.php" / "web.config" setup

Question: First, I'm using shared hosting.  I've set up the DNS so I have one.example.com, two.example.com, etc.  Each subdomain works properly, but they use the default page.tpl.php/look exactly the same as my front page.  I'm assuming the next step is to configure the settings.php, web.config, and to create preprocessed theme hooks.  Is there a good D7 tutorial on how to do all of this via "subdomains"?
Also, I'm planning on using the "Domain" module.  I've got it properly configured.  But, don't really see a point in using it until the above mentioned is setup properly.
Answer: Instructions for multisite installations are in sites/default/settings.php. To quote from that file:

For example, for a fictitious site installed at http://www.drupal.org/mysite/test/, the 'settings.php' is searched in the following directories:

sites/www.drupal.org.mysite.test
sites/drupal.org.mysite.test
sites/org.mysite.test
sites/www.drupal.org.mysite
sites/drupal.org.mysite
sites/org.mysite
sites/www.drupal.org
sites/drupal.org
sites/org
sites/default

If you are installing on a non-standard port number, prefix the hostname with that number. For example, http://www.drupal.org:8080/mysite/test/ could be loaded from sites/8080.www.drupal.org.mysite.test/.

The lookup can be changed as described in sites/example.sites.php:

This file allows you to define a set of aliases that map hostnames and pathnames to configuration directories. These aliases are loaded prior to scanning for directories, and they are exempt from the normal discovery rules. The aliases are defined in an associative array named $sites, which should look similar to the following:
$sites = array(
  'devexample.com' => 'example.com',
  'localhost.example' => 'example.com',
);

The above array will cause Drupal to look for a directory named "example.com" in the sites directory whenever a request comes from "example.com", "devexample.com", or "localhost/example".

BTW: multisite installations are usually done to facilitate using different databases.


How can i center and horizontal this

Question: I need to center the a paragraf in the CSS. I also want the text to appear horizontial.

 SUCCESS </p11>

 TEST# </p12>

 DATE </p13>

Here is the CSS
p.result1, p.result2 , p.result3, p.result4{
    font-size:12px;
    font-weight:900;
    margin:auto;
}

Any idea?
Comment: Have you tried google?
Comment: check this answer http://stackoverflow.com/a/18200485/1592884
Answer: To center text horizontally apply:
text-align: center;

to the paragraphs that you want to center.
If you want to center the div you just need to provide it a width and set the left and right margins to auto:
width: 20%;
margin: 0 auto;

Comment: Thanks, it is fixed now!
Answer: If you want to center the text, you can use the 'text-align'.
p {
    text-align: center;
}

Demo
More info
Try some research by yourself. There is a lot of resource about html and css online.

How can i center and horizontal this


Java: Project Euler 41:Pandigital prime

Question: Problem: Project Euler Problem 41
The following is the complete programme. My question is on one sentence of code.
public class Practice {
public static void main(String[] args) {
    for(double i=7654321;i>1234566;i-=2){
        if(isUnique(i)){
            if(isPrime(i)){
                    System.out.println(i);
                    break;
            }
        }
    }
    for(double i=4321;i>1233;i-=2){
        if(isUnique(i)){
            if(isPrime(i)){
                    System.out.println(i);
                    break;
            }
        }
    }
}

static boolean isUnique(double num){
    String str = String.valueOf(num);
    for(int i=0;i<str.length();i++){
        if(str.charAt(i)=='9'){return false;}
        if(str.charAt(i)=='8'){return false;}
        if(str.charAt(i)=='0'){return false;}  //<---***Sentence 1***
    }
    for(int i=0;i<str.length()-1;i++){
        for(int j=i;j<str.length()-1;j++){
            if(str.charAt(i)==str.charAt(j+1)){return false;}
        }
    }
    return true;
}

static boolean isPrime(double num){
    for(double i=3;i<=num/2;i+=2){
        if(num%i==0){return false;}
    }
    return true;
}

}
I got the correct answer if the Sentence 1 (if(str.charAt(i)=='0'){return false;})
is NOT included. If Sentence 1 is included, the programme terminates immediately. Why?
Answer: Since you are using a double, all your Strings are on the form
7654321.0

which all contain a 0, ending the isUnique() calls immediately. Using an int instead makes more sense for investigating prime numbers.
Answer: If you use the debugger you can see that the value of your parameter  double num  is 7654321.0
The .0 causes the method to terminate. Solution: don't use a double but a long or int.

Java: Project Euler 41:Pandigital prime


Boas práticas (Refactoring) - melhor maneira de tratar um método com for dentro de outro

Question: Pessoal usando boas prática em Java como devo converter esse método?
Devo quebrar em vários métodos e dentro de cada um deles fazer o for?
public void salvarObjetos(Objeto objeto){

   for(Objeto1 obj : container.getList()){
        .
        .
        .
        ObjetoManager.save(obj);
        for(Objeto2 obj2 : obj.getLitObj()){
            .
            .
            .
            Objeto2Manager.save(obj2);
            for(Objeto3 obj3 : obj2.getListObj2()){
                .
                .
                .
                Objeto3Manager.save(obj3);
            }
        }
    }

}

Answer: A questão de um for dentro de outro cria uma complexidade ciclomática muito alta. Mais em miúdos, uma carga mental grande para poder entender o quê o método deve fazer.
Você pode utilizar algumas técnicas descritas no livro "Clean Code" do uncle Bob ( o título é maior mas procurando por "clean code" já vai achar, o autor é o Robert C. Martin ).
Basicamente ele sugere que você crie um método para cada for e tente ser o mais claro possível no nome do método.
Eu iria por este caminho:
public void salvarObjetos(Objeto objeto) {
   for(Objeto1 obj : container.getList()) {
        ObjetoManager.save(obj);
        salvarObjetos2(obj.getLitObj);
    }
}

private void salvarObjetos2(List<Objeto2> obj2List) {
  for(Objeto2 obj2 : obj2List){
    Objeto2Manager.save(obj2);
    salvarObjetos3(obj2.getListObj2());
  }
}

private void salvarObjetos3(List<Objeto3> obj3List) {
  for(Objeto3 obj3 : obj2.getListObj2()){
    Objeto3Manager.save(obj3);
  }
}

Lembrando que você deve tentar descrever da melhor forma possível os nomes dos métodos e não só algo como salvarObjetosX claro que se somente persistir um objeto no banco de dados então não há como escrever de outra forma.
Repare que da forma que dividi o código fica menos carregado de entender cada conteúdo do for, digo isso pois normalmente não é só um método por for, há também atribuições de valores, verificações de condições...
Onde eu trabalho a gente tem uma meta de que cada método não deve ter mais que 15 linhas, se tiver deve haver um bom motivo. Ficamos vagando em ser consistentes com nossas regras de desenvolvimento ou flexíveis com elas.
Comment: ahhh... sim... eu já votei na sua pergunta pq ela ajuda muita gente com a mesma dúvida... hehehehe
Comment: Show, era oq eu pensava mesmo. já iniciei a leitura do livro código limpo. Me deparei com o código desse exemplo na empresa que eu entrei. Perguntei pra ter certeza de chegar e sugerir as mudanças. muito obrigado.
Comment: @FernandoLopes Se gostou da resposta poderia votar? Faz parte da comunidade indicar boas respostas ou indicar respostas ruins.
Comment: I sorry... havia me esquecido. pena não poder ainda marcar com ponto positivo. vlw


Disable all Joomla 3.0 inline styling

Question: I need to disable all joomla inline styling for everything.
My query isn't in regards to the text editor.
I have no use at all for inline styling in the majority of scenarios.
It really holds me back especially on a current project with a custom template.
Any solutions? or plugins? (i have searched)
Comment: Maybe adding some jquery code to the main template ?
Comment: I'm aware I can do that as well as overriding [style] via css. But I would prefer a cleaner solution.
Comment: Where are you seeing inline style, I thought Joomla 3.1 core didn't have any inline styles.
Comment: I built templates with no styles. The layout is fluid, and everything fits to screen & on resize.

Then i populated the site with content (text & images). And the header titles & other parts external to the article contents seem to have inline styling. And it's a nightmare with text editors.

So I need a backend/ cms solution, JS won't cut it.
Answer: Here's a simple plugin you can run and use to find which elements contain which properties, for instance, class, style, title, width, etc.
Fiddle at http://jsfiddle.net/SyFum/2/

Answer: Be aware that this will remove the inline "style" attributes from all elements:

To be absolutely effective, place it just before the  tag, just in case you may have any other jQuery scripts adding css("something") to the elements.

Disable all Joomla 3.0 inline styling


How did i resolve these scout-apm + rails warning getting on heroku server during build deployment?

Question: e: Calling DidYouMean::SPELL_CHECKERS.merge!(error_name => spell_checker)' has been deprecated. Please call DidYouMean.correct_error(error_name, spell_checker)' instead.
remote: I, [2022-09-07T13:32:05.994002 #19]  INFO -- : Raven 3.1.2 ready to catch errors
remote: [Scout] [09/07/22 13:32:06 +0000 release.7924 (19)] WARN Exception loading instruments:
remote: [Scout] [09/07/22 13:32:06 +0000 release.7924 (19)] WARN : undefined method call' for class Redis::Client'
remote:
remote:               alias_method :call_without_scout_instruments, :call
remote:               ^^^^^^^^^^^^
remote: Did you mean?  caller
remote: [Scout] [09/07/22 13:32:06 +0000 release.7924 (19)] WARN : ["/app/vendor/bundle/ruby/3.1.0/gems/scout_apm-5.3.1/lib/scout_apm/instruments/redis.rb:40:in alias_method'", "/app/vendor/bundle/ruby/3.1.0/gems/scout_apm-5.3.1/lib/scout_apm/instruments/redis.rb:40:in block in install'", "/app/vendor/bundle/ruby/3.1.0/gems/scout_apm-5.3.1/lib/scout_apm/instruments/Redis.rb:29:in class_eval'", "/app/vendor/bundle/ruby/3.1.0/gems/scout_apm-5.3.1/lib/scout_apm/instruments/Redis.rb:29:in install'", "/app/vendor/bundle/ruby/3.1.0/gems/scout_apm-5.3.1/lib/scout_apm/instrument_manager.rb:82:in install_instrument'", "/app/vendor/bundle/ruby/3.1.0/gems/scout_apm-5.3.1/lib/scout_apm/instrument_manager.rb:37:in install!'", "/app/vendor/bundle/ruby/3.1.0/gems/scout_apm-5.3.1/lib/scout_apm/agent.rb:41:in install'", "/app/vendor/bundle/ruby/3.1.0/gems/scout_apm-5.3.1/lib/scout_apm.rb:223:in block in class:Railtie'", "/app/vendor/bundle/ruby/3.1.0/gems/railties-184.108.40.206/lib/rails/initializable.rb:32:in instance_exec'", "/app/vendor/bundle/ruby/3.1.0/gems/railties-188.8.131.52/lib/rails/initializable.rb:32:in run'", "/app/vendor/bundle/ruby/3.1.0/gems/railties-126.96.36.199/lib/rails/initializable.rb:61:in block in run_initializers'", "/app/vendor/ruby-3.1.2/lib/ruby/3.1.0/tsort.rb:228:in block in tsort_each'", "/app/vendor/ruby-3.1.2/lib/ruby/3.1.0/tsort.rb:350:in block (2 levels) in each_strongly_connected_component'", "/app/vendor/ruby-3.1.2/lib/ruby/3.1.0/tsort.rb:431:in each_strongly_connected_component_from'", "/app/vendor/ruby-3.1.2/lib/ruby/3.1.0/tsort.rb:349:in block in each_strongly_connected_component'", "/app/vendor/ruby-3.1.2/lib/ruby/3.1.0/tsort.rb:347:in each'", "/app/vendor/ruby-3.1.2/lib/ruby/3.1.0/tsort.rb:347:in call'", "/app/vendor/ruby-3.1.2/lib/ruby/3.1.0/tsort.rb:347:in each_strongly_connected_component'", "/app/vendor/ruby-3.1.2/lib/ruby/3.1.0/tsort.rb:226:in tsort_each'", "/app/vendor/ruby-3.1.2/lib/ruby/3.1.0/tsort.rb:205:in tsort_each'", "/app/vendor/bundle/ruby/3.1.0/gems/railties-188.8.131.52/lib/rails/initializable.rb:60:in run_initializers'", "/app/vendor/bundle/ruby/3.1.0/gems/railties-126.96.36.199/lib/rails/application.rb:363:in initialize!'", "/app/config/environment.rb:5:in '", "/app/vendor/bundle/ruby/3.1.0/gems/bootsnap-1.13.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:32:in require'", "/app/vendor/bundle/ruby/3.1.0/gems/bootsnap-1.13.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:32:in require'", "/app/vendor/bundle/ruby/3.1.0/gems/zeitwerk-2.6.0/lib/zeitwerk/kernel.rb:35:in require'", "/app/vendor/bundle/ruby/3.1.0/gems/activesupport-18.104.22.168/lib/active_support/dependencies.rb:324:in block in require'", "/app/vendor/bundle/ruby/3.1.0/gems/activesupport-126.96.36.199/lib/active_support/dependencies.rb:291:in load_dependency'", "/app/vendor/bundle/ruby/3.1.0/gems/activesupport-18.104.22.168/lib/active_support/dependencies.rb:324:in require'", "/app/vendor/bundle/ruby/3.1.0/gems/railties-184.108.40.206/lib/rails/application.rb:339:in require_environment!'", "/app/vendor/bundle/ruby/3.1.0/gems/railties-22.214.171.124/lib/rails/application.rb:523:in block in run_tasks_blocks'", "/app/vendor/bundle/ruby/3.1.0/gems/rake-13.0.6/lib/rake/task.rb:281:in block in execute'", "/app/vendor/bundle/ruby/3.1.0/gems/rake-13.0.6/lib/rake/task.rb:281:in each'", "/app/vendor/bundle/ruby/3.1.0/gems/rake-13.0.6/lib/rake/task.rb:281:in execute'", "/app/vendor/bundle/ruby/3.1.0/gems/rake-13.0.6/lib/rake/task.rb:219:in block in invoke_with_call_chain'", "/app/vendor/bundle/ruby/3.1.0/gems/rake-13.0.6/lib/rake/task.rb:199:in synchronize'", "/app/vendor/bundle/ruby/3.1.0/gems/rake-13.0.6/lib/rake/task.rb:199:in invoke_with_call_chain'", "/app/vendor/bundle/ruby/3.1.0/gems/rake-13.0.6/lib/rake/task.rb:243:in block in invoke_prerequisites'", "/app/vendor/bundle/ruby/3.1.0/gems/rake-13.0.6/lib/rake/task.rb:241:in each'", "/app/vendor/bundle/ruby/3.1.0/gems/rake-13.0.6/lib/rake/task.rb:241:in invoke_prerequisites'", "/app/vendor/bundle/ruby/3.1.0/gems/rake-13.0.6/lib/rake/task.rb:218:in block in invoke_with_call_chain'", "/app/vendor/bundle/ruby/3.1.0/gems/rake-13.0.6/lib/rake/task.rb:199:in synchronize'", "/app/vendor/bundle/ruby/3.1.0/gems/rake-13.0.6/lib/rake/task.rb:199:in invoke_with_call_chain'", "/app/vendor/bundle/ruby/3.1.0/gems/rake-13.0.6/lib/rake/task.rb:243:in block in invoke_prerequisites'", "/app/vendor/bundle/ruby/3.1.0/gems/rake-13.0.6/lib/rake/task.rb:241:in each'", "/app/vendor/bundle/ruby/3.1.0/gems/rake-13.0.6/lib/rake/task.rb:241:in invoke_prerequisites'", "/app/vendor/bundle/ruby/3.1.0/gems/rake-13.0.6/lib/rake/task.rb:218:in block in invoke_with_call_chain'", "/app/vendor/bundle/ruby/3.1.0/gems/rake-13.0.6/lib/rake/task.rb:199:in synchronize'", "/app/vendor/bundle/ruby/3.1.0/gems/rake-13.0.6/lib/rake/task.rb:199:in invoke_with_call_chain'", "/app/vendor/bundle/ruby/3.1.0/gems/rake-13.0.6/lib/rake/task.rb:188:in invoke'", "/app/vendor/bundle/ruby/3.1.0/gems/rake-13.0.6/lib/rake/application.rb:160:in invoke_task'", "/app/vendor/bundle/ruby/3.1.0/gems/rake-13.0.6/lib/rake/application.rb:116:in block (2 levels) in top_level'", "/app/vendor/bundle/ruby/3.1.0/gems/rake-13.0.6/lib/rake/application.rb:116:in each'", "/app/vendor/bundle/ruby/3.1.0/gems/rake-13.0.6/lib/rake/application.rb:116:in block in top_level'", "/app/vendor/bundle/ruby/3.1.0/gems/rake-13.0.6/lib/rake/application.rb:125:in run_with_threads'", "/app/vendor/bundle/ruby/3.1.0/gems/rake-13.0.6/lib/rake/application.rb:110:in top_level'", "/app/vendor/bundle/ruby/3.1.0/gems/railties-18.104.22.168/lib/rails/commands/rake/rake_command.rb:23:in block in perform'", "/app/vendor/bundle/ruby/3.1.0/gems/rake-13.0.6/lib/rake/application.rb:186:in standard_exception_handling'", "/app/vendor/bundle/ruby/3.1.0/gems/railties-126.96.36.199/lib/rails/commands/rake/rake_command.rb:20:in perform'", "/app/vendor/bundle/ruby/3.1.0/gems/railties-22.214.171.124/lib/rails/command.rb:48:in invoke'", "/app/vendor/bundle/ruby/3.1.0/gems/railties-18.104.22.168/lib/rails/commands.rb:18:in '", "/app/vendor/bundle/ruby/3.1.0/gems/bootsnap-1.13.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:32:in require'", "/app/vendor/bundle/ruby/3.1.0/gems/bootsnap-1.13.0/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:32:in require'", "/app/bin/rails:4:in '"]
Answer: It looks like this was an error with the latest redis client: https://github.com/scoutapp/scout_apm_ruby/issues/458
It has been fixed in the latest version of the gem (5.3.2).


Rewrite $\frac{1}{1-\sqrt[3]{2}}$ as a polynomial question

Question: I've been looking for a way to rewrite the following fraction as a polynomial equation in $\sqrt[3]{2}$: $$\frac{1}{1-\sqrt[3]{2}}.$$ Now, to rewrite $1/(1-\sqrt{2})$ as a polynomial equation, it is enough to simply multiply by $(1+\sqrt{2})/(1+\sqrt{2})$, to get $$\frac{1}{1-\sqrt{2}} \frac{1+\sqrt{2}}{1+\sqrt{2}} = \frac{1+\sqrt{2}}{-1} = -(1+\sqrt{2}).$$ But this doesn't work with the other fraction (or maybe I'm missing something, haha). I've tried multiplying with different powers of two (or two raised to some fraction) to get the bloody $1/3$ power away, but it seems to persist. I've also tried successive multiplications of $(1+2^{1/3})/(1+2^{1/3})$ but that doesn't seem to bring anything either. My general ideas are to multiply by 1, choosing the correct fraction. Or doing the $+1$ and $-1$ trick, choosing $1$ appropriately. But I haven't been able to find the correct $1$. Any ideas?
Comment: multiply with $1+\sqrt[3]{2}+(\sqrt[3]{2})^2$ on numerator and denominator
Comment: Related: http://usamts.org/Solutions/Solutions_25_2.pdf (Page 4)
Answer: Write $\alpha = \sqrt[3]{2}$. We have $(\alpha-1)(\alpha^2+\alpha+1) = \alpha^3 - 1 = 1$, hence $\frac{1}{1-\alpha} = -\alpha^2 - \alpha - 1$.
Comment: Of course!! Should've seen this :P Thank you!
Answer: Try multiplying by $$\frac{2^{2/3}+2^{1/3}+1}{2^{2/3}+2^{1/3}+1}$$
Comment: Yup ^^ Got it! Thanks a lot
Answer: For a more general approach, let $\alpha$ be any algebraic number; suppose that $\alpha$ has minimal polynomial $p(x)$ and you want to evaluate $1/f(\alpha)$, where $f$ is a polynomial which is not a multiple of $p$.  (If $f$ is a multiple of $p$ then $f(\alpha)=0$ and so $1/f(\alpha)$ makes no sense.)
Use the Euclidean algorithm for polynomials to divide $p(x)$ by $f(x)$ and thereby to obtain an identity
$$1=p(x)a(x)+f(x)b(x)\ ,$$
where $a$ and $b$ are polynomials.  Substituting $x=\alpha$ gives by definition $p(\alpha)=0$ and therefore
$$\frac{1}{f(\alpha)}=b(\alpha)\ ,$$
which is what you want.
In your case you have $p(x)=x^3-2$ and $f(x)=1-x$.  Euclid works in one step,
$$x^3-2=(-x+1)(-x^2-x-1)-1$$
and so
$$1=(-x+1)(-x^2-x-1)-(x^3-2)\ .$$
Substituting $x=\alpha={\root3\of2}$ gives
$$1=(1-\alpha)(-\alpha^2-\alpha-1)-0=(1-\alpha)(-1-\alpha-\alpha^2)\ ,$$
and so
$$\frac{1}{1-\root3\of2}=-1-{\root3\of2}-({\root3\of2})^2\ .$$
Comment: Very nice! Wish I could accept more answers :) I like the Euclidean algorithm argument


Looking for suitable backup solution Mac OS X to offsite Centos 6 server 1TB of working data

Question: I'll start by saying what we have in place currently:

On site file server (Mac OS X Server) that is used by GFX designers and they have a working 1TB of data.
Offsite server with 2TB available storage (Centos 6)
Mac OS X server rsync data to offsite server every 6 hours (rsync -avz --delete --progress  -e ssh ...)
Mac OS X server does full data backup to LTO 4 tape on a 10 day recycle (Mon-Fri for 2 weeks)
rsync pushes about 60GB of file changes a day.

The problem:

The onsite tape backup is failing as 1TB of graphics files don't compress well to fit onto a 800GB LTO4 tape.
Backup is incredibly slow doing a full backup.
Pain in the backside getting people to remember to change the tape. Often gets forgotten
etc

The quick solution:

Buy LTO5 Drive and tapes. However this has been turned down because of the cost...

What I would like:

Something that works in the same way rysnc works. Only changed data is sent over the wire and can be scheduled to run multiple times during the day. Data that is sent is compressed and sent over SSH.
Something that keeps a 14day retention but doesn't keep duplicate data
So as an example if I have 1TB of working data and 60GB of changes are made each day then I expect around 1.84TB of data to be stored on the offsite server.
To work with the Mac OS X server and Centos 6 server.
Not cost an arm and a leg. Must be a cheaper solution than buying an LTO5 drive with tapes (around £1500).
Be able to be setup to run autonomously.
Have some sort of control panel that will allow an admin to easily restore a file/folder.

Any recommendations?
Comment: Maybe you can configure http://sparkleshare.org/ to do exactly what you want. But I don't know it well enough.
Comment: I've had to deal with convincing management on purchasing a new backup system. The key is to not focus on the cost of the new system. Instead, focus on the efficiency and reliability. These are the critical aspects when determining a data restoration system. The more complicated the process, the more prone to have bad backups to restore from.
Answer: Try rsnapshot (rsnapshot.org). It does exactly what you're after: it's in the RPMForge yum repos (so is packaged for CentOS), operates over rsync via SSH, and keeps a configurable number of incremental backups.
edit: You could implement a recovery front end by exporting the rsnapshot datastore over NFS or Samba (or a webserver/anything else) and let users pick up old copies of their files themselves.
Comment: I like this. Only thing its missing is the GUI for easy restoration. If anything else doesn't come up then I'll definitely test this out.
Answer: I use rsnapshot to handle approximately the same data volumes you're talking about and it works quite nicely.  As has already been pointed out it doesn't have a fancy front-end but it does a great job at snapshot retention and minimizing file storage space.
For GUI-based tools, consider looking into CrashPlan at http://www.crashplan.com.  There are several cost levels (Home, Pro, etc.), one of which may suit your needs.  I believe it's Java-based but IIRC it came with its own JRE.  I use it for home backups, and I briefly tested the Pro (server-based) version but other things distracted me from giving it a full evaluation.  But it looked promising.
One thing to watch out for regardless of which solution you use is handling (or ignoring) of resource fork data.  Your OSX server deals with resource forks transparently, but you may lose the resource forks if you are using applications and/or filesystems that are not aware of them and thus would discard them.  Maybe it doesn't matter in your environment, but it's worth pointing out that the data can get dropped pretty easily and without warning.
Comment: Nice catch on the resource fork thing! I never realised this and just checked my backups to find any files using resource fork data are 0kb files. Luckily they are only font files so not end of the world. Looking at crash plan now.
Comment: http://www.whoopis.com/howtos/rsync-hfs-howto/ nice article getting rsync to work with resource forks. Maybe there is a rsnapshot version too
Comment: @Brady: Before you decide that missing or zero-size resource forks are a non-issue for fonts, you might want to do a test restore and see if the font is still usable. Fonts are notorious for storing data that's more critical than you might expect in the resource forks.  I've had many fonts become un-usable after being handled by utilities that were not resource-fork-aware (e.g. scp, rsync, etc.) Good luck!
Answer: Would just buying a bunch of cheapo =>1TB USB hard disks and treating them like tapes, but with the ability to rsync to/from them, do what you need?
Comment: Ya canna' change the laws of physics...you either buy more hardware to accommodate the storage and speed requirements, or make due with kludges. If the data were important, you spend the extra money and amortize the cost over the expected lifespan of the equipment.
Comment: With regards to this, you could also look into Virtual Tape Library technology.
Comment: Not ideal really. Although I say 1TB that does often reach 1.2TB until some archiving is done. The cost of HDDs are very expensive ATM and buying 10 1.5TB external HDDs isn't cheap. Plus backing up to HDD's over USB2 is going to be slower than out tape setup. This solution doesn't tick many boxes. I know there are better solutions out there.
Comment: Well, you're going to need the space somewhere no matter what and it doesn't get much cheaper than consumer hard drives per GB
Comment: @Dan maybe so but to me its a solution that comes at an additional cost. A cost that's not needed when we have 2TB of offsite backup already paid for.
Comment: ...bring the offsite server on site, and rotate backups to an offsite storage area?
Answer: Another option is Bacula. It's free, works on both CentOS (found in yum) and OS X (build from source) and it's a full client-server backup suite. It, however, does not use SSH to transfer but I do believe that encryption methods are available. You can control how long items are kept, when backups run, what is backed up, etc. There is a GUI for it if you install Webmin on the CentOS server and add the Bacula  plugins. The GUI allows you to restore how many files you need to and it gives you a directory tree view to select your files.
It's kind of a pain to set up, though. I was really hoping that I could "learn as I go" when I set it up, but that wasn't the case. I actually had to RTFM (I know, right?)
Answer: Assuming you would like to keep a full backup of the data on each backup device you may want to consider LBackup, which features an extendable pre / post scripting sub system which allows you to handle bakcups to disk images and even removable media such as an external hard drives / memory sticks.
This page from the LBackup developer section provides a means to detect an attached disk and then mount that disk. By modifying the fstab you may prevent devices from mounting automatically.
Essentially, this setup will allow you to have a number of removable drives which may be rotated and which will automatically be unmounted from the system once the backup finishes. You could even add a post action script to notify you (via email, txt, call, beep, speak etc.) that the backup has completed successfully and that the disk is ready to be taken off site.
Finally, if you are using 3.5" hard disks you could reduce the cost of removable drive enclosures by using something like the RTX110-3Q and protective drive cases from WiebeTech. With that kind of system in place you could just rotate the bare drives which could save you some cash on enclosures (you mentioned you wanted to keep the price down).
Just some thoughts which may be helpful. I initially, wrote the script (listed above) for detecting drives connected via USB. This was because I arranged a backup a friends system which had no internet connection. The backup was performed to a set of rotated USB flash drives. The data was then encrypted using software encryption to the USB sticks should they be lost in transit.
Using the scripting sub system you could add additional checks such as file system integrity checks prior to backup, media integrity checks and even checksums for the snap shots.
Finally, with regards encryption, WiebeTech offers drive enclosures which support hardware encryption.
Disclaimer : I am involved with the development of the free as in free LBackup project.
Comment: If you haven't already, you might want to check out the [FAQ](http://serverfault.com/faq#promotion), particularly the part about being here for the wrong reasons.


Multiselector doesn't execute animations simultaneously in jQuery

Question: When i run
<code>$("[id^=menuItem]").fadeOut(1000);
</code>
the fading out is done simultaneously to all the components. However, bore that i execut a for loop doing something else to the elements, upon the completion of which i wish to fade out all of them at the same time by
<code>var i;
for(i = 1; i <= 6; i++)
    $("div#item" + i).delay(i * 1000).fadeIn(1500);
$("[id^=item]").fadeOut(400);
</code>
For some reason, the fading out starts on the first element before the second, which is started before the third etc. It creates a very cool effect, indeed, but it's not what i need to achieve in my project.
Why does it happen??
I suspect that the answer will be that the final fading out starts as soon as each component is done with the initial fading in. In that case, my question will be reformulated to how one can delay the execution of the multiselected fadeout until a certain something has been finished (i.e. the last item has done fading in).
Answer: It has probably to do with the fact that the different components get ready for the next step at different times. Maybe i should use callback function after the fade in. Of course, that would execute a whole bunch callbacks so one will need to use $.when/.then syntax.


Is it possible to configure trunking between a NetGear Switch and a Cisco Router?

Question: Hardware:
Cisco 2921 Router
Netgear GS752TXS Switch.  Tags data with either Vlan1 (192.168.1.0/24) or Vlan2 (192.168.2.0/24) depending on mac address.
I want the cisco router to perform inter-vlan routing. The switch and the router will be connected with one cable on one interface.
I created sub-interfaces for the two VLANs on the router (Gi0/0.1) and (Gi0/0.2) and enabled dot1q encapsulation.
On the switch side if it were cisco, I would do:
interface gi0/0
switchport trunk encapsulation dot1q
switchport mode trunk
How do I do this on a netgear switch?
Answer: i'm not very familiar with netgear devices. the config seems do be similar to HP Switches. You had to set the Interfaces Tagged or Untagged for the VLAN IDs.
Example Port1 is connected to the Router:

set vlan1 UNTAGGED on Port 1 (it's the native Vlan; dot1q Frames are send in the native Vlan)
set all other Vlans you want to transport on this interface TAGGED on Port1

This is different to Cisco Trunks you had to specify each VLan you want to transport on the Trunk Link. I configured a few Trunks between Cisco and HP and this is the way how it works.
Have a look at:
http://documentation.netgear.com/gs108t/enu/202-10337-01/GS108T_UM-10-3.html
Comment: cisco and netgear have different meanings for the term trunk.  For netgear it means port aggregation, cisco it means tagged for all vlans
Comment: Thank you for replying.

Hmm I'm not sure what you mean.  The switch is already tagging the data with the proper VLAN's.  What I'm wondering is how I change the interface on the netgear switch that will connect to the router to a trunk port. (Or if that's even necessary).  I will have a very brief window to test this so I want to get the config right before I do it.
Comment: If you tag multiple vlans on a port it will effectively create a trunk if the port on the opposite side is also tagging the same vlans.
Comment: a little more detail in my answer now
Comment: @JamesRyan This is exactly why I'm confused.  The manual refers to trunking but it's really aggregation.  User1008764: When you say "this is different to cisco trunks you had to specify each Vlans you want to transport on the Trunk Link" I don't know what you mean.  On the cisco switch I just enable trunking and encapsulation.  No need to specify the VLANs it will be passing. NickW: So you're saying as long as I tag multiple VLANs on the netgear's interface, it will work?
Comment: configuring a Trunk Port on Cisco Devices means that all Frames going out that Interface are encapsulated with a dot1q Header and are transported via the Native VLan. Per default the native VLan is VLan 1. The VLAN ID of the original Frame is "tagged" within the dot1q Header. All VLans are transported via this Trunk and there is nothing else to do. If your Native VLan is not VLan 1 you had to specify the Native VLan Id in the Trunk configuraion.
Comment: too long comment. so here we continue: On Netgear and HP Switches you always had to specify the Native VLAN with the untagged command -> Vlan 1 untagged port1. And there is a second step to do. You had to specify which VLans should use this Link -> vlan 2 tagged Port 1, vlan 3 tagged port 1,...
Comment: So to confirm, this is the setup I'm going with.

On the Cisco Device, I'm creating the subinterfaces 192.168.1.1 VLAN10 and 192.168.2.1 VLAN20 on the Gi0/0 port.

Then on the Netgear Switch:  Put the access ports in their respective VLANs as untagged, and then put the trunk port as tagged in both VLAN 10 and 20.  Anything else?
Comment: yes on the netgear switch set the trunk port untagged for vlan1. that's all.


How to make for efficent nested loop with a pandas dataframe

Question: the below python code works with a pandas dataframe but I was wondering how to make it more efficient.
columns = list(data)
lenn=len(columns)
lenn

i=0
while i<lenn:
    j=i+1
    while j <lenn:
        print(data.iloc[:,i]*data.iloc[:,j])
        #print(data.iloc[:,j])
        j=j+1
    i=i+1

Answer: We can do shift
data.shift(axis=1)*data

Update 1
s=data.shift(axis=1)*data
for x in list(s):
    print(s.loc[:,s])

Update 2
for x in list(data):
    print(data.loc[:,x],data.shift(axis=1).loc[:,x])

Update 3
import itertools
t=list(itertools.combinations(range(df.shape[1]), 2))
for x in t:
    print(data.iloc[:,x[0]],data.iloc[:,x[1]])

Comment: amazing! but what if I wanted to select each column?
Comment: @andrewcz change the shift to shift(1), check the update
Comment: does that select each column individually? what is i wanted to print out each column?
Comment: @andrewcz will update, also if the update work for you , would you like accept, check mark at the left
Comment: Amazing! thank you so much for your help!! what if just wanted to print out the columns not multiply them. just select every adjacent column?
Comment: If I wanted to print columns 1,2 and 1,3  and 1,4 and then 2,3  2,4 and 3,4....
Comment: Thats amazing!! yes!! Thank you!! although i dont really understand the code. Is there a simpler way possibly.
Comment: @andrewcz check what i did by using intertools in here https://stackoverflow.com/questions/36429507/python-combinations-without-repetitions


Qual é a permissão correta para pastas em servidores linux em produção?

Question: Lendo o manual do PHP e alguns tutorias fiquei em dúvida sobre qual permissão deixar nas pastas após uploads de imagens. Alguns tutorias falam para deixar como 0755, outras como 0750, qual usar neste caso para a segurança da aplicação e servidor na web?
1º Exemplo:
chmod ("/arquivo/diretorio", 0755);

2º Exemplo:
chmod ("/arquivo/diretorio", 0750);

Comment: Não existe uma única maneira correta. Tem que entender como funciona e usar a que atende seu caso específico. Copiar de algum lugar é péssima idéia.
Comment: O problema é que depende de toda uma série de coisas no ambiente de instalação, fica complexa uma resposta cobrindo todos os casos. Depende de quem é o Owner da pasta, depende se vai querer acesso por FTP também, tem que saber quem é o usuário do webserver (que geralmente é o do PHP também), e assim por diante. Cada caso é um caso. Em geral, "quanto menos melhor" desde que a aplicação funcione. Se funcionar com 700, não precisa de 750, se precisar de 750, mas funcionar bem, não precisa de 755, mas isso é uma simplificação muito grande. Tem muito detalhe em "jogo". Melhor estudar e entender.
Comment: Marquei a duplicata, pq quem pesquisar essa aqui vai achar a resposta mais detalhada também, já que a resposta aceita é na linha daquela outra..
Comment: @Bacco, obrigado pela resposta, não deixando acesso total ou seja 0777 ta valendo então? Se quiser deixar uma resposta!
Comment: Entendi, valeu!
Comment: Boa, mas tinha dado uma busca antes,  veio muitas mas não essa! Mas o link me ajudou muito, obrigado mesmo. ;)
Answer: A permissão é dada da seguinte forma:
o primeiro octeto é a permissão para o usuário (dono do arquivo), o segundo octeto é para o grupo, o terceiro octeto é para todos os outros usuários. É importante você deixar a permissão mínima para usuários desconhecidos para evitar ataques no servidor.


Criptografia de uma classe em C#

Question: Tenho o seguinte código em PHP:
<code>    $params = json_decode(trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $api_secret, base64_decode($enc_request), MCRYPT_MODE_ECB)));
</code>
Onde o resultado é um array e não uma string.
Os meus dados que preciso enviar são esses:
<code>Dados dados = new Dados ();

dados.Controller = "Get";
dados.Action = "FindIdUsuario_get";
dados.Email = "firstname.lastname@example.com";
dados.Pass = "teste";
</code>
Como faço pra criptografar esses classe usando Rijndael para enviar na minha url?
UPDATE
Segue o código da criptografia que uso em php:
<code>$request_params = array();
$request_params['controller'] = 'Get';
$request_params['action'] = 'FindIdUsuario_get';
$request_params['email'] = 'email@example.com';
$request_params['pass'] = 'teste';
echo base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $public_key, json_encode($request_params), MCRYPT_MODE_ECB));
</code>
Comment: http://stackoverflow.com/questions/20567056/rijndael-encryption-decryption-c-sharp-vs-php
Comment: não vai rolar isso que vc quer fazer.
Comment: Resposta curta: serialize o objeto em JSON, encripte, do outro lado decripte e de-serialize o JSON de volta num objeto. Porém: a) por que passar via GET, e não via POST? b) por que não usar SSL/TLS em vez de uma criptografia "feita à mão"? c) os dois lados da comunicação possuem a chave secreta? d) **NUNCA** USE O MODO ECB NA PRÁTICA!!! Use um modo mais seguro, como CBC ou CTR, ou melhor ainda um autenticado, como OCB/CCM/GCM/EAX.
Comment: Eu não quero criptografar uma string, e sim um classe.
Comment: P.S. Se o código em PHP não puder ser modificado por algum motivo (por exemplo, se ele for de terceiros) e tudo o que você precisa é criar um código C# "compatível", por favor edite sua pergunta dando um exemplo de resultado esperado, aí talvez possamos te ajudar melhor (mas fica ainda a ressalva de que usar ECB não é seguro na prática, em particular se você enviar o mesmo bloco mais de uma vez).
Comment: O que é esse `$public_key`? O AES/Rijndael é um algoritmo de criptografia **simétrica**, de modo que a mesma chave é usada pra cifrar e pra decifrar. Por acaso essa variável é a mesma coisa que `$api_secret`?
Comment: E a mesma sim. Eu só quero saber como fazer a criptografia de um array em c# da mesma forma que faço em PHP.
Answer: Classes são conjuntos de dados. Basicamente (e totalmente a grosso modo) é uma estrutura. Você até poderia manipular em baixo nível e criptografar essa classe, mas a partir deste feito, o VM não reconhecerá mais esta classe e eliminará ela da memória.
Se deseja ocultar TODOS os dados dessa classe, tem que aplicar criptografia a cada campo do mesmo, já que por baixo dos panos estes dados estarão sequenciais e não existirá essa divisão bonita e legível que vemos na hora de programar, deixando a "Classe" totalmente criptografada.
Para enviar este mesmo por uma URL, basta tu organizar em uma string maior, criptografar esta string e passar. Outro método MUITO MELHOR é por Post (form).

Criptografia de uma classe em C#


How to schedule a task to run every x-minutes on Windows Server 2003 R2

Question: How to add a scheduled task that should run every x-minutes on Windows Server 2003 R2.
I have followed many suggestion from the web, but I always end up with some interruption after 1 or 2 runs.
Here is what I did:

New Scheduled Task
Schedule > Daily Task 08:00 AM, every 1 day
Schedule > Advanced > Repeat task every 30 minutes, duration 31 minutes (why???)
Enabled it

Not working after 1 run and the next run time is +1 day at 08:00 AM
How to fix this problem?
Comment: Show us the schedule log, that will help figure it out. Also, check the System event log for the times it fails.
Comment: @mfinni where can I find schedule log? Not sure if it fails or it is just the logic. But lets start with schedule log.
Comment: @mfinni found it
Answer: It sounds like the task might not be completing successfully, and multiple instances of the task might be trying to run at the same time.
Open up Scheduled Tasks from the Control Panel.
Right click on the task you've created and click "Properties."
Navigate to the "Schedule" tab.
Choose the start time (00:10 AM)
Make sure that Schedule Task Daily is set to Every 1 day(s).
Click Advanced.
Check the "Repeat Task" checkbox.
Until: (select bullet) Time: (enter 11:59 PM) and click "OK"
Open the "Settings" tab now.
[Check] Stop the task if it runs for: [0] hour(s) and [9] minute(s).  Click "OK" This will prevent multiple instances of the scheduled task from running at the same time, possibly causing the conflicts you've described.
If the scheduled task is set to run every 30 minutes, set it to stop the task after 29 minutes (in case it hangs for some reason).
If this is the problem you'll want to look at what your task is doing, and see what might be causing it to hang.  A successfully executed task will exit with Last Result = 0x0.
Answer: You can try this:
<code>schtasks /create /tn "Task Name" /tr <path to script> /sc minute /mo 10
</code>
This task will run every 10 minutes, the first time is right after you make this command.
Answer: Schedule the task in this way:

Daily at 00:00 AM, every 1 day
Repeat task every x minutes to 11:59 PM (or duration: 23h 59m)

Duration 31 minutes will cause the task to be repeated only once (so it will be run at 8:00 AM and 8:30 AM).
Comment: +1 because I never even thought of trying to use 00:00 AM. I can never seem to remember when 12:00 AM or PM occurs. Afternoon or Midnight... why is that so hard I wonder? Thanks!
Comment: Well, I use 24-hour format on daily basis, I used AM/PM notation because John used it. Now I see I made a mistake. I should wrote 12:00 AM. And it looks like this is quite common problem for many people: http://en.wikipedia.org/wiki/12-hour_clock#Confusion_at_noon_and_midnight
Comment: +1 for the clearing what the "stop task if it runs longer than " really does. That is - if you say "stop after 5 hours", those "5 hours" are about the complete task length, together with all of its repetitions. And not about the duration of just one action trigger, that is - not about one repetition.
Answer: The duration specifies how long you want to keep repeating the task. Set the duration to 23 hours and 59 minutes and your task will repeat every 30mins for the duration of an entire day. http://support.microsoft.com/kb/814596


Folland's ''Real Analysis'': Proving the Chain Rule.

Question: In Folland's Real Analysis, Second Edition, he proves the chain rule as Proposition 3.9:
''Suppose that $\nu$ is a $\sigma$-finite signed measure and $\mu, \lambda$ are $\sigma$-finite measures on $(X, \scr{M})$ such that $\nu < \!\! < \mu$ and $\mu < \!\! < \lambda$.
a.  If $g \in L^1(\nu)$, then $g(d\nu / d\mu) \in L^1(\mu)$ and
\begin{equation} \int g d\nu = \int g \frac{d\nu}{d\mu}. \end{equation}
b.  We have $\nu < \!\! < \mu$, and
\begin{equation} \frac{d\nu}{d\lambda} = \frac{d\nu}{d\mu}\frac{d\mu}{d\lambda} \;\;\;\; \mu-\text{a.e.''} \end{equation}
Assume that (a) has been proven.  In Folland's proof of (b), he immediately asks the reader to set $g = \chi_E (d\nu / d\mu)$, in preparation to use (a), where $E \in \scr{M}$ is arbitrary.
My question is this:  In the case that $|\nu|(E) = \infty$, how do we know that $g \in L^1(\mu)$, as the hypotheses of (a) demands.  Of course, if it were the case that $|\nu|(E) < \infty$, then $\chi_E \in L^1(\nu)$ and so $g \in L^1(\mu)$ by applying (a) to $g' = \chi_E$.  But in the case that $|\nu|(E) = \infty$, it seems that we must rely on the $\sigma$-finiteness of $\nu$ to show $g \in L^1(\mu)$.
I am fairly sure that this is a straightforward application of the definitions plus the MCT (or some variant of this idea), but I have not been able to put the pieces together correctly, it seems.  Any clarification would be greatly appreciated.
Thanks.
Answer: The following is the original proof in Folland:

Note that in the beginning of the proof, we have the assumption that $\nu\geq 0$. In the case that $\nu(E)=\infty$ (with assumption $\nu\geq 0$), instead of showing $g=\chi_E(d\nu/d\mu)$ is in $L^1(\mu)$, one needs to use the $\sigma$-finiteness to reduce the proof to the finite case.
Answer: This doesn't exactly answer the question directly, but it sufficed for me.
An excellent proof of this chain rule that completely avoids the roadblock discussed in my original question can be found here:
http://unapologetic.wordpress.com/2010/07/12/the-radon-nikodym-chain-rule/


Laravel csrf token within PHP form

Question: I created a little helper function for accepting friend requests. This function lies within a PHP file (obviously) and looks like this:
(Only the relevant part)
foreach($friendrequests as $request){
    $username = DB::table('users')->where('id', $request->sender_id)->value('name');
    $notify .= '
';
    $notify .= ''.$username.'
möchte dein Freund sein';
    $notify .= '<form action="/friend/request/accept/'.$request->sender_id.'" method="post"><input type="hidden" name="_token" value="csrf_field();"><button type="submit">Akzeptieren</button></form>';
    $notify .= '<form action="/friend/request/deny/'.$request->sender_id.'" method="post"><input type="hidden" name="_token" value="csrf_field();"><button type="submit">Ablehnen</button></form>';
    $notify .= '
';
}

I know it's kind of messy. I'm fairly new to Laravel.
Anyway, there are two forms. One for accepting and one for denying the request. Now the thing I'm struggling with is the csrf token.
How do I implement this within the PHP helper file? I know how to use them in the blade templates, but I can't seem to make it work within the helper function.
Answer: Try to add _token hidden element to your code as below. You can also use csrf_token() helper function  to add the form token inside forms.
foreach($friendrequests as $request){
        $username = DB::table('users')->where('id', $request->sender_id)->value('name');
        $notify .= '
';
        $notify .= ''.$username.'
möchte dein Freund sein';
        $notify .= '<form action="/friend/request/accept/'.$request->sender_id.'" method="post"><input type="hidden" name="_token" value="'.Session::token().'"><button type="submit">Akzeptieren</button></form>';
        $notify .= '<form action="/friend/request/deny/'.$request->sender_id.'" method="post"><input type="hidden" name="_token" value="'.Session::token().'"><button type="submit">Ablehnen</button></form>';
        $notify .= '
';
    }

Answer: You have added the fields, but you need to concatenate the csrf_token() value to your string. Right now, it will literaly print csrf_token as value.
Try this:
$notify .= '<form action="/friend/request/accept/'.$request->sender_id.'" method="post"><input type="hidden" name="_token" value="' . csrf_token() . '"><button type="submit">Akzeptieren</button></form>';

Also, the csrf_field() function will echo an input field with the tokens value to the current request, csrf_token() will display only the token value.

Laravel csrf token within PHP form


Center uneven row in table

Question: I have a table with two rows; one with 5 definitions and one with 4. Is there anyway to get the second row to be in the center of the top row where the columns don't line up?

        Standard Solenoid
        "Classic" Solenoid
        Manual Lever
        Palm Button
        Foot Pedal/Treadle

        Cam Roller
        Piston
        Remote Pilot
        Differential Pilot

Comment: do you mean something like the »colspan« attribute of the  ??
Comment: no because colspan would push the second row off center and that is not what i am trying to achieve
Answer: wrap the second row in another table and put the whole thing into one  that has a colspan of 5 like this...
http://jsfiddle.net/FzUhA/1/

        Standard Solenoid
        "Classic" Solenoid
        Manual Lever
        Palm Button
        Foot Pedal/Treadle

           Cam Roller
           Piston
           Remote Pilot
           Differential Pilot

Comment: ha... well... I haven't used tables in this way since 1997, so, "oldschoolz" the only approach I have to solve this particular problem.
Answer: This moves the second row to the center, it has equal spacing on the left and the right side. See fiddle

        Standard Solenoid
        "Classic" Solenoid
        Manual Lever
        Palm Button
        Foot Pedal/Treadle

        Cam Roller
        Piston
        Remote Pilot
        Differential Pilot

Comment: Only works if you have a border, so no good for me. nice hack tho

Center uneven row in table


.NET core web API, how to change the root name of the XML returned when using IAsyncEnumerable?

Question: I would like to use the new IAsyncEnumerable<T> in my .net core 3.1 web api. This works alright, except I am not happy with the name of the XML root element. It appears to be ArrayOfX and I would like something like Xs. How do I achieve this?
To be more specific. My controller:
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    [HttpGet]
    public async IAsyncEnumerable<WeatherForecast> Get()
    {
        await Task.Delay(0);
        var rng = new Random();

        for (var index = 1; index < 5; index++)
        {
            yield return new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            };
        }
    }
}

public class WeatherForecast
{
    public DateTime Date { get; set; }
    public int TemperatureC { get; set; }
    public string Summary { get; set; }
}

In Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.AddMvcCore(options =>
        {
            options.OutputFormatters.Clear(); // Remove json for simplicity
            options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
        });
}

And the XML output:
<ArrayOfWeatherForecast xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><WeatherForecast><Date>2020-03-26T08:39:59.2303161+01:00</Date><TemperatureC>-13</TemperatureC>Warm</WeatherForecast><WeatherForecast><Date>2020-03-27T08:39:59.2389359+01:00</Date><TemperatureC>22</TemperatureC>Sweltering</WeatherForecast><WeatherForecast><Date>2020-03-28T08:39:59.2389696+01:00</Date><TemperatureC>33</TemperatureC>Scorching</WeatherForecast><WeatherForecast><Date>2020-03-29T08:39:59.2389719+02:00</Date><TemperatureC>-2</TemperatureC>Bracing</WeatherForecast></ArrayOfWeatherForecast>

How do I get WeatherForecasts instead of ArrayOfWeatherForecast?
Comment: Looks like the issue is probably in ControllerBase.  With Xml serialization you current have public WeatherForecast[] WeatherForeCast { get;set;} To fix you need to add before the previous line [XmlElement("WeatherVoreCast")].  I believe that is burried in the ControllerBase code.
Comment: @jdweng My demo project is based on a Microsoft template with a few modifications, all of these listed above. There is no property of type WeatherForecast[], only the Get() method in the controller. And ControllerBase is part of standard mvc (namespace Microsoft.AspNetCore.Mvc). So I am not sure what you mean.
Comment: That is what I thought.  The service is automatically when it see the array creating two xml tags (ArrayOfWeatherForecast,and WeatherForecast).  The service is using Xml Serialization to read/write XML.  Xml doesn't allow an array as the root element.  If you have only one WeatherForeCast the remove the Enumerable from IAsyncEnumerable.
Comment: @jdweng I would like to use the IAsyncEnumerable (see https://learn.microsoft.com/en-us/aspnet/core/web-api/action-return-types?view=aspnetcore-3.0 for further details) to return multiple items. But thanks for your suggestion.
Comment: You can't have your cake and have pie too.  If you want IAsyncEnumerable as root element in xml then you are going to live with ArrayOfWeatherForecast.  Since your can't have an array as root in xml with serialization.
Comment: @jdweng I still hope I can. See https://stackoverflow.com/questions/13056518/remove-arrayof-from-mvc-web-api-response for a similar case.
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/210300/discussion-between-jesper-mygind-and-jdweng).
Answer: You could write your own XmlSerializerOutputFormatter like below:
public class MyCustomXmlSerializerOutputFormatter : XmlSerializerOutputFormatter
{
    protected override void Serialize(XmlSerializer xmlSerializer, XmlWriter xmlWriter, object value)
    {

        xmlSerializer = new XmlSerializer(typeof(List<WeatherForecast>) ,new XmlRootAttribute("WeatherForecasts"));

        xmlSerializer.Serialize(xmlWriter, value);
    }
}

Startup.cs
public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        services.AddMvcCore(options =>
        {
            options.OutputFormatters.Clear(); // Remove json for simplicity
            options.OutputFormatters.Add(new MyCustomXmlSerializerOutputFormatter());
        });
    }

Result:
Comment: Absolutely perfect. Thanks


Split command equivalent/replacement that gives total count of pieces/parts?

Question: The standard split command on Unix/Linux allows you to split files into fixed size pieces in terms of bytes or lines, with the output file names suffixed with letters or numbers (e.g. PREFIXaa, PREFIXab, ... or PREFIX1, PREFIX2, ...)
However, it's not clear from the output names alone how many pieces there should be.
Is there a standard tool that will do this, i.e. outputting to e.g. PREFIX1of4, PREFIX2of4... or similar? Or is this a job for Perl (i.e. I find a Perl script).
Thanks!
Wodow
Answer: if you need to fully identify the "piece number" from the generated "piece files" names you can use "-d" and have the suffix argument to be a directory name where the "piece files" should be generated.  Using "-a" you can specify the number of digits to be used to generate the suffix names.
example: split the file "cfg.pm", 3 lines per output file; use 3 digits for the generated suffixes (making sure the name space isn't exhausted); use number-only suffixes; trick split to generate digit-only file names by specifying a directory as a prefix
mkdir ./s
split -a 3 -l 3 -d cfg.pm s/

after that,
ls s | tail -1

will implicitly give you the number of generated files
ls s|tail -1
414

Comment: errata: "ls s | tail -1" will give you the number of generated files minus 1 because the suffix generator starts with zero
Answer: Picking up from adirau's answer:
If your system has the Perl script called rename (and it's a version that will support doing this) you can rename your files so that each number is incremented by one and have a prefix and a suffix:
count=$(($(ls s | tail -n 1) + 1))
rename "my \$n=sprintf(\"%03d\", \$_+1); my \$c=sprintf(\"%03d\", $count); s/.*/prefix\${n}of\${c}/" *

This would rename the files from:
000
001
002

to:
prefix001of003
prefix002of003
prefix003of003

This is the bulk of that Perl script, by the way:
use strict;

use Getopt::Long;
Getopt::Long::Configure('bundling');

my ($verbose, $no_act, $force, $op);

die "Usage: rename [-v] [-n] [-f] perlexpr [filenames]\n"
    unless GetOptions(
        'v|verbose' => \$verbose,
        'n|no-act'  => \$no_act,
        'f|force'   => \$force,
    ) and $op = shift;

$verbose++ if $no_act;

if (!@ARGV) {
    print "reading filenames from STDIN\n" if $verbose;
    @ARGV = <STDIN>;
    chop(@ARGV);
}
for (@ARGV) {
    my $was = $_;
    eval $op;
    die $@ if $@;
    next if $was eq $_; # ignore quietly
    if (-e $_ and !$force)
    {
        warn  "$was not renamed: $_ already exists\n";
    }
    elsif ($no_act or rename $was, $_)
    {
        print "$was renamed as $_\n" if $verbose;
    }
    else
    {
        warn  "Can't rename $was $_: $!\n";
    }
}


Field type that is an integer, but accept some strings that means no value is provided?

Question: I have a field named "Price" that should allow anything from 0 - no maximum value, so I set it as an Integer and set 0 for the minimum value (and put a suffix to show up for the price).
However, the field contented is generated by parsing a JSON feed, and the feed owner sometimes puts "on demand" for some items, meaning the price can be negotiated on demand or the price is private and only shared when a client shows enough interest to buy.
The Feeds JSONPath Parser module parses the text string and doesn't import the fields with text for the Price field as it's not an Integer. Therefore resulting in a blank field input.
Should I replace all empty values with a 0 and then on view results set 0 to be rewritten to the "on demand" text? Or is there another way that I should explore?
I need to keep the Price field as an Integer since I use it for a range filter in my view.
Comment: Are those the only 2 variations? Either an integer or "on demand"? There's no other status like "free" or "POA" etc?
Comment: @Beebee nope just that it seems for now, it's for apartments/houses to rent or buy, so I assume sometimes they want to keep the price private?
Answer: If you have only one possible non-integer value, leave it as integer, just make it optional (not required). As far as I understand Feeds JSONPath Parser, non-integer value will simply get omitted, giving you no value for this field - exactly consistent as in fact you don't have that price.
Then in your template files check if it's set. If it isn't, show "on demand" string, with a link to make a demand or, well, anything you need.
Comment: Ah yes I'll need to edit my templates too, forgot about those.


Strange vertical line appear in my Android studio

Question: I was working normally with my Android Studio. Normally, I use my real phone to run the app, but today I use the virtual device in Android Studio. When I hide the device manager tab, it shows a strange vertical line in my coding space, which is very annoying to me.
Please see the photo, you can see the line cutting the "String phone".
Comment: check this answer and try solution your problem by it https://stackoverflow.com/a/72709232/11654799
Comment: Setting 'Hard wrap at' to 0 should eliminate it or uncheck 'Show hard wrap and visual guides' in Editor | General | Appearance - can also search in 'Settings' for "hard wrap".
Comment: Does this answer your question? [How to remove the vertical line in the android studio?](https://stackoverflow.com/questions/72708463/how-to-remove-the-vertical-line-in-the-android-studio)
Answer: If the line is at column 80 or 100 or something like this, it is most probably a visual guideline for code width. There should be some option in the settings to either deactivate it or specify the column at which it should be displayed.
Edit: Take a look at this answer that shows how to set the code margin and other options.


Why I cannot convert bitmap to .PNG and save it into storage in Android Oreo Device?

Question: I want to convert android view to image file and save it to internal storage in Android Oreo device. But my following code is not working.
Here is XML code:-
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:id="@+id/layout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        android:background="@color/teal_200"
        android:gravity="center"
        android:orientation="horizontal"
        app:layout_constraintBottom_toTopOf="@+id/btnSaveID"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/kohli" />

    </LinearLayout>

    <Button
        android:id="@+id/btnSaveID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:paddingLeft="50dp"
        android:paddingRight="50dp"
        android:text="@string/save"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/layout1" />

</androidx.constraintlayout.widget.ConstraintLayout>

Here is JAVA code:-
public class MainActivity extends AppCompatActivity {
    LinearLayout layout;
    OutputStream outputStream;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        layout = findViewById(R.id.layout1);

        findViewById(R.id.btnSaveID).setOnClickListener(v -> {

            if (Build.VERSION.SDK_INT >= 23) {
                String requiredPermission = Manifest.permission.READ_EXTERNAL_STORAGE;
                int checkVal = checkCallingOrSelfPermission(requiredPermission);

                if (checkVal == PackageManager.PERMISSION_GRANTED) {
                    saveImage2(layout, MainActivity.this);

                } else {
                    checkPermission(layout);
                }
            } else {
                saveImage2(layout, MainActivity.this);

            }
        });

    }

    private void saveImage2(LinearLayout layout1, Context context) {
        layout1.setDrawingCacheEnabled(true);
        layout1.buildDrawingCache();
        Bitmap bitmap = Bitmap.createBitmap(layout1.getWidth(), layout1.getHeight(), Bitmap.Config.ARGB_8888);
        if (bitmap != null) {
            Canvas canvas = new Canvas(bitmap);
            layout1.draw(canvas);

            Drawable bgDrawable = layout1.getBackground();

            if (bgDrawable != null) {
                bgDrawable.draw(canvas);
            } else {
                canvas.drawColor(Color.WHITE);
            }

            layout1.draw(canvas);
            String name = System.currentTimeMillis() + ".png";
            try {
                savePng(context, bitmap, name);
            } catch (IOException e) {
                e.printStackTrace();
            }
 }
    }

    public static void savePng(Context context, Bitmap bitmap, @NonNull String name) throws IOException {
        Uri uri;
        OutputStream fileOutputStream;
        String path;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            ContentResolver resolver = context.getContentResolver();
            ContentValues contentValues = new ContentValues();
            contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, name + ".png");
            contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/png");
            contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);
            uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
            fileOutputStream = resolver.openOutputStream(Objects.requireNonNull(uri));
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
            fileOutputStream.close();
            Toast.makeText(context, "Saved!", Toast.LENGTH_SHORT).show();
        } else {
            String imagePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
            File image = new File(imagePath, name + ".png");
            fileOutputStream = new FileOutputStream(image);
            uri = getUriFromPath(context, imagePath);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
            fileOutputStream.close();
            Toast.makeText(context, "Saved!", Toast.LENGTH_SHORT).show();
            path = image.getAbsolutePath();
            MediaScannerConnection.scanFile(context, new String[]{path}, new String[]{"image/*"},
                    new MediaScannerConnection.MediaScannerConnectionClient() {
                        public void onMediaScannerConnected() {
                        }
                        public void onScanCompleted(String path, Uri uri) {
                        }
                    });
        }
    }

    private static Uri getUriFromPath(Context context, String imagePath) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
            return FileProvider.getUriForFile(context, "com.noobprogroammer.sampleproject.fileprovider", new File(imagePath));
        return Uri.fromFile(new File(imagePath));
    }

private void checkPermission(LinearLayout layout) {
        PermissionListener permissionListener = new PermissionListener() {
            @Override
            public void onPermissionGranted() {
                saveImage2(layout, MainActivity.this);
            }

            @Override
            public void onPermissionDenied(List<String> deniedPermissions) {
                Toast.makeText(MainActivity.this, "Permission required to download", Toast.LENGTH_SHORT).show();
            }
        };

        TedPermission.with(MainActivity.this)
                .setPermissionListener(permissionListener)
                .setPermissions(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .check();
    }

}

I have add path path also:-
<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path
        name="external_files"
        path="." />
</paths>

Added meta-data to Manifest file:-
<provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="com.noobprogroammer.sampleproject.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" />
        </provider>

I have also add android:requestLegacyExternalStorage="true" and Internet permissions also:-
<uses-permission
        android:name="android.permission.WRITE_EXTERNAL_STORAGE"
        tools:ignore="ScopedStorage" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Can anyone find the issue, why this code is not working on Android Oreo Version?
Comment: Please remove all code and xml and such. Post only the code for savePng() function and tell what does not work.
Comment: Also internet permission and requesting legacy external storage is not needed so you can remove that too.
Answer: XML Code
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingHorizontal="15dp"
tools:context=".MainActivity">

<LinearLayout
    android:id="@+id/layout_view"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:orientation="vertical"
    android:background="@color/purple_200">

    <ImageView
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="30dp"
        android:src="@drawable/ic_launcher_background" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Mizanur Rahaman"
            android:textSize="40dp"
            android:textStyle="bold"
            android:textColor="@color/white"
            android:layout_centerInParent="true"/>

    </RelativeLayout>

</LinearLayout>

<Button
    android:id="@+id/btnConvertToimage"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginVertical="10dp"
    android:text="Convert To Image" />

<ImageView
    android:id="@+id/imgResultImage"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

Java Code
public class MainActivity extends AppCompatActivity {
LinearLayout layout_view;
ImageView imgResultImage;
Button btnConvertToImage;

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

    layout_view = findViewById(R.id.layout_view);
    imgResultImage = findViewById(R.id.imgResultImage);
    btnConvertToImage = findViewById(R.id.btnConvertToimage);

    btnConvertToImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                    convert();
                } else {
                    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 12545);
                }
            }

        }
    });

}

private void convert() {
    Bitmap image = getBitmapFromView(layout_view);
    imgResultImage.setImageBitmap(image);
    saveImage(image);
}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case 12545:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "Accepted", Toast.LENGTH_SHORT).show();
                convert();
            } else {
                Toast.makeText(this, "Denied", Toast.LENGTH_SHORT).show();
            }
            break;
    }
}

    private Bitmap getBitmapFromView(View view) {
        //Define a bitmap with the same size as the view
        Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
        //Bind a canvas to it
        Canvas canvas = new Canvas(returnedBitmap);
        //Get the view's background
        Drawable bgDrawable = view.getBackground();
        if (bgDrawable != null) {
            //has background drawable, then draw it on the canvas
            bgDrawable.draw(canvas);
        } else {
            //does not have background drawable, then draw white background on the canvas
            canvas.drawColor(Color.WHITE);
        }
        // draw the view on the canvas
        view.draw(canvas);
        //return the bitmap
        return returnedBitmap;
    }

private void saveImage(Bitmap bitmap) {
    if (android.os.Build.VERSION.SDK_INT >= 29) {
        ContentValues values = contentValues();
        values.put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/" + getString(R.string.app_name));
        values.put(MediaStore.Images.Media.IS_PENDING, true);

        Uri uri = this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        if (uri != null) {
            try {
                saveImageToStream(bitmap, this.getContentResolver().openOutputStream(uri));
                values.put(MediaStore.Images.Media.IS_PENDING, false);
                this.getContentResolver().update(uri, values, null, null);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

        }
    } else {
        File directory = new File(Environment.getExternalStorageDirectory().toString() + '/' + getString(R.string.app_name));

        if (!directory.exists()) {
            directory.mkdirs();
        }
        String fileName = System.currentTimeMillis() + ".png";
        File file = new File(directory, fileName);
        try {
            saveImageToStream(bitmap, new FileOutputStream(file));
            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
            this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }
}

private ContentValues contentValues() {
    ContentValues values = new ContentValues();
    values.put(MediaStore.Images.Media.MIME_TYPE, "image/png");
    values.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis() / 1000);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
    }
    return values;
}

private void saveImageToStream(Bitmap bitmap, OutputStream outputStream) {
    if (outputStream != null) {
        try {
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

}
Add in manifests
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>


Creating readable links for nodes in a view

Question: I have 2 views setup - one is for a directory listing of nodes and the other displays an individual node from that directory.
The directory view is visible at /directory and can be filtered by letter (e.g. /directory/b will show all nodes whose title starts with b)
Currently, the directory listings link to /directory/show/[nid] but I would like them to be friendlier. For example /directory/show/example-title.
I can get close to this if I check 'Output this field as a link' on the Title field and set the 'Link path' to directory/show/[title]. However, that displays the link as /directory/show/Example Title.
Is it possible for this link to be displayed as /directory/show/example-title somehow?
Answer: First way:
For second Views I assume argument handling is used (NID send as argument).

So you should modify this argument,
Add/change this argument validation - select PHP code
There you should check if this $handler->argument is numeric
if not, try find node by title ($handler->argument will title),
if found, assign to $handler->argument found NID.
Return in code TRUE if argument is numeric or node found by title.

Minus of this for nodes with the same titles, so you can use next way.
Another way is using Rules for that:

Add rule for node creation/editing
Add action and use next PHP code for inserting new alias:
     global $language;
     $path = 'node/' . $node->nid;
     $alias = 'directory/show/' . $node->title;
     path_set_alias($path, $alias, NULL, $language->language);

Be sure that $node accessible in your Rules PHP code action, if not, seek patterns like [nid], etc.
Also you should resave all your required nodes for creating new aliases for these nodes, recommend to use for it VBO module.
Comment: The individual node is also being displayed with a view, I thought about linking straight to the node by it's URL/path alias but the view has a different interface that allows for some filtering/unique navigation to happen. (unfortunately I inherited this project so can't easily make major changes)
Comment: Answer changed due to single node displaying in Views.
Comment: Argument handling now added...
Answer: I solved this in the end by overriding the title field template for my directory view and generating the links in there.
So I had started with output like this:
Example Page
and my overriding title field template contained:
<a href="/directory/show/<?php echo str_replace(' ', '-', strtolower($variable['row']->node_title)); ?>">
    <?php echo $variables['row']->node_title; ?>

Which gave me the desired output:
Example Page
If there's a better solution please let me know.


Confidence Interval of the mean response for Weighted Least Squares (WLS)

Question: I know that the confidence interval of the mean response for OLS is:
$$
\hat{y}(x_0) - t_{\alpha /2, df(error)}\sqrt{\hat{\sigma}^2\cdot x_0'(X'X)^{-1}x_0}
$$
$$
\leq \mu_{y|x_0} \leq \hat{y}(x_0) + t_{\alpha /2, df(error)}\sqrt{\hat{\sigma}^2\cdot x_0'(X'X)^{-1}x_0}  .
$$
(the formula is taken from Myers, Montgomery, Anderson-Cook, "Response Surface Methodology" fourth edition, page 407 and 34)
What would be the confidence interval for WLS ?
Many thanks !
Answer: $\newcommand{\e}{\varepsilon}$TL;DR: If you have
$$
y = X\beta + \e
$$
with $\e \sim \mathcal N(0, \sigma^2 \Omega)$ for $\Omega$ known, then it will be
$$
x_0^T\hat\beta \pm t_{\alpha/2, n-p} \sqrt{\hat\sigma^2 x_0^T(X^T\Omega^{-1}X)^{-1}x_0}
$$
with $\hat\beta = (X^T\Omega^{-1}X)^{-1}X^T\Omega^{-1}y$ and
$$
\hat\sigma^2 = \frac{y^T\Omega^{-1}(I-H)y}{n-p}.
$$
This doesn't require $\Omega$ to be diagonal but it is essential that it is known.

Here's how to derive this.
The MLE of $\beta$ is
$$
\hat\beta = (X^T\Omega^{-1}X)^{-1}X^T\Omega^{-1}y
$$
(this is just generalized least squares).
From this it follows that $\hat\beta$ is still Gaussian and
$$
\text E(\hat\beta) = (X^T\Omega^{-1}X)^{-1}X^T\Omega^{-1}\text E(y) = \beta
$$
and
$$
\text{Var}(\beta) = \sigma^2 (X^T\Omega^{-1}X)^{-1}X^T\Omega^{-1}\Omega \Omega^{-1}X(X^T\Omega^{-1}X)^{-1} \\
= \sigma^2 (X^T\Omega^{-1}X)^{-1}
$$
so all together
$$
\hat\beta \sim \mathcal N(\beta, \sigma^2 (X^T\Omega^{-1}X)^{-1}).
$$

In order to get the confidence interval for the (conditional) mean $\mu_0$ at a particular point $x_0$, we need to determine the distribution of
$$
\frac{\hat y_0 - \mu_0}{\hat {\text{SD}}(\hat y_0)}
$$
so we can get the appropriate quantiles.
We have
$$
\hat y_0 = x_0^T\hat\beta \sim \mathcal N(x_0^T\beta, \sigma^2 x_0^T(X^T\Omega^{-1}X)^{-1} x_0)
$$
so this is
$$
\frac{x_0^T\hat\beta - x_0^T\beta}{\sqrt{\hat \sigma^2 x_0^T(X^T\Omega^{-1}X)^{-1} x_0}} = \frac{x_0^T(\hat\beta - \beta) / \sqrt{x_0^T(X^T\Omega^{-1}X)^{-1} x_0}}{\sqrt{\hat \sigma^2}}.
$$
The numerator of that is still Gaussian, and
$$
\frac{x_0^T(\hat\beta - \beta)}{\sqrt{x_0^T(X^T\Omega^{-1}X)^{-1} x_0}} \sim \mathcal N\left(0, \sigma^2\right).
$$
Recall that a t distribution with $d$ degrees of freedom is defined to be
$$
\frac{\mathcal N(0,1)}{\sqrt{\chi^2_d / d}}
$$
where the two distributions are independent.
We've pretty much got the numerator now so the remaining questions are (1) what's the distribution of $\hat\sigma^2$, and (2) if they are independent or not.
We will want to set
$$
\hat \sigma^2 = \frac{y^T\Omega^{-1}(I-H)y}{n-p}
$$
where
$$
H = X(X^T\Omega^{-1}X)^{-1}X^T\Omega^{-1}
$$
is the GLS hat matrix.
That $\Omega^{-1}$ looks a little weird in $\hat\sigma^2$ so let's check that this is unbiased. Using a standard result about the expected value of a quadratic form (and noting that actually $\Omega^{-1}(I-H)$ is symmetric),
$$
\text E(y^T\Omega^{-1}(I-H)y) = \text{tr}\left(\Omega^{-1}(I-H) \text{Var}(y)\right) + (\text E y)^T \Omega^{-1}(I-H) (\text E y) \\
= \sigma^2 \text{tr} \left(\Omega^{-1}(I-H)\Omega\right) + \beta^TX^T\Omega^{-1}(I-H)X\beta.
$$
Using the cyclicity of the trace, that first term becomes $\sigma^2(n-p)$. For the second term,
$$
X^T\Omega^{-1}(I-H)X = X^T\Omega^{-1}X - X^T\Omega^{-1}X(X^T\Omega^{-1}X)^{-1}X^T\Omega^{-1}X = 0
$$
so $\hat\sigma^2$ is indeed unbiased.
Now for its distribution, note that from $y = X\beta + \e$ we could left-multiply through by $\Omega^{-1/2}$ to get
$$
\underbrace{\Omega^{-1/2}y}_{:= z} = \underbrace{\Omega^{-1/2}X}_{:= Z}\,\beta + \underbrace{\Omega^{-1/2}\e}_{:= \eta}
$$
so this is like a homoscedastic linear model $z = Z\beta + \eta$ with $\eta \sim \mathcal N(0,\sigma^2 I)$. In this case we'd get $H_Z = Z(Z^TZ)^{-1}Z^T$ and from the usual theory (see Cochran's theorem) we get
$$
z^T(I-H_Z)z / \sigma^2 \sim \chi^2_{n-p}.
$$
Note that $H_Z = \Omega^{-1/2}X(X^T\Omega^{-1}X)^{-1}X^T\Omega^{-1/2}$ so
$$
z^T(I-H_Z)z = y^T\Omega^{-1/2}(I - H_Z)\Omega^{-1/2}y \\
= y^T \left[\Omega^{-1} - \Omega^{-1}X(X^T\Omega^{-1}X)^{-1}X^T\Omega^{-1}\right]y \\
= y^T\Omega^{-1}(I-H)y = (n-p)\hat\sigma^2
$$
so that shows both how we'd have come up with $\hat\sigma^2$ in the first place, and that
$$
\frac{(n-p)\hat\sigma^2}{\sigma^2}  \sim \chi^2_{n-p}.
$$
This means that
$$
\frac{x_0^T\hat\beta - x_0^T\beta}{\sqrt{\hat \sigma^2 x_0^T(X^T\Omega^{-1}X)^{-1} x_0}} = \frac{x_0^T(\hat\beta - \beta) / \sqrt{\sigma^2 x_0^T(X^T\Omega^{-1}X)^{-1}x_0}}{\sqrt{\hat\sigma^2 / \sigma^2}}
$$
is exactly of the form $\mathcal N(0,1) / \sqrt{\chi^2_d / d}$.
Independence comes from the unweighted theory, as we know
$$
z^T(I-H_Z)z \perp \hat\beta_Z
$$
but
$$
\hat\beta_Z = (Z^TZ)^{-1}Z^Tz = (X^T\Omega^{-1}X)^{-1}X^T\Omega^{-1}y = \hat\beta
$$
and $z^T(I-H_Z)z = (n-p)\hat\sigma^2$ so we don't need to do any extra work.
Thus with much ado we've proved that
$$
\frac{x_0^T\hat\beta - x_0^T\beta}{\sqrt{\hat \sigma^2 x_0^T(X^T\Omega^{-1}X)^{-1} x_0}} \sim \mathcal t_{n-p}
$$
so you can just use the usual $t_{\alpha/2, n-p}$ quantiles.
Comment: Thank you so much for your answer, it really helped me ! Do you know a book or a paper where I could find the equation of the confidence interval for WLS and the following proof ?
Comment: Another question: am I right to assume that $ \hat\sigma^2 $ is the estimator for the variance in each point and thus is in Matrix form with $ size(\hat\sigma^2)=size(\Omega) $ ?
Comment: @JohnTokkaTacos i don't know of an official reference and I don't have my usual ones handy to check, but possibly Seber and Lee, or maybe an econometrics book. And what do you mean by $size(\cdot)$?
Comment: Thanks, I will check the reference.
My question was if $ \hat\sigma^2 $ was a scalar value or a Matrix. After further research I found that it is a scalar value. If I know my $ \Sigma=\hat\sigma^2 \cdot \Omega $ I can find my scalar value by calculating the weights with $ trace(\Omega)=N $ and $ \hat\sigma^2=\frac{1}{N} \cdot \Sigma \sigma^2_i $. Can you confirm this ?
Comment: @JohnTokkaTacos I'm still not sure what you mean. $\hat\sigma^2$ is definitely a scalar as it comes from a quadratic form. When I write $\text{Var}(\varepsilon) = \sigma^2 \Omega$ I'm saying that the covariance structure is completely known except for a scaling parameter $\sigma^2$, so after estimating $\sigma^2$ then $\text{Var}(\varepsilon)$ is totally known (or at least, totally estimated). For a particular point $y_i$ you'd have $\text{Var}(y_i) = \sigma^2 \Omega_{ii}$ and for two points $y_i, y_j$ you'd get $\text{Cov}(y_i, y_j) = \sigma^2 \Omega_{ij}$
Comment: I'll try to be more clear ! Say I have a measuring device and I measure my response variable Y as a function of an independent variable X. I measure each point several times, in order to calculate the measurement error as a function of X. Now in my case the error depends on X (the bigger X, the bigger the measurement error), thus I am doing WLS. I can obtain a vector of the different measurement errors for different values of X. This vector will be $ Var(\epsilon) $. Now I have to calculate $ \Omega $ and $ \sigma^2 $, the latter being the scaling parameter. By which method should I do this ?
Comment: @JohnTokkaTacos $\varepsilon$ represents the error in every single observation. If you measure $y_1,\dots,y_k$ all with some noise but for the same X value, i.e. $x_1 = \dots = x_k$, you'll still have $\text{Var}(\varepsilon)$ as a $k\times k$ matrix. Also as I've emphasized in my answer, this assumes $\Omega$ is known. So like in WLS if you model $\text{Var}(y_i) = \sigma^2 x_i$ now you'd have $\Omega = \text{diag}(x_1, \dots, x_n)$ (assuming here that the $x_i$ are scalars too) so there's no estimation there. Unless you have measurement errors in X? But that's a different problem


Behaviour of likelihood ratio test as sample size increases

Question: I know that the log likelihood statistic, i.e. $X^2=-2(LL_1 - LL_2)$ where $LL_1$ and $LL_2$ are the maximum log likelihoods of two models, one nested in the other, is asymptotically distributed as a chi-squared variate with degrees of freedom equal to the difference in the number of free parameters between the two models as $n \rightarrow \infty$; $n$ is the sample size of the data.
My question: is the difference between the sampling distribution of $X^2$ and the theoretical chi-squared distribution always decreasing as n increases?  If we compare the difference given two different sample sizes, is the approximation of a theoretical chi-square distribution always better at the larger sample size?
I ask because, in simulations of a rather complicated model, the sampling distribution of $X^2$ does come closer to the theoretical distribution as $n$ increases up to a point and then, as $n$ increases further, the fit between the two gets worse.  I did not expect this behaviour and cannot find an explanation.
Comment: I have used 5000 independent simulations each time, and have varied the sample size (n) from 50, 100, 200, 500 and 1000
Comment: For how many simulations (repeated samples) have you assessed the convergence to the Chi2? That is, you are evaluating the convergence at different n. Perfect. Then how many simulations/repeated samples for each n have you performed?
Comment: Could you include some more details of the model and simulations? Maybe show some plots?
Answer: It's not clear to me if this is implied in the original question, but if the data follow the alternate hypothesis rather than the null one, the statistic will tend asymptotically toward a noncentral, rather than standard, $\chi^2$.  Also, there are circumstances in which the asymptotic result doesn't hold, eg https://stats.stackexchange.com/a/52855/163989.  More information on the problem, including some plots, could help.


In UEFA competitions, could a team forfeit a game and still qualify?

Question: My understanding is that, in UEFA football games, a forfeiting team is awarded a 0-3 score (defeat) against the opposing team.
If, in a competition, a team wins the first game 4-0, could the same team decide to forfeit the second leg, so losing 3-0 and assuring it would still qualify to the next round? (I understand this is hypothetical)
Comment: Depends way too much on what competition you're asking about, and there are about as many regulations on this as there are competitions to run them.
Comment: Sure, but it's a fairly good guide as to how other organising bodies would treat this kind of stunt.
Comment: Related: [In which game was a limited overs innings declared to prevent an opponent from qualifying?](https://sports.stackexchange.com/questions/7465/in-which-game-was-a-limited-overs-innings-declared-to-prevent-an-opponent-from-q/). tl;dr: somebody tried this trick. They were thrown out of the competition.
Comment: The tag is for football
Comment: This is also a duplicate of a previous question, which uses UEFA as an explicit example, https://sports.stackexchange.com/questions/3993/is-a-match-forfeit-always-scored-as-3-0-regardless-of-situation.
Answer: Since you explicitly mentioned the UEFA, I'll answer your question using their regulations. And the answer is no. That's not possible.
The UEFA does not allow this behavior in their competitions.
If a team does not play a match or is responsible for it to not take place in any way that team will be disqualified and fined. This means the opponent will advance to the next round, if applicable.
The rules for the Europa League and Champions League are the same in this particular case.
Article 26 in the EL and 28 in the CL:

Refusal to play and similar cases
If a club refuses to play or is responsible for a match not taking
  place or not being played in full, the UEFA Control, Ethics and
  Disciplinary Body declares the match forfeited and disqualifies the
  club concerned in combination with the following fines (...)


a question about calculus?

Question: is calculus about finding the rate of change  of a function ? or are we trying to find the Slope ( Gradient ) of a Curve ??
are differential calculus and differential equation the same thing ??
Comment: These questions seem too general, maybe consult a summary of calculus...
Answer: From Wikipedia:

Calculus is the mathematical study of change, in the same way that geometry is the study of shape and algebra is the study of operations and their application to solving equations. It has two major branches, differential calculus (concerning rates of change and slopes of curves), and integral calculus (concerning accumulation of quantities and the areas under and between curves); these two branches are related to each other by the fundamental theorem of calculus.

Differential calculus and differential equation are not the same thing, but related. Differential calculus deals with the study of basically everything concerning derivatives, and differential equations are one of those things. So one could say that the study of differential equations is a subfield of differential calculus.

a question about calculus?


Adicionar HTML com JavaScript e Permanecer

Question: Estou querendo que seja possível adicionar e depois quando atualize a página ele permaneça salvo no meu HTML.

.menu {
  width: 100%;
  height: 70px;
  background-color: #56B8BD;
  max-height: 70px;
}

.menu ul li {
  float: left;
  list-style: none;
  text-decoration: none;
  color: #FFF;
  font-size: 18px;
  font-weight: bold;
  padding-top: 1%;
}

button {
  width: 56px;
  height: 56px;
  border-radius: 56px;
  font-size: 18px;
  border: none;
  float: right;
  margin-right: 1%;
  margin-top: 0.25%;
}

button:hover {
  transform: scale(1.03);
}

 Barra Menu

    <button onclick="adicionar()">+</button>

Comment: Você precisa persistir essas alterações em algum lugar, seja em banco de dados, localStorage, sessão, memória, arquivo em disco, etc, depende das suas necessidades.
Comment: Não sei se entendi, mas você quer que essa nova `div` seja adicionada ao seu arquivo HTML depois de gerada?
Comment: Seria isto mesmo mas n sei como fazer isso se vocês puderem ajudar
Comment: Que tal localstorage? veja se funciona ai http://kithomepage.com/sos/adicionado.htm
Answer: Para configurar sua conexão ao Banco Mysql em PHP:
<?php
   $db_name = "[Nome do seu banco]";
   $db_user = "[Nome de usuario do seu banco]";
   $db_password = "[Senha do banco]";
   $db_host = "[Host do banco]";

   $conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

   if(!$conn)
        echo "Erro na conexão";

   //Para inserir a quantidade de DIV's
   $sql = "INSERT INTO [Nome da sua tabela] ([nome da coluna])
               VALUES ([valor a ser adicionado])";

   if ($conn->query($sql) === TRUE) {
      echo "Sucesso!";
   } else {
      echo "Error";
   }

   //Para buscar um valor no banco
   $sql = "SELECT * FROM [Nome da sua tabela]";
   $result = $conn->query($sql);

   //Dae voce usa a var result para manipular os dados do BD
?>

Comment: vou dar uma olhada aqui
Comment: Deu certinho vleu amigo