Why can't we use the pythagean theorem on this draining the tank problem?

Question:
The ends of a "parabolic" water tank are the shape of the region inside the graph of $y = x^2$ for $0 \leq y \leq 9$; the cross sections parallel to the top of the tank (and the ground) are rectangles.
At its center the tank is $9$ feet deep and $6$ feet across. The tank is $9$ feet long.
Rain has filled the tank and water is removed by pumping it up to a spout that is $2$ feet above the top of the tank.
Set up a definite integral to find the work $W$ that is done to lower the water to a depth of 4 feet and then find the work.

My integral:
$$W = \int_4^9 62.5\times9\times2\times\sqrt{9-y^2}\times9\times(11 - y) \ dy $$
I did a cross-sectional slice of rectangles so $A(x) = L\times W\times H$
Length and height were givens, I found width using triangles and using the Pythagorean theorem.
Why is this wrong. I've seen that it's suppose to be:
[ 62.5] [ 18 ] [ 11 √y - y^(3/2) ] dy over y in [ 4 , 9 ]
But not sure why.
Please help
Thank you
Comment: Draw a picture of the tank.  Where are there triangles?
Comment: The question is a bit ambiguous if you are not familiar with "parabolic" tanks.  It is shaped like a trough  every vertical left to right cross section is the same parabolic shape.  From front to back the tank does not taper or modify at all.  I think you are picturing it as  bowl shape.
Comment: @MatthewLeingang can't we use Pythagorean on, spherical and hemispherical tanks though?
Answer: The height of the water, $y$ (not the height of the tank) varies as water is pumped out of the tank.
The width of the tank for any $y$ is $2\sqrt y$
This comes from $y=x^2$ and considering the cross section of that parabola.
The length of tank is 9 feet.
The area of each cross section is $18\sqrt y$
The spout is 2 feet above the top of the tank (or 11 feet above the bottom).
$\rho$ is the density of water.
And we only need to pump the water down to the 4 foot mark.
$\rho\int_4^9 (11-y)(18\sqrt y)\ dy$
Comment: Is this because we are taking cross sections of circles, so pi*r^2? and here radius is sqrt(y) = x, so then pi*(sqrt(y))^2 = x or rather pi*(sqrt(y)) = x. But I see now pi in your answer. What are we taking cross sections of?
Comment: Or maybe we take cross sections of rectangles? So A = L*W*H, hence A = 9*(2(sqrt(y))*dy? Is this right?


How to replace 'reply' link with button?

Question: I want to replace the 'reply' link with button. As an intermediate solution I styled the link as a button with CSS, but I want it to be a real html 'button' element. The reason is, I do not want the reply links being visible to search engines, instead of it, I want to handle clicks on buttons with javascript.
I only found this 10 year old discussion on drupal site:  https://www.drupal.org/node/33170.
I created a custom comment.tpl.php and tried to modify the $links['comment']['#links']['comment-reply'] array, but without success.
Comment: Where did you try to modify the array? What function/hook? Or did you modify it in the template file comment.tpl.php?
Comment: I tried to modify it in a `comment.tpl.php` template file
Answer: There are two methods below. Both are equally effective except the second one requires that the <button> element be taken out of the list of links and put elsewhere in the template. This is either annoying or awesome depending on what outcome you're going for.
Method 1: Override MYTHEME_links()
In Drupal 7, you can turn the comment "Reply" link into a <button> element by overriding core's theme_links() function. It isn't pretty, but it's effective.
Add the function below to your theme's template.php file (replace "MYTHEME" with your theme name). Clear your cache for the change to take effect.
function MYTHEME_links($variables) {
  $links = $variables ['links'];
  $attributes = $variables ['attributes'];
  $heading = $variables ['heading'];
  global $language_url;
  $output = '';

  if (count($links) > 0) {
    // Treat the heading first if it is present to prepend it to the
    // list of links.
    if (!empty($heading)) {
      if (is_string($heading)) {
        // Prepare the array that will be used when the passed heading
        // is a string.
        $heading = array(
          'text' => $heading,
          // Set the default level of the heading.
          'level' => 'h2',
        );
      }
      $output .= '<' . $heading ['level'];
      if (!empty($heading ['class'])) {
        $output .= drupal_attributes(array('class' => $heading ['class']));
      }
      $output .= '>' . check_plain($heading ['text']) . '</' . $heading ['level'] . '>';
    }

    $output .= '
';

    $num_links = count($links);
    $i = 1;

    foreach ($links as $key => $link) {
      $class = array($key);

      // Add first, last and active classes to the list of links to help out themers.
      if ($i == 1) {
        $class [] = 'first';
      }
      if ($i == $num_links) {
        $class [] = 'last';
      }
      if (isset($link ['href']) && ($link ['href'] == $_GET ['q'] || ($link ['href'] == '<front>' && drupal_is_front_page()))
         && (empty($link ['language']) || $link ['language']->language == $language_url->language)) {
        $class [] = 'active';
      }
      $output .= '
 $class)) . '>';

      if (isset($link ['href'])) {
        if ($key == 'comment-reply') {
          // Special handling for comment 'Reply' link.
          $output .= '<button type="button">' . $link ['title'] . '</button>';
        }
        else {
          // Pass in $link as $options, they share the same keys.
          $output .= l($link ['title'], $link ['href'], $link);
        }
      }

      elseif (!empty($link ['title'])) {
        // Some links are actually not links, but we wrap these in  for adding title and class attributes.
        if (empty($link ['html'])) {
          $link ['title'] = check_plain($link ['title']);
        }
        $span_attributes = '';
        if (isset($link ['attributes'])) {
          $span_attributes = drupal_attributes($link ['attributes']);
        }
        $output .= '' . $link ['title'] . '';
      }

      $i++;
      $output .= "
\n";
    }

    $output .= '
';
  }

  return $output;
}

Breaking it down...
This bit of code:
      if (isset($link ['href'])) {
        // Pass in $link as $options, they share the same keys.
        $output .= l($link ['title'], $link ['href'], $link);
      }

was changed to
      if (isset($link ['href'])) {
        if ($key == 'comment-reply') {
          // Special handling for comment 'Reply' link.
          $output .= '<button type="button">' . $link ['title'] . '</button>';
        }
        else {
          // Pass in $link as $options, they share the same keys.
          $output .= l($link ['title'], $link ['href'], $link);
        }
      }

Of course you'll need to customize the output with whatever you need, whether it be a <form> wrapper or onclick attribute.
Unfortunately we can't use theme('button'...) because that would give us an input element. Of course we could change that by overriding theme_button() but that would affect all input elements on the site, and you would still need to override theme_links() in order to call it.
Method 2: MYTHEME_preprocess_comment()
If you don't mind taking "Reply" out of the links list altogether, this method will also work. It uses the comment preprocessor to unset the link, but not before taking the value of the URL and stuffing it into a new variable.
Again, add the function below to your theme's template.php file (replace "MYTHEME" with your theme name).
function MYTHEME_preprocess_comment(&$variables) {
  if (isset($variables['content']['links']['comment']['#links']['comment-reply'])) {
    $variables['reply_url'] = $variables['content']['links']['comment']['#links']['comment-reply']['href'];
    unset($variables['content']['links']['comment']['#links']['comment-reply']);
  }
}

Then add this (or a variation of it) wherever you would like it to appear in your copy of comment.tpl.php:
<?php if (isset($reply_url)): ?>
<button onclick="window.location.href='<?php print $reply_url ?>'">Reply</button>
<?php endif; ?>

Clear your cache for the change to take effect.
Comment: Cool. It's just generally a good idea to keep logic out of template files, which is why I suggest the preprocessor. Glad to help.
Comment: I chose the second method because of less copy/paste of code. But I made it a little bit simpler. Instead of creating the `MYTHEME_preprocess_comment` function, I simply unset the `$content['links']['comment']['#links']['comment-reply']` variable in the `comment.tpl.php`, and add a button as you have shown in your answer.


Mongodb driver C# Index not used

Question: In MongoDB:
db.estr.createIndex({_id:1, Atualizar:-1});

In C#
var a = await db.dados.Distinct(x=>x.codigo).toListAsync();
var b = await db.estr.find(x=>!a.contains(x._id) && x.Atualizar).toListAsync();

Index Stats
{
    "name" : "_id_1_Atualizar_-1",
    "key" : {
        "_id" : 1.0,
        "Atualizar" : -1.0
    },
    "host" : "OMNIIS2012HOM:27017",
    "accesses" : {
        "ops" : NumberLong(0), <----- not utilizade
        "since" : ISODate("2020-03-24T11:00:25.011-03:00")
    }
}

x.Atualizar é boolean
Answer: Recebi a resposta que resolveu aqui
Como o _id esta negado ele faz scan, então o ideal é criar o índice Atualizar/_id
db.estr.createIndex({Atualizar:-1, _id:1})

Dessa maneira ele busca por Atualizar e faz scan somente nos que preencherem essa condição, ficando muito mais rápido do que fazendo primeiramente por _id.

Mongodb driver C# Index not used


Random forest on multi-level/hierarchical-structured data

Question: I am quite new to machine learning, CART-techniques and the like, and I hope my naivete isn't too obvious.
How does Random Forest handle multi-level/hierarchical data structures (for example when cross-level interaction is of interest)?
That is, data sets with units of analysis at several hierarchical levels (e.g., students nested within schools, with data about both the students and the schools).
Just as an example, consider a multi-level data set with individuals on the first level (e.g., with data on voting behavior, demographics etc.) nested within countries at the second level (with country-level data; e.g., population):

ID  voted age female country population
1   1     19  1      1       53.01
2   1     23  0      1       53.01
3   0     43  1      1       53.01
4   1     27  1      1       53.01
5   0     67  0      1       53.01
6   1     34  1      2       47.54
7   0     54  1      2       47.54
8   0     22  1      2       47.54
9   0     78  0      2       47.54
10  1     52  0      2       47.54

