Syntax Error invalid syntax for def Data(path)

Question: Here is the line of code where I am getting an error
def Data('C:/Users/username/Desktop/d.txt'):
    fp = open('C:/Users/username/Desktop/d.txt')

I get the following error:
File "read.py", line 17
    def DataExtract('C:/Users/username/Desktop/d.txt'):
                                                    ^
SyntaxError: invalid syntax

Not sure what the problem is and what is causing the invalid syntax
Thank you!
Here is the code I am working on:
def DataExtract('C:/Users/username/Desktop/d.txt'):
fp = open('C:/Users/username/Desktop/d.txt')
data = {}
line = fp.read().split("\n")[2:7:5]:
while line:
    name, _, cont = line.partition(":")
    keys, _, values = cont.partition("=")
    keys = keys.split(",")
    values = values.split(",")
    temp_d = {}
    for i in range(len(keys)):
        key = key[i].strip()
        val = values[i].strip()
        temp_d[key] = float(val)
    data[name] = temp_d
    line = fp.readline()
fp.close()

return data
x = DataExtract('C:/Users/username/Desktop/d.txt')
mul_p = x['d1']['p'] * x['d2']['p']
print(mul_p)

Comment: Your function definitions and calls are not matching up?
Comment: Do you mind explaining what you mean a little further?
Comment: Couple of issues,  your indentation under the def is not correct.  all lines should move right about 3 spaces, 2nd your def line should not have the 'path' in it.  it should have nothing or the variables that the passed in parameters are set to.
Comment: This is weird. You asked a question and I gave you this function as answer here. https://stackoverflow.com/questions/57640068/reading-a-tuple-assignment-e-g-written-as-such-d1-p-m-h-20-15-22-from/57640467#57640467 You told me its not working and I told you why. And now you are asking it as a new question itself -_-
Comment: Yes, I tried your code; but it didn't work and I think it was because I was not understanding some parts of it and not using the code right. I am new to python and not sure how things work just yet. I am just trying to learn some of the details where I get errors on. But I am still working on the code you gave me...thank you
Answer: As mentioned earlier in the comments by @LhasaDad.
I am observing two errors in your attached code.
First Error:
First is the "def" statement. The function needs a variable placeholder not the value of the variable. For example:
>>> def fun('hello'):
  File "<stdin>", line 1
    def fun('hello'):
                  ^
SyntaxError: invalid syntax
>>> def fun(5):
  File "<stdin>", line 1
    def fun(5):
            ^
SyntaxError: invalid syntax

The correct way is

>>> def fun(var):
...     print(var)
...
>>> #Then call the function using below method
...
>>> fun('hello')
hello
>>> fun(5)
5

Second Error:
There should always be and indentation (tab or 4 spaces gap after a def statement)
So in your case hopefully this will work
def DataExtract(file_path):
    fp = open(file_path)
    data = {}
    line = fp.read().split("\n")[2:7:5]
    while line:
        name, _, cont = line.partition(":")
        keys, _, values = cont.partition("=")
        keys = keys.split(",")
        values = values.split(",")
        temp_d = {}
        for i in range(len(keys)):
            key = keys[i].strip()
            val = values[i].strip()
            temp_d[key] = float(val)
        data[name] = temp_d
        line = fp.readline()
    fp.close()

# Now call the function as
DataExtract('C:/Users/username/Desktop/d.txt')

You can also read how to use python functions from def
https://www.w3schools.com/python/python_functions.asp


How to enable Spring's auto-configuration report in tests?

Question: I just found out that Spring has a debug mode, which gives insights on the auto-configuration. For a server, it can be enabled by passing --debug as an application parameter.
Is there a way to enable the debug mode also for tests (executed with the SpringJUnit4ClassRunner)?

If the auto-configuration report is working, it should print some output like this:
=========================
AUTO-CONFIGURATION REPORT
=========================

Positive matches:
-----------------

   ConfigServiceBootstrapConfiguration#configServicePropertySource matched
      - matched (OnPropertyCondition)

   ConfigurationPropertiesRebinderAutoConfiguration matched
      - @ConditionalOnBean (types: org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor; SearchStrategy: all) found the following [org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor] (OnBeanCondition)

   ConfigurationPropertiesRebinderAutoConfiguration#configurationPropertiesBeans matched
      - @ConditionalOnMissingBean (types: org.springframework.cloud.context.properties.ConfigurationPropertiesBeans; SearchStrategy: current) found no beans (OnBeanCondition)

   ConfigurationPropertiesRebinderAutoConfiguration#configurationPropertiesRebinder matched
      - @ConditionalOnMissingBean (types: org.springframework.cloud.context.properties.ConfigurationPropertiesRebinder; SearchStrategy: current) found no beans (OnBeanCondition)

   EncryptionBootstrapConfiguration matched
      - @ConditionalOnClass classes found: org.springframework.security.crypto.encrypt.TextEncryptor (OnClassCondition)

   PropertyPlaceholderAutoConfiguration#propertySourcesPlaceholderConfigurer matched
      - @ConditionalOnMissingBean (types: org.springframework.context.support.PropertySourcesPlaceholderConfigurer; SearchStrategy: current) found no beans (OnBeanCondition)

Negative matches:
-----------------

   ConfigServiceBootstrapConfiguration.RetryConfiguration did not match
      - required @ConditionalOnClass classes not found: org.springframework.retry.annotation.Retryable,org.aspectj.lang.annotation.Aspect (OnClassCondition)

   DiscoveryClientConfigServiceBootstrapConfiguration did not match
      - @ConditionalOnProperty missing required properties spring.cloud.config.discovery.enabled (OnPropertyCondition)

   EncryptionBootstrapConfiguration.RsaEncryptionConfiguration did not match
      - @ConditionalOnClass classes found: org.springframework.security.rsa.crypto.RsaSecretEncryptor (OnClassCondition)
      - Keystore nor key found in Environment (EncryptionBootstrapConfiguration.KeyCondition)

   EncryptionBootstrapConfiguration.VanillaEncryptionConfiguration did not match
      - required @ConditionalOnMissing classes found: org.springframework.security.rsa.crypto.RsaSecretEncryptor (OnClassCondition)

   EurekaDiscoveryClientConfigServiceBootstrapConfiguration did not match
      - @ConditionalOnClass classes found: org.springframework.cloud.config.client.ConfigServicePropertySourceLocator (OnClassCondition)
      - @ConditionalOnProperty missing required properties spring.cloud.config.discovery.enabled (OnPropertyCondition)

Exclusions:
-----------

    None

Unconditional classes:
----------------------

    None

Answer: --debug sets a debug property which then switches on the auto-configuration report. You can do the same in your test using, for example, @TestPropertySource on your test class:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Application.class)
@TestPropertySource(properties = "debug=true")
public class YourTests {
    // …
}


Conflito entre jquery e min-jquery

Question: estou com problemas, pois o meu código ta dando conflito com o minjquery, não sei oq acontece, quando coloco ele todos os meus outros códigos que tenho não funcionam.... Me ajudem por favor!
http://www.redepurple.com.br/social/Code/chatjs/jquery.js
Obrigada a todos pela ajuda, resolvi colocando a última versão do Jquery, que foi a única que funcionou com todos os scripts juntos, e tirei também um outro que estava dando "conflito" de outro plugin.
Comment: Você está colocando os dois de uma vez ou é quando coloca o `.min` que dá problema ?
Comment: Obrigada lindo @Gumball dá isso: VM2515:1 Uncaught ReferenceError: scrollcode is not defined
Comment: Porque usar ambos?
Comment: O min eu uso no meu outro projeto, e o jquery eu uso em um chat. Quando eu tiro o jquery, funciona o meu outro projeto, quando eu boto para de funcionar. E aí eu fico nessa, sem saber o que fazer
Comment: Por favor, gente queria muito que funcionasse :\
Comment: E assim, o que para de funcionar é um Jquery básico, como enviar um formulário POST, coisas simples, estranho...
Comment: Dá-te algum erro na consola quando tiras o jQuery 1.3?
Comment: Olha não sei o que é consola, mas o que acontece é que tudo para de funcionar, quando eu envio uma mensagem a página da refresh em vez de funcionar a function
Comment: @TenaAndrade vamos devagar. Coloque o `.min` do jQuery na página, salve. Depois abra sua página no navegador, aperte CTRL SHIFT J no teclado. Abrirá um Console de Informações. Atualiza a página e veja o erro que dá. Mas o Sérgio está certo provavelmente, você está colocando uma biblioteca em cima da outra.
Comment: Haaaa @TenaAndrade. Pode ser que você esteja colocando o script embaixo dos outros códigos. O `.min` tem que ser o primeiro script de todos. Daí depois vem o script do `scrollcode`. É o que eu imagino, por enquanto...
Answer: Pelo que vejo na tua página estás a carregar o jQuery 1.3, 1.7 e 2.0 em sitios diferentes, isso gera conflitos e na verdade só precisas de um deles. O que der conflito é provavelmente por teres código antigo, mudando esse código o problema deve ficar resolvido. Nunca é bom carregar versões diferentes da mesma biblioteca.
Deixa somente o jQuery mais moderno (2.0) e coloca aqui no site novas perguntas que possas ter com eventuais erros que vejas na consola ter na consola.
O que pode ser o teu problema é que páginas diferentes vão buscar o jQuery a diretorias diferentes. Nesse caso não há sobreposição de bibliotecas e, apesar de ser sempre bom usar versões mais modernas, não é urgente mudar e pode funcionar com ambas.
Pelo que encontro tens

 // jQuery v1.7.2

e ainda esse link que indicas na pergunta com http://www.redepurple.com.br/social/Code/chatjs/jquery.js, que é a versão 1.3...
Se queres mais ajuda que isto tens de especificar qual a página que dá problemas e colocar aqui o HTML dessa página. O ideal é isolar o código que não funciona e mostrar aqui só isso.
Answer: A versão .min não se trata de uma versão com recursos reduzidos, mas sim compactada, ou seja, ela é mais leve para carregar, mas tem todos os recursos da versão descompactada, em geral você usa as versões completas em ambientes de desenvolvimento, pois elas tem alguns recursos de debug e podem ser analisadas mais facilmente em caso de erros e problemas, e usa as versões .min em ambiente de produção, para ficar mais leve o carregamento e não mostrar mensagens de erro.
Você não deve carregar varias versões do jquery uma sobre a outra, escolha uma para trabalhar e carregue apenas ela. Em projetos novos eu aconselho usar a ultima versão e caso algum plugin/complemento (como o seu chat) não funcione corretamente, carregue o plugin migrate.
Answer: Estava dando uma olhada no seu código fonte e encontrei o que provavelmente seja o problema.
Veja na imagem abaixo:

Acho que essa deve ser a página que você está fazendo.
Nesse caso veja que o plugin de jQuery está depois do Jquery Form.
Ele tem que vir antes. Na verdade, o jQuery ou jQuery Min tem que vir primeiro, antes de qualquer outro plugin que use jQuery. Seria bom você colocar esses scripts antes de fechar a tag .
Se não for essa página, nos mostre como está o código fonte (não tudo) só a parte dos scripts, que está com problemas.

Conflito entre jquery e min-jquery


Exposing attributes in a defined type in puppet

