Let $V=\mathcal P_2(\mathbb{R})$ prove $\varphi_j(p)=p(j)$ is a basis of $\mathcal P_2(\mathbb{R})'$

Question: I would appreciate help with the first part of a problem I am self-studying:

Let $V=\mathcal P_2(\mathbb{R})$ prove $\varphi_j(p)=p(j)$ is a [dual] basis of $\mathcal P_2(\mathbb{R})'$

I think I should first show the $\varphi_j(p)$ are linear independent:
If $a_0\varphi_0+a_1\varphi_1+a_2\varphi_2=0$ then all the $a_i$ are $0$.
Taking $(a_0\varphi_0+a_1\varphi_1+a_2\varphi_2)p(j)=0$ I would like to show each $a_j=0$ but I don't see how to do that.
Maybe my whole approach is incorrect.
Thanks
Comment: Could you please explain your notation a little more?  I don't know what $\mathcal P_2(\mathbb{R})$ is or what $p(j)$ is.  Do you mean that $V$ is the space of polynomials over $\mathbb{R}$ of degree at most 2?
Comment: @ChocolateAndCheese Yes. Sorry for not being adequately explicit. And $\mathcal P_2(\mathbb{R})'$ is the dual space. I am assuming $p(j)$ is $p$ evaluated at $j$. That is part of my problem as that would be a scalar.
Comment: @ChocolateAndCheese And at this point, it is not know what the basis of $\mathcal P_2(\mathbb{R})$ is. In fact, that is the second part of the problem.
Answer: To show linear independence, we need to show that if $a_0\phi_0 + a_1\phi_1 + a_2\phi_2  = 0$, then $a_i = 0$ for $i=0,1, 2$.  We know that $\Phi =a_0\phi_0 + a_1\phi_1 + a_2\phi_2 $ is an element of $V^{'}$, the dual space of $V$, and so $\Phi$ is a map from $V$ to $\mathbb{R}$.  We are assuming that $\Phi = 0$, or in other words, $\Phi(p) = 0$ for every $p\in V$.
Consider $p = (x-1)(x-2) = x^2 -3x + 2 \in V$.  By our previous assumption we have
\begin{eqnarray}
0 &=& \Phi(p) \\
&=& (a_0\phi_0 + a_1\phi_1 + a_2\phi_2)(p) \\
&=& a_0\phi_0(p) + a_1\phi_1(p) + a_2\phi_2(p) \\
&=& a_0p(0) + a_1p(1) + a_2p(2)\\
&=& a_0(2) + a_1(0) + a_2(0)\\
&=& 2a_0
\end{eqnarray}
This implies that $a_0 = 0$.  So now we can play this same game (i.e., find other polynomials $q, r$) to show that $a_1 = 0$ and $a_2 = 0$.  This would prove the linear independence of $\phi_0, \phi_1$, and $\phi_2$.
Comment: Nice. It looks as if this also answers the second part - to find the corresponding basis $(p_0, p_1, p_2)$ of $\mathcal P_2(\mathbb{R})$ if you scale appropriately. Then, for for your example, $\varphi_0(p(0))$ would $=1$ in accordance with the definition of a dual basis.
Comment: With pleasure. Thanks
Comment: I'm surprised this question entailed such a creative approach. Usually the problems to a large extent involve correctly applying definitions and using an example as a template. But I am a self-studier with no math background and haven't been to class for about 50 years. So maybe this was intimated in a lecture. With regards,
Comment: @Andrew Glad to help.  Sometimes there are clever tricks/techniques that you learn along the way that would be hard to come up with yourself.  Best of luck in your studies!


Count number of nodes to be output

Question: I'm trying to figure out how many articles( nodes? ) will be displayed in a listing on our website, to use it to add classes to the elements that are rendered, so one can easily have different styling depending on the number of frontend elements. Right now there are six elements, so preprocess_node(&$variables) is called 6 times in template.php in my theme, but:  How can I obtain the number of nodes in the preprocess_page() - hook?
The nodes seems to be produced by a Promoted articles - type of listing.
Comment: Is your listing based on a view?
Comment: No, it looks like it is a kind of Promoted articles - listing. It is used on the frontpage and several subpages on our website. The setup is quite complex, and to me at least quite confusing, I'm new at drupal but have experience in other systems.
Comment: To get a specific answer, it might help to post your current code.
Answer: No need to modify template files. Instead create a view of Article content type and then follow the below steps.

Into view Header part add field Global: Result summary
Now into above field configuration, inside Display text area add @total token.
Comment: This is good to know, but it is not really what I'm asking, and for me this is not at all the easiest approach now. Thanks anyway.
Answer: You can use the following code inside your THEME_preprocess_page():
function THEME_preprocess_page(&$variables) {
  $content_type = 'article';
  $total = 0;
  foreach($variables['page']['content']['system_main']['nodes'] as $nid => $node) {
    if($node['#bundle'] == $content_type) {
        $total++;
    }
  }
  //if you have installed the devel module you can use dpm() to see the result;
  dpm($total);

}

Remember clean the cache.
Comment: Using db_query in a theme function is usually not the right way to go, and often dangerous. And it seems the Asker wants to know the number of articles on the page, not necessarily the total number of articles in the system.
Comment: @matt2000 Oh, thanks, I misunderstood the question, I will edit the answer now, thanks for the comment.
Comment: @matt2000 I edited the answer, now it works as expected ;-)
Comment: This answer is sort of what I was looking for, but: only one node is in the nodes-array, but 4-6 are displayed. So I'm thinking these where found in some other array, but I'm still searching to find out where...
Comment: @jonasfh in which page are you trying to see the info? I test in the  page only and it works, let me know the page to make some test
Comment: @jonasfh you got some advance?
Comment: @AdrianCidAlmaguer I found the answer now. Inside $variables['page']['content']['system_main']['nodes'][NNNNN] there is a field field_uib_profiled_article that contains the actual articles displayed on the front page.
Answer: I found the answer, and I'm posting this for reference:
$nid = $variables['node']->nid;
$arr =
  $variables['page']['content']['system_main']['nodes'][$nid]['field_uib_profiled_article'];
// counting number of elements with numeric keys:
$num_elements = count(array_filter(array_keys($arr), 'is_int'));
// $num_elements contains the number of profiled articles.
// this approach is similar to that of Adrians answer.

// Nodes could also be found with
$num_elements =
  count($variables['node']->field_uib_profiled_article['und']);

The main page had a single node containing a profiled_article - field. This field had a list of nodes that are displayed on the front page. Sorry for the incomplete description in the question, but I simply did not know where to look...

Count number of nodes to be output


Drupal security measures

Question: I have got a list of security violations for my website from security team. It says

Cookie without HttpOnly flag set
Autocomplete Password Enabled

So, what is this basically? Can I overcome this in my Drupal 7 site?
Comment: You got two comments which answered the separate questions, but both seem right to me. For the autocomplete password enabled - check out http://drupal.org/project/pci_update
Answer: Ask for the actual security report.  They often contain explanations about what the problem really is, as well as offering a solution.
I believe this will take care of the password autocomplete issue; I have a client who requires this and have it deployed on a few sites.
function mymodule_form_alter (&$form, &$form_state, $form_id)
{
  // http://www.midwesternmac.com/blogs/jeff-geerling/disabling-autocomplete-forms

  if ($form['#id'] == 'user-login') {
    $form['#attributes']['autocomplete'] = 'off';
  }
}

Comment: For what it's worth, there's now a very small module that does this, called PCI Update (https://drupal.org/project/pci_update). It also turns off autocomplete on the login *block*.
Answer: From the documentation for session.cookie_httponly (you should set this flag to true in your php.ini file):

Marks the cookie as accessible only through the HTTP protocol.
  This means that the cookie won't be accessible by scripting languages, such as JavaScript.
  This setting can effectively help to reduce identity theft through XSS attacks
  (although it is not supported by all browsers).

Check out the documentation for session.cookie_httponly.
Comment: You can also do this via an ini_set() in your settings.php if you don't want to make a gloabl change.
Comment: @MPD - Yes and you could also use a `php_flag` directive in a `.htaccess` file.

Drupal security measures


Loop through values and display in a pdf file

Question: i have written the following code:
As you can see there is a for loop to go through some values and display them in the generated pdf. The problem is that all the values are being written at the same place.
I have tried to insert a new line but it does not seem to work. Can anyone suggest me how i can do it? Do i need to write a nested  for loop so that it the values at different y positions?
<code>$pdf = pdf_new();

            // open a file
            pdf_open_file($pdf, "C:/xampp/htdocs/final/6.pdf");
            pdf_set_info($pdf, "Author", "");
            pdf_set_info($pdf, "Title", "");
            pdf_set_info($pdf, "Creator", "");
            pdf_set_info($pdf, "Subject", "");
            // start a new page (A4)
            $x = 595;
            $y = 842;
            pdf_begin_page($pdf, $x, $y);
            pdf_set_parameter($pdf, 'FontOutline', 'Arial=c:\windows\fonts\arial.ttf');
            pdf_setcolor($pdf, "stroke", "rgb", 0, 0, 0, 1.0);

            // get and use a font object
            $font = pdf_findfont($pdf, "Arial", "host", 1);

            pdf_setfont($pdf, $font, 10);

            // print text
            pdf_show_xy($pdf, "QUOTATION" , 250, $y - 60);
            pdf_show_xy($pdf, "Customer Name: " . $this->customer_details['first_name'] .
                " " . $this->customer_details['last_name'], 50, 770);
            pdf_show_xy($pdf, "Date: " . date("F j, Y, g:i a"), 50, 750);
            pdf_show_xy($pdf, "Number of items requested: " . $count_items_req, 50, 730);
            pdf_show_xy($pdf, "Number of items found: " . $count_items_found, 50, 710);

            // add an image under the text
            $image = $image = PDF_load_image($pdf, "png",
                "C:/xampp/htdocs/final/images/footer_logo.png", "");

            PDF_fit_image($pdf, $image, 50, 785, "");
            pdf_moveto($pdf, 20, 780);
            pdf_lineto($pdf, 575, 780);
            pdf_stroke($pdf);

            // draw another line near the bottom of the page
            pdf_moveto($pdf, 20, 50);
            pdf_lineto($pdf, 575, 50);
            pdf_stroke($pdf);

            //Draw the lines
            $offset = 184;
            $i = 0;
            pdf_moveto($pdf, 20, $y - 160);
            pdf_lineto($pdf, $x - 20, $y - 160);
            pdf_stroke($pdf);

            pdf_moveto($pdf, $x - 400, $y - 160);
            pdf_lineto($pdf, $x - 400, 80);
            pdf_stroke($pdf);

            pdf_moveto($pdf, $x - 200, $y - 160);
            pdf_lineto($pdf, $x - 200, 80);
            pdf_stroke($pdf);

            pdf_moveto($pdf, $x - 100, $y - 160);
            pdf_lineto($pdf, $x - 100, 80);
            pdf_stroke($pdf);

            pdf_continue_text($pdf, '');
            pdf_continue_text($pdf, '');

            pdf_show_xy($pdf, "Searched Item", 70, $y - 150);
            pdf_show_xy($pdf, "Searched Item", 70, $y - 150);

            pdf_show_xy($pdf, "Item name", 240, $y - 150);
            pdf_show_xy($pdf, "Item name", 240, $y - 150);
            pdf_show_xy($pdf, "Price", $x - 180, $y - 150);
            pdf_show_xy($pdf, "Price", $x - 180, $y - 150);
            pdf_show_xy($pdf, "Discounted Price", $x - 100, $y - 150);
            pdf_show_xy($pdf, "Discounted Price", $x - 100, $y - 150);
            for ($i = 0; $i < count($this->quotation_details); $i++)
            {

                 pdf_show_xy($pdf, $this->quotation_details[$i]['name_searched'] , 70, $y - 500);

            }

            // and write some text under it
            pdf_show_xy($pdf, "", 250, 35);

            // end page
            pdf_end_page($pdf);

            // close and save file
            pdf_close($pdf);
</code>
Answer: You don't need a nested loop, you just need to change the value you subtract from $y each time. You can do it like so:
<code>
$placeholder = 500; // initial value
for ($i = 0; $i quotation_details); $i++)
{
  pdf_show_xy($pdf, $this->quotation_details[$i]['name_searched'] , 70, $y - $placeholder);
  $placeholder = $placeholder - 20;
}
</code>
You might want to subtract by more or less than 20. Play around and find a value that looks good.