Lets say that voted is the response/dependent variable and the others are predictor/independent variables. In these types of cases, margins and marginal effects of a variable (partial dependence) for some higher-level variable (e.g., population) for different individual-level variables, etc., could be very interesting. In a case similar to this, glm is of course more appropriate -- but when there are many variables, interactions and/or missing values, and/or very large-scale datasets etc., glm is not so reliable.
Subquestions: Can Random Forest explicitly handle this type of data structure in some way? If used regardless, what kind of bias does it introduce? If Random Forest is not appropriate, is there any other ensemble-type method that is?
(Question Random forest on grouped data is perhaps similar, but doesn't really answer this.)
Comment: Hi @MikaelAndersson, did you find a solution to the questions you raised? I am facing a similar situation and hope to hear your experience. Thanks.
Answer: In a single classification tree, these groups are coded the same as any other categorical variable. This is often done as either binary coding or just using an integer. There are different arguments for using either. In random forests if you are using binary coding, some groups will be included/excluded for any given tree. So you may have an indicator for country_2 but not country_3. If you leave the group variable as an integer then the ordering can affect the outcome as well. What does it mean for country > 5 and country < 12? How does that change if you randomly re-label the countries with new integers?
At each step in growing a tree, the algorithm is looking for the split that optimizing the criteria. If there are large differences between groups then the grouping variable will be important, but if it is only moderately important and you prune a tree, then the variable may essentially excluded.
Like most other machine learning algorithms, CART and random forests do not necessarily account for dependency between observations within groups the way you would expect in a hierarchical regression model. If there is dependency between observations, it should be captured by the random forest algorithm through the generation of many trees that use the grouping variable. However if other variables demonstrate greater discrimination then the grouping variable may be ignored.
In your case, country and population are perfectly collinear. There is no information gained by using both variables in your model. So you can think about how a random forest model would treat these variables in your data.
Answer: Random Forests would work fine, but you have to be very careful when you tune the hyperparameters (especially if you want a realistic measure of generalization performance).  The traditional OOB error estimates will be way optimistic since there is rampant "twinning" in your data.
To get proper tuning and generalization estimates you need to understand what are the characteristics of any new data you expect to encounter.  If you want to extrapolate to new countries, then you'll need to set up some manner of re-sample based tuning (such as k-fold cross validation) that does stratified sampling by country.
You also need to be careful how you encode the data into a Random Forest.  It appears that country is a categorical variable.  Feeding it in as a numeric would be a bit rough, but not hopeless (especially if you ordered the IDs by something useful).
Comment: I suppose their optimism depends on what new data might look like.  If new data came from other counties, then this random forest would likely not perform as well as it's OOB errors indicate.  This is because the OOB errors are still coming from samples from the same set of counties for example.
Comment: Could you expand a little on why the OOB error estimates will be too optimistic?
Comment: I am be missing something but rfs are known to be incapable of extrapolation ....
Answer: I'm actually working on a R package that runs randomForest as the local classifier along a pre-defined class hierarchy. The package can be found in R Forge under 'hie-ran-forest'. The package is already operational, although  it is failing one of the cran test (for MAC), I'm not sure exactly why. In addition to actually running randomForest for each parent node down the hierarchy, the package also contains predict functions and performance functions. One of the performance measures actually accounts for the hierarchical class structure.
The package addresses cross level interaction by first running random forest as the local classifier at each parent node of the class hierarchy. Next the predict function retrieves the proportion of out of bag votes that each case received in each local classifier. Then there are two ways to turn the proportion of votes to crisp classification: 1. a stepwise majority rule- Start with the local classifier closest to the tree root and select the child of this classifier that received the highest proportion of votes. Next, look at all the children of the selected node and again select the child that received the highest proportion of votes in the relevant local classifier. Continue until a terminal node is reached. 2. a multiplicative majority rule- multiply the proportion of votes along each path from the tree root to any of the terminal modes and select the node that received the highest multiplicative proportion of votes.
The multiplicative proportion of votes are comparable to the proportion of votes produced by a regular randomForest
Comment: Can you clarify that your package addresses "cross-level interactions", & if so, how it does this? Just saying that a package exists isn't much of an answer (I don't mean to be too critical here, but CV is looking to build a permanent repository of high-quality ML information & the fact that a package exists doesn't quite meet that standard.)
Comment: Note, your username, w/ a link to your userpage, is automatically attached to every post you make here. So there is no need to sign your posts--in fact, we prefer you don't. If you want people to be able to contact you, you can post a method (eg, your email address) on your userpage.
Comment: That's great, thanks @YoniGavish. Why not edit your answer & add that information into it?
Comment: Is that better @gung?
Comment: Yeah, that will do it, @YoniGavish, +1. Welcome to the site.


How can you universally override the get and post methods in RSpec?

Question: I'd like to override the get and post methods in RSpec.
I want to do this in order to deal with subdomains in my tests. As far as I can tell, the only way to deal with subdomains is to alter the @request object before each call. I could do this before each and every test but that's going to lead to some really messy code.
In an effort to keep things DRY I've tried using a config.before(:each) method in spec_helper.rb however this doesn't seem to be run in the same scope as the test and doesn't have access to @request.
My next bsest approach is therefore to overrride get and post which are in the correct scope.
def get *args
  @request.host = @required_domain if @required_domain
  super *args
end

I can include this code in the top of each spec file but I'd rather set it universally. If I set it in spec_helper.rb though it does not get called.
Where can I set this to override the default get method?
Answer:

however this doesn't seem to be run in the same scope as the test.

That's not quite right - it's run in the same scope, but before @request is configured, so it has no effect.
Try this:
module RequestExtensions
  def get(*)
    @request.host = @required_domain if @required_domain
    super
  end
end

RSpec.configure do |c|
  c.include RequestExtensions, :type => :controller
end

HTH,
David
Comment: That worked great thank you! I've edited your answer slightly just to include the call to `super` in the `get` method which I presume is still required?
Answer: I just ran into an issue which routed me to this question. The accepted solution guided me to the more effective implementation as of rack-test 0.6.3.
I manually created ./spec/helpers/rspec_http_request_override_helper.rb
module RspecHttpRequestsOverrideHelper

  def get(uri, params = {}, env = {}, &block)
    super(uri, params, set_json_headers(env), &block)
  end

  def post(uri, params = {}, env = {}, &block)
    super(uri, convert_to_json(params), set_json_headers(env), &block)
  end

  def put(uri, params = {}, env = {}, &block)
    super(uri, convert_to_json(params), set_json_headers(env), &block)
  end

  def delete(uri, params = {}, env = {}, &block)
    super(uri, convert_to_json(params), set_json_headers(env), &block)
  end

  # override other HTTP methods if necessary

  private

  def set_json_headers(env={})
    env.merge({'ACCEPT' => "application/json", 'CONTENT_TYPE' => 'application/json'}) unless env.nil?
  end

  def convert_to_json(params={})
    params.to_json unless params.nil?
  end

end

Then I added the below to my spec_helper.rb
# require assuming project root is loaded into ruby's class paths
require './spec/helpers/rspec_http_request_override_helper'
RSpec.configure do |config|
  config.include RspecHttpRequestsOverrideHelper

  # Other settings
end

And that was it!
Note: The get method above doesn't convert the params value to json intentionally. Param values are encoded into the query string and then sent. Not as part of the HTTP body in the request, even though the GET http method supports sending a body; see here for more details.
My issue was that the rspec test helpers for an API I am building were converting boolean types to string types when sending the request to the API. Turns out when you don't specify a content-type header for json the data is passed as multipart/form-data or x-www-form-urlencoded depending on the HTTP method; see here for more details. This was converting my special data types, which are valid in json like integers and booleans, into strings. And effectively needing me to convert them on the API's end. It wasn't until I added validation for the input into my API that this was exposed. Yay for validations and tests!
Now, I needed to effectively apply a content-type header to all my requests and convert the params to json when sending the requests; I was calling the http methods with the params value being a ruby hash. I have over 200 tests so going in an manually changing them all would not have been an optimal solution. So I implemented the below solution. Which works very well.
I decided to follow the same method definition as rack-test was and then I could effectively call super after editing the requests.
My failing tests now started passing and my previous tests where none the wiser.
Hopefully this helps others who run into a similar issue.
Answer: The question betrays incorrect assumptions. You shouldn't be writing controller specs in the first place. This should all be done with Cucumber -- and in that case, you can just specify particular URLs, so the problem goes away.
Comment: Controller specs are a very standard thing even in conjunction with cucumber. Why do you say they're inappropriate?
Comment: I wouldn't call controller specs "standard...in conjunction with Cucumber". Most developers I know who write Cucumber stories do so as a replacement for controller specs. And that's the way it usually should be. Controller specs are inappropriate because they test implementation in a domain where user-facing behavior is what's actually important. Thus, they're needlessly painful to write and (usually) don't actually test what should be tested. Conclusion: avoid entirely, except in a few edge cases. RSpec is generally only useful at the model level.
Comment: While I do agree that full integration testing is a more useful and powerful way to test controllers I do think RSpec is still useful. Perhaps my ideas of its usefulness are your edge cases but ensuring that the right things end up in the database, the wrong things don't, things do/don't get deleted, ensuring that access control is happening at the right level These are all things that aren't verified by cucumber. I don't think controller specs need to be long but they are useful
Comment: "These are all things that aren't verified by cucumber" -- dead wrong. Your Cucumber stories can and should be making simple checks to ensure that records get created or deleted. As for access control happening at the right level, that's an implementation concern, not a behavioral one. All your tests should care about is that the access control is *happening*, not where.
Comment: Although I disagree with your position on some of this and this would be an interesting discussion to have in person your style of commenting is one that I find (probably unintentionally) inflammatory. For that reason and since we won't resolve these approaches in the comments I'm going to respectfully disagree and sign off. Thank you for your input.
Comment: You know, I'd actually prefer to have this discussion if it's OK with you. If we disagree, that probably means *at least* one of us is wrong. If I'm wrong, I really would like to know. If you're wrong, you really should know. So please, let's continue.
Comment: BTW, what are you finding inflammatory? I've reread my comments with that in mind, and really don't see it. I'm certainly not pulling my punches here in terms of saying things are inappropriate, but I don't see anything that I'd consider inflammatory if it were addressed to me.
Comment: You've got a very direct abrupt phrasing to your comments which to someone who doesn't  know you doesn't seem to come across how you intend them. When communicating in writing, statements like "dead wrong" and your opening quotation of my comments gives a hostile impression. I can see that they probably weren't meant that way but that's how they come across. Rudeness like beauty can sometimes lie in the eye of the beholder though.
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/5918/discussion-between-peter-nixey-and-marnen-laibow-koser)


Build valid json object in Twig