Question: I'd like to access attributes that are inside instances of defined types from other classes/instances.
This is very similar to a question asked on SO before -  In Puppet, how can I access a variable/attribute inside a defined type?, however from what I understood the answer was specifically related to accessing parameters as opposed to arbitrary variables.
For example, given the following defined type:
define server (
  $server_name = 'my_server'
){
  $server_history = 'A long story'
}

I can successfully use getparam(...) to fetch server_name but I cannot do the same for server_history.
Also, if server was a class as opposed to to a defined type, accessing this variable is straightforward using something like server::serverhistory
Does anyone have any ideas on how to expose these variables? Or am I approaching this completely the wrong way?
Edit: For some higher level context on what I'm trying to do my server type gets instantiated by 3 other classes. A variable in the server type builds out some directory paths based on parameters provided to it by these classes (which naturally, are specific to those classes). There are some other classes that would like to use the directory path variable to place files there.
Comment: You are likely approaching it the wrong way. The reason you can easily access variables within a class is that they can be treated as a sort of singleton. Saying: 'server::serverhistory' refers to the same instance of the 'server' class no matter what. Meanwhile a defined type is more akin to an object or function and can be instantiated multiple times. There isn't a very concrete way to reference which instance you are referring to. (Not entirely true, but it's close enough). Perhaps you could update the question to illustrate your actual goal, and we can suggest a solution to your problem.
Comment: It feels like you're really stretching the functionality of defined types and variable scope in a manner that they're not intended. (This [similar question](http://stackoverflow.com/questions/19013084/in-puppet-how-can-i-access-a-variable-attribute-inside-a-defined-type) may help a bit) I would re-think what you're trying to achieve, a profile class may be what you are looking for (pass a hash/array that then uses your defined type to create the files, leaving the parameter accessible). [This gist](https://gist.github.com/joshsouza/9394cd03b4142ee41a5aa08df8dd3735) might trigger ideas.
Comment: @JoshSouza, sure, I've edited my answer to clarify what I am actually trying to do
Comment: Thanks for the pointers :)
Answer: You ask

I'd like to access attributes that are inside instances of defined types from other classes/instances.

and you go on to clarify that you're after

arbitrary variables.

In fact, ordinary variables in the body of a defined type are not attributes of that type, nor of any instance thereof.  They are not part of the accessible persistent state of instances of such types at all.
More generally, Puppet treats defined types just like native types in almost every observable way, but by the same token, it does not provide any features that serve to distinguish defined types as a special case.  You are looking for such a feature, and it does not exist.
Since your design idea will not work, you'll need to think of an alternative.  You say

my server type gets instantiated by 3 other classes. A variable in the server type builds out some directory paths based on parameters provided to it by these classes (which naturally, are specific to those classes). There are some other classes that would like to use the directory path variable to place files there.

Since the paths you're after are characteristic of specific classes, it makes sense for them to be accessible directly via those classes.  It seems odd to me that you would even want to access them indirectly via resources declared by those classes.
Comment: Yep I ended up shuffling my code around a bit. It doesn't feel as elegant as what I was initially trying to do, but it works and is -relatively- maintainable


How to approach conditional Icon swapping based on app state using Riverpod in Flutter?

Question: In my custom AppBar.leading I want to display a certain IconButton depending on an app state value using the Riverpod package. This IconButton also conditionally switches depending on the platform. Besides some set-up boilerplate using this example I'm not sure how to continue. I'll show my current state below:
models/flash_status.dart:
enum FlashStatus {
  auto,
  on,
  off,
}

// ignore: missing_return
String flashStatusInStringFormat(FlashStatus flashStatus) {
  switch (flashStatus) {
    case FlashStatus.auto:
      return 'Auto';
    case FlashStatus.on:
      return 'On';
    case FlashStatus.off:
      return 'Off';
  }
}

providers/providers.dart:
import 'package:flutter_riverpod/flutter_riverpod.dart';

import 'package:MyApp/models/flash_status.dart';

final flashStatusProvider = StateProvider((ref) => FlashStatus.auto);

lib/main.dart:
import 'package:flutter_riverpod/flutter_riverpod.dart';

void main() {
  runApp(
    ProviderScope(
      child: MyApp(),
    ),
  );
}

class MyApp extends StatelessWidget {...

widgets/tool_bar.dart:
import 'dart:io' show Platform;

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import 'package:MyApp/providers/providers.dart';

class ToolBar extends StatelessWidget with PreferredSizeWidget {
  @override
  final Size preferredSize;

  ToolBar({
    Key key,
  })  : preferredSize = Size.fromHeight(50.0),
        super(key: key);

  IconData get flashIconAuto =>
      Platform.isAndroid ? Icons.flash_auto : CupertinoIcons.bolt_badge_a;

  IconData get flashIconOn =>
      Platform.isAndroid ? Icons.flash_on : CupertinoIcons.bolt_fill;

  IconData get flashIconOff =>
      Platform.isAndroid ? Icons.flash_off : CupertinoIcons.bolt_slash;

  @override
  Widget build(BuildContext context) {
    return AppBar(
      automaticallyImplyLeading: false,
      backgroundColor: Colors.transparent,
      leading: IconButton(
        icon: Icon(flashIconAuto),
        tooltip: 'Turn on camera flash',
        onPressed: () {},
      ),
    );
  }
}

I'm not sure where to go from here, I have to use Consumer to wrap the IconButton right? How do I handle conditionally showing the right icon based on state? Am I missing model methods to update the state? What do the onPressed handlers look like?
Answer:     import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

enum FlashStatus {
  auto,
  on,
  off,
}

final flashStatusProvider = StateProvider((ref) => FlashStatus.auto);

class FlashScreen extends StatefulWidget {
  @override
  _FlashScreenState createState() => _FlashScreenState();
}

class _FlashScreenState extends State<FlashScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: ToolBar(),
    );
  }
}

class ToolBar extends StatelessWidget with PreferredSizeWidget {
  @override
  final Size preferredSize;

  ToolBar({
    Key key,
  })  : preferredSize = Size.fromHeight(50.0),
        super(key: key);

  IconData get flashIconAuto =>
      Platform.isAndroid ? Icons.flash_auto : CupertinoIcons.bolt_badge_a;

  IconData get flashIconOn =>
      Platform.isAndroid ? Icons.flash_on : CupertinoIcons.bolt_fill;

  IconData get flashIconOff =>
      Platform.isAndroid ? Icons.flash_off : CupertinoIcons.bolt_slash;

  @override
  Widget build(BuildContext context) {
    return AppBar(
      automaticallyImplyLeading: false,
      backgroundColor: Colors.transparent,
      leading: Consumer(builder: (context, ScopedReader watch, child) {
        final status = watch(flashStatusProvider);
        print(status.state);
        switch (status.state) {
          case FlashStatus.on:
            return IconButton(
              icon: Icon(flashIconOff),
              tooltip: 'Turn off camera flash',
              onPressed: () =>
                  context.read(flashStatusProvider).state = FlashStatus.off,
            );
            break;
          case FlashStatus.off:
            return IconButton(
                icon: Icon(flashIconOn),
                tooltip: 'Turn on camera flash',
                onPressed: () =>
                    context.read(flashStatusProvider).state = FlashStatus.on);
            break;
          default:
            return IconButton(
                icon: Icon(flashIconOn),
                tooltip: 'Turn on camera flash',
                onPressed: () =>
                    context.read(flashStatusProvider).state = FlashStatus.on);
        }
      }),
    );
  }
}


Is Hessian of neural nets with NLL loss positive semi-definite?

Question: I learned that expected Hessian of negative log likelihood is the same as Fisher information matrix, which is known to be positive semi-definite
$$
\begin{aligned}
F(\theta)
&= E_{x \sim p_\theta}[-\nabla_\theta^2 \log p_\theta( x)] \\
&= E_{x \sim p_\theta}[\nabla_\theta\log p_\theta( x)(\nabla_\theta\log p_\theta( x))^T]
\end{aligned}
$$
If this is the case, my reasoning goes, any neural network that outputs negative log likelihood loss should also have positive semi-definite Hessians with regard to its parameters, because Hessians (i.e. observed Fisher information), when averaged, should be similar to the Fisher Information Matrix.
But it is contradiction to the fact that neural networks are non-convex.
Please help me resolve this contradiction. Thanks!
Comment: H=F only near the global optimum (where the Hessian must be positive definite).
Comment: @JohnMadden I wanted to know why that's the case, but you helped me figuring out the answer anyway. Thanks!
Answer: Hessian of the loss is defined over data distribution whereas Fisher information is defined over model's distribution:
$$
\begin{aligned}
H(\theta)
&= E_{x \sim Data}[-\nabla_\theta^2\log p_\theta (x)] \\
&= E_{x \sim Data}[-\frac{\nabla_\theta^2 p_\theta}{p_\theta} + \nabla_\theta \log p_\theta(x) \nabla_\theta \log p_\theta(x)^T] \\
& \neq E_{x \sim Data}[\nabla_\theta \log p_\theta(x) \nabla_\theta \log p_\theta(x)^T]
\end{aligned}
$$
which is defferent from
$$
\begin{aligned}
F(\theta)
&= E_{x \sim p_\theta}[-\nabla_\theta^2\log p_\theta (x)] \\
&= E_{x \sim p_\theta}[-\frac{\nabla_\theta^2 p_\theta}{p_\theta} + \nabla_\theta \log p_\theta(x) \nabla_\theta \log p_\theta(x)^T] \\
&= E_{x \sim p_\theta}[\nabla_\theta \log p_\theta(x) \nabla_\theta \log p_\theta(x)^T].
\end{aligned}
$$
Actually, many people seems to ignore this distinction, which led them to use "empirical Fisher". See [Kunstner et al., 2019], which clearly draws distinctions between various terms on Fisher information, and points out possible problems on using empirical Fisher inadvertantly.
Reference:
Kunstner et al. Limitations of the Empirical Fisher Approximation for Natural Gradient Descent. Neurips. 2019.


jQuery select all data from selected rows

Question: I have a table. I want to get name, lastname, email from all selected rows (check is set). Maybe name, lastname, email will be arrays.
How can I do it?
I've tried this:

var tableControl= document.getElementById('mytable');
$("#btn").click(function () {
    var result = [];
    $('input:checkbox:checked', tableControl).each(function() {
        result.push($(this).parent().next().text());
    });
    alert(result);
});

    Check
    Name
    Lastname
    Country
    Email

    <input id="check_1" type="checkbox" name="check[]">
    Petya
    L1
    Country1
    Email1

    <input id="check_2" type="checkbox" name="check[]">
    Kolya
    L2
    Country2
    Email2

    <input id="check_3" type="checkbox" name="check[]">
    Vasya
    L3
    Country3
    Email3

But I get only selected names. How can I get the other columns?
Comment: i think it has to be `tableControl.find('input[type="checkbox"]:checked').each(...)` or not? and why do you use vanilla js for get element by id and not jquery? `$('#myTable')` and not `document.getElementById('myTable'')`
Answer: This is one possible way of doing things . I set a class for every type of column. You can use that to find out all the other information of the checked rows.
Observe the console. you get all the information in one object which you can then use for whatever further functions you might want it to do