accepts_nested_attributes_for - belongs_to, has_many, fields_for

Question: Is there any possible way to use nested_attributes_for in the way show below?
Basically I want to create a person, one or more cars and add details to each car.   This is just a mock up, not a very realistic example.  I get snagged when trying to build the details for the car as it hasn't been created yet.
Models:
class Person < ActiveRecord::Base
   has_many :cars
   accepts_nested_attributes_for :car
end

class Car < ActiveRecord::Base
  belongs_to :person
  has_many :details
  accepts_nested_attributes_for :details
end

class Detail < ActiveRecord::Base
  belongs_to :car
end

Form:
form_for @person do |f|
  #fields
  f.fields_for :car do |car|
    #fields
    car.fields_for :details |detail|
      =detail.text_field :content
    end
  end
end

Answer: Have a look at that http://railscasts.com/episodes/196-nested-model-form-part-1?view=asciicast


How to build a WCF to ASP.net MVC (client) architecture using JSON format/endpoint as way of communication?

Question: I am leaning towards WCF as my main source of service (I may need multiple end-points in the future), and here are the things that I have been stuck at...

WCF to CLIENT: How can I make my MVC accept JSON data from WCF service and parse it into C# primitive/complex types?
CLIENT to WCF: How can I send JSON formatted data from MVC to WCF and have it parsed to C# primitive/complex types?
side question: How can I make WCF use REST as its protocol and transmit JSON format data? Do I use REST starter kit or is it built in on WCF?

Basically, this is my architecture:
WCF === (format: JSON) ===> ASP.net MVC 3 (...and back)
WCF === (format: JSON) ===> misc client (...and back)
code samples would help greatly!
Thanks in advance for the help! :)
Answer: WCF RESTful web services are going to be your friend. In order to force the web service to return JSON take a look at this related answer.
Update: If you have control over both the client and the service it may be worth looking into WCF Data Services as an alternative. Less code = more productivity (in some cases ;))
Comment: Server side paging can be implemented using: http://blogs.msdn.com/b/astoriateam/archive/2010/02/02/server-paging-in-data-services.aspx, or on the client side: http://solidcoding.blogspot.com/2007/11/paging-with-linq.html. While I haven't used the standard LINQ paging approach in the past against Data Services I don't see why it wouldn't work.
Comment: @JanCarloViray - On second thought, you're talking about consuming a WCF Data Service from an MVC page (presumably using AJAX), so if you are looking for an OData client library for Javascript, take a look at http://www.odata.org/developers/odata-sdk. It talks about OData clients for various languages including Javascript. In that case I would probably suggest utilizing server side paging because you don't really have Linq in Javascript to help you out.
Comment: i heard that Data Services doesn't support many LINQ features.. how is it in your experience?
Comment: Data Services is strongly tied to Linq to Entities. What linq features are you concerned about being left out?
Answer: A RESTful WCF service will work, like M.Babcock said, but you can just use Ajax to call your controller action; you call your controller, which in turn calls your WCF service and returns a JsonResult. Something like this...
Controller:
public JsonResult GetData()
{
    var result = wcf.GetSomeData();
    return Json(result);
}

View:

Here's a link to a better tutorial.
Comment: hmm.. seems like asp.net MVC as a 'REST service' would be better solution for this one huh.


Gitlab Runner removes dist folder

Question: I am using gitlab runner on windows and runner is removing my artifact before my deploy stage is called
Running with gitlab-runner 10.7.1 (b9bba623)
  on Gitlab runner 8953950b
Using Shell executor...
Running on DZIVOPC...
Fetching changes...
Removing dist/
Removing node_modules/

Why is this happening.
From documnetation
Artifacts:

You can only use paths that are within the project workspace. To pass artifacts between different jobs, see dependencies.

Then in dependencies:

Note that artifacts from all previous stages are passed by default.

I have tried both with and without and with cache and without.
Still nothing :)
Answer: Add at the end of your gitlab-ci:
cache:
  untracked: true

Answer: Actually, the problem was in the
cache_dir variable. It was renamed in the newer versions so it wasn't set.

Gitlab Runner removes dist folder


Which solver is suitable for bilevel problems, CPLEX or Gurobi?

Question: I am trying to model a bi-level problem using a solver.
I wonder about CPLEX and Gurobi: which one is the best choice? Based on my research, there is no important difference between these two, or am I wrong?
Answer: You can easily find benchmark tests that compare CPLEX and Gurobi
Some of those benchmarks argue that CPLEX is better than Gurobi, while others affirm that Gurobi has a better performance than CPLEX.
Therefore, we can conclude that both solvers have similar performances when solving Mixed-Integer Linear Programming problems (as is the case of your bilevel optimization problem), see e.g. 1, 2, 3.
You may choose your solver based on:

Previous experience with the solver
License availability (both solvers have a free academical license)
Solver documentation.

Both solvers are well-documented.

CPLEX user guide
Gurobi documentation

Community (to help you with questions related to the solver usage)

A good metric is the number of questions related to CPLEX and Gurobi here on Stack Overflow (from October 15):

CPLEX: 896 questions
Gurobi: 438 questions


somar input no formato time

Question: Tenho 3 input o primeiro recebe hora de inicio o segundo hora de saída e o terceiro a subtração entre eles.
function calcular(){
    var segent = parseInt(document.getElementById('segent').value, 10);
    var segsai = parseInt(document.getElementById('segsai').value, 10);
    document.getElementById('resultseg').value = segent - segsai;
}

preciso calcular entrada - saída, porem com esse código ele retorna valores estranhos como -2, 0, -8...
Obrigado!
Answer: Isso acontece porque a conta está a ser feita ao contrário.
Deveria ser segsai (hora saída) que é o valor maior, menos segent (hora entrada) que será o valor menor.

var calc = document.getElementById('calcular');
calc.onclick = function(){
    var segent = parseInt(document.getElementById('segent').value, 10);
    var segsai = parseInt(document.getElementById('segsai').value, 10);
    document.getElementById('resultseg').value = segsai - segent;
}
<input id="segent" value="09:00" type="time"/>
<input id="segsai" value="17:00" type="time"/>
<input id="resultseg"/>
<button id="calcular">calcular</button>

somar input no formato time


Connect MySQL with Cloud Storage in GCP