Question: So I'm trying to build a JSON object in a Twig template and ran into some issues.
Responding to a POST request with something like this from a Twig works fine:
<code>{"urls": ["/a","/b"]}
</code>
However if there's invalid json for example a trailing comma, like this;
<code>{"urls": ["/a","/b",,,,,]}
</code>
then javascript complains when it receives it (which makes sense as it's invalid).
Doing something like this will always result in invalid JSON because of the trailing comma:
<code>{"urls": [
{% for i in objects %}
    "/img/example/'~i.get_url()",
{% endfor %}
]}
</code>
Question:
So how do you use Twig to loop over an array of objects and build a valid JSON object?
Comment: A templating language isn't really suited to creating complex objects. This is something you should be solving in PHP.
Comment: Thanks guys! that makes sense now that I think about it I'll build the object in the model or a service. @Matteo the get_url() is just for example purposes, the problem is the last comma.
Comment: Don't go this way. Templates should DISPLAY only and not contain any logic. I know it's tempting, but still…
Comment: The problem is the last comma? or if the get_url return an invalid url?
Comment: If you can't do this in your controller, at least use a custom Twig function to create your json. https://symfony.com/doc/current/templating/twig_extension.html
Answer: You can check if is the last loop iteration with the standard cycle twig variable, as example:
<code>{"urls": [
{% for i in objects %}
    "/img/example/'{{i.get_url()}}"{% if not loop.last %}  , {%endif%}
{% endfor %}
]}
</code>
Check this working example
Hope this help
Answer: You could create a custom twig filter and output it on the page like :
<code>{{ objects |obj2Json }}
</code>
In the filter you could just json_encode the object.
https://symfony.com/doc/current/templating/twig_extension.html

Build valid json object in Twig


What is this musical symbol (inverted "Z" inside a staff)

Question: Can anyone identify the symbol circled in the image below? It's from a piece of piano music.
Answer: Ordinary quarter rest in a somewhat uncommon but not unheard-of style.  French publisher?
Comment: That's nothing -- wait 'til you run into scores (also French, usually) where the flags are backwards!
Comment: Sometimes you will also see what looks just like a backwards eighth rest -- like what you circled above but without the bottom part.  That is also a quarter rest.
Comment: @JörgWMittag Brilliantly put, I'm going to use that one! By night I'm a musician, but by day I'm an engineer from the UK, and my pet peeve is that Americans insist on calling them "English" units when the correct term is "US Customary." The US gallon, for example is completely different from the British gallon (which of course has fell out of use years ago.) But which of these makes more sense: `A B H C` or `A Bb B C`?? We all like to be different in some way or other ;-)
Comment: @steveverrill Interestingly, the B H in German notation comes from earlier times, when tritones were forbidden as "diabolus in musica" in sacred music.  The way to avoid a tritone was to distinguish between "square b" or B natural when using with an E and "round b" or B flat when using with an F.  From these, we get our natural and flat signs.  German H reflects the natural sign, and German B reflects the flat sign.  Oh, and by the way, we Americans have our pet peeves at UK insistences too, "Mitchigan" being among them.  :)
Comment: @steveverrill The term that can be memorized well. Some guys insist on do, re, mi or even ut, re mi. So, what?!
Comment: @BobRodes Wow, that is a very interesting bit of music trivia to have emerged from off-topic nationalistic banter! BTW, I always say "Mishigan", "BirmingHAM" (Alabama) and "BIRMINGham" (UK) ;-)
Comment: If some self-important toff attempts to correct you on Michigan, you can always mention that it is a French transliteration of the Native American Meesheega, meaning "great water", and encourage him to improve his education. :)
Comment: @LevelRiverSt the gallon may have fallen out of use, but the imperial system of measurement is alive and well in the UK, as you will quickly realize if you discuss with anyone from the US the size of a pint or the number of ounces it contains.  But calling US units "English" is perfectly justified as England is the source of these units.  We just missed the innovation of the imperial system because we had already left the empire by that point.
Answer: As there are 4 beats in the bar, it has to be a crotchet (quarter note ) rest. It's probably easier to draw than the regular one, but there is an alternative which is the opposite way round to the quaver rest, again, easier to write.


Completing the square: How does $5x^2−4Nx+2N^2$ get to this?

Question: I've been stuck on this for the past few hours. For context, you can refer to this thread, and in particular this answer which makes sense, but skips over all the steps.
How does
$5x^2-4Nx+2N^2=$
Become
$5(x-\frac{2N}{5})^2+\frac{6N^2}{5}$?
Comment: make it a monic polynomial first.  Then complete the square with the first two terms.
Answer: First let $P(x)$ be the polynomial you want,then we can factor out of the 5
$$P(x)=5\left(x^2-\frac45Nx+\frac25N^2\right)=5\left(x^2-2\cdot\frac25Nx+\frac25N^2\right)$$
Now since
$$(a+b)^2=a^2+2ab+b^2$$
So
$$P(x)=5\left(\underbrace{x^2-2\cdot\frac25 Nx\color{red}{+\frac4{25}N^2}}_{\left(x-\frac{2N}{5}\right)^2}\color{red}{-\frac4{25}N^2}+\frac25N^2\right)=5\left(\left(x-\frac{2N}5\right)^2+\frac6{25}N^2\right)\\\boxed{P(x)=5\left(x-\frac{2N}{5}\right)^2+\frac65N^2}$$
Comment: Why does the -4/5Nx become -2 2/5Nx?
Comment: @Rene It appears that banana means $-\frac{4}{5} = -2 \cdot \frac{2}{5}$ rather than the mixed number $2~\frac{2}{5} = 2 + \frac{2}{5}$.
Comment: That makes sense. Thanks for all the help
Answer: $$5x^2-4Nx+2N^2 = 5(x^2-\frac{4N}{5}x) \;+ 2N^2$$
Now, you add the square of half the $\frac{4N}{5}x$ term, without the $x$. But you also subtract it to balance the equation on the outside (Remember the 5 on the outside of the parentheses)
$$5(x^2-\frac{4N}{5}x \;+(\frac{4N}{10})^2)\;+2N^2-5(\frac{4N}{10})^2$$
$$5(x-\frac{4N}{10})^2\;+2N^2-5(\frac{4N}{10})^2$$
Simplifying,
$$5(x-\frac{2N}{5})^2+\frac{6N^2}{5}$$
Comment: Sorry, it should be fixed now.


how do i add a login menu to superfish menu module?

Question: I thought i would be able to add the default User Login menu to a Superfish block, but it doesn't appear in the drop down list to be able to select when configuring the Superfish block.
Can anyone advise how to create a login menu for superfish that disappears when users are logged in. I have my Main Menu in Superfish 1 block, and my User Menu (contains logout) in my Superfish 2 block (works perfectly as only appears when logged in), and wanted a Superfish 3  for User Login (to only appear when logged out).
Perhaps there is an easier way to do this, so open to suggestions?
Comment: i have added a menu item to User Menu for Login (/user/login), this works fine when Im logged out as just 'Member Login' appears, but when logged in, the Member Login item is still visible in the menu. Any ideas?
Answer: Instead of using SuperFish, you should consider using:
TB Mega Menu

TB Mega Menu allows you to create a mega menu with an innovative
back-end user interface and synchronized with Drupal core menu.

Synchronized with Drupal core menu, auto updated if there's any change with - -  - Drupal core menu
Bootstrap framework
Responsive ready
Multiple built-in styles designed with years of theming experience
Visual and friendly user interface - what you see is what you get
Custom style for each element of your mega menu, just input extra css class name
Multiple built-in CSS3 animated effects
Work independently with themes

Speaking from experience, I know you can add the login block to TB Mega Menu
Here is a Video Tutorial
Answer: I merely added an extra option to my main menu called 'Member Login' path user/login , then once you login this automatically disappears and I get my User Menu appear in my Superfish2 block with has my logout and other options that are only permitted by authenticated users. Thanks for advise on other menus.


How to compose for male falsetto?

Question: I'm writing a musical theatre piece and I want one of the male character's parts to be sung completely in falsetto, but I have no idea what clef to write it in. Would I write it in treble clef or tenor clef?
To my understanding, the range for male falsetto is equivalent to a soprano, right? So if I were to write it in tenor clef it would be very high up on the ledger lines. Would it make more sense to write it in treble clef and write it as I would for a soprano?!
Also: At what note does falsetto usually start? Is it like female head voice, or does it start lower? I'm extremely confused on this since I'm female.
Comment: It starts on different notes for different people.  A bass's falsetto will be rather different from a tenor's.
Comment: It will depend to an extent on where the vocalist's break point is - it'll be different for each person. The key may or may not be appropriate. Write it on the stave that's familiar, and put an 8va or 15va on the clef sign to show it's up an octave or two.
Answer: The range for male falsetto tends to be that of alto.  A few soloists might dip into mezzosoprano ranges, but alto is quite more common.
One reason is that for a usable falsetto range, you are better off with a deeper chest voice and that limits the higher range.  If you want your singer to stay solidly in falsetto, you'll still want to avoid low alto range (A3 tends to be on the low side even for a baritone falsetto so you cannot expect significant volume there and below without register change, but the actual falsetto low point varies between singers).
With regard to the clef, you'll use standard violin clef.  It's fine for spelling out the range, and today's singers who are comfortable in that range are used to it.
There are several hardly-anything-but falsetto parts in Orff's Carmina Burana written in bass clef and labelled for baritone.
I would not recommend doing that: falsetto singing is not a weird trick on the side nowadays so you can expect singers with control of that range and technique to be more comfortable with violin clef.

How to compose for male falsetto?


iPhone: Recognize the human voice accurately

Question: I am developing an application where I need to recognize human(to be precise baby crying) voice. I referred following articles for recording sound on iPhone microphone and sample it.
http://mobileorchard.com/tutorial-detecting-when-a-user-blows-into-the-mic/
http://developer.apple.com/library/ios/#samplecode/aurioTouch/Introduction/Intro.html
http://developer.apple.com/library/ios/#samplecode/SpeakHere/Introduction/Intro.html
...but I didn't get how can I accurately distinguish the human voice from any other voice. Any help or sample code on this would be really helpful.
So far I wrote following code:
<code>-(void)levelTimerCallback:(NSTimer *)timer {
  [recorder updateMeters];
  const double ALPHA = 0.05;
  double peakPowerForChannel = pow(10, (0.05 * [recorder peakPowerForChannel:0]));
  lowPassResults = ALPHA * peakPowerForChannel + (1.0 - ALPHA) * lowPassResults;
  NSLog(@"frequency: %f", lowPassResults);
  NSLog(@"Average input: %f Peak input: %f", [recorder averagePowerForChannel:0], [recorder peakPowerForChannel:0]);
  if (lowPassResults < 0.95)
    [self playSound];
}
</code>
Thanks.
Comment: Aha...I forgot to append my code. :)

-(void)levelTimerCallback:(NSTimer *)timer {
 [recorder updateMeters];

 const double ALPHA = 0.05;
 double peakPowerForChannel = pow(10, (0.05 * [recorder peakPowerForChannel:0]));
 lowPassResults = ALPHA * peakPowerForChannel + (1.0 - ALPHA) * lowPassResults;

    NSLog(@"frequency: %f", lowPassResults);

    NSLog(@"Average input: %f Peak input: %f", [recorder averagePowerForChannel:0], [recorder peakPowerForChannel:0]);

 if (lowPassResults < 0.95)
  [self playSound];
}
Comment: I basically used code given at http://mobileorchard.com/tutorial-detecting-when-a-user-blows-into-the-mic/. Based on Andrew's response I don't think I will be able to recognise baby crying sound. Is there anyway to find out what would be the value of lowPassResults in my above code for baby crying sound? Is there any documents that says different sounds with their frequency/amplitude?
Answer: This is a very difficult problem. Speech recognition is a complex subject, and even massive companies can't get it right. A suggestion would be to sample it and see if it is within a certain, high-pitched range. Beyond that, you would need to read up on speech recognition theory.
As this answer shows, it is not within the range of the iPhone SDK, so it will not be a simple answer.
Comment: Thanks Andrew. I don't want exact sound recognition functionality but if I could find out what could be the frequency/amplitude of baby crying then that would fine too.


How to declare sub matrices after using mat2cell?

Question: I have 6x6 matrix (ud), which I have split into 3x3 small blocks using the below:
%Splitting of array
B = mat2cell(ud, udBlockVectorR, udBlockVectorC);

Next, I want to find the median of each sub matrices in B.
I tried using this,
for i = 1: 1: udNumBlockC
for j = 1: 1: udNumBlockC
%Find the median of each block
udMV = median( B{i, j}, :);
end
end