var tableControl= document.getElementById('mytable');
    $("#btn").click(function () {
        var result = [];
        $('input:checkbox:checked', tableControl).each(function() {
            var obj={};
            var parent=$(this).parent().parent();
            obj.name=(parent.find( ".name" ).text());
            obj.last=(parent.find( ".last" ).text());
            obj.country=(parent.find( ".country" ).text());
            obj.email=(parent.find( ".email" ).text());
            result.push(obj);
        });
        console.log(result);
    });

    Check
    Name
    Lastname
    Country
    Email

    <input id="check_1" type="checkbox" name="check[]">
    Petya
    L1
    Country1
    Email1

    <input id="check_2" type="checkbox" name="check[]">
    Kolya
    L2
    Country2
    Email2

    <input id="check_3" type="checkbox" name="check[]">
    Vasya
    L3
    Country3
    Email3

<button id="btn">Click</button>
Comment: Yes, I do work with jquery. I agree, jquery is powerful but this particular task I'm working on required only javascript to be used. Thanks Rachel. :)
Comment: Thanks @RachelGallen . I really appreciate it. :) Although, I wasnt using jquery and was using plain javascript. But very helpful fiddle. I'm going to save this link.
Comment: @IhavCoder oh yeah, i didn't think of that (the jquery/plain js thing) .. jquery is quite easy and useful though once you get used to it (and it doesn't take long to learn) .. Glad to be of help :)
Comment: @IhavCoder i just saw from your profile that you're already working with jquery.  Didn't notice that before last comment! But sure, help along the way is always good i find.. :)
Answer: Instead of clicking a button every time you want to sum up your results, i would suggest you handle the result object anytime a checkbox is clicked, this makes for a more stable state and handles dynamic changes better. Consider changing your code to look like:
var tableControl = $('#mytable');

//An object that maps checkbox id to an object containing name, last and email
var result = {};
tableControl.find('input:checkbox').click(function() {
   var key = $(this).attr('id');
   //If checkbox clicked and not checked, then remove object from map
   if(!$(this).is(":checked")){
      delete result[key];
      return;
   }
   var row = $(this).parent().parent();
   //Get children based on the start of the id string
   var firstName = row.children("td[id^='name']").text();
   var lastName = row.children("td[id^='last']").text();
   var email = row.children("td[id^='email']").text();
   result[key] = {
    name: firstName,
    last : lastName,
    email: email
   }
 });

This way, anytime a checkbox is clicked, the results object will update immediately to reflect the desired value. The result object would look something like this:
{
  "check_1": {
    "name": "Petya",
    "last": "L1",
    "email": "Email1"
  },
  "check_2": {
    "name": "Kolya",
    "last": "L2",
    "email": "Email2"
  },
  "check_3": {
    "name": "Vasya",
    "last": "L3",
    "email": "Email3"
  }
}

https://jsfiddle.net/p35kz2u1/6/
Comment: I was gonna tell the same thing as you did. I do the same way as you've written here. :D
Comment: Right? I always find it makes more sense (and easier to maintain) to update the dependent values as the event occurs rather than at an arbitrary time when user is ready to use the data.
Comment: Correct. That's why I also do this the same way you've done it. :)
Answer:

var tableControl= document.getElementById('mytable');
    $("#btn").click(function () {
        var result = [];

        $('input:checkbox:checked', tableControl).each(function() {
            // Get the entire text
            //alert($(this).closest('tr').children('td').text());
            //alert($(this).parent().next().find('td').text());
            // Get each column
            $(this).closest('tr').children('td').each(function(e){
              alert($(this).text());
            });
            result.push($(this).closest('tr').children('td').text());
        });
        alert(result);
    });

    Check
    Name
    Lastname
    Country
    Email

    <input id="check_1" type="checkbox" name="check[]">
    Petya
    L1
    Country1
    Email1

    <input id="check_2" type="checkbox" name="check[]">
    Kolya
    L2
    Country2
    Email2

    <input id="check_3" type="checkbox" name="check[]">
    Vasya
    L3
    Country3
    Email3

<button id="btn">Get Data</button>
Answer: var tableControl= $('#mytable');
$("#btn").click(function () {
    var result = [];
    tableControl('input[type="checkbox"]:checked').each(function() {
        var nodeArray = $(this).parents('tr').find('td');
        var innerArray = [];
        for(var i = 1; i < nodeArray.length; i++) {
            if(nodeArray.hasOwnProperty(i)) {
                innerArray.push(nodeArray[i].text());
            }
        }
        if(innerArray.length > 0) {
          result.push(innerArray);
        }
    });
    alert(result);
});

please try out this, i have not tested, but i think it should do what you want.
Answer: You can use something like below. I modified your inner query to go to parent and looks for siblings.

 var tableControl = $('#mytable');
 $("#btn").click(function() {

   var result = [];
   $('input:checkbox:checked').each(function(item) {
     $(this).parent().siblings().each(function() {
       result.push($(this).text())
     });
   });
  alert(result)
 });

    Check
    Name
    Lastname
    Country
    Email

    <input id="check_1" type="checkbox" name="check[]">
    Petya
    L1
    Country1
    Email1

    <input id="check_2" type="checkbox" name="check[]">
    Kolya
    L2
    Country2
    Email2

    <input id="check_3" type="checkbox" name="check[]">
    Vasya
    L3
    Country3
    Email3

  <button id ="btn">Click Me</button>


How do you remove the default Drupal 7 administration menu?

Question: I have disabled the "Toolbar" module, and cleared the cache; yet, it persists.
How do I remove it?
Answer: Weird, it just took time. I came back a few hours later and it was gone. Perhaps there are cache clearing issues in Drupal 7.
Answer: There's a permission in Drupal 7 labelled Use the administration toolbar.  Try unsetting this permission from the account.


Factoring a cubic equation but I want a way to figure out the factor of the function

Question: $(5-x)(x-2)(x-2)-4=0$
I want to expand this, subtract the four from the constant then factor this again. How do I find the linear factor? Are there easier ways to do this?
If it helps, the original question is that we have two equations $y=4/(x-2)^2$ and $y=5-x.$ One intersection is at point $(1,4)$, so I have to find the coordinates of the other points of intersection.
Comment: Well you have been given one root, and can factor that out to get a quadratic.
Comment: I don't know how to use that root unless it's a zero root
Comment: If $p(1)=0$ then $(x-1)$ is a factor of $p(x)$. You can use polynomial division with $p(x)=(x-1)q(x)+r$ where $r$ is a constant (because it has lower degree than the divisor, which is linear). Then set $x=1$ to get $0=0+r$ so that $r=0$. This is applicable generally for roots and factors of polynomials and is a very useful thing to get your head round..
Answer: Because we are searching were $y=4/(x−2)^2$ and $y=5−x$ intersects, we have the equation: $5-x- \dfrac{4}{(x−2)^2} =0$, which is equal to $\dfrac{(5-x)(x-2)^2 -4}{(x-2)^2} =0$ expanding this we get that this is also equal to $\dfrac{-(x^3-9x^2+24x-16)}{(x-2)^2}$ as we can see, x cannot be equal to 2, and also, this fraction only will be 0 if the numerator is zero, so, we are searching where $x^3-9x^2+24x-16=0$, as we know, 1 is a solution, so we can factor this as $(x-1)(ax^2+bx+c)$. As we can obtain, $a = 1$, $b = -8$ and $c= 16$ so, finally, we have the equation $(x-1)(x^2-8x+16)$. Now, looking at the roots of the quadratic part, we see that 4 is the only solution, so $y=4/(x−2)^2$ and $y=5−x$ intersects at $(1,4)$ and $(4,1)$.
Comment: Oh man it's so much more confusing when roots are equal to the intersection. It's just a jumble of concepts that screws you over at first (polynomial graphs) but after gong through a few hurdles you figure out how the dots connect together. Doing polynomial questions was harder than derivative questions because I spent an hour at a lot of questions just trying to see what knowledge I'm missing.
Thanks tho, I understand now.
Answer: This equation with its unique feature provides us a quick solution by factorizing 4.
Given:
\begin{align}(5-x)(x-2)(x-2)-4=0 , (5-x)(x-2)(x-2)=4  \\(5-x)(x-2)^2=4\cdot(\pm1)^2=1\cdot(\pm2)^2\end{align}
Try:
\begin{align}5-x=4,x-2=\pm1 \to x=1, y=4\end{align}
\begin{align}5-x=1,x-2=\pm2 \to x=4, y=1\end{align}
Answer: \begin{align}(1,4) , (4,1)\end{align}


Exclude a class within a clickable class

Question: I have the following structure (.holder has a 40px padding so lots of room around element .classA):

  Hello

When a user clicks on .holder something happens, but I want to stop that click from firing if the user clicks element .classA
This is what I currently use, but I want to say when .holder is clicked but not .classA
$(document).on('click', '.holder', function() {
  modClose();
});

Is that possible?
Answer: Just stop the event propagation when .classA is clicked:
$('.classA').on('click', function(evt) {
    evt.stopPropagation()
});

$(document).on('click', '.holder', function() {
    modClose();
});

From jQuery documentation about stopPropagation:

Description: Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
Answer: Another way, although similar:
$(document).on('click', '.holder', function(e) {
        if($(e.target).hasClass('classA')) return;
        modClose();
    });

Answer: You can check the target of the event:
http://jsfiddle.net/KwcAj/
$(document).on('click', '.holder', function(e) {
  if (e.target != this) {
    console.log('stop');
    return;
  }
  console.log('go');
});

Answer: You can check targets className
$(document).on('click', '.holder', function (e) {
  if (e.target.className.indexOf('classA') == -1) {
    modClose();
  }
});


CMake - No rule exists to target

Question: In Ubuntu, I have downloaded a third-party shared library (liba1.so), placed in /lib/extern/lib . The associated header files I placed in /lib/extern/include. My own header files are placed in /include/public/ and /include/private/ . And now (to test mylib) I want to link this in my main.cpp code, using CMake.
My structure:
**My structure:**
|
|
+---CMakeLists.txt
|
+---lib
|    |
|    +---extern
|         |
|         +---lib
|         |    |
|         |    +---liba.so
|         |    +---libb.so
|         |    +---liba12.so
|         |
|         +---include
|                |
|                +...headers.h
|
+---include
|     |
|     +---public
|     |     |
|     |     +---file1.hpp
|     |     +...
|     |
|     +---private
|            |
|            +---file2.hpp
|            +...
|
+---src
     |
     +---public
     |     |
     |     +---file1.cpp
     |     +...
     |
     +---private
     |     |
     |     +---file2.cpp
     |     +...
     |
     +---main.cpp

My CMakeLists.txt:
cmake_minimum_required(VERSION 3.9...3.19)
if(${CMAKE_VERSION} VERSION_LESS 3.12)
     cmake_policy(VERSION ${CMAKE_VERSION})
endif()

project(mylib VERSION 0.0.1 DESCRIPTION "Test" LANGUAGES CXX )

set(CMAKE_CXX_FLAGS "${CMAKE_C_FLAGS} -DTPM_POSIX")
set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

add_library(${PROJECT_NAME} STATIC src/private/file2.cpp src/public/file1.cpp )
add_library(lib SHARED IMPORTED)