Question: I am designing a network infrastructure, I am really new to this, I already have the initial part of the infrastructure defined, but now I find a detail, I need to design a scheme for data storage, where for example have:
• Instances with MySQL that only process the data but do not store anything, for example 2 GB of RAM and a 4-core processor.
• Another instance or service where I can store the data processed by MySQL, where the most important feature is the size of the HDD or SSD.
The data processed by MySQL must be stored in the other instance that I mention in the second point and also have to be able to access them in real time.
I was reading and I think the problem can be solved by connecting to MySQL & Cloud Storage, but I'm not sure if this is the solution. Currently there is a scheme similar to the following:
Current Scheme
I want to do the same scheme, but with google resources, I hope they can help me and sorry for me English
Comment: Cloud storage is not the same thing as block storage, which is what MySQL needs.
Answer: The purpose of Google Cloud Storage is to allow to store and retrieve any amount of data at any time, but you cannot modify data directly in Google Cloud Storage.
You can keep your scheme by using Google Compute VM instances and resizing or adding persistent disks when it requires more storage space [1].
However, if it is not required to keep your scheme, I recommend you to deploy your MySQL database in Google Cloud SQL that supports most common features of MySQL; the list of all differences between standard database and Cloud SQL functionality is provided here [2]. Cloud SQL offers high performance, scalability, and convenience. You can increase storage capacity and machine type of a Cloud SQL instance after its creation.
[1] Resizing a persistent disk: https://cloud.google.com/compute/docs/disks/add-persistent-disk#resize_pd
[2] Differences between Cloud SQL and standard MySQL functionality: https://cloud.google.com/sql/docs/features#differences
Comment: More details about Google Cloud SQL for MySQL are available at this page [3] (https://cloud.google.com/sql/docs/mysql/)

Connect MySQL with Cloud Storage in GCP


Generate hyperlink on each row for html table that contains database data

Question: I created Ajax based dependent dropdown list and based on the selected item I selected table from database and displayed html table as output.
Now I want to generate hyperlink for each row of html table .This hyperlink is used to access public files based on the fid
I think i cannot use views because i am generating html table based on selected item from dropdownlist
I would be more thank full if anyone can share some ideas
Comment: Still you can make use of views here. Make the drop-down list as an exposed filter and select the style under FORMATE as table
Answer: If you have custom code that generates the table then it should be easy to output the link to files as well.
I assume you are looking for info on how to get the link to the file having your file id from the database.
You will need this:
Given a File ID (fid) how can I get the HTML that represents that fid?
EDIT:
After you provided some sample code I was able to figure out what you need:
You need a slash in front of drupal.
FileName . "\">

Comment: Thanks for your reply.I have filename.using filename i have set path to public files as shown while($data = $result->fetchObject()){
    // Fill the table rows
    $rows[] = array(

      $data->Title,

      $data->Year,
      "FileName . "\">" . $data->FileName . ''
 This generates filename as link in html table but path is wrong .Any idea how to set path to public files.I am not sure what i am going is correct way or not .My main idea is to select row from html table and read and download public excel file.plz share your thoughts &ideas
Comment: can you post a print_r of your $data object? print_r($data);
Comment: @NickOwhile($data = $result->fetchObject()){
 $rows[] = array(
 $data->AuthorsList,
 //$data->FileName,
 "FileName.''shows file name with link but path to access file is wrong
    );
  }
$output = theme_table(
 array(
    "header" => $header,
    "rows" => $rows,
     "attributes" => array(),
     "sticky" => true,
      "caption" => "",
      "colgroups" => array(),
      "empty" => t("Table has no row!") // The message to be displayed if table is empty
    )
  ).theme("pager");
  return $output; plz ask if its not clear
Comment: I asked to see the result of printing the $data object. Can you change your code to while($data = $result->fetchObject()){ print_r($data);exit();} This will print the first raw $data object and you will see the actual fields and values available.
Comment: stdClass Object ( [Bib_ID] => 1 [AuthorsList] => H.K. Ciezki,G. Adomeit [Title] => Shock-tube investigation of self-ignition of n-heptane-air mixtures under engine relevant conditions [Journal] => Combustion and Flame [Year] => 1993 [CommonProperties] => equivalence ratio, temperature,ignition delay [FileName] => C&F_Dagaut_1995_Fig 1A_Pg134-97-03.xls is the raw data after i execute print_r(data).I have filename.
Comment: I have problem in setting path FileName . "\">" . $data->FileName . '' This link redirects me to http://localhost/drupal/sandbox/ajax/dropdown/view/sites/default/files/C&F_Dagaut_1995_Fig%201A_Pg%20134-97-03.xls. instead of localhost/sites/default/files/C&F_Dagaut_1995_Fig 1A_Pg 134-97-03.xls.Any idea how to set path in "
Comment: :Amazing its perfectly working.can i view excel file like a table with out downloading it?
Comment: Good. Just using html you cannot display the excel file directly. You can open it in PHP and create the html version of it. That will work in all browsers. Other solutions require some Microsoft plugins but it's not going to help you on other platforms.


How to convert a React Fragment to an Array?

Question: I am using an external library, Carousel, which expects its children to be composed of an array of react Components passed to it, i.e.:
<Carousel>
  <Component1/>
  <Component2/>
  <Component3/>
</Carousel>

I am also using a component, which returns a react fragment, filled with Components that I would like to pass to that Carousel Component.
The solution that I had in mind is to convert that fragment to an array. Is there a way to do that ?
for example, I want to turn this
<>
    <Component1/>
    <Component2/>
    <Component3/>
</>

to this
[<Component1/>, <Component2/>, <Component3/>]

then, all is left is to run map() on the input.
Comment: Fragment are not real markdown, it should work if you pass it in a fragment to the carousel
Comment: Which Carousel library is this?
Comment: @AjeetShah     "react-responsive-carousel": "^3.2.12",
Comment: @Zerowiel as a fragment, the carousel looked on all the components as a single element, compromising the very purpose of the carousel
Answer: Some cursory experimentation led to me finding that you can use fragment.props.children, which can then be mapped. See the following super-basic example:
export default function App() {
  const myFragment = <>
     12
  </>;

  return (

      {myFragment}
      {myFragment.props.children
          .map(i =>
{i}
)
      }
      Hello

  );
}

Comment: This seems like a great answer/place to start... OP question is deceptively tricky, and I was going to comment that a potential *and very hacky* way to do it would be to assign a key to the fragment, then access it by way of `this._internalReactFiber.key`. Which, again, is *not* a terribly good idea/something I'd do in, say, an interview coding question.
Answer: you can just return it like an array, what I have here:
my Component.js:
function Component() {
  return [
1
,
2
,
3
];
}

export default Component;

my App.js
import Component from './Component'

function App() {
  return (

      <Component />

  );
}

export default App;

and it printed 3 divs with 1 2 3 on the screen, as expected
Comment: this causes the carousel to look on all 3 divs as one and it doesn't work correctly, arrows are not displayed, etc.


Training a model on a broad patient population, then testing on a specific subset population

Question: This is a question that has been bugging me because I see this practice done in many medical papers.  Here's the scenario: you create a prognostic model from a general population of breast cancer patients with sensible exclusion criteria like no previous cancer.  Your variables end up being age, HER2 receptor status, and estrogen receptor status.  What I see in many papers is the authors validate the model, but then also test it on multiple groups of patients with very specific characteristics.  Like testing performance for HER2+ and ER+ patients only, or only on young patients who are Stage III.  They then say things like, "the model performed well on ER+/HER2- patients but not HER2+ patients overall."
Something in my gut says that it is not great practice to train a model on a broad patient population then test it on multiple different subsets of patients (e.g. only Stage III patients, or only patients <50 yrs who are Black).  I am not a statistician by training so I have no evidence for this.  Anyone know if there are bias issues with this practice?
Comment: Can you clarify what you mean by 'prognostic'. I assume that it means response to treatment? It seems that what you are describing are sub-populations for which the model does or does not fit well. This indicates that including co-variates such as age, prior health status, etc. might have improved even the fit of the original model on the larger population. However, on average it did fit well enough. But when you then look at sub-populations the possibility to improve the model becomes more apparent.
Comment: By prognostic I mean, "able to predict a patient's outcome."  In my example, it could be the model's ability to predict probability of 5-year overall survival.

Yes, the model was trained on a broad population of breast cancer patients, but the researchers then test it on a bunch of sub-populations and state conclusions like "the model performed well with X types of patients but not Y types."  My gut tells me you can't draw conclusions like that if you trained the model on a broad population.
Comment: If X and Y-types were present in the original model, this means that either the model fit for one of these types was poor and/or one of these types was underrepresented. The model could therefore be improved by including co-variates that distinguish these types, e.g. age or by giving them more relative weight. One would have to exclude the possibility that the difference between X and Y is not due the previous reasons (underrepresentation, difference in age).
Answer: It's not so much that there is a problem with bias.  It's that the research sounds inefficient and would accomplish more by including these subpopulations (and the variables that define them) in the modelling. I agree with @user12719 that additional covariates would no doubt be useful to include, and I'd add that statistical interactions might emerge as relevant too.  That is to say, not only might the original model benefit from new covariates, and not only might it perform better or worse when considering subgroups defined by those covariates, but certain predictors might loom larger or smaller, or even switch signs, depending on the subgroup under consideration.  The method you described seems to gloss over much of this.
Comment: I should have given a little more detail.  These "sub-populations" are from an external validation data set from another institution.  No data-splitting of the modeling patients.  What I was thinking is if testing the model on multiple patient sub-populations from your external validation set raises problems of multiple comparisons (it performs well/worse on some population due to chance).  Something just doesn't quite seem right with training the model on a heterogeneous population and testing it on a small homogeneous sub-population of patients (again, from another institution).


The caller was not authenticated by the service when calling from Ruby?

Question: I need to consume a SOAP web service using the Savon Ruby client. I think the endpoint is written using the .NET framework, and, in fact, we currently have a .NET client library provided by the service team.
When using the client library, it works perfectly and data is retrieved sucessfully, but when using the Savon client, I'm getting:
(a:InvalidSecurity) The caller was not authenticated by the service. (Savon::SOAPFault)

The thing is, we already checked the SOAP requests, and both seem to be the same. The only difference is that one is done using Ruby and the other is done using .NET.
Below are a couple examples of both requests:
.NET client
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Header>
<Identity xmlns="http://vauto.com/webservices/Haystak/1.0/" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <AccessId>2A6B3F9FC49D1F4388AF7064045D964E</AccessId>
  <AccessStamp>2014-01-31T16:46:07.1597194-05:00</AccessStamp>
  <Signature>et0KyY1ZnjCM5z7BhQR9Q3Fj7V4=</Signature>
</Identity>
</s:Header>
<s:Body>
<GetVehicles xmlns="http://vauto.com/webservices/Haystak/1.0/">
  <request xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    <EntityId>TEST01</EntityId>
  </request>
</GetVehicles>
</s:Body>
</s:Envelope>

Ruby client:
<?xml version="1.0" encoding="UTF-8"?>
  <env:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xmlns:wsdl="http://vauto.com/webservices/Haystak/1.0/"
            xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
  <env:Header>
    <Identity xmlns="http://vauto.com/webservices/Haystak/1.0/"
              xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
      <AccessId>2A6B3F9FC49D1F4388AF7064045D964E</AccessId>
      <AccessStamp>2014-02-03T10:24:50.3690365-05:00</AccessStamp>
      <Signature>ykKc5tWCyY9UVb+zw50hfAxOnSA=</Signature>
    </Identity>
</env:Header>
<env:Body>
  <wsdl:GetVehicles>
    <request xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <EntityId>TEST01</EntityId>
  <EntityName i:nil="true" />
  <HaystakId i:nil="true" />
  <Vins i:nil="true"
          xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays" />
    </request>
  </wsdl:GetVehicles>
</env:Body>

The WSDL for the web service is as follows:

Any help is greately appreciated. I'm kind of lost and don't know what else to try in order to consume that web service.
Answer: A couple of things:

Your two SOAP requests are structurally very different, one is a <wsdl:GetVehicles> request (Savon) and the other is a <HelloWorld> (.NET).
The order of the tags in your header is different.  Ideally, this should not make a difference, but if the XML API on the server is retarded it can make things misbehave.
Your .NET identity block is namespaced but your Savon identity block is not.
Your Savon request has a namespace xmlns:wsdl="http://tempuri.org/" which looks invalid.

SOAP is a misnomer, because it's not simple, and I've always thought that it is monumentally more difficult when you make calls between Microsoft and non-Microsoft ecosystems.
First steps first, ensure you are generating the same request in both clients, and take it from there.  Identical requests should elicit identical responses.
Comment: I'd do my best to break it so they have to write it correctly.
Comment: +1. "SOAP is a misnomer, because it's not simple"... hmmm, I thought they were being sarcastic when they said it was simple. "...if the XML API on the server is retarded it can make things misbehave." - so incredibly true. "Identical requests should elicit identical responses.", yes, definitely so. That's what we expect when we build any sort of service.
Comment: @theTinMan you haven't lived till you've seen a SOAP server implemented in regex... and you're the poor bastard who has to interface with it.
Comment: Is there a way to change savon's  per just GetVehicles? I configured everything to match by hard coding the message except per that wsdl
Comment: In the end as suggested on the responses the problem had to do with using wsdl:GetVehicles instead of plain GetVehicles


javascript syntax questioon

Question: So let's say I have the following code:
function c (f,i) {
  let x = i;
  if (f(x,i)){
     x--;
  }
  if (f(x,2)) {
     console.log(1);
  }
  else {
     console.log(2);
  }
}

what exactly happens in the if statements, I don't understand the syntax behind it.
f is no function, it's a variable, so what happens here? does it equal to f * ( x * i)? whats the operands behind this syntax.
Thanks in advance
Comment: "f is no function, its a variable" - the two are not exclusive. Matter of fact, `f(x,i)` is a call expression, so unless `f` is a function, this will throw.
Comment: Actually, I'd assume that `f` is a function. You can pass functions to other functions in javascript
Comment: If 'f' is no function your code is bad and you will receive the error 'Uncaught TypeError: f is not a function'; if you need to pass 'f' as argument function look the @edwin suggestion.
Answer: A variable can also hold a function. It's possible to call c like this:
c(function(x, i) {/* do some check with x and i */}, 10);

In the if statements, the function you pass is called to do a check. A function like this is called a callback function. You have to pass it to the c function as in the example above. So if you call c, you can also determine how the check is done that c does.

javascript syntax questioon


Como implementar múltiplos drivers de autenticação

Question: Estou construindo um sistema onde é necessário haver dois tipos de autenticação, a primeira referente a usuários comuns, que irão acessar a frente da loja, e a segunda para administradores, que irão acessar o ambiente de administração.
O problema:
por padrão o Laravel 5 possui apenas um driver de autenticação, o que possibilita que usuários comuns logados na frente da loja tenham acesso ao ambiente de administração, e vice-versa.
Identificar o que é usuário e o que é administrador é até fácil com um sistema de níveis (roles), porém não é tão efetivo quanto a divisão destas sessões.
Como posso implementar uma segunda sessão de autenticação apenas para administradores? como por exemplo: Auth::admin()
Comment: Por que o uso de roles não é efetivo nesse caso?
Answer: Voce pode "emular" uma nova Auth Class.
O componente Laravel Auth é basicamente o Illuminate\Auth\Guard class, and this class have some dependencies.
Então, basicamente você tem que criar uma nova Guard class...

class CilentGuard extends AuthGuard
{
public function getName()
{
    return 'login_' . md5('ClientAuth');
}

public function getRecallerName()
{
    return 'remember_' . md5('ClientAuth');
    }
}

E um ServiceProvider para inicializar a class, passando as dependencias.
<?php

use Illuminate\Support\ServiceProvider;
use Illuminate\Auth\EloquentUserProvider;
use Illuminate\Hashing\BcryptHasher;
use Illuminate\Auth\Reminders\PasswordBroker;
use Illuminate\Auth\Reminders\DatabaseReminderRepository;
use ClientGuard;
use ClientAuth;

class ClientServiceProvider extends ServiceProvider
{

    public function register()
    {
        $this->registerAuth();
        $this->registerReminders();
    }

    protected function registerAuth()
    {
        $this->registerClientCrypt();
        $this->registerClientProvider();
        $this->registerClientGuard();
    }

    protected function registerClientCrypt()
    {
        $this->app['client.auth.crypt'] = $this->app->share(function($app)
        {
            return new BcryptHasher;
        });
    }

    protected function registerClientProvider()
    {
        $this->app['client.auth.provider'] = $this->app->share(function($app)
        {
            return new EloquentUserProvider(
                $app['client.auth.crypt'],
                'Client'
            );
        });
    }

    protected function registerClientGuard()
    {
        $this->app['client.auth'] = $this->app->share(function($app)
        {
            $guard = new Guard(
                $app['client.auth.provider'],
                $app['session.store']
            );

            $guard->setCookieJar($app['cookie']);
            return $guard;
        });
    }

    protected function registerReminders()
    {
        # DatabaseReminderRepository
        $this->registerReminderDatabaseRepository();

        # PasswordBroker
        $this->app['client.reminder'] = $this->app->share(function($app)
        {
            return new PasswordBroker(
                $app['client.reminder.repository'],
                $app['client.auth.provider'],
                $app['redirect'],
                $app['mailer'],
                'emails.client.reminder' // email template for the reminder
            );
        });
    }

    protected function registerReminderDatabaseRepository()
    {
        $this->app['client.reminder.repository'] = $this->app->share(function($app)
        {
            $connection   = $app['db']->connection();
            $table        = 'client_reminders';
            $key          = $app['config']['app.key'];

            return new DatabaseReminderRepository($connection, $table, $key);
        });
    }

    public function provides()
    {
        return array(
            'client.auth',
            'client.auth.provider',
            'client.auth.crypt',
            'client.reminder.repository',
            'client.reminder',
        );
    }
}

Neste Service Provider, eu coloquei alguns exemplo de como criar um 'novo' componente para lembrar a senha. Agora você precisa criar duas novas facades, uma para autenticação e outra para os lembrar a senha.
<?php
use Illuminate\Support\Facades\Facade;

class ClientAuth extends Facade
{

    protected static function getFacadeAccessor()
    {
        return 'client.auth';
    }
}

E
<?php
use Illuminate\Support\Facades\Facade;

class ClientPassword extends Facade
{

    protected static function getFacadeAccessor()
    {
        return 'client.reminder';
    }
}

Claro que, para o lembrar senha, você precisa criar a tabela no banco de dados, a fim de trabalhar. Neste exemplo, o nome da tabela deve ser client_reminders, como você pode ver no método registerReminderDatabaseRepository no Service Provider. A estrutura da tabela é a mesma que a tabela original. Depois disso, você pode usar seu ClientAuth da mesma maneira como você usa a classe Auth. E a mesma coisa para ClientPassword com a Password Class.
ClientAuth::gust();
ClientAuth::attempt(array('email' => $email, 'password' => $password));

ClientPassword::remind($credentials);

Não se esqueça de adicionar o seu provider de serviços para a providers list de serviços no arquivo app/config/app.php.
Comment: Amigo, só uma dúvida. Onde eu deveria colocar essa nova Guard Class? no caso, CilentGuard.


Implementing multithread using XCode for IPhone

Question: Is there a way implement multi threading in IPhone using xcode? Could you refer me to few tuts that I could use.
Thanks and Regards
Abishek R Srikaanth
Comment: Have you really tried Google?
Comment: possible duplicate of [Where can I find a good tutorial on iPhone/Objective c multithreading?](http://stackoverflow.com/questions/1004845/where-can-i-find-a-good-tutorial-on-iphone-objective-c-multithreading)
Comment: The response is in an other question : [good-tutorial-on-iphone-objective-c-multithreading](http://stackoverflow.com/questions/1004845/where-can-i-find-a-good-tutorial-on-iphone-objective-c-multithreading)
Answer: The easiest way to implement multi-threading is probably going to be using NSOperationQueue. You subclass NSOperation, or create an NSBlockOperation with the code block you want to run in the background. Set a completion block if you need to be notified on the main thread when the background task finishes. Then add your operation to an NSOperationQueue and you're set! You can also set dependancies on the operation to run a series of events one at a time, or add many operations to the queue if you don't care what order they're executed in.
There are other ways of doing threading, but NSOperation is especially nice since it wraps everything up into a neat unit of work, where you're less likely to make shared memory mistakes, and also you can trust NSOperationQueue to look at the number of cores in your device and do the right thing when it comes to running many operations at once.


Difference between feature, feature set and feature vector

Question: I learnt that a feature is an individual measurable property of a phenomenon being observed.
Say for example, I am representing a human being.
Then various features could be the age, weight, height, etc. Now if I place these features in a vector, a feature vector is formed. From what I have got, the feature vector (an array), in this case will be having three elements-  The first being the age, then weight and finally the height. Similarly for 'n' individuals, I would be having 'n' feature vectors each having 3 elements.
In this context what is a feature set?
Answer: A feature vector is a vector that stores the features for a particular observation in a specific order.
For example, Alice is 26 years old and she is 5' 6" tall. Her feature vector could be [26, 5.5] or [5.5, 26] depending on your choice of how to order the elements. The order is only important insofar as it is consistent.
A feature set is a set of all the attributes that you're interested in, e.g. height and age.
The implicit assumption when using this terminology is that your data is tabular -- somehow, you have chosen to represent it as a "flat", matrix-like format. But non-tabular data formats, like network graphs, video, audio, images, binary data sequences, ... these all require some amount of engineering to represent as feature vectors.
Answer: Feature: is a list of numbers eg: age, name, height, weight etc., that means every column is a feature in relational table.
Feature Vector is representation of particular row in relational table. Each row is a feature vector, row 'n' is a feature vector for the 'n'th sample.
Feature Set: Help to predict the output variable.
Example: To predict the age of particular person we need to know the year of birth. Here Feature Set = Year of Birth.
Normally good feature set can be identified using expert domain knowledge or mathematical approach.
Hope this will help you. Cheers!!!.
Answer: From a simple data structures perspective, the difference is that a set has no inherent order and contains no duplicates (c.f. a bag of lottery balls) while a vector has order and may contain any value (similar to an array or one-dimensional matrix).


Is there a way to subtract one array from another in kotlin

Question: I would like to subtract one IntArray from another in the most efficient way, for example (3,3,2) minus (1,2,4) to get (2,1,-2) as output. I tried doing while loops, but for some reason it just didn´t do anything (im pretty new to kotlin/programming). This is what I tried:
var firstArray: IntArray = intArrayOf(1,2,3)
var secondArray: IntArray = intArrayOf(4,4,1)
var differ: IntArray = intArrayOf(0,0,0)

fun difference(){
    var i = 0
    while (i < 3) {
        differ[i] = firstArray[i] - secondArray[i]
        i = i + 1
    }
}

I couldn´t find a correct syntax for kotlin. Any help is appreciated!
Comment: what do you mean by "it just didn't do anything"? if you call `difference()` it would calculate the difference of both... and set the values in `differ` accordingly... so your code isn't wrong... it's just not the most idiomatic/optimized one... the shortest other solution to your problem is just: `firstArray.zip(secondArray, Int::minus)` or `firstArray.zip(secondArray) { a, b -> a - b }` ... from there you can call: `toIntArray()` , `toTypedArray()`, `toList()` or just simply do `.forEach(::println)`
Answer: You can use zip with map to achieve it
val differ = firstArray.zip(secondArray).map { el1, el2 ->
    el1 - el2
}

zip joins two arrays together, creating List of pairs of elements (zip docs).
Comment: note that you can use the overloaded zip-function to simplify it: `firstArray.zip(secondArray) { el1, el2 -> el1 - el2 }` or just `firstArray.zip(secondArray, Int::minus)`...
Comment: Cool thing... +1
Answer: Your method difference doesn't even have a return value…
If you want to subtract one array from another and do that index based for each element, then you should create a fun that takes two arguments, the minuend and the subtrahend, and has a return value, the resulting IntArray:
fun main() {
    var firstArray: IntArray = intArrayOf(1,2,3)
    var secondArray: IntArray = intArrayOf(4,4,1)

    // call the subtraction function
    val difference = subtract(firstArray, secondArray)

    // print the result
    for (i in difference) {
        print("$i ")
    }
}

fun subtract(minuend:IntArray, subtrahend:IntArray): IntArray {
    // check if both have same length and throw an Exception if not
    if (minuend.size != subtrahend.size) {
        throw RuntimeException("Cannot handle arrays of different size")
    } else {
        // then initialize an empty result array
        val result: IntArray = IntArray(minuend.size)

        // subtract the elements from another, index based
        for (i in 0..minuend.size - 1) {
            // and store the result in the corresponding index of the result array
            result[i] = minuend[i] - subtrahend[i]
        }

        // and finally return the result
        return result
    }
}

Answer: Not exactly Array, but you can get IntArray
  val firstArray = arrayOf(1,2,3)
  val secondArray = arrayOf(1,1,1)
  val thirdArray:IntArray

  thirdArray=firstArray.zip(secondArray).map { it.first - it.second }.toIntArray()
  print("Diff ${thirdArray[0]} ${thirdArray[1]} ${thirdArray[2]} ")

Comment: you could also just call `toTypedArray()` instead... note that there exists an overloaded zip function that accepts a transform function directly, so you can skip that `map`-step...


$i^*(\omega)$ vanish on S $\Leftrightarrow$ A is tangent to $S$

Question: If $\omega\in \Omega^2(\mathbb{R}^3)$ is a 2-form: $\omega=f\;dx\wedge dy+g\;dx\wedge dz+h\;dy \wedge dz$, and $S$ is a surface in $\mathbb{R}^3$, prove that $i^*(\omega)$ vanish on $S$ $\iff$ $A=h\frac{\partial}{\partial x}-g\frac{\partial}{\partial y}+f\frac{\partial}{\partial z}$ is tangent to $S$.
The only clue I have been able to find is that there exists this isomorphism:
$$ \phi:\mathfrak{X}(\mathbb{R}^3)\longrightarrow \Omega^2(\mathbb{R}^3)$$
$$ A \longmapsto \phi(A),$$
where $\phi(A)(B,C)=(B\times C)\cdot A$. In this way $\phi(A)=h\;dx\wedge dy-g\;dx\wedge dz+f\;dy \wedge dz$, which is similar to what we are working about. Any idea?
Comment: $i^*$ is the pullback of the identity function
Answer: By duality, $\omega$ corresponds to the vector field $(h,-g,f)$. Then $\iota^\ast(\omega)$ measures exactly the normal component of $(h,-g,f)$ with respect to $S$. With this in mind, there's nothing else to do.
Explicitly, we identify $$F_1\partial_x + F_2\partial_y +F_3 \partial_z \leftrightarrow F_1 \;{\rm d}y\wedge dz +F_2 \,{\rm d}x\;\wedge {\rm d}y + F_3\; {\rm d}x \wedge {\rm d}y.$$You can check that this is an isomorphism between $\mathfrak{X}(\Bbb R^3)$ and $\Omega^2(\Bbb R^3)$. This works for the following reason: if $\beta_2$ denotes that isomorphism, and $$\begin{align} {\rm id}\colon & \quad C^\infty(\Bbb R^3) \ni f \mapsto f \in \Omega^0(\Bbb R^3)\\ \beta_1:& \quad \mathfrak{X}(\Bbb R^3) \ni F_1\partial_x+F_2\partial_y+F_3\partial_z \mapsto F_1\,{\rm d}x+F_2\,{\rm d}y+F_3\,{\rm d}z \in \Omega^1(\Bbb R^3) \\ \beta_3:&\quad C^\infty(\Bbb R^3) \ni f \mapsto f\,{\rm d}x\wedge {\rm d}y\wedge {\rm d}z \in \Omega^3(\Bbb R^3),\end{align}$$then $\beta_1 \circ {\rm grad} = {\rm d} \circ {\rm id}$, $\beta_3\circ {\rm div} = {\rm d} \circ \beta_2$ and $\beta_2 \circ {\rm curl} = {\rm d} \circ \beta_1$. Also, if $F,G \in \mathfrak{X}(\Bbb R^3)$, we have $$\beta_1(F)\wedge \beta_1(G) = \beta_2(F \times G).$$
Comment: I do not understand why $i^*(\omega )$ measures the normal component of (h,-g,f).
Comment: It is because $\iota^*(\omega)$ only "eats" vectors which are tangent to $S$ and $\omega(u,v) = \langle u \times v, (h,-g,f)\rangle$.
Answer: Remark that if $\Omega$ is the determinant form on $\mathbb{R}^3$, $\Omega(A,..)=\omega$.
Suppose that the restriction of $\omega$ to $S$ is  zero and $A$ is not tangent to $S$, there exists $x\in S, u,v\in T_xS$ such that $A(x),u,v)$ is a basis of $\mathbb{R}^3$, this impllies that $\Omega(A(x),u,v)\neq 0$ contradiction.
On the other hand, suppose that $A(x)\in T_xS, x\in S$ we deduce that for every $u,v$ in $T_xS$, the dimension of $Vec(A(x),u,v)$ is at most 2 this implies that $\Omega(A(x),u,v)=\omega_x(u,v)=0$.


Sharing Assets folder between front end and backend of ASP.NET MVC solution

Question: I've recently been put in charge of finishing a project that one of our former developers began building.
Basically what I'm trying to do is set up a path to a shared assets folder that will contain images to be shared and accessed via both the front and back ends which sit on the same domain.
The back end has the functionality to upload images to this shared folder to be displayed on the front end.
There are multiple environments - localhost , staging and the live site itself.
The previous dev created a Paths class to handle this however it seemed to duplicate the assets from the backend to the front end.
So the path I want to set is for the assets root directory which would be;

localhost/sitename.com.au/Assets
staging.sitename.com.au/Assets
sitename.com.au/Assets

The problem is that if I use the ~/Assets it stays on the subdomain level and I need it to go up a level to the site root (see below)
Here's the current url structures:
LOCAL DEV

localhost/sitename.com.au/Front-End Solution
localhost/sitename.com.au/System.Administration Solution

STAGING (TEST SERVER)

staging.subdomain.sitename.com.au
staging.admin.sitename.com.au

LIVE

subdomain.sitename.com.au
admin.sitename.com.au

I'm only relatively new to this so any help is appreciated.
Comment: add this comment as an aswer to your question. Otherwise, it remains categorized as opened.
Comment: Problem resolved using virtual directories (example.com/Assets) in each solution pointing to a central physical path (C:/.../application/SharedAssets)on IIS server.
Answer: Problem resolved using virtual directories (example.com/Assets) in each solution pointing to a central physical path (C:/.../application/SharedAssets) on IIS server.


How to call this tkinter gui function?

Question: How do i access windows function in Mygui class?
I want to create colored content in my tkinter box#
but i can't pass value to it.
      from tkinter import *
            class Mygui:
                def window(self, colour):
                    self.main_window=Tk()
                    self.main_window.geometry('300x100')
                    self.main_window.title('Login')
                    self.top_frame=Frame(self.main_window)
                    self.top_frame.pack()
                    self.label=Label(self.top_frame, fg=colour, text="Sample Text", width=45)
                    self.label.pack(side="top")
                    self.label1=Label(self.top_frame,text=" ", width=45)
                    self.label1.pack(side="top")
                    self.my_button = Button(self.main_window, text="Retry", command=self.do_something,  height=2, width=18)
                    self.my_button.pack()

                    mainloop()
                def do_something(self):
                    print('ok')

            class login:
                def example(self):
                    print("Start")
                    Mygui.window('blue')

            a = login.example(' ')

The error i get is:
  Start
  Traceback (most recent call last):
  File "B:/data/loginMech/test.py", line 25, in <module>
  a = login.example(' ')
  File "B:/data/loginMech/test.py", line 23, in example
  Mygui.window('blue')
  TypeError: window() missing 1 required positional argument: 'colour'

Answer: Mygui is a class, not a function. So, you have to construct an instance of it, like this:
gui = Mygui()

And then you can call methods on that instance:
gui.window('blue')

When you write Mygui.window, that's an unbound method, which you can call by explicitly passing it a self argument along with its other arguments. But you'd still need to have something to pass as that self:
gui = Mygui()
Mygui.window(gui, 'blue')

In general, you don't want to do this. There are cases where unbound methods are useful, but if you have one, you probably know you have one.

And you need to do the same thing with login:
log = login()
log.example()

By calling login.example, you're using an unbound method again. And then you're passing ' ' as the self argument. This doesn't make any sense, because ' ' is not a login instance, but CPython 3.x happens to not check for that error, so you get away with it.
Answer: Abarnet pointed out one fix however in Tkinter it might be better to inherit from the Tkinter class Tk to start you GUI.
Take this example. A much smaller amount of code and produces the same results desired.
import tkinter as tk

class MyGUI(tk.Tk):
    def __init__(self, colour):
        tk.Tk.__init__(self)
        self.geometry('300x100')
        self.title('Login')
        tk.Label(self, fg=colour, text="Sample Text", width=45, pady=10).grid(row=0, column=0)
        tk.Button(self, text="Retry", command=self.do_something, height=2, width=18).grid(row=1, column=0)

    def do_something(self):
        print('ok')

MyGUI("Blue").mainloop()

Results:

How to call this tkinter gui function?


Installing PHP7 on CentOS 6.8, encountering GLIBC issue

Question: I am trying to install PHP 7 from REMI repo, I managed to install it but when I try to issue command:
yum install php70

I get error
Error: Package: php70-php-cli-7.0.12-2.el7.remi.x86_64 (remi-safe)
           Requires: libc.so.6(GLIBC_2.15)(64bit)

I tried to look into installing GLIBC_2.15 on CentOS 6.8 but mostly found that it is not recommended. Is there any workaround or better way to install php7?
Comment: Dont mix and match packages and repos for el6 and el7.
Answer: You are obviously trying to install a EL-7 package on an EL-6 distro.

Remove the remi-release package
install the correct version
yum clean metadata

And PHP 7 is also available for EL-6 in my repo.
Reminder: follow the Wizard instructions.


ProxyPass: discard body data

Question: I have some rules like
<code><Location /xyz>
    ProxyPass http://example.com/abc
    ...
</Location>
</code>
I want to accept requests to http://mypage.lan/xyz/123 and deliver the data of http://example.com/abc/123. I need to accept POST request, but I don't want to send the body content to example.com. I would like to send a GET request, but a POST request with Content-Length: 0 would be fine, too.
Is it possible, to configure Apache 2 not to promote the request body?
Answer: No, it's not possible for the body data to be modified in this way by Apache (or to proxy a different method than received).  The most modification that it can do is to tweak headers.
I'd question the need for a web service that behaves in this way (just send the right request from the client?), but if you do need to do this, consider using application code running within Apache that modifies the request in the needed  ways and creates its own request to the backend server.
Comment: I mean that you could use application code like PHP, perl, or python that can run within Apache, not an Apache module.

ProxyPass: discard body data


Factor $X^7-(4+i)\in\mathbb{Q}(i)[X]$...if possible.

Question:
I think $X^7-(4+i)\in\mathbb{Q}(i)[X]$ is irreducible (simply because I don't know how to go about factoring it). Would it suffice to show that it is irreducible over $\mathbb{Z}[i]$?

If so, I can consider
\begin{align*}
X^7-(4+i)+\langle i\rangle=X^7-1+\langle i\rangle\in\dfrac{\mathbb{Z}[i]}{\langle i\rangle}[X]\cong\mathbb{Z}[X],
\end{align*}
where $\langle i\rangle$ is the prime ideal (since $\mathbb{Z}[i]/\langle i \rangle\cong\mathbb{Z}$ is a domain) generated by $i$.  Am I completely off my rocker?
Comment: You made a very bad error. In $\mathbf Z[i]$ the element $i$ is a unit, so $\mathbf Z[i]/(i)$ is *zero* rather than $\mathbf Z$. The ideal $(i)$ in $\mathbf Z[i]$ is the whole ring, not a prime ideal. This situation is not at all like $\mathbf Z[x]/(x) \cong \mathbf Z$.
Comment: Not by a long shot: $\mathbf Z[i]/(4+i)$ is finite. You really need to review modular arithmetic in the Gaussian integers.
Comment: I see. We do have though $\mathbb{Z}[i]/(4+i)\cong\mathbb{Z}$, yes?
Comment: Another error was in typesetting: writing $$ instead of $\langle i\rangle$.  I fixed it.
Answer: Hint: I think you might be expected to notice that $4+i$ is prime in $\mathbb Z[i]$ and to think about whether you can adapt Eisenstein's Criterion to this slightly different case.
Comment: @Brandon: No, that idea does not work in general. Consider in $\mathbf Q(\sqrt{5})[x]$ the quadratic polynomial $x^2-x-1$. It is irreducible in $\mathbf Z[\sqrt{5}][x]$ but it factors in $\mathbf Q(\sqrt{5})[x]$. This is related to the issue of rings being integrally closed or not. Unlike $\mathbf Z[\sqrt{5}]$, the ring $\mathbf Z[i]$ is integrally closed.
Comment: I see how $4+i$ is prime. Since $4+i\in<4+i>$ and $4+i\not\in<(4+i)^2>=<15+8i>$, by Eisenstein's we conclude irreducibility. Yes? In general, is it sufficient to show irreducibility in $\mathbb{Q}$ adjoin anything by showing irreducibility in $\mathbb{Z}$ adjoin the same thing? In general, this is because the field of fractions of $\mathbb{Z}$ is $\mathbb{Q}$?
Comment: @Brandon KCd's comment illustrates what I mean about thinking about this problem. If you study algebra you will find ideas like "integrally closed" often given as abstract definitions, but they were developed by thinking about problems which arise when you try to extend useful things you know about $\mathbb Z$ and $\mathbb Q$ to extensions.
Answer: Let $R$ be a GCD domain and $K$ its field of fractions. A non-constant polynomial $f\in R[X]$ is irreducible if and only if it is primitive and irreducible in $K[X]$; see here.
Fortunately $\mathbb Z[i]$ is a GCD domain (it's even a Euclidean domain), so $X^7-(4+i)$ is irreducible in $\mathbb Q(i)[X]$ iff $X^7-(4+i)$ is irreducible in $\mathbb Z[i][X]$. Now you can use the Eisenstein's criterion for the prime ideal $\mathfrak p=(4+i)$. (Why is this a prime ideal? Well, this is proved e.g. here: $a+bi$ is prime in $\mathbb{Z}[i]$ if and only if $a^2+b^2$ is prime in $\mathbb{Z}$. In fact, $\mathbb Z[i]/(4+i)\simeq\mathbb Z/17\mathbb Z$ which is a finite field.)
Comment: Note that the @KCd's example $R=\mathbb Z[\sqrt 5]$ isn't a GCD domain.


A sequence of functions ${f_n}$ that converges non-uniformly to $f$ but the limit of the integrals equals the integral of the limits?

Question: Construct an example to show that it is possible to have a sequence of continuous functions $\{f_n\}$ that converges non-uniformly to a continuous function $f$ on a closed interval $[a,b]$, but we also have that
$$
\lim_{n\to\infty}\int_a^b f_n(x) dx = \int_a^bf(x) dx
$$
The example I thought of was to define
   $f(x) = \left\{
     \begin{array}{lr}
       nx & : 0\leq x < 1/n\\
       \frac{-n}{n-1}x+\frac{n}{n-1} & : 1/n \leq x \leq1
     \end{array}
   \right.$
I'm fairly certain that $f_n(x) \to f(x)=-x+1$ non-uniformly on $[0,1]$ and both of the integrals would be equal to $\frac{1}{2}$. This example seems a little messy to me though. Are there any cleaner looking examples, perhaps with $f_n$ not defined piece-wise?
EDIT: Looking at my example, I'm not sure that $f_n \to f$ anymore, since that doesn't even converge pointwise.
Answer: Consider $[a,b]:=[0,1]$ and $f_n(x):=4n^2\max\{x(1/n-x),0\}$. Then $f_n$ is continuous and converges to $f(x):=0$, but the convergence is not uniform, since $f_n(1/(2n))=1\not\to0=f(0)$. Moreover,
\begin{align*}
\int_0^1f_n(x)dx=4n^2\int_0^\frac{1}{n}(x/n-x^2)dx=\frac{2}{3n}\to0=\int_0^1f(x)dx.
\end{align*}
Answer: You can modify your solution by making your function equal to a bump centered at $x = 1/n$ with width $1/2n$ and height $\sqrt{n}$, and zero elsewhere outside the bump. Then your sequence of functions will converge to $f$ being the zero function but not uniformly, but the integrals will converge to zero which is the integral of the limit $f$.


Using argparse with function that takes **kwargs argument

Question: I'm using argparse to take input and pass it to a function that takes as arguments two variables and **kwargs.
Here's my function:
import requests
import sys
import argparse

def location_by_coordinate(LAT, LNG, **kwargs):
    if not kwargs:
        coordinate_url = "https://api.instagram.com/v1/locations/search?lat=%s&lng=%s&access_token=%s" % (LAT, LNG, current_token)
        r = requests.get(coordinate_url).text
    else:
        coordinate_url = "https://api.instagram.com/v1/locations/search?lat=%s&lng=%s&access_token=%s" % (LAT, LNG, current_token)
        for key, value in kwargs.iteritems():
            if 'DISTANCE' in kwargs:
                distance = kwargs.get('DISTANCE')
                if distance > 5000:
                    print distance
                    print "max distance is 5000m, value is reassigned to default of 1000m"
                    distance = 1000
                    coordinate_url = "https://api.instagram.com/v1/locations/search?lat=%s&lng=%s&access_token=%s" % (LAT, LNG, current_token)
                    r = requests.get(coordinate_url).text
                else:
                    pass
                    coordinate_url = "https://api.instagram.com/v1/locations/search?lat=%s&lng=%s&access_token=%s" % (LAT, LNG, current_token)
                    r = requests.get(coordinate_url).text
            if 'FACEBOOK_PLACES_ID' in kwargs:
                fb_places_id = kwargs.get('FACEBOOK_PLACES_ID')
                payload = {'FACEBOOK_PLACES_ID': '%s' % (fb_places_id), 'DISTANCE': '%s' % (DISTANCE)}
                r = requests.get(coordinate_url, params=payload).text
            if 'FOURSQUARE_ID' in kwargs:
                foursquare_id = kwargs.get('FOURSQUARE_ID')
                payload = {'FOURSQUARE_ID': '%s' % (foursquare_id), 'DISTANCE': '%s' % (DISTANCE)}
                r = requests.get(coordinate_url, params=payload).text
            if 'FOURSQUARE_V2_ID' in kwargs:
                foursquare_v2_id = kwargs.get('FOURSQUARE_V2_ID')
                payload = {'FOURSQUARE_V2_ID': '%s' % (foursquare_v2_id), 'DISTANCE': '%s' % (DISTANCE)}
                r = requests.get(coordinate_url, params=payload).text
    #print r
    return r

Given this function and its use of **kwargs, how should I setup the subparsers?
Here's how I've setup the command line parser thus far:
 def main():
        parser = argparse.ArgumentParser(description="API Endpoints tester")
        subparsers = parser.add_subparsers(dest="command", help="Available commands")

        location_by_parser = subparsers.add_parser("location_by_coordinate", help="location function")
        location_by_parser.add_argument("LAT", help="latitude")
        location_by_parser.add_argument("LNG", help="longitude")

        arguments = parser.parse_args(sys.argv[1:])
        arguments = vars(arguments)
        command = arguments.pop("command")
        if command == "location_by_coordinate":
            LAT, LNG = location_by_coordinate(**arguments)
        else:
            print "No command provided..."

    if __name__ == "__main__":
        main()

Obviously, the above main() function works fine with the location_by_coordinate() function when I call it at the command line like this:
$ python argstest.py location_by_coordinate 40.5949799 -73.9495148

But with the code the way it is currently, if I try:
$ python argstest.py location_by_coordinate 40.5949799 -73.9495148 DISTANCE=3000

Obviously, I get:
argstest.py: error: unrecognized arguments: DISTANCE=3000

But I'm not sure how to setup a subparser for **kwargs. If I try to setup a subparser like this:
location_by_parser.add_argument("**kwargs", help="**kwargs")

and then try that command again:
$ python argstest.py location_by_coordinate 40.5949799 -73.9495148 DISTANCE=3000

That doesn't work because the arguments object (which is a dictionary), becomes this:
{'LAT': '40.5949799', 'LNG': '-73.9495148', 'command': 'location_by_coordinate', '**kwargs': 'DISTANCE=3000'}
And this Traceback is returned:
Traceback (most recent call last):
  File "argstest.py", line 118, in <module>
    main()
  File "argstest.py", line 108, in main
    foo = location_by_coordinate(**arguments)
  File "argstest.py", line 40, in location_by_coordinate
    return r
UnboundLocalError: local variable 'r' referenced before assignment

How can I enable argparse to handle/to parse what is entered at the command line that is intended to be passed to the function via **kwargs?
Comment: You might also look at a package that builds on top of `argparse` called `plac`.  It tries to populate a parser based on the argument definitions of one or more functions.  https://pypi.python.org/pypi/plac
Answer: Do you understand what is going on with the
{'LAT': '40.5949799', 'LNG': '-73.9495148', 'command': 'location_by_coordinate', '**kwargs': 'DISTANCE=3000'}

arguments dictionary?  You defined a 'positional' argument with the name ('dest') of '**kwargs'.  You could just as well named it 'foobar'.  The parser assigned the string 'DISTANCE=3000' to that attribute in the args namespace, which turned into a dictionary key:value pair in arguments.
You could, of course, look for arguments['**kwargs'], and parse the value for yourself:
v = arguments['**kwargs']  # or pop if you prefer
if v is not None:
    k, v = v.split('=')
    arguments[k] = int(v)

It could be generalized to handle multiple pairs (defined with `nargs='*').

argparse does not handle arguments the same way as Python functions, so there's nothing exactly analogous the **kwargs.
The normal way to accept something like distance is with 'optionals' or flagged arguments.
parser.add_argument('-d','--distance', type=int, help=...)

which will accept
python argstest.py location_by_coordinate 40.5949799 -73.9495148 --distance=3000
python argstest.py location_by_coordinate 40.5949799 -73.9495148 --distance 3000
python argstest.py location_by_coordinate 40.5949799 -73.9495148 --d3000
python argstest.py location_by_coordinate 40.5949799 -73.9495148

It could also be setup to use --DISTANCE or other names.  In the last case args namespace will have a default value for distance.  The default default is None.
That's the straight forward way of adding kwarg like arguments to argparse.
Accepting arbitrary dictionary like pairs, distance:3000, distance=3000, has been asked before on SO.  The answers have always been some variation of the parsing that I sketched above.  It could be done in a custom Action class, or post parsing as I suggest.
oops, this answer is nearly a clone of one I wrote a few days ago:
https://stackoverflow.com/a/33639147/901925
A similar 2011 question:
Using argparse to parse arguments of form "arg= val"
Python argparse dict arg
=================================
(edit)
Example with a function that takes *args:
In [2]: import argparse
In [3]: def foo(*args, **kwargs):
   ...:     print('args',args)
   ...:     print('kwargs',kwargs)
   ...:
In [4]: parser=argparse.ArgumentParser()
In [5]: parser.add_argument('arg1')
In [6]: parser.add_argument('arg2',nargs='+')

In [7]: args=parser.parse_args('one two three'.split())
In [8]: args
Out[8]: Namespace(arg1='one', arg2=['two', 'three'])

So I have 2 positional arguments, one with a single string value, the other with a list (due to the + nargs).
Call foo with these args attributes:
In [10]: foo(args.arg1)
args ('one',)
kwargs {}

In [11]: foo(args.arg1, args.arg2)
args ('one', ['two', 'three'])
kwargs {}

In [12]: foo(args.arg1, arg2=args.arg2)
args ('one',)
kwargs {'arg2': ['two', 'three']}

I defined 'positionals', but it would have worked just as well with 'optionals'.  The distinction between positionals and optionals disappears in the namespace.
If I convert the namespace to a dictionary, I can pass values to foo in various ways, either through the *args or through **kwargs.  It's all in how I call foo, not in how they appear in args or arguments.  None of this is unique to argparse.
In [13]: arguments = vars(args)
In [14]: arguments
Out[14]: {'arg2': ['two', 'three'], 'arg1': 'one'}

In [15]: foo(arguments['arg2'], arguments['arg1'])
args (['two', 'three'], 'one')
kwargs {}

In [16]: foo(arguments['arg2'], arguments)
args (['two', 'three'], {'arg2': ['two', 'three'], 'arg1': 'one'})
kwargs {}

In [17]: foo(arguments['arg2'], **arguments)
args (['two', 'three'],)
kwargs {'arg2': ['two', 'three'], 'arg1': 'one'}

In [24]: foo(*arguments, **arguments)
args ('arg2', 'arg1')             # *args is the keys of arguments
kwargs {'arg2': ['two', 'three'], 'arg1': 'one'}

In [25]: foo(*arguments.values(), **arguments)
args (['two', 'three'], 'one')    # *args is the values of arguments
kwargs {'arg2': ['two', 'three'], 'arg1': 'one'}

Comment: I'm not entirely sure what you are asking, but I've added some examples of passing `args` values to a function that uses `*args`.
Comment: Just a hint: you can set `parser.add_argument('arg2',nargs='*')` which makes optional arguments truly optional
Comment: Thanks for this answer, very informative. It is possible to create an optional argument with argparse that will work with a function that takes *args? In other words, pass a list with argparse to a function?
Comment: Ok, thank you, that's what I asking. Much appreciated!
Answer:
How can I enable argparse to handle/to parse what is entered at the
  command line that is intended to be passed to the function via
  **kwargs?

This command:
$ python argstest.py location_by_coordinate 40.5949799 -73.9495148 DISTANCE=3000

does NOT execute the function call:
location_by_coordinate(40.5949799, -73.9495148, DISTANCE=3000)

That is easy to prove:
def location_by_coordinate(x, y, **kwargs):
    print "I was called!"

Go ahead and parse the args, and you'll see that the function isn't called.  As a result, all your work setting up a subparser with the name location_by_coordinate was in vain.
The argparse module just examines sys.argv, which is a simple list of strings.  Each string is one of the 'words' entered on the command line after the python command.

By default, the argument strings are taken from sys.argv,...
https://docs.python.org/3/library/argparse.html#the-parse-args-method

Yeah, sys.argv is a scary name, but a list of strings is just a list of strings.  If you look at the argparse docs, all the examples do this:
parser.parse_args('--foo FOO'.split())

A list of strings you create with split() is no different than some list of strings that sys.argv refers to.
You need to call your location_by_coordinate() function yourself.  In order to do that, you need to get the args from the command line, assemble the args that should be kwargs in a dictionary, and call your function like this:
location_by_coordinate(lat, lon, **my_dict)

If you have these values:
lat = 10
lon = 20
my_dict = {'a': 1, 'b': 2}

then the function call above will be equivalent to:
location_by_coordinate(10, 20, a=1, b=2)

Here is an example:
import argparse

def dostuff(x, y, **kwargs):
    print x, y, kwargs

parser = argparse.ArgumentParser()
parser.add_argument("LAT")
parser.add_argument("LON")
parser.add_argument("--distance")
args = parser.parse_args()
my_dict = {}
my_dict["distance"] = args.distance

dostuff(args.LAT, args.LON, **my_dict)

$ python my_prog.py 10 20 --distance 1
10 20 {'distance': '1'}

You can also get a dict from the parser:
...
...
args = parser.parse_args()
args_dict = vars(args)
print args_dict

--output:--
{'LAT': '10', 'distance': '1', 'LON': '20'}

lat = args_dict.pop('LAT')
lon = args_dict.pop('LON')
print args_dict

--output:--
{'distance': '1'}

location_by_coordinates(lat, lon, **args_dict)

If you want to make the user type:
DISTANCE=3000

on the command line, first of all I would not make them type all caps, so lets make the goal:
distance=3000

Add another mandatory argument to the parser:
location_by_parser.add_argument("distance", help="distance")

Then after you parse the following:
$ python argstest.py location_by_coordinate 40.5949799 -73.9495148 distance=3000

you can do this:
arguments = parser.parse_args()
args_dict = vars(arguments)

The args_dict will contain the key/value pair 'distance': 'distance=3000'.  You can change that dict entry to 'distance': '3000' by doing the following:
pieces = args_dict['distance'].split('=')

if len(pieces) == 2 and pieces[0] == 'distance':
    args_dict['distance'] = pieces[1]

Or, you can set things up so that the parser will automatically execute that code by creating a custom action that executes when the distance arg is parsed:
class DistanceAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        #values => The value for the distance command line arg
        pieces = values.split('=')

        if len(pieces) == 2 and pieces[0] in ['distance', 'wave_action']:  #only allow 'distance=' and 'wave_action='
            setattr(namespace, self.dest, pieces[1]) #The dest key specified in the parser gets assigned the value
        else:
            raise argparse.ArgumentTypeError('Usage: distance=3000.  Only distance=, wave_action= allowed.')

You can use the action like this:
location_by_parser.add_argument(
    "distance",
    help="longitude",
    action=DistanceAction
)

And if you want to get fancy, you can collect all the name=val args specified on the command line into one dictionary named, say, keyword_args, which will allow you to call your method like this:
args = parser.parse_args()
args_dict = vars(args)
keyword_args = args_dict["keyword_args"]

location_by_coordinates(lat, lon, **keyword_args)

Here's the parser configuration:
location_by_parser.add_argument(
    "keyword_args",
    help="extra args",
    nargs='*',
    action=DistanceAction
)

import argparse
import sys

def location_by_coordinates(x, y, **kwargs):
    print x
    print y
    print kwargs

class DistanceAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        allowed_keywords = ['distance', 'wave_action']
        keyword_dict = {}

        for arg in values:  #values => The args found for keyword_args
            pieces = arg.split('=')

            if len(pieces) == 2 and pieces[0] in allowed_keywords:
                keyword_dict[pieces[0]] = pieces[1]
            else: #raise an error
                #Create error message:
                msg_inserts = ['{}='] * len(allowed_keywords)
                msg_template = 'Example usage: distance=3000. Only {} allowed.'.format(', '.join(msg_inserts))
                msg = msg_template.format(*allowed_keywords)

                raise argparse.ArgumentTypeError(msg)

        setattr(namespace, self.dest, keyword_dict) #The dest key specified in the
                                                    #parser gets assigned the keyword_dict--in
                                                    #this case it defaults to 'keyword_args'

parser = argparse.ArgumentParser(description="API Endpoints tester")
subparsers = parser.add_subparsers(dest="command", help="Available commands")

location_by_parser = subparsers.add_parser("location_by_coordinate", help="location function")
location_by_parser.add_argument("LAT", help="latitude")
location_by_parser.add_argument("LNG", help="longitude")
location_by_parser.add_argument("keyword_args", help="extra args", nargs='*', action=DistanceAction)

arguments = parser.parse_args()
args_dict = vars(arguments)

print args_dict

lat = args_dict['LAT']
lon = args_dict['LNG']
keyword_args = args_dict['keyword_args']

location_by_coordinates(lat, lon, **keyword_args)

Example:
$ python prog.py location_by_coordinate 40.5949799 -73.9495148 distance=3000 wave_action=1.4

{'LAT': '40.5949799', 'LNG': '-73.9495148', 'command': 'location_by_coordinate', 'keyword_args': {'distance': '3000', 'wave_action': '1.4'}}

40.5949799
-73.9495148
{'distance': '3000', 'wave_action': '1.4'}

$ python prog.py location_by_coordinate 40.5949799 -73.9495148 x=10
...
...
  File "2.py", line 25, in __call__
    raise argparse.ArgumentTypeError(msg)
argparse.ArgumentTypeError: Example usage: distance=3000. Only distance=, wave_action= allowed.


Uniqueness of extension of zero measure

Question: Let $(\Omega,\mathscr F)$ be a measurable space with two probability measures $\mu, \nu: \mathscr F\to[0,1]$ defined over it. Suppose that $\mathscr C\subset\mathscr F$ is some class of sets and
$$
  (\mu-\nu)|_\mathscr C = 0.
$$
Which necessary and sufficient conditions are known on $\mathscr C$ in order to assure that $\mu = \nu$?
For example, it is sufficient for $\mathscr C$ to be a ring of sets generating $\mathscr F$, as it follows from Caratheodory's extension theorem. However, is that  condition also necessary?
In particular, if $\sigma(\mathscr C) = \mathscr F$ can it be the case that $\mu\neq \nu$?
Answer: An interesting example is here (but not exactly what is asked here):
R. O. Davies, Measures not approximable or not specifiable by means of balls.
Mathematica 18 (1971) 157--160.
A metric space X, two Borel probability measures defined on X, the two measures agree on all balls of the metric, but the two measures do not agree on all Borel sets.
Comment: Thanks a lot, it is interesting. I also added a link, if you don't mind.
Answer: A sufficient condition is that $\mathcal{C}$ is a set of generators of $\mathcal{F}$ closed under pairwise intersections (a $\pi$-system). The proof goes via Dynkins lemma and can be found in "Probability with Martingales" by Williams.
Edit: The first version was not quite right. This works: Let $\Omega=\{1,2,3,4\}$ and $\mathcal{F}=2^\Omega$. Let $$\mathcal{C}=\big\{\{1,2\},\{3,4\},\{1,3\},\{2,4\}\big\}.$$ Clearly $\mathcal{F}=\sigma(\mathcal{C})$. Define $\mu$ by $\mu\{1\}=\mu\{4\}=1/6$ and $\mu\{2\}=\mu\{3\}=1/3$. Define $\nu$ by $\nu\{1\}=\nu\{4\}=1/3$ and $\nu\{2\}=\nu\{3\}=1/6$. Then $\nu$ and $\mu$ agree on $\mathcal{C}$, but are different probability measures. The counterexample is from "Counterexamples in Probability" by Stoyanov.
Comment: Just to update: this is Lemma 1.6 in the book mentioned. Strangely, I didn't find it in the book by Bogachev.

Uniqueness of extension of zero measure


Are there any sports for which the world's best player is female?

Question: For this question I'm referring to sports in which men and women can compete together on equal terms (even if they often don't). For example, rock climbing would count (if they climb the same rock and are measured by the same metrics), while the hammer throw would not (since men and women throw different hammers). Competitions where score is given out by a jury count too.
I'm wondering if there is a sport of this kind in which the world's best player is/was female. It doesn't have to be current; I'd also like to know if it has happened at any point in history. I'm aware that determining "the best player" isn't always easy, but looking for something where the best female players in the world are truly competitive with the best male players.
I know it's outside the scope of this site, but the closest I know is in chess, where the greatest female player of all time (Judit Polgar) 1) broke several records for which men also qualify and 2) won individual games against the world champion. However she was never world champion, with a peak world ranking of #8.
Comment: related, not quite duplicate: [Would the top 100 men in most physical sports beat each of the top 100 women?](https://skeptics.stackexchange.com/questions/43039/would-the-top-100-men-in-most-physical-sports-beat-each-of-the-top-100-women)
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/96084/discussion-on-question-by-allure-are-there-any-sports-for-which-the-worlds-best).
Comment: I've attempted to integrate the comments into the question and tidied everything up here. Further comments which attempt to improve the question are welcome, but others are liable to be deleted. In particular, any discussion of what is or isn't a sport is best on [meta](https://sports.meta.stackexchange.com/) and particularly with reference to our existing [What is counted as sport?](https://sports.meta.stackexchange.com/questions/51/what-is-counted-as-sport).
Answer: Equestrian Sports comes to my mind as the only Olympic Sports where men and women face each other in competitions. Dressage, in particular, is dominated by women. Isabell Werth and Anky van Grunsven are possibly the most prominent, having dominated the world class for the last 20 years.
I just came across this ESPN article which argues that in shooting, women are consistently doing better than men.
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/96083/discussion-on-answer-by-e-sommer-are-there-any-sports-for-which-the-worlds-bes).
Answer: Libby Riddles won the Iditarod in 1985, and then Susan Butcher won it 4 of the next 5 years. So it would be quite fair to say that in the late 1980's women were the world's top mushers.
One could argue I suppose that the dogs have the most athletic part of that sport. However, surviving and doing anything productive in an Alaskan blizzard is more than athletic enough for me, and the dogs (particularly lead dogs) themselves are often as not also female.
Answer: The current world record in endurance cycling is held by Amanda Coker.
Endurance sports are definitely something where women perform similar to men, or even outperform them (their bodies are much more economic when it comes to consuming calories).
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/96085/discussion-on-answer-by-danubian-sailor-are-there-any-sports-for-which-the-world).
Answer: Lynn Hill was arguably the best climber in the world in the late 80s and early 90s.

In 1990, at the final stage of the World Cup Final, she was one of three competitors and the only woman to reach the top of the wall—and the only climber to complete the hardest move.

She was also the first person to free climb The Nose on El Capitan, a famous challenge that had been attempted by many.
Comment: It would be really interesting to see men and women climb the same routes. With Adam Ondra currently injured it's conceivable that Janja Garnbret could win the men's lead climbing world cup this year.
Answer: Some sports have historically been played mostly by women, like synchronised swimming. Although it's hard to measure performance of individual swimmers and compare male and female ones, nowadays the top female swimmers are clearly better than the top male ones. That might change (or not) as male synchronised swimming develops.
Answer: It's a fairly uk-centric 'sport' but in long distance fell running Jasmin Paris must be one of the worlds best, she holds the outright course record for the Spine Race by a considerable margin and for several years held the outright record for the Ramsey round (both of which attract international competitors/attempts). She has also come second overall in the Dragons back race.
Another long distance fell running legend Nicky Spinks holds the outright record for the double Bob Graham round though somewhat more niche as very few people have (or would!) attempt it.
Answer: Women seem to do well in very long-distance swimming.
https://db.marathonswimmers.org/longest-swims/
https://en.wikipedia.org/wiki/Diana_Nyad
Comment: This article mentions that women being better at very long-distance swimming is backed by science: https://www.telegraph.co.uk/news/2019/09/17/cancer-survivor-becomes-first-swim-channel-four-times-non-stop/ "Women have an advantage due to their higher body fat, which provides insulation against the cold and better buoyancy." Suggest editing into answer.
Answer: In aerobatics Patty Wagstaff was the best of the US in the 1990s.  I think at world championship level the women and men had separate competitions; I can't quite remember.
Answer: Tanya Streeter has held the overall free diving record, albeit for a brief two months.

In 2002, she broke the men's No Limit (NLT) world diving record by diving to a depth of 525 feet (160 m) near the Turks and Caicos Islands, a record which was surpassed later that year by French diver Loïc Leferme (162 m).
Answer: I am surprised that no one mentioned ultra-runners Courtney Dauwalter and Camille Herron.
In 2017, Dauwalter won the MOAB 240 race (238 miles!!) beating the 2nd place finisher by over 10 hrs. This race is open to both men and women. She also has won 8 of her last 9 ultra-distance races losing only to Camille Herron who (as of March 2019) currently holds 5 world records involving ultra distance races:
Camille Herron's World Records:

50 miles (80 km) | Road  | 5h 38min 41s | 6:46 per mile (4:12 per km)
100 miles (160 km) | Road/Trail | 12h 42min 40s | 7:37 per mile (4:43 per km)
100 miles (160 km) | Track | 13h 25min 00s | 8:03 per mile (5:00 per km)
12 Hours | Track | 92.66 miles (149.12 km) | 7:46 per mile (4:49 per km)
24 Hours | Track | 162.919 miles (262.193 km) |  8:50 per mile (5:29 per km)

Taken from Wikipedia link above sourced from International Association of Ultrarunners and Ultrarunning Magazine
Answer: Drag Racing
There is no men's or women's division. Everyone races everyone.
For years, Shirley Muldowney dominated in the most powerful class.  Still today, Angelle Sampay is setting records and beating the men she competes against on a weekly basis.  Same is true for the Force Sisters and Leah Pruett, who are all world champions.
Answer: In the summer olympics 1992, Zhang Shan from China won gold in skeet shooting. Back then it was a mixed event.
Answer: Trail Orienteering
It is a sport of pure map reading, with physical racing element removed completely, designed to create an outdoor event available to many, including people using mobility aids like crutches or a wheelchair. To be successful, you need to depend mostly on your brain and somewhat on your eyes, so physical strength difference between men and women (or young and old, or healthy and disabled) doesn't matter much.
This year's World Championships have been held in Portugal two weeks ago. It consisted of 3 individual events (with winners being 2 women and 1 man) and 2 team events (with both winning teams being split 2-1 genderwise, once with more men and once with more women).
All results can be found here: http://wtoc2019.fpo.pt/


Como posso sobrepor gráficos com datas diferentes pelo Matplotlib?

Question: Como posso sobrepor três gráficos com datas diferentes em um mesmo gráfico? O código acaba gerando inícios diferentes, mas precisava plotar isso à partir de um mesmo início para a composição de um trabalho inserir a descrição da imagem aqui.
import numpy as np
import pandas as pd
import pandas_datareader.data as wb
import matplotlib.pyplot as plt
import yfinance as yf

yf.pdr_override()
%matplotlib inline

CRFB3 = yf.download('CRFB3.SA', start = '2017-07-20', end = '2019-07-20')['Adj Close']
MGLU3 = yf.download('MGLU3.SA', start = '2011-05-02', end = '2013-05-02')['Adj Close']
ASAI3 = yf.download('ASAI3.SA', start = '2021-03-01', end = '2023-03-01')['Adj Close']

norm_CRFB3 = CRFB3/CRFB3.iloc[0]*100
norm_MGLU3 = MGLU3/MGLU3.iloc[0]*100
norm_ASAI3 = ASAI3/ASAI3.iloc[0]*100

plt.plot(norm_CRFB3, linestyle='-', marker='o', color = 'blue', markersize = 2)
plt.plot(norm_MGLU3, linestyle='-', marker='o', color = 'red', markersize = 2)
plt.plot(norm_ASAI3, linestyle='-', marker='o', color = 'green', markersize = 2)

plt.ylabel('Retorno', fontsize=10)
plt.xlabel('Período', fontsize=10)

axes = plt.gca()
axes.yaxis.grid(color='black', alpha=0.5, linestyle='--', linewidth=1)

plt.title('Desempenho Varejo - Período Pós-IPO')
plt.figure(figsize=(15, 8))
plt.show()

Answer: Visto que nos 3 casos se trata de um período de 2 anos podemos contar o número de dias desde a data inicial de cada um.
start1 = pd.to_datetime('2017-07-20')
start2 = pd.to_datetime('2011-05-02')
start3 = pd.to_datetime('2021-03-01')
a = norm_CRFB3
b = norm_MGLU3
c = norm_ASAI3
a.index = (pd.to_datetime(a.index) - start1).days
b.index = (pd.to_datetime(b.index) - start2).days
c.index = (pd.to_datetime(c.index) - start3).days

plt.plot(a, linestyle='-', marker='o', color = 'blue', markersize = 2)
plt.plot(b, linestyle='-', marker='o', color = 'red', markersize = 2)
plt.plot(c, linestyle='-', marker='o', color = 'green', markersize = 2)


Why the complexity in MutationObserver?

Question: I looked at the MutationObserver API, identified unnecessary complexity, and wrote my wrapper function for it:
  window.observeDom = (element, callback, config) => {
    let conf = config || { childList: true };
    const observer = new MutationObserver(callback.bind(element));
    observer.observe(element, conf);
    return observer;
  };

Altho I prefer this function 10x over the original API, I still wonder whether there is an actual measurable performance difference in reusing the observer instance to observe different DOM nodes. Can you explain?
Answer: I don't get your point, but if you want to use a single callback to observe multiple distinct threads in a DOM this architecture is probably more useful than having another MutationObserver instance for every such thread.
Consider observing all  elements on a page using common pattern thus requiring single function to react on mutating any of those elements. You might observe  element and move complexity to your callback for deciding whether some mutation was affecting any of those  elements you are actually interested in. But that decision logic is implemented in Javascript then instead of running natively in browser. I'd bet this is having an impact on performance.
So you might observe each  element instead. Your wrapper is then creating quite as many observer instances as there are  elements in your document. That's impacting memory. And the browser has to iterate over many observers to iterate over every observer's single-item list of observerd nodes which might have another slight impact on performance. In addition by binding callback to node on every observation you actually create as many callback instances as there are  elements in your document. That's wasting memory in addition.
To observe 1000  elements this way there will be 1000 observer instances to be managed by browser, each bound to one out of 1000 differently bound, but actually identically working, function instances. Each observer is controlling one-item list of nodes to observe.
Now, using the very same callback to be registered for observing a bunch of records to be handled equivalently isn't as complex as it seems. The one and only callback might be reduced to handle the expected mutations, only. It won't have to inspect DOM to decide what element has been mutated and whether that's interesting in your case (accessing DOM is always to be considered bottleneck on performance).
To observe the same set of 1000  elements using advised API it takes 1 observer instance, 1 function instance and a single list containing 1000 references on nodes to be observed so any mutation is causing invocation of that single function. So, in this case there is only one thing to be managed a 1000 times in memory and that's the association of nodes to be observed with the actual observer.
To conclude, the API is slightly more complex to suit observations of many nodes widely spread over your document without wasting time and memory in Javascript. I'd consider this more beneficial than having a simple API even though the latter might suffice in your very specific use case.

Why the complexity in MutationObserver?