However, it does not give me the answers I am looking for.
How do I declare the sub matrices, so that I can use them for the above purpose?
Answer: Split up the 6x6 matrix ud as follows,
>> B = mat2cell(ud, [3 3],[3 3])
B =
    [3x3 double]    [3x3 double]
    [3x3 double]    [3x3 double]

Next, to get a single value from median for a 2D array, you need to reshape the input (i.e. 3x3 -> 9x1), otherwise you get a value for each column. Horizontally concatenate each sub-matrix so you can reshape them all at once (i.e. 3x12 -> 9x4).  For ud = magic(6):
>> meds = median(reshape([B{:}],3*3,[]))
meds =
     7    29    23    14

In the above command, [B{:}] is the 3x12. The reshape command puts all the values in each 3x3 matrix as one of 4 columns. Then median computes the median for each column (sub-matrix).
The order of sub-matrixes is (row,col): (1,1), (2,1), (1,2), (2,2).
Comment: @Amilia If the answer does what you asked, please condider accepting it (use the large tick mark). This request (compare each element with the median) was not on the original question. Anyway: yes, use a `for` loop, or use `arrayfun(@(n) B{n}>=meds(n), 1:numel(B))`, which will give you a cell array with the comparison results
Comment: Alright, thank you:) next, if i want to compare every element in the 3x3 sub matrix, with the median of the sub matrix, how do i call for each element? use for loop?


Unir listas baseada em valor de coluna chave

Question: Estou convertendo 2 dataframes em 2 listas. E vou agrupa-las pela coluna CNPJ_UF_MES (sempre a 1ª coluna de cada dataframe. No exemplo real, unirei mais de 2 dataframes.
Após agrupar essas listas, terei listas de listas. e preciso uni-las baseados na coluna chave.
import pandas as pd

df1 = pd.DataFrame({
    'CNPJ_UF_MES': ['1-MG', '1-MG', '2-MG'],
    'CLIENTE_PAR_COMEX': ['1_2_3', '2_3_4', '3_4_5'],
    'REG': ['1110', '1110', '1110'],
    'COD_IP_PAR': ['200', '200', '200'],
    'COD_CLIENTE': ['xxr', 'xxv', 'xxw'],
    'IND_COMEX': ['wer', 'cad', 'sder'],
    'IND_EXTEMP': ['key_1', 'key_2', 'key_3'],
    'DT_INI': ['01032021', '01032021', '01032021'],
    'DT_FIN': ['31032021', '31032021', '31032021'],
    'VALOR': ['wer', 'cad', 'sder'],
    'PIPE_FIN': ['', '', '']
})

df2 = pd.DataFrame({
    'CNPJ_UF_MES': ['1-MG', '1-MG', '1-MG', '1-MG', '2-MG', '2-MG'],
    'CLIENTE_PAR_COMEX': ['1_2_3', '2_3_4', '3_4_5','1_2_3', '2_3_4', '3_4_5'],
    'REG': ['1110', '1110', '1110', '1110', '1110', '1110'],
    'COD_MCAPT': ['C-200', 'C-200', 'C-200', 'C-200', 'C-200', 'C-200'],
    'DT_OP': ['07032021', '07032021', '07032021', '08032021', '08032021', '08032021'],
    'VALOR': ['1', '2', '3', '1', '2', '3'],
    'QTD': ['2', '2', '2', '2', '2', '2'],
    'CNPJ_ADQUI': ['123', '123', '123', '123', '123', '123'],
    'PIPE_FIN': ['', '', '', '', '', '']

})

list1 = df1.values.tolist()
#print(list1)

values = set(map(lambda x:x[0], list1))
newlist1 = [[y for y in list1 if y[0]==x] for x in values]

print(newlist1)

list2 = df2.values.tolist()
#print(list2)

values = set(map(lambda x:x[0], list2))
newlist2 = [[y for y in list2 if y[0]==x] for x in values]

print(newlist2)

##Estou tendo problema aqui:
list3 = newlist1.append(newlist2)
print(list3)

Gostaria de ter listas de listas agrupadas pela coluna chave.
Alguma ideia?
Esse é o output desejado:
[[
  ['2-MG', '3_4_5', '1110', '200', 'xxw', 'sder', 'key_3', '01032021', '31032021', 'sder', ''],
  ['2-MG', '2_3_4', '1110', 'C-200', '08032021', '2', '2', '123', ''],
  ['2-MG', '2_3_4', '1110', 'C-200', '08032021', '2', '2', '123', '']
  ],
 [
  ['1-MG', '1_2_3', '1110', '200', 'xxr', 'wer', 'key_1', '01032021', '31032021', 'wer', ''],
  ['1-MG', '2_3_4', '1110', '200', 'xxv', 'cad', 'key_2', '01032021', '31032021', 'cad', ''],
  ['1-MG', '1_2_3', '1110', 'C-200', '07032021', '1', '2', '123', ''],
  ['1-MG', '2_3_4', '1110', 'C-200', '07032021', '2', '2', '123', ''],
  ['1-MG', '3_4_5', '1110', 'C-200', '07032021', '3', '2', '123', ''],
  ['1-MG', '1_2_3', '1110', 'C-200', '08032021', '1', '2', '123', '']
  ]]

Posteriormente vou manipular essas listas e criar arquivos CSV, cada arquivo agrupado pela coluna chave "CNPF_UF_MES".
Comment: Se são os mesmos campos, porque vc não concatena os dataframes e depois gera as listas?
Comment: Obrigado pelo retorno. Porém as colunas dos dfs são bem distintas, e preciso converter em listas antes.
Answer: Você pode agrupar um Dataframe pelos dados em uma coluna com o método DataFrame.groupby() que divide o objetos em grupos definidos por um critério, nesse caso em especifico serão os dados da coluna CNPJ_UF_MES que definirão os grupos em cada Dataframe.
A partir desses grupos é possível construir um dicionário result cujo as chaves serão os dados da coluna CNPJ_UF_MES e os valores serão uma lista de listas obtidas com a concatenação dos valores de cada grupo:
result = {}                                         #Inicializa o dicionário que irá manter o resultado.
#Itera em df por ambos os Dataframes...
for df in [df1, df2]:
  #...agrupa df onde n é o dado em CNPJ_UF_MES e g é o respectivo grupo...
  for n, g in df.groupby("CNPJ_UF_MES"):
      #...testa se já existi a chave n em result...
      if n in result:
        result[n] += g.values.tolist()              #...se sim, concatena a lista em result com a lista obtida do grupo.
      else:
        result[n] = g.values.tolist()               #...se não, cria a chave em result e adiciona a lista obtida do grupo como valor.

pprint.pprint(list(result.values()), compact=True)  #Imprime a lista com os valores de result.

[[
  ['1-MG', '1_2_3', '1110', '200', 'xxr', 'wer', 'key_1', '01032021','31032021', 'wer', ''],
  ['1-MG', '2_3_4', '1110', '200', 'xxv', 'cad', 'key_2', '01032021','31032021', 'cad', ''],
  ['1-MG', '1_2_3', '1110', 'C-200', '07032021', '1', '2', '123', ''],
  ['1-MG', '2_3_4', '1110', 'C-200', '07032021', '2', '2', '123', ''],
  ['1-MG', '3_4_5', '1110', 'C-200', '07032021', '3', '2', '123', ''],
  ['1-MG', '1_2_3', '1110', 'C-200', '08032021', '1', '2', '123', '']
 ],
 [
  ['2-MG', '3_4_5', '1110', '200', 'xxw', 'sder', 'key_3', '01032021', '31032021', 'sder', ''],
  ['2-MG', '2_3_4', '1110', 'C-200', '08032021', '2', '2', '123', ''],
  ['2-MG', '3_4_5', '1110', 'C-200', '08032021', '3', '2', '123', '']
 ]]

Teste o código no Repl.it


From Naive Bayes to "real percentages"

Question: I am working on a problem which is well suited to be solved with a Naive Bayes classifier:

I want to know if a certain instance belongs to a certain class.
I have three attributes that can help decide.
I have a training set from which I can estimate probabilities for these attributes.

Now for each attribute I have estimated probabilities based on the traing set, which match my intuition. Even the independence assumtion probably largely holds in my case.
But then the classic Naive Bayes approach wants me to multiply the probabilities for the attributes. And although in various tutorials the result of that multiplication is also called a probability, its quite clear that they are not, but rather probability densities.
To give a simple, practical example:

Attribute 1 estimates a 60% chance of my instance belonging to class
A.
Attribute 2 estimates a 60% chance of my instance belonging to
class A.
Attribute 3 estimates a 60% chance of my instance belonging
to class A.

0.6*0.6*0.6 = 0.214, but the probability of my instance belonging to class A is certainly larger than 21.4%.
I have trouble understanding that in the above simple example (three independent attributes, each one indicating with 60% that the instance is of class A), there is no simple way to compute the probability of the instance indeed being of class A.
Can this be somehow achieved? If it is not possible, what is the reason for it?
Answer: Think about the opposite of the situation you have--all attributes giving a 40% chance of belonging to class B. This gives $.4 \times.4\times.4 = .064$.
Since $.214 > .064$, your best guess is class A.
But then, what is the probability of being in class A? You just have to essentially, normalize all class probabilities in terms of the total of the class probabilities. Your total "probability" is $.064 + .214 = .278$.
Divide the two class probabilities by the total probability to get what you're looking for.$$A = \frac{.217}{.278}  = 78\%$$
$$B = \frac{.064}{.278} = 22\%$$
It really is as simple as that. If you want to get more technical I believe there are some issues with thinking of these numbers are "probabilites", but for most purposes this interpretation is just fine. There is a 78% chance your unknown is class A and a a 22% your unknown is class B.

From Naive Bayes to "real percentages"


How can I customise the flexibleSpace property in SliverAppBar in Flutter?

Question: Instead of using FlexibleSpaceBar in the flexibleSpace property of SliverAppBar I want to use a custom widget tree, when expanded, but upon scrolling, I want to display a custom text, and not the widget tree.
I have created a custom widget tree which shall be assigned to the flexibleSpace property, but I don't know how to display custom text on scrolling, and hide the widget tree.
SliverAppBar(
          expandedHeight: 180.0,
          backgroundColor: const Color(0xFF9e0118),
          iconTheme: IconThemeData(color: Colors.white),
          floating: true,
          pinned: true,
          flexibleSpace: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Container(
                  margin: EdgeInsets.only(top: 16.0),
                  padding: EdgeInsets.only(left: 32.0, right: 32.0),
                  child: Text(
                    'Some text',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                        color: Colors.white,
                        fontFamily: 'PlayfairDisplay',
                        fontStyle: FontStyle.italic,
                        fontSize: 16.0),
                  )),
              Container(
                  margin: EdgeInsets.only(top: 16.0),
                  padding: EdgeInsets.only(left: 32.0, right: 32.0),
                  child: Text(
                    'some text',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                        color: Colors.white,
                        fontFamily: 'PlayfairDisplay',
                        fontSize: 16.0),
                  )),
            ],
          ),
        ),