set_target_properties(lib PROPERTIES IMPORTED_LOCATION ${CMAKE_CURRENT_BINARY_DIR}/lib/extern/lib/liba.so)

set_target_properties(lib PROPERTIES IMPORTED_LOCATION ${CMAKE_CURRENT_BINARY_DIR}/lib/extern/lib/libb.so)

set_target_properties(lib PROPERTIES IMPORTED_LOCATION ${CMAKE_CURRENT_BINARY_DIR}/lib/extern/lib/liba12.so)

target_link_libraries(${PROJECT_NAME} PUBLIC lib)

target_include_directories(${PROJECT_NAME}
   PUBLIC
     $<INSTALL_INTERFACE:lib/extern/include>
     $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/lib/extern/include>

     $<INSTALL_INTERFACE:include/public>
     $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/public>

     $<INSTALL_INTERFACE:include/private>
     $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include/private>
)

add_executable(test src/main.cpp)

target_link_libraries(test PRIVATE mylib)

ERROR:

[build] Consolidate compiler generated dependencies of target mylib
[build] [ 60%] Built target mylib [build] Consolidate compiler generated dependencies of target test
[build] gmake[2]: *** No rule exists to target "lib/extern/lib/liba12.so",
[build] required by "test" to create. Ending.
[build] gmake[1]: *** [CMakeFiles/Makefile2:111: CMakeFiles/test.dir/all] Error 2
[build] gmake: *** [Makefile:91: all] Error 2
[proc] The command: /usr/bin/cmake --build /home/mathew/proj/build --config Debug --target all -j 10 -- exited with code: 2 and signal: null [build] Build finished with exit code 2

Comment: What do you hope to accomplish by setting the `IMPORTED_LOCATION` for the same library three times?
Answer: Your imported files are relative to the source directory, not the build directory. You need to use CMAKE_CURRENT_SOURCE_DIR instead of CMAKE_CURRENT_BINARY_DIR when setting IMPORTED_LOCATION.
Comment: After 6 hours of programming, I noticed that I get undefined references in the includes of the external library.... After using   `**CMAKE_CURRENT_BINARY_DIR**`   instead of `**CMAKE_CURRENT_SOURCE_DIR**`
Comment: At compile time: make sure `lib/extern/lib` is mentioned in a `target_link_directories`. At runtime, make sure the *dynamic* linker can find your libraries. Easiest is to fiddle with `LD_LIBRARY_PATH`.
Comment: target_link_directories did not work. The error (undifined reference) does not appear in my code but the includes of third-party shared library in /lib/extern/includes/headers ..

CMake - No rule exists to target


Conducting correlation and one way ANOVA using data from a PostgreSQL database

Question: I am trying to discern the best way to calculate a correlation and perform a one-way ANOVA on data I am taking from a PostgreSQL database.

What tools should I use?
Can I do this using the SQL language itself?
Is there an easy way to export the data?
Answer: Although you can substitute the values into the ANOVA formulas and correlation formulas yourself, maybe even calculate everything using SQL you probably want to use the ANOVA and correlation features of a statistical software. All major statistical software (SAS, SPSS, Stata, R, Statistica etc) are able to connect to databases and get the data table with a simple SQL query. Besides direct connections you can use files as well to transfer the data: export the data into a file and import them into the statistical software. The comma separated values format is often used, but many other formats may work well.
Comment: http://stackoverflow.com/questions/1408897/connecting-gnu-r-to-postgresql
Comment: I have been trying to connect R to the database and have been failing mightily. Any suggestions?
Answer: For simple correlation, in would use the statistical functions which are directly available in Postgre.
e.g.  ----> SELECT CORR(x, y) FROM YourTable;
For ANOVA it is a bit tougher.  You might be better off transforming your problem to one involving regression and use the regression formulas.
http://www.postgresql.org/docs/8.2/static/functions-aggregate.html
Comment: As suggested by GaBorgulya, you are better off using a stat package. Unless PostGre is able to do multiple regression (which looks like it does not), you are limited to testing the difference between 2 groups since your two groups could be dummy coded into 1 variable.    http://psych.unl.edu/psycrs/statpage/coding_eg.pdf
Comment: can that do ANOVA?


To what degree do professional pit band guitarists follow the chord charts for pieces?

Question: I've been recently having a go at playing the guitar part for 'Catch Me If You Can'. I don't claim to be a high standard guitarist but I have a performance diploma and yet these parts are ridiculously hard for me to play. Any of the melody lines are simple enough but it's when the chord charts come out I fall to pieces. An example would be from the song 'Don't break the rules'. An extract is below:

There are some very fast chord changes in bars 62 and 65 (tempo is 210bpm) which makes me question whether, in the pit, a guitarist would actually be expected to play these chords or whether they are for reference from what the piano is doing.
Am I missing a trick? Using smaller voicings rather than playing the full chords or do I just need to sit down and drill these chords into my head?
Answer: It's typical of stuff I play in big band arrangements. Yes, you're expected to play it verbatim. Often, though, with the awkward to get full chords, a two or three voice chord is enough. With a keyboard or piano player as well, they will sometimes, not always have a very similar chord arrangement, so if you played, say, C#m instead of C#m6, it won't hurt.There's sometimes the need for full-blooded chords, but, dependent on band size, particular arrangement, et al,smaller chords are good.
I notice in bars 62 and 65 there's a sort of push going on, with the chord coming in on the quaver before the bar following. Bars 60 and 64 aren't too clear as to where the change happens either. I'd have to go with the flow if I was sight reading it for a live performance. But, to be fair, unless the MD is really listening to everything (while conducting, playing, watching for cues, etc. etc.) he may forgive a dropped quaver chord or two. Let's hope so! But pros will play it perfectly first time. After which, the MD may decide that's not how he wants it anyhow...
Dip. level LCM would include this sort of level reading, from memory.
EDIT: I'd have to question the second half of bar 65. G#7b9/D# for three and a half beats, or is the slash there to make sure D# and C#m6 both make up the last two quavers. These are the bits that make it difficult even for a pro to read!
Comment: I think the G#7b9/D# is just for a quaver but is offset slightly so that it doesn't collide with the C#m6 chord. That's what the recording appears to do and I've found an alright voicing of it to jump between the two so I just need to get it memorised now.
Comment: @TimHargreaves - 3rd fret barre, I'd use. I'd like to listen - what is the reference?
Comment: 3rd fret barre? Could you link a chart for that? I would have used this voicing: http://chordgenerator.net/.png?p=x64545&f=-42131&s=8

Here's the link to the song: https://youtu.be/zNJxHVJtAVw?t=1m6s. I think it is on the 3rd beat of bar 65 that the piano plays it.
Comment: @TimHargreaves - sorry, I don't know how! Too old, stupid, and whatever! Tried your chord, and could only hold the barre on 4th fret with index finger! I should have said 4th fret barre, forgot it's G#, thought G and C...
Comment: Just realised my chord chart has the fingering mixed up. Think we're on about the same voicing. You mentioning the 3rd fret confused me but I'm following now.
Answer: The chords that are played make a huge difference in a song. In their own way, they are more important than the melody for the backup. If you have other players (like on the keyboard or whatever) you can get away with playing the easier versions as long as your not playing the wrong chord altogether.
Comment: Pretty well what I answered. Welcome. As a new poster, read through a lot of the answers, to find out how we work on this site. We try to be specific, complete and accurate.
Comment: But it's a nice summary, don't you agree?
Answer: I'd suggest that you almost never use barre chords.  They muddy your sound, slow you down and in theory the bass and piano are going to handle what you leave out.  You might find something similar to the feel of your example in the chart for 77 Sunset Strip and you can find the tune itself on youtube.  I don't know anything about playing at the bpm you're talking about, sorry!


Prove that if $K$ is a closed and bounded subset of $\Bbb R$ then every open cover of $K$ has a finite subcover

Question: Let $K$ be a subset of $\Bbb R. $ All  of the following statements are
equivalent in the sense that any one ofthem implies the two others:
(i)$ K$ is compact.
(ii) $ K$ is closed and bounded.
(iii) Any open cover for $ K$ has a finite subcover.
I was interested in the proof of $ii\implies iii.$ The proof was outlined as an excercise in the way mentioned below:
(Note: The definition being used in this context is -"A set $K$ is compact iff for every sequence in $K$ there exists a convergent subsequence in $K$ which converges at a point in $K$.")
Assume $K$ satisfies $(i)$ and $(ii),$ and let $\{O_λ : λ ∈ Λ\}$ be an open cover for $K.$ For contradiction, let's assume that no finite subcover exists. Let $I_0$ be a closed interval containing $K,$ and bisect $I_0$ into two closed intervals $A_1$ and $B_1.$
(a) Why must either $A_1 ∩ K$ or $B_1 ∩ K$ (or both) have no finite subcover consisting of sets from $\{O_λ : λ ∈ Λ\}.$
(b) Show that there exists a nested sequence of closed intervals $I_0 ⊇ I_1 ⊇ I_2 ⊇ ···$ with the property that, for each $n,$ $I_n ∩ K$ cannot be finitely covered and $\lim |I_n| = 0.$
(c) Show that there exists an $x ∈ K $ such that $x ∈ I_n$ for all $n.$
(d) Because $x ∈ K,$ there must exist an open set $O_{λ_0}$ from the original collection that contains $x$ as an element. Argue that there must be an $n_0$ large enough to guarantee that $I_{n_0} ⊆ O_{λ_0}.$ Explain why this furnishes us with the
desired contradiction.

I attempted to follow this outline as follows, and prove the implication required in a rigorous manner :
Assume $K$ satisfies $(i)$ and $(ii),$ and let ${O_λ : λ ∈ Λ}$ be an open cover for $K.$ For contradiction, let's assume that no finite subcover exists. Let $I_0$ be a closed interval containing $K,$ and bisect $I_0$ into two closed intervals $A_1$ and $B_1.$
Now, we claim that both $A_1 ∩ K$ and $B_1 ∩ K$ have no finite subcover each, consisting of sets from ${O_λ : λ ∈ Λ},$ at the same time.
Assuming that if possible, both $A_1 ∩ K$ and $B_1 ∩ K$ have finite subcover each, consisting of sets from ${O_λ : λ ∈ Λ}.$ Now, as $A_1\cup B_1=I_0$, this means $(A_1\cap K)\cup (B_1\cap K)=K\cap (A_1\cup B_1)=K\cap I_0=K$ has a finite subcover, a contradiction. So our claim holds.
Next, we claim that (from (b)) that there exists a nested sequence of closed intervals $I_0 ⊇ I_1 ⊇
 I_2 ⊇ ···$ with the property that, for each $n,$ $I_n ∩ K$ cannot be finitely covered
and $\lim |I_n| = 0.$
Now, we define for a closed interval $J=[a,b]$, $|J|=b-a\gt 0.$
From the previous claim we consider, $I_1=A$ and $I_1'=B$. Now, both $I_1,I_1'$ can't be finitely covered with $O_c,$ for then it would imply $K$ can be finitely covered with $O_c$. We choose an arbitrary set from $I_1,I_1'$ such that the chosen set, cannot be finitely covered with $O_c.$ WLOG, assuming $I_1$ is such a set. We then again bisect $I_1$ into $I_2$ and $I_2'$ and by the analogous argument as above, we may say, either $I_2$ or $I_2'$ cannot be covered with $O_c.$ We then choose such a set out of $I_2$ and $I_2'$ and repeat the process.
We hence, get a sequence of $I_n,n\in\Bbb N$ such that $I_0 ⊇ I_1 ⊇ I_2 ⊇ ···$ with $\lim |I_n| = 0,$ since from definition of $|I_n|$ we have $|I_n|=\frac{b-a}{2^n}$, where, $I_0=[a,b].$

But I am having some issues with this.
Firstly, for a set $A$ we generally denote the cardinality of $A$ as $|A|.$  But, as $I_0$ is a closed interval, and as it seems that $I_n,n\in \Bbb N,$ are also some nested closed intervals in $I_0$, and hence all the $I_n's$ are infinite sets so, the point, they make in the claim i.e $\lim |I_n| = 0,$ looks absurd. Hence, I defined $|I_n|$ appropriately.
Secondly, neither do I know how to divide $I_n$ into  a nested sequence of closed intervals $I_0 ⊇ I_1 ⊇
 I_2 ⊇ ···$ with the property that, for each $n,$ $I_n ∩ K$ cannot be finitely covered. To be precise, I could not prove the property, that "$I_n ∩ K$ cannot be finitely covered, for each $n\in \Bbb N.$"
Any help will be greatly appreciated. Sinve, I am stuck at this step, I can't proceed to do the remaining steps.
I am also looking for a less circuitous proof of this implication, if it exists.
Comment: (iii) is usually the *definition* of a compact set.
Comment: @MartinR The definition I am using is -"A set $K$ is compact iff for every sequence in $K$ there exists a convergent subsequence in $K$ which converges at a point in $K$"
Comment: Didn't you [just ask](https://math.stackexchange.com/q/4707146) this?
Comment: @FShrike Ha ha, yeah I admit it might be confusing at first, but if you look closely there I asked $iii\implies ii$ but here, I asked $ii\implies iii.$
Comment: @ThomasFinley: I would suggest to add that information to the question.
Comment: @MartinR Ok. Thanks for the suggestion.
Comment: Your definition of compact is more generally known as *sequentially compact*. It is a theorem that metric spaces are compact iff. they are sequentially compact
Answer: You solved your first issue correctly, i.e. here $|\cdot|$ does not denote the cardinality but the length of the interval.
As for the second issue, just apply recursively to $I_n\cap K$ the result of your first step: it is a closed and bounded subset of the closed interval $I_n$ (like $K$ was a closed and bounded subset of the closed interval $I_0$) and (by induction hypothesis) it is not finitely covered by $(O_\lambda)_{\lambda\in\Lambda}$ hence if you bissect $I_n$, one (at least) of the two closed subintervals, call it $I_{n+1},$ will be such that $K\cap I_{n+1}$ is not finitely covered either. But this seems to be what you already did, so I do not really understand your trouble.
Mine is elswhere: You want to prove $(ii)⟹(iii)$ but the exercise you quote assumes $(ii)$ and $(i)$ to derive $(iii)$. It seems they want to use it for (c), saying "pick one $x_n$ in each $I_n\cap K,$ then by $(i)$ the sequence $(x_n)$ has a convergent subsequence, [...]" but this can be achieved much cheaply without $(i)$: since $\lim|I_n|\to0$ and $(I_n)$ is a nested sequence, the sequence $(x_n)$ itself converges because it is Cauchy.
Incidentally:

Your post will be clearer from the beginning if, as commented in the previous one, you adopt the standard vocabulary, i.e. replace everywhere "compact" with "sequentially compact" (especially in (i)), and "every open cover of K has a finite subcover" with "K is compact" (especially in (iii)).
This $(ii)\implies(iii)$ is the non-easy part of Heine-Borel theorem $(ii)\iff(iii).$ Your proof is standard and is essentially the same as the proof on Wikipedia's page of "If a set is closed and bounded, then it is compact" (except that there, they generalize to $\Bbb R^n$).


Edit parent view controller's title from child

Question: I have app with UICollectionViews in UIPageViewController based on this tutorial for UIPageViewController, now I've embedded main view controller in navigation controller, and I want to change title of nav bar dynamically when in detail view, but how can I access it?
At first I've tried to embed in navigation controller Page View Controller, but nav bar wasn't displayed.

edit:
I've found out, that I can add navigation item to Time Snap Detail View Controller and set its title here, even though it's not visible in storyboard.
But how can I edit title in navigation bar, when I'm in Page View Controller?(In this case, on stack of the navigation controller is Main View Controller, which has Page View Controller as child view controller).
Comment: have you tried `self.title = @"My Title"` from inside your page view controller?
Comment: hi, it doesn't work, in parent view controller, it's added like this: `[self addChildViewController:self.pageController];
    [[self view] addSubview:[self.pageController view]];
    [self.pageController didMoveToParentViewController:self];`
Comment: then `self.parentViewController.title = @"My Title"`?
Comment: this doesn't work either, self.parentViewController is read-only
Comment: You're not assigning anything to `self.parentViewController`, just changing the title. That doesn't work either?
Comment: no, I've tried even `[self.parentViewController setTitle:@"sdfsdf"];` with same result
Comment: Any solution to this? I have exactly the same problem! :o
Comment: check my [latter question](http://stackoverflow.com/questions/21443555/uipageviewcontroller-within-navigationcontroller), I haven't tried it though because I used different UI
Answer: I tried this, and it's ok:
childVC.parentViewController.navigationItem.title = @"abc";

Answer: The parent in view controller is not working anymore. Looks like the only way is to save the parent in this child view controller's method and set it's title:
override func didMove(toParent: UIViewController?)

Answer: try this. it's working for me in almost same scenario
    self.navigationController.parentViewController.navigationItem.title = @"sdfsdf.";


Receiving warning & suggestion to scale predictors even though predictors have already been rescaled

Question: I am using the glmer function from the lme4 package to model nest attendance as a function of temperature, temporal variables, and experimental treatment. My model is relatively complicated — it contains multiple polynomial terms and interactions. The model is specified as:
FullModel<-glmer(Attendance~poly(TemperatureS, 2, raw=FALSE)+CoverType+poly(IncDayS,2, raw=FALSE)+poly(TimeS,2,raw=FALSE)+poly(TemperatureS,2,raw=false)*CoverType+poly(TemperatureS,2,raw=FALSE)*poly(IncDayS,2, raw=FALSE)+(1|ID), data=Attendance, family=binomial)

Where:

Attendance is binary (on vs. off the nest), coded as 0/1
Temperature is numeric
Incday= day of incubation, numeric
Time is numeric
CoverType is categorical with two levels
ID is the identity of the bird the observation is from, categorical with 14 levels

All of the numeric variables (so temperature, day of incubation, and time) have been scaled using the rescale function from the arm package, which centers and divides by 2 standard deviations, per Gelman 2007. However, when I run the model, I get the following warning message:

Warning message: Some predictor variables are on very different
scales: consider rescaling

Why am I getting this warning if the numeric predictors have already been rescaled? Given that they have been scaled, is it okay to ignore this warning, or will this affect my model results?
All thoughts are greatly appreciated!
Comment: How are `TemperatureS` and `Temperature` related? `IncDayS` and `IncDay`?
Comment: How many observations do you have in each `Attendance` group? Is there some reason you are using polynomial terms instead of potentially more helpful restricted cubic splines? Are you sure that you need the interaction term between two polynomials (which I suspect might be leading to the warning)?
Comment: Sorry for the confusion! I shouldn't have used TemperatureS and Temperature interchangeably. Temperature is the unscaled version, TemperatureS is the rescaled version. The same goes for IncDay and IncDayS. I'm only using the rescaled versions in the models.
Comment: @EdM, I am a relative novice when it comes to statistics and haven't heard about restricted cubic splines. I will look into those. As for the interaction term, I included it because in species similar to the one I'm studying, incubating adults have been observed leaving their nests unattended more frequently earlier on in the incubation cycle because younger embryos are less sensitive to temperature changes than older ones. Because of that, I thought it was likely that there might be a significant interaction between temperature and day of incubation.
Answer: Before you worry too much about the warning, pay more attention to the model construction. I fear that you might have jumped into a complicated model containing interacting polynomial terms, without looking in detail at what the data themselves indicate. Look at the raw data very carefully as a function of your predictors before you proceed. A few suggestions for what to do next follow.
First, see how well a model with only linear terms for the continuous predictors might work. That would cut down the model complexity substantially and make it easier for your audience to understand. My hunch, without seeing your data, is that the warning you get arises from the interaction term between two quadratic orthogonal polynomials, which are coded internally in ways that aren't necessarily intuitive and might lead to apparent differences in scale among predictor terms. Even if you need non-linear terms for the main effects, you might be able to get away with interaction terms that only involve linear trends.
Second, if you do need to incorporate non-linear terms for continuous predictors, it's usually better to use restricted cubic splines. Forcing a quadratic fit can give poor fit at the extremes of the data range. A restricted cubic spline with 3 knots will give a smooth, flexible fit between the outermost knots and a simple linear fit outside those knots, while only using up 1 more degree of freedom than a linear fit. They are simply provided, for example, by the rcs() function in the R rms package. I suspect that a model (1) replacing the polynomial terms with splines and (2) limiting the interactions to linear terms will remove your warning.
Third, in terms of the model itself, try to get some local statistical support. For example, there's both an IncDayS and a TimeS predictor. It's not clear what different processes those 2 time-related predictors are capturing, and if they are highly correlated then the model results might be hard to interpret. I also wonder whether this might be better described by a repeated-events survival model. Those issues might need expert help from someone you can work closely with.
Fourth, devote some effort to becoming less of a novice in statistics. As you know, properly performed biological field studies depend on a detailed understanding of the subject matter, which continues to develop over time. Proper experimental design and analysis of results similarly depend on an understanding of statistical principles. You don't need to become a professional statistician yourself, but you do need to know enough to handle simple designs, to know when to seek outside help, and how to talk intelligently with an expert when needed. An Introduction to Statistical Learning is one free and accessible reference. Look over the resources provided by Frank Harrell under the RMS (Regression Modeling Strategies) and BBR (Biostatistics for Biomedical Research) headings. Consult the R Companion for the Handbook of Biological Statistics.
Comment: Thank you for this advice. I didn't include this in the original post for the sake of brevity, but the polynomial terms were chosen after plotting the data and observing a nonlinear relationship. I created competing models using the linear vs. polynomial term for each variable using AICc, and the polynomial terms outperformed the linear terms. I thought, based on the thread linked below, that I needed to use polynomial terms in the interaction if polynomial terms were used with those main effects. But, if that is not the case, then I will try using just linear predictors in the interaction.
Comment: All variables were checked for multicollinearity using both Spearman's rank correlation prior to model building and by checking the vif of the model. In addition to adjusting the interaction term to contain just the linear versions of the predictors,  I will switch to using restricted cubic splines for the nonlinear terms. Thank you again for taking the time to answer my question.

Link to thread referenced in my previous comment: https://stats.stackexchange.com/questions/51985/interactions-terms-and-higher-order-polynomials
Comment: @C.H. my answer could be seen to underplay the importance of evaluating the high-order interaction terms; my intent was that you should evaluate whether omitting those terms made any substantive difference in the model. A useful compromise with two interacting flexibly transformed continuous predictors (splines, polynomials, etc), recommended by Frank Harrell in Section 2.7.2 of his [course notes](https://hbiostat.org/doc/rms.pdf), is to specify an interaction of one predictor in its untransformed form with the nonlinear transformation of the other, and also vice-versa.


How do i count the number of observations from 2 columns where the variables cannot be separated from one another

Question: I have a data frame of 222 observations and 2 variables: landslide_z_prediction and y (occurrences)
landslide_z_prediction takes values from 0 to 1 while ytest takes on integers 0 or 1.
my task is to find out how many of the predicted positives/negatives were predicted correctly.

if z < 0.5 --> predicted negative
if z > 0.5 --> predicted positive
if y = 0 --> observed negative
if y = 1 --> observed positive

The scenarios are:
a) if z < 0.5 and y = 0 --> prediction is correct
b) if z <0.5 and y = 1 --> prediction is wrong
c) if z > 0.5 and y = 1 --> prediction is correct
d) if z > 0.5 and y = 0 --> prediction is wrong
I have placed my 222 observations in a data.frame format
combined_predicitons <- data.frame(landslide_z_predicted, ytest)

How am I able to extract out the number of occurrences of each scenarios?
Comment: Plase, provide a sample of the data that you want to analyze. In order to understand the matter.
Answer: Hy,
I found one solution for your problem with the dplyr package. Here is the code:
library(dplyr)

# generate sample data
df <- data.frame(landslide_z_predicted=runif(75), y=sample(c(0, 1), 75, replace=T))

# add is_correct and case variables to the data frame
df <- df %>%
  mutate(is_correct = case_when((landslide_z_predicted < 0.5) & !y ~ TRUE,
                                (landslide_z_predicted >= 0.5) & y ~ TRUE,
                                TRUE ~ FALSE)) %>%
 mutate(case = case_when((landslide_z_predicted < 0.5) & !y & is_correct ~ "case_01",
                          (landslide_z_predicted < 0.5) & y & !is_correct ~ "case_02",
                          (landslide_z_predicted >= 0.5) & y & is_correct ~ "case_03",
                          (landslide_z_predicted >= 0.5) & !y & !is_correct ~ "case_04"))

# count the occurrences of the cases
df %>% select(case) %>% group_by(case) %>% summarize(count=n())

First I generate a variable called is_correct. This is True/False if the prediction was correct or not. In the second mutate I list all your cases from your question and name them "case_01", "case_02" ,... With that in hand I can group the data frame by the cases and count the occurrences.
Comment: i have edited the length of my landslide_z_predicted from 75 to 222. but the second half of the code does not run...
Comment: Would be nice if you show your code. I can't guess what you have done exactly. Becuase the code above did work for all numbers of observations. Thx!
Answer: If I understand correctly, you want a make a confusion matrix.
In order to make it I can suggest you this:
1 - Change z values into 1 or 0 according with your threshold:
Since your threshold is at 0.5 you could use round.
combined_predicitons$landslide_z_predicted_dicotomy = round(combined_predicitons$landslide_z_predicted)

Otherwise, use ifelse, if the value predicted is over the threshold, it will output a value of 1, 0 otherwise.
threshold = 0.5
combined_predicitons$landslide_z_predicted_dicotomy = ifelse(combined_predicitons$landslide_z_predicted >= threshold, 1, 0)

2 - Create the table
table(combined_predicitons$y, combined_predicitons$landslide_z_predicted_dicotomy)

With this, you'll have the number of ocurrences of each scenario.
Comment: i am getting an error that says Error in table(combined_predicitons$y, combined_predicitons$landslide_z_predicted_dicotomy) : all arguments must have the same length. I changed the number of variables from 75 to 222.
Comment: This problems come that length(combined_predicitons$y), and length(combined_predicitons$landslide_z_predicted_dicotomy) are different. And they shouldn't. {Unless class(combined_predicitons$landslide_z_predicted) is not "numeric" or is not the same size as y}

I found that there was an extra space at my second chunk of code. But this shouldn't be the problem.

I re-runned the code and I have no errors.

Check with class(combined_predicitons$y), class(combined_predicitons$landslide_z_predicted) and class(combined_predicitons$landslide_z_predicted_dicotomy) that they're all numeric.
Comment: I assume that when you say "I changed the number of variables from 75 to 222" it's about the number of rows.

Check that if there are more rows, each row has y and landslide_z_predicted values.


Extracting the Address tag from HTML using BeautifulSoup

Question: Can't seem to string the following HTML:
[<address class="styles_address__zrPvy"><svg class="styles_addressIcon__3Pu3L" height="42" viewbox="0 0 32 42" width="32" xmlns="http://www.w3.org/2000/svg"><path d="M14.381 41.153C2.462 23.873.25 22.1.25 15.75.25 7.051 7.301 0 16 0s15.75 7.051 15.75 15.75c0 6.35-2.212 8.124-14.131 25.403a1.97 1.97 0 01-3.238 0zM16 22.313a6.562 6.562 0 100-13.125 6.562 6.562 0 000 13.124z"></path></svg>Level 1 44 Market Street, Sydney</address>]

The "title" is working fine but the "address" is not extracting.
path = "C:\\Users\\mpeter\\Downloads\\lksd\\"

titleList = []

for infile in glob.glob(os.path.join(path, "*.html")):
    markup = (infile)
    soup = BeautifulSoup(open(markup, "r").read(), 'lxml')
    title = soup.find_all("title")
    title = soup.title.string
    titleList.append(title)

streetAddressList = []

for infile in glob.glob(os.path.join(path, "*.html")):
    markup = (infile)
    soup = BeautifulSoup(open(markup, "r").read(), 'lxml')
    address = soup.find_all("address", class_={"styles_address__zrPvy"})
    address = soup.address.string
    streetAddressList.append(address)

with open('output2.csv', 'w') as myfile:
   writer = csv.writer(myfile)
   writer.writerows((titleList, streetAddressList))

When I take out the address = soup.address.string it works but extracts the whole Element.
Comment: You could use `regex` to only find the adress. When you've already got the whole element in `adress`
Comment: @grumpyp, looking into it now. Any pointers on how it would be done I'm guessing 'address = re.compile (r"Something")'. Not sure what to put in something though.
Answer: Using findall we can get all matched content. then need to iterate over the resultset to get the each content.
use this code:
from bs4 import BeautifulSoup
import pandas as pd
strs = '[<address class="styles_address__zrPvy"><svg class="styles_addressIcon__3Pu3L" height="42" viewbox="0 0 32 42" width="32" xmlns="http://www.w3.org/2000/svg"><path d="M14.381 41.153C2.462 23.873.25 22.1.25 15.75.25 7.051 7.301 0 16 0s15.75 7.051 15.75 15.75c0 6.35-2.212 8.124-14.131 25.403a1.97 1.97 0 01-3.238 0zM16 22.313a6.562 6.562 0 100-13.125 6.562 6.562 0 000 13.124z"></path></svg>Level 1 44 Market Street, Sydney</address>] [<address class="styles_address__zrPvy"><svg class="styles_addressIcon__3Pu3L" height="42" viewbox="0 0 32 42" width="32" xmlns="http://www.w3.org/2000/svg"><path d="M14.381 41.153C2.462 23.873.25 22.1.25 15.75.25 7.051 7.301 0 16 0s15.75 7.051 15.75 15.75c0 6.35-2.212 8.124-14.131 25.403a1.97 1.97 0 01-3.238 0zM16 22.313a6.562 6.562 0 100-13.125 6.562 6.562 0 000 13.124z"></path></svg>14, Bengaluru, India</address>]'
soup = BeautifulSoup(strs, 'lxml')
addresses = soup.find_all(class_={"styles_address__zrPvy"})
addr = []
df = pd.DataFrame()
for address in addresses:
    addr.append(address.text)
df['address'] = addr
df

Output:
   address
0   Level 1 44 Market Street, Sydney
1   14, Bengaluru, India

now the list of addresses is in Dataframe. you can write this dataframe into a csv using df.to_csv()
Comment: Hey, it isn't working as it is a 'soup.find_all'. The reason for this is because I am pulling it from multiple files. Any assistance is greatly appreciated
Comment: Updated the answer with findall()
Comment: Hi Subbu, sorry, though how do I implement it so it writes the list to a CSV? As you can see from my sample above, it has that as the end function. You're help is greatly appreciated.
Comment: updated the answer with creating a dataframe and writing into a csv file
Comment: Hi @Subbu VidyaSekar, sorry to be a pain but can you amend it so it's using the 'glob' function as it is being extracted from _local_ HTML files. The original code above is what I want it to come from. Thanks mate =)


Is it valid using testing data for model selection when validation data cannot do the job?

Question: In Hastie's Elements of statistical learning, it says:
"The training set is used to fit the models; the validation set is used to estimate prediction error for model selection; the test set is used for assessment of the generalization error of the final chosen model."
My understanding the authors mean that when using this strategies to compare two algorithms, one should build algorithms on training data and run them on the validation data to compare them and decide on a winner.
I have a further question on this issue: What if validation data (or cross validation) gives Two winners.
Suppose I built two models, say M1 and M2, they perform equally well in cross validation. That is, I do not have a winner using validation data. Now I apply the two models to predict testing data and I see M1 performs better than M2.
My question is: in this case, can I consider M1 as the better model.
This question is basically asking whether it is valid to use testing data to do model selection when validation (cross validaiton) data cannot choose the best model.
Comment: Heiste? Do you mean Hastie, Tibshirani and Friedman?
Comment: https://en.wikipedia.org/wiki/Data_dredging
Comment: Hi Nick, your are right. The name should be Hastie
Answer: I think there's some confusion about the general framework. You should really think of three different sets:
1.) Training data, used to fit each model
2.) Testing data, independent of the training data, which is used to test how the models fit from (1) perform on new data and is used to decide which model appears to work best for predicting new data.
Note that with cross-validation, the the partitioning of (1) and (2) is done repeatedly.
3.) Validation data. In step (2), while we didn't use the testing data to fit the individual models, we did select the model we wanted based on the testing data. Therefore, we did do some fitting with the testing  data (i.e., model selection), so we should expect some bias in the performance. To remove this bias, we will withhold some from both the training and testing data, and apply our finally selected model to this hold out. This should give us an unbiased estimate of the average prediction error, under a few assumptions (i.e., the full dataset we are using looks like the data we will use in practice, conditional independence of the samples, etc.).
So with this in mind, I think your question is what to do if the testing data does not appear to show any real difference between two different models. In this case, I would not suggest using your held-out validation set to determine which model to use. The reason for that is that you will have now "poisoned the well", i.e., the whole point of the validation set is that it is supposed to be independent of all modeling decisions so we can get unbiased estimates of predictive error. You lose that once you use it to make modeling decisions. Furthermore, unless the validation set is much larger than the test/training set (which itself is a bad idea), you shouldn't expect to be able to differentiate any better using the validation set.
With that in mind, it appears we have seen that the two models predict pretty evenly, given our current data. In that case, you could consider just randomly picking one of the two (all the evidence so far says they perform equally well), picking one for reasons other than predictive power (i.e., elastic net models are easier to interpret than random forests, so if both preform equally well, chose elastic net model in case you want to dive into the "why" part of your model) or just simply average the predictions from your two models for your final prediction.
Comment: Your definition of validation and test sets are opposite to common convention.


Use of uninitialized value in numeric eq (==) at /usr/share/perl5/Net/Server/Fork.pm line 168

Question: On my new Debian Bookworm, the file /usr/share/perl5/Net/Server/Fork.pm generates an error in logs each time Munin calls it. The error logged is

"Use of uninitialized value in numeric eq (==)  at
/usr/share/perl5/Net/Server/Fork.pm line 168."

In Debian Bullseye, there is no error.
By the way, here are the differences between the two versions :
5c5
< #  Copyright (C) 2001-2017
---
> #  Copyright (C) 2001-2022
146a147
>         $self->register_child($pid, 'fork');
167c168
<     if (SOCK_DGRAM == $sock->getsockopt(SOL_SOCKET,SO_TYPE)) {
---
>     if (SOCK_DGRAM == unpack('i', $sock->getsockopt(SOL_SOCKET, SO_TYPE))) {

The line 168 is the last diff, where the problem occurs.
I don't know the Perl, so how can I solve this and report the error to Perl package owner ?
Answer: It looks like this issue is already reported to the project in github perl-net-server issue 32.  You could add your own analysis there to see if this can get better attention.
I don't see it reported in the central Perl bug tracking system so you might want to add it there.  If so, please include a link to the github issue.
The code fix for this should be pretty easy:
my $sockopt = unpack('i', $sock->getsockopt(SOL_SOCKET, SO_TYPE));
if (defined $sockopt and SOCK_DGRAM == $sockopt) {

assuming that variable name isn't used nearby in the code.


Compactness of the set of $n \times n$ orthogonal matrices

Question: Show that the set of all orthogonal matrices in the set of all $n \times n$ matrices  endowed with any norm topology is compact.
Comment: The column vectors of an orthogonal matrix are unit vectors. And there are $n$ column vectors.
Comment: It would also be expeditious to use the operator norm.  What is the operator norm of an orthogonal matrix?
Answer: Recall a compact subset of $R^{n \times n}$ is a set that is closed and bounded. One way to show closedness is to observe that the orthogonal matrices are the inverse image of the element $I$ under the continuous map $M \rightarrow MM^T$. Boundedness follows for example from the fact that each column or row is a vector of magnitude $1$.
Comment: "Magnitude 1" means Euclidean norm here.
Comment: Why is the map continuous? Can you explain it a little bit more? I am thinking of a clear and concise way to prove it. (I have background in functional analysis.)
Comment: Can you elaborate on how this implies boundedness?
Comment: Each entry must be of absolute value at most 1, since the column it is in has magnitude 1, for example.
Comment: Yes but what is the norm?
Comment: The map is polynomial in the entries of $A$. Also, a function which is continuous in each coordinate (if the space has the product topology, which it does) is continuous.


Colocar data da postagem em portugues usando [processwire]

Question: Eu estou a usar o processwire e para colocar a data da criação do poste usei o seguinte código
<?php  echo ( date("F j, Y ", $page->created). "at " . date("g:i A", $page->created));  ?>

No entanto este código faz mostrar a data no formato inglês e eu gostaria de traduzir para portugues
Vou mostrar a alteração que fiz

 Posted on <?php  echo ( date("F j, Y ", $page->created). "at " . date("g:i A", $page->created));  //antes
                                        //Alteração apartir daqui
                                      // strftime("%A, %d de %B de %Y", strtotime( $page->created));
                                        $en = ['','January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
                                        $pt = [' de ', 'janeiro', 'fevereiro', 'março', 'abril', 'maio', 'junho', 'julho', 'agosto', 'setembro', 'outubro', 'novembro', 'dezembro'];
                                            echo("
");
                                         echo str_replace($en, $pt, strftime("%d de %B de %Y as %H:%M", strtotime($date)));
                                        ?>

O que estava antes  September 2, 2015 at 10:31 AM
Depois da alteração 01 de janeiro de 1970 as 01:00
As datas são diferentes
Se alguem puder adicione a tag processwire no stackoverflow ingles já existe criada
Comment: Então vc não pode mudar o locale?
Answer: De acordo com esta discussão, você pode fazer da seguinte forma definindo a linguagem no seu config.php:
$config->timezone = 'America/Sao_Paulo';
setlocale(LC_ALL, 'pt_BR');

E exibir a data da seguinte forma:
echo strftime("%A, %d de %B de %Y", strtotime( $page->created));

Caso não possa alterar a linguagem padrão, você pode traduzir manualmente:
    $date = '1441186272'; // $page->created

    $en = array('','January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
    $pt = array(' de ', 'janeiro', 'fevereiro', 'março', 'abril', 'maio', 'junho', 'julho', 'agosto', 'setembro', 'outubro', 'novembro', 'dezembro');

    echo str_replace($en, $pt, strftime("%d de %B de %Y as %H:%M", $date));

Retornará:

28 de Setembro de 2015 as 08:54
Comment: Defenir a Linguagem afectaria todo o template e eu pertendo que que apenas traduza quando primo o botão que criei "PT" então eu fiz uma variável que substituiria  consoante o botão que foi primido
Comment: ´$config->timezone = 'America/Sao_Paulo';
           setlocale(LC_ALL, 'pt_BR');
           echo strftime("%A, %d de %B de %Y", strtotime( $page->created));´

apos colocar o codigo o que foi exibido foi

antes
September 2, 2015 at 10:31 AM

depois
Thursday, 01 de January de 1970
Comment: Formatei a resposta com mais uma alternativa para que tu possas utilizar sem alterar a linguagem padrão.
Comment: Returnou o seguinte:

 Posted on September 2, 2015 at 10:31 AM

Thursday, 01 de January de 1970

A data não cuicide e não traduziu na totalidade
Comment: Como fizestes??
Comment: editei lá em cima @Marcelo de Andrade
Comment: Você está dando um return, editei meu código. Troque o "return" por um "echo".
Comment: Mostrei lá em cima como ficou.
Comment: Retirei da resposta a função strtotime, o seu campo já deve ser do tipo date/datetime. Ficando da seguinte forma: `echo str_replace($en, $pt, strftime("%d de %B de %Y as %H:%M", $date));`
Comment: retorna o mesmo sem a função
Comment: Alguma ideia como solucionar isto ?
Comment: Qual retorno você tem ao dar um echo em `$page->created` ?
Comment: retorna '1441186272' parece  o tempo em segundos ou assim
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/29712/discussion-between-marcelo-de-andrade-and-amadeu-antunes).


Transforming coordinates system to obtain an ellipse in the standard form

Question: Let $E$ be the ellipse $x^2+xy +y^2 = 1$. I would like to obtain the area of $E$ with the formula $ab\pi$. I am not able to transform the equation in the form $\dfrac{x^2}{a^2}+\dfrac{y^2}{b^2} = 1$. The textbook I am following uses a transformation to describe $E$ as $$\dfrac{X^2}{\left(\dfrac{1}{\sqrt{3}}\right)^2}+\dfrac{Y^2}{1^2}=1$$
I do not understand what intermediate steps lead to this transformation.
EDIT : As some were curious, this is the original question:
Use Stoke's Theorem to to evaluate $\oint_C\vec{F}\cdot\vec{dr}$. Assume C is oriented counterclockwise as viewed from above.
$$\vec{F} = z\vec{i}+x\vec{j} + y\vec{k}$$
$C$ is the curve of intersection of the plane $x + y + z = 0$ and the sphere $x^2 + y^2 + z^2 = 1$.
Hint : recall that the area of an ellipse $\dfrac{x^2}{a^2}+\dfrac{y^2}{b^2} = 1$ is $ab\pi$
The textbook solution : 3 * Area of R = $3 \cdot \dfrac{\pi}{\sqrt(3)}$=$\sqrt3\pi$
Comment: This transformation does not preserve area. If you want an area-preserving transformation, you should rotate coordinates $45^\circ$ and in the new coordinates you will have the ellipse $$\frac{X^2}{2} + \frac{Y^2}{2/3} = 1.$$
Comment: https://math.stackexchange.com/questions/2341632/transform-curve-into-canonical-form-and-determine-type
 that should help you
Comment: Another area-preserving transformation is $x=X,$ $y=Y-X/2.$
Comment: So now I'm curious exactly what transformation the book chose to use and why. The parts you didn't show us presumably answer "what" and probably give some clues to "why".
Comment: I added the original question to add extra context as it could perhaps help answer the question.
Answer: Let $X=\dfrac x2$ and $Y=\dfrac x2  + y$.
Then $\dfrac{X^2}{\left(\dfrac{1}{\sqrt{3}}\right)^2}+\dfrac{Y^2}{1^2}=3X^2+Y^2=\dfrac34x^2+\dfrac14x^2+xy+y^2=1$.
Addendum:
The above explains the intermediate steps that led to the transformation, as the original post requested, but it should be noted, as alluded to in the comments, that the transformation
$\begin{pmatrix}X\\Y\end{pmatrix}=\begin{pmatrix}\frac12 & 0 \\ \frac12 &1\end{pmatrix}\begin{pmatrix}x\\y\end{pmatrix}$ has determinant $\frac12$, so this transformation halves area, and that must be taken into account when addressing the underlying question about the area of the ellipse.
Comment: Watch out. This change of coordinates is not a rotation and is not area-preserving.
Comment: You could also get $X^2+Y^2=\left(\dfrac1{\sqrt2}\right)^2$ with $X=\dfrac{x+y}2$ and $Y=\dfrac{x-y}2$
Comment: How I came up with this:  I figured that $X=ax+by$ and $Y=cx+y,$ and I solved $3X^2+Y^2=1$ to see that $a=0, 2c=1, $ and $3a^2+c^2=1$
Comment: @AmerYR: You can do it by completing the square: $y^2 + xy = (y+\tfrac12 x)^2 - (\tfrac12 x)^2$.
Comment: @Lubin:  I was merely answering the original post, asking for "what  intermediate steps lead to this transformation" from $x^2+xy+y=1$ to $3X^2+Y^2=1$; yes, as others have pointed out, this transformation does not preserve area; the determinant is $\frac12,$ and that must be accounted for when calculating area
Comment: How to come up with these transformations?
Comment: @J.W.Tanner: The square is missing on $y^2$ in the very last step.
Comment: @HansLundmark:  thank you for pointing out the typographical error.  I have edited to insert the missing superscript $2$
Comment: But your transformation does not have determinant equal to $1$.
Comment: Right, @J.W.Tanner. I think it would have been helpful to OP to point this out when you did your answer up.
Comment: Ok, @Lubin, I edited my answer accordingly
Answer: The better solution of your original problem is indeed to apply Stokes's Theorem on the original curve. Take the filled in disk bounded by the circle $C$ in the plane $x+y+z=0$. When you compute $\text{curl}\,\vec F\cdot\vec n$, you will get a constant. Then multiply this constant by the area of the circle (easy enough, since it's a circle of radius $1$).
EDIT: The textbook answer is correct, but their "derivation" is highly suspect.
Answer: This ellipse contains the six points $(\pm1,0)$, $(0,\pm1)$, $(-1,1)$, and $(1,-1)$. It's symmetric about both diagonals through the origin.
Thus the diagonal $y=-x$ is the major axis, and $y=x$ is the minor axis; the endpoints of the major axis are $(-1,1)$ and $(1,-1)$, so that the semimajor axis is of length $\sqrt2$, while the endpoints of the minor axis are $\pm(\frac1{\sqrt3},\frac1{\sqrt3})$, the semiminor axis thus being of length $\frac{\sqrt2}{\sqrt3}$.
Thus I make the area to be $$\frac{2\pi}{\sqrt3}\,,$$ while your text seems to be claiming that the area is $\pi/\sqrt3$.
Comment: Yes, @J.W.Tanner, this shows the advantage of looking at the geometry. As it happens, I was already familiar with this ellipse, and its reflection in either axis, $x^2-xy+y^2=1$, in connection with a bit of recreational mathematics I occasionally divert myself with.
Comment: Yes, the textbook claims that the area in the region is $\pi/sqrt(3)$
Comment: Right. I'm sure this won't be the first time you find an annoying error in a text.
Comment: You can see that the area of the ellipse is greater than that of the square with vertices $(\pm1,0)$ and $(0,\pm1)$, which is $2$, so if the textbook says the area is $\pi/\sqrt3$, which is less than $2$, that's wrong


How to get to a better level at playing guitar

Question: I've been playing on the guitar for more than a year now. Started on my own without any experience. To describe my level of play - I can play fingerstyle Pirates of the Caribbean, Stairway to heaven intro, Wish you were here (fingerstyle+strumming), Smells like teen spirit (finger and strum), etc.. So I can play a song with a range of chords from C,D,E,Em,A,Am,F,G,Csus,Dm,Bb...
But to the question: What would you recommend if I look forward to improving more? Should I play on my own, listen to covers, learn from ultimate guitar or try joining some group? I personally feel that I am reaching my limits when it comes to playing on my own and yet don't think I am good enough to play in a band or whatever.
Thanks for the tips.
Comment: This question could be answered by the use of three words... "Practice", "Practice" and "Practice"
Comment: If you want to level up fast, find a good teacher.
Comment: It's not even clear if you are speaking of electric, acoustic or classical guitar.
Comment: I think your question is way to broad and will end up getting closed. Anyway, do whatever you enjoy when playing and keep a critical point of view on your playing. Joining a band is a great way to improve yourself and have fun at the same time.
Comment: @NeilMeyer Practice better, not harder. Bad practices can not only heavily limit stuff like speed and accuracy, but also end in injuries or bad habits that are hard to break. OP is not asking how to practice more, as in frequency, but how to practice better, as in quality. "Practice until you can't" is not as a good general advice as one might intuitively think.
Answer: One thing that helps me maintain an interest in playing guitar, is that I recognize that no matter how good I might get, there will always be room for improvement.  Kudos to you for your desire to continually develop your skill!
In answer to your question

Should I play on my own, listen to covers, learn from ultimate guitar or try joining some group?

My recommendation is to do any or all of the above, as long as it keeps you interested and excited to continue to learn and improve.  Anything you do on guitar will help you improve.  But some things will motivate you more than others. Things you enjoy will be more likely to keep you interested in spending time with your instrument.
Spend more time doing things you enjoy than things you dread. You want playing time to mostly be something you look forward to.  But some hard work is a necessary ingredient of improvement.  However - the drills, practice and other intentional hard work will be more fun if you have a goal you are working towards that promises a sense of satisfaction and pride once accomplished.
I find that playing with other musicians provides both inspiration and an opportunity to learn from them.  I have developed a number of close musician friends who I met at events that attract musicians (open mic nights, song writing seminars, music sessions, open jams, house concerts, music festivals, etc.). Sometimes I will just get together with a friend and jam, or I will participate in open jams that are organized by local musicians I have connected with.
Another thing that really inspired me to accelerate my improvement trajectory was joining (actually forming in my case) a band.  Like you, I never thought I was good enough to be in a band. But I continued to get great feedback after performances at open mics from other musicians who even invited me to join their band.
Then I was "forced" into starting my own band after sitting in on a few numbers with another local band who introduced me to the manager of the venue.  I was called later that week to ask if "my band" could perform the next Friday night.  So I scrambled to put together a band and create a set list that all the musicians knew - and the rest was history.
So don't ever think you are not good enough to be in a band.  You may be surprised to learn that there are bands who could benefit from what you might have to offer.  Don't hold out for top dollar for your first band placement - offer your services for the opportunity to learn and have fun. Maybe you could be a backup guitarists for times when the regular guitarists can't make a gig.
Playing in a band provides a whole new level of inspiration because other band members are constantly pushing you to learn new material to expand the repertoire of the band.  And practicing with the other musicians in the band who must all learn to maintain a consistent tempo and work together as a cohesive musical entity - will help you become a better musician.
It's been said that "you play better golf when you play with better golfers". The same concept applies to musicians.  If you are lucky enough to be the least talented musician in the band (like me), the other musicians will both inspire you and help you improve.  Being surrounded on stage and at band practice with superior talent, gives you more motivation to step up your own game.
Perhaps you can make being in a band a goal that will help provide motivation to continually improve.  Keep learning to play new material.  Try to learn to play popular songs from memory.  Look for ads at music stores and in local newspapers and online (including Craig's List in the US) for bands looking to add a guitarists. Go to open mics and talk to other musicians.
If you can't find an existing band that needs your services, don't be afraid to start your own band. If you believe that you could get a good band booked at local music venues that pay - you will find musicians who will play in your band.
Keep reaching for a higher level of musicianship.  Create goals that motivate you to work towards a tangible or intrinsic reward.  Most important of all - keep it fun and enjoy the journey!  Rock on bro.
Answer: There are a lot of amazing players who like to share their knowledge. I'm fairly advanced, but when I want to learn a new song that I'm finding difficult to work out or some new technique, I turn to Youtube. You can almost always find what you're looking for. This was not available to me when I was starting out. You needed to take lessons or buy instructional booklets with videos. One on one lessons are still the best way to learn, but it's not necessary if you have a good ear. If you do have a good ear, try transcribing your favourite solos and performance pieces. You learn a lot that way. Using software that slows the track down while preserving the pitch can be very useful here. And in general, if you want to become a better musician, listen to a lot of different things that stretch your vocabulary.
Answer: Vary guitars and styles acoustic / electric. Picking strumming, blues, folk, rock. Get your chord change speed up and learn barre equivalents of fingered chords.  All this can be helped by online tutorials or a teacher. Then join a band.
One tip - if you are looking at online chords and there are ones that are virtually impossible to play, it is very likely that the guitarist was playing this a different way further up the fret board. It took me ages to figure that out.
Answer: Learn more about scales and chord theory, especially roman numeral analysis. This will enable you to analyze songs and understand how they work, and be able to transpose them to other keys. Along with that just try to figure out as many songs as you can by ear.
Answer: Start keeping a practice book.  It can contain exercises you are doing, lists of tunes you know and want to practice to keep good at, or tunes you want to learn some day, and so on.  When you practice, use your little book to add some structure to your practice.  For example, in a one-hour practice session I might spend 20 minutes doing scales and exercises, 20 minutes practicing songs I know, and 20 minutes trying to figure out songs I don't know, or just goofing around and being creative.  All of this comes out of my practice book, which helps me to remember what I've done, what I'm doing, and what I want to do.
Answer: I've seen several contributors here write about the importance of playing with others and I recommend it highly. You have options like joining a band, or attending a local jam session or just calling up a couple of musician friends and having them over to play songs each of you already know. Playing with others can inspire a person and at the same time show a person areas that need additional study and attention and almost every time you do this, you learn more about what your strong points are and what your weak points are. Also you can apply study techniques that you learned in  school such as taking notes when reading material about theory and technique. For some reason, taking notes seems to help the brain better understand the ideas being presented in the text. Don't worry to much about not being as good as somebody else, we've all been through that stage and you can work through it like the rest of us. It can be a little uncomfortable but it isn't generally permanent or fatal.


Retornar função python em um popover html

Question: Estou com um código que tem gera uma tabela com nomes de alunos e ao lado de cada nome um botão "detalhes". O objetivo é que ao clicar nesse botão abra uma pequena table ao lado do botão com as notas dos alunos. As função que retorna a nota de cada aluno funciona, só não consigo fazer com que o resultado da função apareça dentro do popover. Obs: A table com as notas de cada aluno deve ficar ao lado do seu nome, assim quanto mais a baixo ou a cima estiver o nome do aluno a table deve aparecer ao lado do botão.
Comment: Por favor, esclareça seu problema ou forneça detalhes adicionais a fim de destacar exatamente o que você precisa. Da forma como está escrito atualmente é difícil dizer com exatidão o que você está perguntando.
Answer: Para mostrar a resposta de uma função dentro de um popover, siga os passos abaixo:
Crie um evento de "clique" no botão "detalhes", e declare (dentro deste evento) que você deseja exibir as notas dos alunos quando este botão for pressionado.
Supondo que você não saiba como fazer isso...
Primeiro, adicione ao botão de "detalhes", um evento que reconheça o clique, como mostro abaixo:
document.querySelector('#botao_detalhes').addEventListener('clique', function() {
  // Este código mostra o resultado da função e mostra as notas dos alunos, dentro do popover
});

Depois, crie uma função que retorna as notas de cada aluno e uma variável que armazene os resultados:
const notas = obter_nota_de_cada_aluno();

Por último, só o que você precisará fazer é exibir o resultado da função no popover com o método innerHTML (que vai configurar o conteúdo HTML), veja:
document.querySelector('#seu_popover').innerHTML = notas_dos_alunos;

Answer: Para exibir o resultado da função dentro do popover, você pode usar o evento click do jQuery para detectar quando o botão "detalhes" é clicado e, em seguida, chamar a função que retorna as notas do aluno. Você também pode usar a função html do jQuery para atualizar o conteúdo do popover com o resultado da função.
Veja um exemplo de como fazer isso:

    Nome do aluno

      <button class="btn-detalhes" data-aluno="123">Detalhes</button>

Lembre-se de que você também precisará adicionar estilos CSS para posicionar o popover corretamente ao lado do botão.
Comment: Eu coloquei o return da função para já retornar em html.       pc = notas
    r = "Notas dos quizzes"
    for i in range(0,len(pc)):
        r += ("%s" %i)
    r += ""
    for n in pc:
        if n == '-':
            r += ("-")
        else:
            r += ("%.2f" %n)
    r += ""           Não deu certo ainda, não sei se é por conta do formato que é retornado.  Afunção já retorna a table em si pronta.


What is "Main page content" block?

Question: what is "Main page content" block?
and why do I get "Region for Main page content block field is required."
when I disabled it?
I have commerce kickstart installed
Comment: Why do you want to remove it?
Comment: I was just trying to make some sense out of it all, I was trying to remove unnecessary stuff from the home page and than I got this error...
Answer: Main page content block is the primary content of whichever page you are viewing.
Removing does not normally make sense.

What is "Main page content" block?