Answer: You may want to wrap your widget tree inside a FlexibleSpaceBar widget and add your widget tree as background. I hope I understood your question right. Check this gif.
SliverAppBar(
      expandedHeight: 180.0,
      backgroundColor: const Color(0xFF9e0118),
      iconTheme: IconThemeData(color: Colors.white),
      floating: true,
      pinned: true,
      flexibleSpace: FlexibleSpaceBar(
        collapseMode: CollapseMode.pin,
        centerTitle: true,
        background: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Container(
                margin: EdgeInsets.only(top: 16.0),
                padding: EdgeInsets.only(left: 32.0, right: 32.0),
                child: Text(
                  'Some text',
                  textAlign: TextAlign.center,
                  style: TextStyle(
                      color: Colors.white,
                      fontFamily: 'PlayfairDisplay',
                      fontStyle: FontStyle.italic,
                      fontSize: 16.0),
                )),
            Container(
                margin: EdgeInsets.only(top: 16.0),
                padding: EdgeInsets.only(left: 32.0, right: 32.0),
                child: Text(
                  'some text',
                  textAlign: TextAlign.center,
                  style: TextStyle(
                      color: Colors.white,
                      fontFamily: 'PlayfairDisplay',
                      fontSize: 16.0),
                )),
          ],
        ),
      ),
    ),

Comment: Thank you. This solves a part of my problem which is that I can hide my custom widget tree on scrolling. The second part is that I also want to be able to display some text on the app bar while its pinned, and the user is scrolling, currently, its just blank with the red background.
Comment: Hey, I just saw your comment. Let me think and give you answer if it's not resolved yet.
Comment: Sure. Please do. Thanks.
Answer: To complete @westdabestdb answer, to make the title appear on scroll, it's really simple.
You just need to add the Animated Widget of you your choice and use the addListener from your scroll controller to switch a boolean. To find more Animated Widgets go to the official docs for Flutter Animated Widgets: https://flutter.dev/docs/development/ui/widgets/animation
Here is an example with an AnimatedOpacity Widget and the Parallax collapse mode which in my opinion work pretty well together.
class YourPage extends StatelessWidget {
  const YourPage({Key key}) : super(key: key);

  ScrollController _scrollController;
  bool _isScrolled = false;

  @override
  void initState() {
    _scrollController = ScrollController();
    _scrollController.addListener(_listenToScrollChange);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        body: CustomScrollView(
          controller: _scrollController,
          slivers: <Widget>[
            SliverAppBar(
              expandedHeight: 144.0,
              pinned: true,
              forceElevated: true,
              ////////////////////////////////////
              // HERE IS THE PART TO BE ADDED
              title: AnimatedOpacity(
                duration: Duration(milliseconds: 300),
                opacity: _isScrolled ? 1.0 : 0.0,
                curve: Curves.ease,
                child: Text("YOUR TITLE HERE"),
              ),
              ////////////////////////////////////
              flexibleSpace: FlexibleSpaceBar(
                titlePadding: const EdgeInsets.only(bottom: 8.0),
                centerTitle: true,
                collapseMode: CollapseMode.parallax,
                background: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    Container(
                        margin: EdgeInsets.only(top: 16.0),
                        padding: EdgeInsets.only(left: 32.0, right: 32.0),
                        child: Text(
                          'Some text',
                          textAlign: TextAlign.center,
                          style: TextStyle(
                              color: Colors.white,
                              fontFamily: 'PlayfairDisplay',
                              fontStyle: FontStyle.italic,
                              fontSize: 16.0),
                        )),
                    Container(
                        margin: EdgeInsets.only(top: 16.0),
                        padding: EdgeInsets.only(left: 32.0, right: 32.0),
                        child: Text(
                          'some text',
                          textAlign: TextAlign.center,
                          style: TextStyle(
                              color: Colors.white,
                              fontFamily: 'PlayfairDisplay',
                              fontSize: 16.0),
                        )),
                  ],
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

// METHODS
  void _listenToScrollChange() {
    if (_scrollController.offset >= 48.0) {
      setState(() {
        _isScrolled = true;
      });
    } else {
      setState(() {
        _isScrolled = false;
      });
    }
  }
}

You will just have to play around with the values of the if in the _listenToScrollChange
 and the Duration of the animation to obtain the desired output.
Comment: Yeah that's probably right, I didn't get to try it myself. To do a workaround, what you could do is to check if _isScrolled should be changed or not, resulting in less setStates. Just change the if to this => if(_scrollController.offset >= 48.0 && !_isScrolled) and else if(_isScrolled)
Comment: I had a similar question, when I tried this answer I did get the desired output but the UI of the app became very laggy and slow. The response time decreased rapidly. Is there a workaround?
Comment: This method calls setState() on the entire widget tree too often which would surely make the UI laggy.


What's the benefit of not using ImagePullPolicy set to Always?

Question: In the Kubernetes documentation it mentions that the caching semantic of using ImagePullPolicy: Always makes the ImagePullPolicy quite efficient. What reasons would I want to choose a different ImagePullPolicy?
Comment: Possible reason: To be even more efficient then just quite :)
Answer: It heavily depends on your versioning/tagging strategy.
When new replicas of your application are created (because your app has scaled up, or a pod has died and it's been replaced by a new pod), if you use ImagePullPolicy: Always and you have pushed a different version of your application using the same tag (like people do when using latest), the new created replicas might run a totally different version of the application than the rest of the replicas, leading to an inconsistent behavior.
You also may want to use a different value than Always when on a development environment like minikube.
Answer: There isn't much of a disadvantage to ImagePullPolicy: Always, but having the control means that:

if you have an underlying image provider that doesn't provide caching (ie you're not using Docker), you have control to make sure that it's not called every time the kubelet wants the image
even with Docker caching, it's still going to be slightly faster to not attempt to pull the image every time. If you know that you never re-use a tag (which is recommended) or you're explicitly specifying the image digest then there's no benefit to ImagePullPolicy: Always
if you have an installation where you're pulling the image onto the node using a separate mechanism, you may want it to not attempt an automatic fetch if something goes wrong and the image doesn't exist.

Note that in fiunchinho's answer it mentions that you can use it to keep various replicas of an application in sync. This would be dangerous as images are pulled per node, so you could end up with different versions of the application running on different nodes.


Bilinear form as a product of two linear functionals

Question: I have seen a few answers to this question in this site, one of them deals with a very special case, while the other one only one side of the problem is proved, so I wanted a better answer and asked this question.
Let $f$ be a bilinear form on a finite dimensional vector space $V$ over some field $\mathbb F$. I was trying to prove that $f$ can be expressed as a product of two linear functionals i.e. $$f(u,v) = L_{1}(u) L_{2}(v) \text{for} L_{1},L_{2} \in V^*$$ if and only if $f$ has rank $1$.
I just know the definitions. If someone suggests an answer it will be very much helpful.
Comment: I edited to state that $f$ is a bilinear form on $V$, which I think you accidentally omitted.  If this is incorrect, please rollback my edit.
Comment: @Aweygan any help solving the problem?
Answer: Note that the end of the statement should be "has rank $1$ or $0$".
Suppose that there are linear functionals $L_1,L_2\in V^*$ such that$$\tag{1}\bigl(\forall (u,v)\in V\bigr):f(u,v)=L_1(u)L_2(v).$$Fix a basis $B=\{e_1,e_2,\ldots,e_n\}$ of $V$. Then there are elements $a_1,a_2,\ldots,a_n,b_1,b_2,\ldots,b_n$ of $\mathbb F$ such that, whenever $\alpha_1,\alpha_2,\ldots,\alpha_n\in\mathbb F$,$$L_1(\alpha_1e_1+\alpha_2e_2+\cdots+\alpha_ne_n)=\alpha_1a_1+\alpha_2a_2+\cdots+\alpha_na_n$$and$$L_2(\alpha_1e_1+\alpha_2e_2+\cdots+\alpha_ne_n)=\alpha_1b_1+\alpha_2b_2+\cdots+\alpha_nb_n.$$Therefore, the matrix of $f$ with respect to $B$ is$$\begin{bmatrix}a_1b_1&a_1b_2&\cdots&a_1b_n\\a_2b_1&a_2b_2&\cdots&a_2b_n\\\vdots&\vdots&\ddots&\vdots\\a_nb_1&a_nb_2&\cdots&a_nb_n\end{bmatrix}=\begin{bmatrix}a_1\\a_2\\\vdots\\a_n\end{bmatrix}.\begin{bmatrix}b_1&b_2&\cdots&b_n\end{bmatrix},$$which has rank $1$ or $0$.
On the other hand, if the matrix of $f$ with respect to $B$ has rank $1$ or $0$, then the columns are all multiples of a single column. That is, there are elements $\lambda_1,\lambda_2,\ldots,\lambda_n,c_1,c_2,\ldots,c_n$ of $\mathbb F$ such that the matrix of $f$ with respect to $B$ is$$\begin{bmatrix}\lambda_1c_1&\lambda_1c_2&\cdots&\lambda_1c_n\\\lambda_2c_1&\lambda_2c_2&\cdots&\lambda_2c_n\\\vdots&\vdots&\ddots&\vdots\\\lambda_nc_1&\lambda_nc_2&\cdots&\lambda_nc_n\end{bmatrix}$$and then, if you define$$L_1(\alpha_1e_1+\alpha_2e_2+\cdots+\alpha_ne_n)=\alpha_1\lambda_1+\alpha_2\lambda_2+\cdots+\alpha_n\lambda_n$$and$$L_2(\alpha_1e_1+\alpha_2e_2+\cdots+\alpha_ne_n)=\alpha_1c_1+\alpha_2c_2+\cdots+\alpha_nc_n,$$you will have $(1)$.


Can i use Dynamic variable(like time) to construct static final variable(constant)

Question: For building File name i'm constructing name like below mentioned way
public static final String JSON_LOG_FILE_NAME = "JSON"
  +getUserName() + System.currentTimeMillis()
  + ".txt";

this is working till yesterday and now it is giving exceptioninintializationerror.
And my doubt is can use dynamic values like android device time and database values as a part of static final variable.
Answer: It doesn't make any sense to use final when you want it to be modified based on time.
You can create a final variable like "JSON" and you can use concatenation to name the file.
FOR YOUR CASE: The above logic is valid i.e The file name changes only when the class is loaded and not every time you use the variable. The value is constant and you wont find the value of time changing dynamically when ever you use it.
Comment: You have an edit rejected. If you want to change code in an answer, check the profile of the user. If they are currently around, make a comment. If they haven't been here a long time, go for the edit, and mention that in the edit comment. If it gets rejected, leave a comment on the answer with the suggestion. If you get to 2,000 reputation, you can make those types of edit without review.
Answer: I would suggest to use ch.qos.logback.classic.Logger to generate file on time bases.
Here is the complete example. Hope this helps you
Logback - set log file name programmatically
Comment: it is not just about time but getUsername() method which retrieves from Db also.am i using in a right way?


Music is to ____?____ as chemistry is to IUPAC

Question: I was wondering if there is any governing body for music theory like IUPAC is for chemistry.
Comment: It might help the non-chemists to briefly explain what IUPAC is.
Comment: Chemistry is about facts.  Music is about creating.  What is it that you would 'govern' ?
Comment: @CarlWitthoft It might be useful to standardize terminology, for example.
Comment: It's only useful to "standardize terminology" if it is used to communicate something important and there are significant consequences if the communication fails. That is clearly important in chemistry, but completely unimportant for music - unless somebody can provide solid evidence that using incorrect music terminology might kill people!
Comment: OP is asking about is there any institutes/convention that provide the 'standard' values. IUPAC is international Union for Pure and Applied Chemistry; or similarly many physics standards stored at Bureau of Weights and Measures.
Comment: I'm voting to close this question as off-topic because it is asking for an organization and unrelated to performance of music.
Comment: Where else would I ask this question...
Answer: Internationally, the closest I can think of would be the Society for Music Theory. The society holds annual conferences, releases a biannual publication called Music Theory Spectrum, etc.
Some countries have their own, more specific societies. The Society for Music Analysis in the UK is especially terrific.
Comment: The SMA may well be a terrific organization, but I would guess that at least 99.99% of active musicians in the UK have never heard of it, and even fewer are actually members.
Comment: I'm not sure that's really relevant. As one reason of several I could list: think about the number of people that are musicians as "just a hobby"; now think about the number of "hobby" chemists!


Como executar uma requisição síncrona em um looping

Question: No exemplo abaixo
let arr = [
  { 3 : 'teste' },
  { 5 : 'teste' },
  { 1 : 'teste' },
  { 2 : 'teste' },
  { 0 : 'teste' },
  { 4 : 'teste' }
];

arr = arr.sort( ( a , b ) => { return Object.keys(b)[0] - Object.keys(a)[0] } )

console.log( arr )

/*
[ { '5': 'teste' },
  { '4': 'teste' },
  { '3': 'teste' },
  { '2': 'teste' },
  { '1': 'teste' },
  { '0': 'teste' } ]
*/

arr.forEach( ( el, key ) => {

  fetch( this.url + el[ Object.keys(el)[0] ], {
      method: 'GET',
      headers: {
          Accept: 'application/json'
      }
  }).then((response) => {
      return response.json();
  }).then((result) => {

  ...

} )

Eu ordeno um array em ordem decrescente baseado na key de cada objeto dentro dele, pois quando executo o looping, preciso executar a requisição do maior para o menor.
O problema é que o fetch é assíncrono ou seja, essa ordem não vai funcionar pois ele executa as requisições em paralelo, e qual receber o resultado primeiro vai entrar no then ou no catch
Preciso que o forEach espere a requisição terminar para ir para o próximo item, é possível?
Answer: Você pode usar o método Promise.all() para executar todas as requisições assíncronas e, quando todos os resultados forem recebidos, trabalhar com eles na mesma ordem em que foram chamados.
Promise.all([req_1, req_2, req.3]).then(reqs => {
    console.log(reqs) // [result_1, result_2, result_3]
})

Seu código ficaria parecido com este:

let arr = [
  { 3 : 'teste' },
  { 5 : 'teste' },
  { 1 : 'teste' },
  { 2 : 'teste' },
  { 0 : 'teste' },
  { 4 : 'teste' }
];

arr = arr.sort(( a , b ) => Object.keys(b)[0] - Object.keys(a)[0])

const URL = "https://httpbin.org/anything"
let requests = arr.map(obj => fetch(URL, {
  method: "POST",
  body: JSON.stringify(obj)
}))

Promise.all(requests)
  .then(responses => {
    responses.forEach(response => {
      response.json().then(json => console.log(json.data))
    })
  })
Comment: Obrigado pela resposta @fernandosavio, a solução quase resolveu meu problema, no promisse.all estão entrando muitos resultados, e quando ele faz o looping as vezes eles entram no then fora ordem, o que faz sentido pois mesmo que o then não esteja esperando uma requisição, ainda sim há atrasos de processamento creio eu, o que acaba quebrando o ciclo, você saberia como resolver isso?
Comment: isso só acontece no mozilla na verdade
Comment: Estranho, na [documentação da MSN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all#Return_value) especifica que o array passado para a função é na ordem do array de Promises.


Tensor Product: Denseness

Question: This is thread is just a note.
Given Hilbert spaces.
Then denseness will be inherited on tensor products:
$$\mathcal{D},\mathcal{E}\text{ dense}\implies\mathcal{D}\otimes\mathcal{E}\text{ dense}$$
How to prove this from scratch without orthonormal bases?
Answer: This answer is community wiki.
First for simple tensors one has:
$$\|\varphi\otimes\psi-\varphi_n\otimes\psi_n\|\leq\|\varphi-\varphi_n\|\cdot\|\psi\|+\|\varphi_n\|\cdot\|\psi-\psi_n\|\leq\delta_\varphi(1+\|\psi\|)+\|\varphi\|\delta_\psi$$
Next for sums it still holds true by continuity of addition:
$$\|\varphi\otimes\psi+\varphi'\otimes\psi'\|\leq\|\varphi\otimes\psi\|+\|\varphi'\otimes\psi'\|$$
Finally the result follows as sums are dense in the Hilbert tensor product.

Tensor Product: Denseness


Excel - Faixa de valores de CEP

Question:
Tenho uma lista de CEP's, sendo faixa inicial e faixa final que vão determinar a localidade, nomeei a coluna A como "ONE" e a coluna B como "TWO", e fiz um PROCV + SE +E, ou seja se o CEP procurado fosse maior que o intervalo ONE e menor que o TWO, ele retornaria necessariamente o valor da coluna de ONE e faria o Proc com a localidade, mas não deu certo, alguém consegue me ajudar por favor?
Answer: Como vai?
Primeiramente, cabe notar que a maneira com que você tentou realizar essa busca não iria funcionar dessa maneira com o PROCV, pois essa fórmula faz buscas por chaves (valor procurado) exatamente iguais ao valor informado, por isso não deu certo.
Sendo assim, o que eu fiz foi uma gambiarra, mas que pode ajudar: como a condição para retornar o estado correto é que o CEP informado pelo usuário seja maior ou igual ao CEP da primeira faixa e menor ou igual ao CEP da segunda faixa, eu criei uma coluna a mais, em que é feita a validação e a concatenação dessas duas condições, assim:

Assim, o PROCV procura as células correspondentes em que o valor procurado é "VERDADEIROVERDADEIRO".
Eu testei com quatro CEPS diferentes e funcionou.
Vou deixar a planilha nos comentários para você testar.
Qualquer problema , me avise.
Comment: E aí Andréa, tudo bem? Bom dia, primeiramente obrigado pelo retorno, eu havia visto um vídeo antes que explicava meio por cima essa gambiarra mas não me aprofundei nela, vou testar dessa forma.

O arquivo que você deixou anexo, ao menos aqui quando eu baixei é um arquivo diferente, baixa uma planilha com dados medicinais.
Comment: Oi! Você tinha razão! Segue a planilha de novo. Desculpe. Espero que ajude agora: https://www.transfernow.net/dl/20210601m26IbpYi

Excel - Faixa de valores de CEP


How can Teamviewer share images by using direct port behind a firewall

Question: I found this:
How does teamviewer find my computer
but I could not understand and the answers are not what I am looking for.
I'm looking for a solution in .net.
If I have an image-Sender-app and how can Teamviewer connect to image-Receiver-app? Is there any tunnelig system included? Or does Teamviewer only use Port 80?
Does Skype use same methode for voice chat?
* EXAMPLE *
I am on PC-A and I have an 50KB image here as Screenshot-Frame and would like to send it to my PC-B. Now, TV (teamviewer) looks on the whole portrange from 1 to 65,000 if any port could connect the SERVER-PC. I think minimum Port 80 will success, right? But on my computer also port 4001 is open, TV will use 4001 for the feature. On PC-B it checks also for open ports and founds port 80 and 6500 and will use 6500 for the feature. My question is now, where are data going to? Is my image first going to SERVER-PC by using port 4001 and the 50KB is stored for short time there and PC-B will download it on port 6500? I cannot believe that that is the truth because it would create too much TV-SERVER-PC traffic. But how can it work?

Regards
Answer: The other answer covers the essentials really.
This article (old, but still relevant) describes how Skype gets around firewalls - maybe it helps explain the method better.
As far as I know, TeamViewer employs the exact same method - both TeamViewer client apps connect actively to a central server, and then negotiate the connection as described in the article.

My question is now, where are data going to? Is my image first going to SERVER-PC by using port 4001 and the 50KB is stored for short time there and PC-B will download it on port 6500? I cannot believe that that is the truth because it would create too much TV-SERVER-PC traffic. But how can it work?

PC-A and PC-B communicate directly with each other. SERVER-PC is used only to establish communication between the two, to punch the hole into both computers' firewalls. The crucial trick in the article is this (Emphasis mine):

Bob's Skype program then punches a hole in its own network firewall: It sends a UDP packet to 184.108.40.206 port 1414. This is discarded by Alice's firewall, but Bob's firewall doesn't know that. It now thinks that anything which comes from 220.127.116.11 port 1414 and is addressed to Bob's IP address 220.127.116.11 and port 2828 is legitimate - it must be the response to the query which has just been sent.
Comment: thanks for your comment. please, I updated my question with an example to show where I have the big questionmark. Can you try to answer?
Comment: @goldengel I added some more detail, maybe it helps.
Comment: @community. I made 100 bounties and cannot send it now to Pekka.
Comment: @goldengel when the bounty expires, the community user awards half of the amount that you sponsored. It's fine - I just hope the information helps
Comment: @Pekka: Thanks that sounds good. When installing now PC-A application. I need to send a UDP packet on port 1414 to open firewall there as I understood. But how to switch the port while receiving from Alice's 2828 image to my local 1414? Where to switch this port? I made an image in question. Please see the "green boxed portswitcher" which I don't know what is is really.
Comment: @goldengel I assume the port number is information that is sent to the central server, so PC-A knows which port to target on PC-B and vice versa... I'm not really familiar with communication on protocol level, so I can't give any more detail here, sorry
Comment: But that is the key question. Because if port is switched on server, what is about data?
Answer: The first answer in the other Teamviewer question is correct - it uses a central server to work through firewalls - probably falling back to making HTTP POSTs with the more restrictive firewalls. This way the two Teamviewers are not communicating with each other, only with the central server.
Comment: I am not asking for code voltagex you missunderstood. I want to know the tools to get stuff working using DotNet. I updated my question.
Comment: Create a webservice that receives images from A. Have a method for B to receive images. Your client A sends {image,ID, for-b}. Your client B requests {image,for-b} and downloads all available images.
Comment: Ok, that sound like default way how to share image. The keyquestion is why is your description not working on firewalls but TV can do this? What port is used? (in the example on my question)


OutOfMemoryError and problems with ObservableList into ComboBox

Question: I make an fxml file in javafx2.
I have a List of Person objects. The name of this List, is Entries. I have an ObservableList, myObservableList. Inside of this I want to put labels. Each label must contains a pair of image person and text of his name.
I write this code:
for (int i=0; i<numberOfEntries; i++){
    currentEntry = Entries.get(i);
    name=currentEntry.getName();
    image1 = new Image("file:"+currentEntry.getIcon());
    imageView1= new ImageView();
    imageView1.setFitHeight(50);
    imageView1.setFitWidth(70);
    imageView1.setImage(image1);
    label = new Label(name, imageView1);
    label.setFont(new Font("serif", 32));
    myObservableList.add(label);
}

It works ok, but after a few puts of images the JVM gives me the below error message:
Caused by: java.lang.OutOfMemoryError: Java heap space.

This error comes from the code line      image1 = new Image("file:"+currentEntry.getIcon());
Finally, I want to put all elements of myObservableList into a ComboBox items. For this reason in Initialize method of java controller I write:
    myComboBox.setItems(myObservableList);

    ListCell buttonCell = new ListCell() {
         @Override protected void updateItem(Label item, boolean isEmpty) {
         super.updateItem(item, isEmpty);
            setText(item==null ? "" : item.getText());
        }
    };

    myComboBox.setButtonCell(buttonCell);

I am sure that I have not enough experience in javafx, and I do not know how must I handle for I have a combobox with pairs of icon and text in the same cell for all items.
I want to express my lot of thanks to Peter Duniho and PakkuDon for their help for improve English in my text.
Comment: How many items (approximately) in the list? How big, on average, are the images?
Comment: The list get the up load from a data base. I have a table "Person" with 8 columns. From this I read only 2 columns, the first name, and the file name (of icon of person).
May be approximately 200 persons names and icons. All this must up load to the combo box. Each icon is about 70Kb or 100kb.
I not know how I handle this.
Answer: It is almost always a mistake to use a Node class as the data type for a ComboBox (or for any other control). You should use a class that represents the data only, and register a cell factory to configure how the data are displayed.
In your case, if you include the image in the data, you are likely to run into memory problems. Each image is likely to be represented in memory by a few megabytes. So your data class should hold the image name, and then you can use the cell in the combo box to create an image.
Here's some sample code to give you the idea:
Data class (Person.java):
public class Person {
    private final String name ;
    private final String imageFileName ;

    public Person(String name, String imageFileName) {
        this.name = name ;
        this.imageFileName = imageFileName ;
    }

    public String getName() {
        return name ;
    }

    public String getImageFileName() {
        return imageFileName ;
    }
}

UI code to create ComboBox from a List<Person>:
List<Person> entries = ... ; // populated from DB

ComboBox<Person> comboBox = new ComboBox<>();
comboBox.getItems().addAll(entries);

comboBox.setCellFactory(new Callback<ListView<Person>, ListCell<Person>>() {
    @Override
    public ListCell<Person> call(ListView<Person> listCell) {

        return new ListCell<Person>() {
            private final ImageView = new ImageView();
            @Override
            public void updateItem(Person person, boolean empty) {
                super.updateItem(person, empty);
                if (empty) {
                    setText(null);
                    setGraphic(null);
                } else {
                    File imageFile = new File(person.getImageFileName());
                    String imageUrl = imageFile.toURI().toURL().toExternalForm();
                    Image image = new Image(imageUrl, 70, 50,
                        // preserve ratio
                        true,
                        // smooth resizing
                        true,
                        // load in background
                        true);
                    imageView.setImage(image);
                    setText(person.getName());
                    setGraphic(imageView);
                }
            }
        };
    }
});

You can use the same ListCell implementation for the ComboBox's buttonCell.
The point here is that cells are only created for the visible cells, so the images are loaded "on demand" as the cells are displayed. Using the Image constructor that takes the width and height parameters also reduces the memory footprint, as the Image object can resize as it loads.
Finally, note that it's important to use the flag to load images in the background, which keeps the UI responsive. If you scroll quickly, you'll likely see some images not loaded for a brief while; the cells will repaint appropriately once the image becomes available.
Comment: dear James_D,
Lot of thanks for your answer is very helpful for me.
I use java 7 and your line:

comboBox.setCellFactory(listView -> new ListCell() {

is for java 8.
If you please to rewrite this for java 7?
Comment: You just have to convert the lambda to a `Callback` class (e.g. an anonymous inner class). I edited in line, I think it is correct but you should be able to fix any typos from here.
Comment: You are very fast and knowledge powerful person.
Really thank you for your kindness help.
Comment: The inner class return 'new ListCell()' alone works well, But all together, the code generates the following error: java.lang.ClassCastException: java.lang.String cannot be cast to libraryChildren.Person
at lbraryChildren.FXMLDocumentController$1$1.updateItem(FXMLDocumentController.java:132), line 132=return new ListCell()
Comment: You are putting `Person` objects in the list, right? Not `String`s.
Comment: My mistake. There was inside of  the text of the fχml file the tag

these automatically generated by scene builder.
the code of James_D works perfectly
Comment: dear friend all well finished. Thank you for your valuable help and I apologize for the inconvenience that I added to you with my many questions.
Mine was ultimately wrong. Your code is perfect.


Java FX image upload from file

Question: i was trying create a image icon on label text field using  file chooser but the current code works for java and not java fx
if anyone know to fix my code it will be very helpful
package EmploymentPayroll;

import java.awt.Image;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.event.ActionEvent;
import javafx.scene.control.Label;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import javax.swing.JOptionPane;

/**
 * FXML Controller class
 *
 * @author Shafeen
 */
public class AddEmployeeController implements Initializable {

    @FXML
    private Label img;
    private ImageIcon format = null;
    String filename = null;
    byte[] person_image = null;

    @Override
    public void initialize(URL url, ResourceBundle rb) {

    }

  @FXML
    private void UploadImageActionPerformed(ActionEvent event) {
        JFileChooser chooser = new JFileChooser();
        chooser.showOpenDialog(null);
        File f = chooser.getSelectedFile();

        filename = f.getAbsolutePath();
        *error*  ImageIcon imageIcon = new ImageIcon(new ImageIcon(filename).getImage().getScaledInstance(img.getWidth(), img.getHeight(), Image.SCALE_DEFAULT));

        *error* img.setIcon(imageIcon);

         try {
            File image = new File(filename);
            FileInputStream fis = new FileInputStream (image);
            ByteArrayOutputStream bos= new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            for(int readNum; (readNum=fis.read(buf))!=-1; ){
                bos.write(buf,0,readNum);
            }
            person_image=bos.toByteArray();
        }

        catch(Exception e){
            JOptionPane.showMessageDialog(null,e);
        }

    }

this is the java fx form where when i click on picture it should load the file and save as BLOB type

error one

error two

thanks for help
Comment: JFileChooser and JOptionPane is also Swing and not JavaFX. Stick to JavaFX if you want your program to be written in JavaFX.
Comment: Use `javafx.stage.FileChooser` and `javafx.scene.control.Alert` instead of the equivalent Swing APIs. And since this is JavaFX you should be using `javafx.scene.image.Image` / `javafx.scene.image.ImageView` instead of `java.awt.Image` / `javax.swing.ImageIcon`. As a general rule, avoid mixing UI toolkits unless you absolutely _have_ to. Remove everything related to AWT/Swing, use the available JavaFX APIs instead, and try again. If you're still having a problem, please provide a [mre].
Comment: And note you would use `label.setGraphic(imageView)` to add an image graphic to a `javafx.scene.control.Label`. I recommend reading some tutorials on JavaFX; check out https://docs.oracle.com/javase/8/javafx/get-started-tutorial/index.html
Comment: java naming conventions, please!
Comment: i got the code working thank you for the efforts
Answer: if anyone is looking to upload images using java fx and save in database in blob format then you can refer this code
thank you
@FXML
    private void UploadImageActionPerformed(ActionEvent event) {

        FileChooser fileChooser = new FileChooser();

        //Set extension filter
        FileChooser.ExtensionFilter extFilterJPG
                = new FileChooser.ExtensionFilter("JPG files (*.JPG)", "*.JPG");
        FileChooser.ExtensionFilter extFilterjpg
                = new FileChooser.ExtensionFilter("jpg files (*.jpg)", "*.jpg");
        FileChooser.ExtensionFilter extFilterPNG
                = new FileChooser.ExtensionFilter("PNG files (*.PNG)", "*.PNG");
        FileChooser.ExtensionFilter extFilterpng
                = new FileChooser.ExtensionFilter("png files (*.png)", "*.png");
        fileChooser.getExtensionFilters()
                .addAll(extFilterJPG, extFilterjpg, extFilterPNG, extFilterpng);
        //Show open file dialog
        File file = fileChooser.showOpenDialog(null);

        try {
            BufferedImage bufferedImage = ImageIO.read(file);
            WritableImage image = SwingFXUtils.toFXImage(bufferedImage, null);
            img.setImage(image);
            img.setFitWidth(200);
            img.setFitHeight(200);
            img.scaleXProperty();
            img.scaleYProperty();
            img.setSmooth(true);
            img.setCache(true);
            FileInputStream fin = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];

            for (int readNum; (readNum = fin.read(buf)) != -1;) {
                bos.write(buf, 0, readNum);
            }
            person_image = bos.toByteArray();

        } catch (IOException ex) {
            Logger.getLogger("ss");
        }
    }

byte[] person_image = null;

 @FXML
    private void handleaddemployee(ActionEvent event) throws IOException {

        try {
                String empID = "nill";
                if (!txtempID.getText().equals("")) {
                    empID = txtempID.getText();
                }

                Employee e = new Employee(
                        empID,
                        person_image
                );
                dbemployee.addEmployee(e);

            } else {
                 System.out.println("not working");
            }

        } catch (SQLException ex) {
           System.out.println("error");

        } catch (NumberFormatException e) {
         System.out.println("number error");

        }

    }

Java FX image upload from file


Angular/Typescript interface and implementing class: Attributes with `@, $` characters in them

Question: I am following the approach of JHipster in my Angular app, which I believe is pretty much best-practice based. As far as models are concerned, this is how they are doing it:
export interface IPerson {
  id: number;
  firstName: string;
  lastName: string;
}

export class Person implements IPerson {

  constructor(
    public id: number,
    public firstName: string,
    public lastName: string) {}

}

I encountered the problem when I tried to add the following attribute (dictated by the third-party API that I'm using and there are many other that contain another special characters, such as $ etc.):
export interface IPerson {
  ...
  '@type': string; // here it's ok
}

export class Person implements IPerson {

  constructor(
    ...
    // here, however, the compiler goes
    // nuts, showing it in red and underlined
    public '@type': string
}

So, it seems it's not the usage in a class itself that is problematic, but rather the usage in the constructor, declaring it this way.
Does anyone have an idea how to at least work around this?
Comment: you can initialize it outside the constructor as a class variable too.
Comment: Why are you using `public '@type': string` in the constructor?
Comment: Because I thought I should initialize it in constructor just like other attributes from the interface. Is there another way?
Answer: I don't know why this is "best practice", but if you want to assign all the properties in the constructor then you simply have to choose another name for the constructor parameters.
class Person implements IPerson {
    '@type': string;
    constructor(type: string, public name: string) {
        this['@type'] = type;
    }
}

However, if Person doesn't get any behaviour attached, I don't see much value in creating a class at all. I would just do
const person: IPerson = { '@type': 'some_type', name: 'developer10' };

I would even say that constructors with long list of arguments are 'bad practice'...
const person = new Person('this', 'that', 'first', 'last); // is that the correct order i dunno..


How to extract an object from an array of objects in JSON?

Question: I have a simple json with an array of objects, I managed to extract the record but it comes up with square brackets, and I want just the object.
var res = {
  "totalSize": 3,
  "done": true,
  "records": [{
    "Id": "1",
    "CaseNumber": "1",
    "Subject": "test1"
  }, {
    "Id": "2",
    "CaseNumber": "2",
    "Subject": "test2"
  }, {
    "Id": "3",
    "CaseNumber": "3",
    "Subject": "test3"
  }]
}

var extractedRecord = res.records.slice(0, 1);

Desired outcome:
  {
    "Id": "1",
    "CaseNumber": "1",
    "Subject": "test1"
  }

Actual outcome:
[
  {
    "Id": "1",
    "CaseNumber": "1",
    "Subject": "test1"
  }
]

See this jsfiddle.
Comment: Read about [`Array.slice()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice). And about arrays, [in JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) and in general.
Comment: Just use `res.records[0]`
Comment: Why was my question downvoted? At least provide some pointers for me to learn for future cases
Answer: Just do res.records.slice(0, 1)[0]

var res = {"totalSize":3,"done":true,"records":[{"Id":"1","CaseNumber":"1","Subject":"test1"},{"Id":"2","CaseNumber":"2","Subject":"test2"},{"Id":"3","CaseNumber":"3","Subject":"test3"}]}

var extractedRecord = res.records.slice(0, 1)[0];
console.log(extractedRecord);

You can also use spread syntax:

var res = {"totalSize":3,"done":true,"records":[{"Id":"1","CaseNumber":"1","Subject":"test1"},{"Id":"2","CaseNumber":"2","Subject":"test2"},{"Id":"3","CaseNumber":"3","Subject":"test3"}]}

var extractedRecord = res.records.slice(0, 1);
console.log(...extractedRecord);
Comment: Do you need `.slice()`?
Comment: @axiac no we don't, but answering based on OP context
Answer: Arrray.prototype.slice(), as its documention states, returns a new array from an original one.
From MDN (my emphasis):

The slice() method returns a shallow copy of a portion of an array
  into a new array object selected from begin to end (end not included)
  where begin and end represent the index of items in that array. The
  original array will not be modified.

Knowing this, it's no surprise you're getting an array returned (i.e. your object encased with [ and ]). Therefore you just need to extract the only item in it:
var extractedRecord = res.records.slice(0, 1)[0];

Comment: I accepted this answer and not the others because @Utkanos provided explanations and not just the code. Cheers.
Answer: Try this code.It will works for you.

var res = {"totalSize":3,"done":true,"records":[{"Id":"1","CaseNumber":"1","Subject":"test1"},{"Id":"2","CaseNumber":"2","Subject":"test2"},{"Id":"3","CaseNumber":"3","Subject":"test3"}]}

const data = res.records[0]
console.log(data);
Comment: Please provide some explanation, otherwise the OP has no way of knowing what they did wrong.
Comment: They did not wrong anything,but this is other way to achieve the answer of question and also getting without slice method.
Comment: This is the only right answer, as in, there is no point of using `slice()` when all you want to do is to access an array element.
Comment: @MichałSadowski yes and no. You are right that this answer shows the shortest route to achieving the desired output. But insofar as the OP expressed confusion about how `slice()` works, it is worth explaining that erroenous thinking.
Comment: @Utkanos true, but it also, I believe, is important to point out how accessing elements of an array should be done.


Misleading comments

Question: Several users tend to give the gist of an answer in a comment under the question. This is bad as it cannot be accepted and cannot be voted upon. Every now and then such an answer is formulated poorly and hence is misleading, or it is straight out false. Does this merit flagging the comment?
The intention of the user is not trolling, but how else can you signal disagreement with a comment?
Comment: Related questions on [meta.math.se](http://meta.math.stackexchange.com/q/1559/8572) and [meta.cooking.se](http://meta.cooking.stackexchange.com/questions/2157/what-should-we-do-with-answers-in-comments-on-questions/2174) and [the mother meta](http://meta.stackexchange.com/q/117251/164022)
Comment: Related questions on [meta.money](http://meta.money.stackexchange.com/q/2298/10997) and [meta.photo](http://meta.photo.stackexchange.com/q/4655/34807)
Answer: Comments are there to request clarification on questions, or to point out problems with answers.
A comment that's a pseudo-answer isn't there to request clarification, so it's good to flag it as not constructive, so that it can be deleted.
You can also choose to take what's written in the comment as the basis for writing your own answer. Just add a short note crediting the commenter too: you'll get the rep points anyway, and hopefully next time they'll provide a proper answer themselves.
Answer: Breaking the implied practice that should be followed here, I will go on and answer rather than comment :)
What I have seen and what I do is handle such misleading or outright wrong comments by posting below it a comment directed to the commenter (i.e. including its @username in the comment). The OP will be notified in any case.
I don't see flagging as the efficient solution here, since the moderators in the SE world are not "truth guardians".
Comment: If it was decided to have the mods remove every answer-as-comment, regardless of whether it is a good answer or not, then the mods wouldn't be put into a position to be the sole judges of whether or not the answer-comments are good or not.
Answer: I agree with Alecos. I think we should treat the comments as a discussion area where it is okay to correct people who are wrong (and to be corrected yourself), with a view on converging on a good question/answer.
If we insist that only correct comments survive then we take a step closer to the philosophically dangerous world in which comments are accepted as being a susbstantive part of the content of record of this site. But the SE sites are supposed to be designed in such a way that the questions and answers contain the relevant content and the comments are purely incidental.
In other words, I think we should worry less about removing incorrect comments, and more about ensuring that a correct and satisfactory answer eventually gets posted.

Misleading comments


What's the difference between Hidden layer and fully connected layer?

Question: I'm newer in the Deep learning domain,
I would like to know what's the difference between a hidden layer and a fully connected layer?
Are they the same thing?
If no, How to create a hidden layer with Tensorflow?
Comment: Your last question is off topic here, as it is about code. I suggest removing that question to avoid your question being closed.
Answer: A hidden layer is any layer that's not an input or an output. Suppose you're classifying images. The image is the input. The predicted class is the output. Any layers in between input and output layers are hidden.
One type of layer is a fully-connected layer. Fully-connected layers have weights connected to all of the outputs of the previous layer.
A layer can be

hidden but not fully-connected (e.g. a hidden convolutional layer), or
fully connected but not hidden (e.g. a fully connected output layer), or
hidden and fully-connected (a standard choice), or
neither hidden nor fully connected (e.g. a deconvolution output layer)
Comment: Thanks for your answer, If I understand what you say, The convolution layer and the pooling layer are hidden layers because they are between the input layer and the output layer.


Test if advertising raised sales?

Question: I have an (offline) advertising campaign that I'm running in one city. I'm trying to figure out how to answer the following questions:

What are the chances that the advertising campaign has no positive effect?
What are the chances that the advertising campaign increased sales by at least X%?

I have historical monthly data for the sales going back 6 months. Given that these are small samples, what are the best statistics to use here? I expect the advertising campaign to have a significant effect, so ideally I'd like to be able to say something even with one new data point (one month of data.)
Comment: Do you got sales development from other cities to compare with?
Comment: Yes, I can compare to other cities or to historical performance for that city (or both.)
Answer: Because your data is temporal in nature, there really isn't anything significant that can be concluded.
You definitely need some kind of a control group (ie. a group of users who were not subjected to the advertising campaign in any way), with both groups being studied in the exact same context (same period, and absolutely no bias other than said advertising campaign).
If you have no access to such data, there really isn't a lot you can say out of 6 points of time-series data.

Test if advertising raised sales?


pygame, load .wav file memory error

Question: I wrote the code in conf.py file
env_sound = pygame.mixer.Sound('resources/sound/env.wav')

And in game.py file, I just import conf
env_sound = conf.env_sound

The error is
File "/path/game.py", line 8, in <module>
    import conf
File "/path/conf.py", line 45, in <module>
    env_sound = pygame.mixer.Sound('resources/sound/env.wav')

MemoryError

The game.py and conf.py are in the same directory.
The size of env.wav is just about 511 kB, and I think it couldn't cause memory error.
What is wrong with it?
Answer: You will need to init the pygame.mixer to make it work. So something along the line of:
#add this somewhere before env_sound = pygame.mixer.Sound('resources/sound/env.wav')
pygame.mixer.init(frequency=22050, size=-16, channels=2, buffer=4096)

Read the pygame doc for further reference.

pygame, load .wav file memory error


Taylor series and integration

Question: Let $f$ be a twice continuously differentiable function on $\mathbb{R}$. Let $0=t_0<t_1<\ldots < t_n=t$ be a partition of $[0,t]$. Then:
$$f(t)-f(0)=\sum_{i=0}^{n-1}f(t_{i+1})-f(t_i) \mbox{.}$$
From Taylor formula we have $$f(t)-f(0)=\sum_{i=0}^{n-1}f'(t_i)(t_{i+1}-t_i)+\frac{1}{2}\sum_{i=0}^{n-1}f''(s_i)(t_{i+1}-t_i)^2 $$
where $s_i$ is some point between $t_i$ and $t_{i+1}$.
Now if we go with mesh of our partition to $0$, from fundamental theorem of calculus we know that the second sum goes to $0$. My question is why is it so?
Comment: I disagree on that "from fundamental theorem of calculus ...". What you are doing is exactly *proving* the fundamental theorem of calculus. You are not assuming it.
Comment: If you were to assume the fundamental theorem of calculus the proof that the second sum tends to $0$ could be much simpler. Just note that, as $\delta \to 0$, the first sum tends to $\int_0^t f'(s)\, ds=f(t)-f(0)$.
Comment: Very good point!
Answer: Let $M = \sup_{s \in [0,t]} |f''(s)|$.
Suppose $t_{i+1}-t_i \le \delta$, then
$|\sum_k f''(s_k)(t_{k+1}-t_k)^2| \le M\sum_k (t_{k+1}-t_k)^2 \le M\delta \sum_k (t_{k+1}-t_k) = M\delta t$.
So given $\epsilon>0$, choose $\delta < {1 \over Mt} \epsilon$.
Comment: Very good explanation, thank you very much!

Taylor series and integration


Normalização de dados em uma rede neural

Question: Estou estudando sobre o uso de redes neurais e aprendi que os dados de entrada devem ser normalizados para que as funções de ativação não operem nos intervalos de saturação, é comum o intervalo de normalização ser [-1,+1]. Porém, para normalizar os dados de entrada devo conhecer o range dos mesmos. Minha dúvida é: Se eu não detenho o range destes dados, como posso normaliza-los?
Comment: se você não tem os dados, como pretende treinar a rede?
Answer: Se você tem os dados use o maior e o menor como range, ou verifique o maior e o menor e a partir deles estipule um range que considere aceitável.
A partir do momento que possuir o range pode normalizar com a formula: