Calculating retail price to hit required margin - including a cost which depends on retail price

Question: I have a pricing rule, which dictates that of retail price, margin must be 20%. I have the cost price and the required margin, I need to calculate the (suggested) retail price.
The formula would look like this, I believe, where 20 is the required margin:
$retailprice=100*cost/(100-20)$
Reasonably straight-forward, even for a math-moron like myself.
Now I run into problems.
In some jurisdictions, there is something called MarginVAT, which means you have to pay a 25% VAT of your margin. This is effectively a cost - but a cost you can only calculate once you know the retail price.
MarginVAT is defined like this:
$marginVAT=(RetailPrice-Cost)*(marginVatPct/100)$
Also not too complicated.
But now I need to combine the two, creating a formula to calculate the suggested retail price, taking marginVAT into consideration.

VAT rate: 25%
Required Margin: 20%

I think the formula looks something like this:
$retailprice = (100x(cost+(retailprice-cost)*(25/100))) / (100-20)$

Does that look correct?
How can I make that simpler - into something I can actually turn into computer code?

Ps. My math skills are quite poor, and my skills in describing math in English terms are quite poor as well, so please excuse me if I made some stupid errors.
Answer: One thing you could do to make it simpler it to write numbers as numbers, rather than percentages, to get rid of those extraneous $100$'s.  Another is to assign variables.
Let $p$ be the retail price, $c$ the original cost, $v$ be the VAT rate, and $t$ be the tax.  If the margin is $20\%$ of the cost plus the tax, we have $$p=1.25(c+t)$$  Also, we know $$t=v(p-c)=vp-vc$$  Substituting the second equation into the first, we find $$p = 1.25(c+vp-vc)\\
p(1-1.25v)=1.25c(1-v)\\
p=\frac{1.25(1-v)}{1-1.25v}c
p=\frac{1-v}{.8-v}c$$
In the example where the VAT rate is $25\%$ this gives $$p=\frac{.75}{.55}c\approx1.3636c$$ and the markup is $36.36\%$ of the cost.
If the cost of an item is $100$, then the sales price will be $136.37$ and the VAT will be $.25\cdot36.37=9.09$.  The margin is $27.28$ which is $20\%$ of $136.37$, except for a little roundoff error.
Comment: Great answer. It works - but one thing still irks me. I don't understand how you go to the 1.25. I assume it is because 0.2 (the margin vat) * 1.25 = 1. But I am not quite sure how you arrived at that. Can you elaborate on that? What if the marginVAT was 10? How would I get to the value that is now 1.25? I assume if the marginVAT was 10, the 1.25 value would become 1.11 - but I am honestly not quite sure how to calculate it - or if I am right.
Comment: You had it in the body of your question:  $\frac{100}{100-20}=1.25$  It depends only on the required margin, not the VAT.  I gathered that the $20\%$ margin was fixed, so I didn't make it a variable.  Is it clear now?
Comment: Very clear, thank you very much. :)


Deploying AWS Global infrastructure with API Gateway, Lambda, Cognito, S3, Dynamodb

Question: Let say I need an API Gateway that is going to run Lambdas and I want to make the best globally distributed performing infrastructure. Also, I will use Cognito for authentication, Dynamodb, and S3 for user data and frontend statics.
My app is located at myapp.com
First the user get the static front end from the nearest location:
user ===> edge location at CloudFront <--- S3 at any region (with static front end)
After that we need to comunicate with API Gateway.
user ===> API Gateway ---> Lambda ---> S3 || Cognito || Dynamodb
API Gateway can be located in several regions, and even though is distributed with CloudFront, each endpoint is pointing to a Lambda located at a given region: Let say I deploy an API at eu-west-1. If a request is sent from USA, even if my API is on CloudFront, the Lambda it runs is located at eu-west-1, so latency will be high anyway.
To avoid that, I need to deploy another API at us-east-1 and all my Lambdas too. That API will be pointing to those Lambdas
If I deploy one API for every single region, I would need one endpoint for each one of them, and the frontend should decide which one to request. But how could we know which one is the nearest location?
The ideal scenario is a single global endpoint at api.myapp.com, which is going to go to the nearest API Gateway which runs the Lambdas located in that region too. Can I configure that using Route 53 latency routing with multiple A records pointing to each api gateway?
If this is not right way to do this, can you point me in the right direction?
Answer: AWS recently announced support for regional API endpoints using which you can achieve this.
Below is an AWS Blog which explains how to achieve this:
Building a Multi-region Serverless Application with Amazon API Gateway and AWS Lambda
Excerpt from the blog:

The default API endpoint type in API Gateway is the edge-optimized API
  endpoint, which enables clients to access an API through an Amazon
  CloudFront distribution. This typically improves connection time for
  geographically diverse clients. By default, a custom domain name is
  globally unique and the edge-optimized API endpoint would invoke a
  Lambda function in a single region in the case of Lambda integration.
  You can't use this type of endpoint with a Route 53 active-active
  setup and fail-over.
The new regional API endpoint in API Gateway moves the API endpoint
  into the region and the custom domain name is unique per region. This
  makes it possible to run a full copy of an API in each region and then
  use Route 53 to use an active-active setup and failover.
Answer: Unfortunately, this is not currently possible. The primarily blocker here is CloudFront.
MikeD@AWS provides the info on their forums:

When you create a custom domain name it creates an associated CloudFront distribution for the domain name and CloudFront enforces global uniqueness on the domain name.
If a CloudFront distribution with the domain name already exists, then the CreateCloudFrontDistribution will fail and API Gateway will return an error without saving the domain name or allowing you to define it's associated API(s).
Thus, there is currently (Jun 29, 2016) no way to get API Gateway in multiple regions to handle the same domain name.

AWS has no update on providing the needful since confirming existence of an open feature request on July 4, 2016.  AWS Form thread for updates
Answer: Checkout Lambda@Edge

Q: What is Lambda@Edge?  Lambda@Edge allows you to run code across AWS
  locations globally without provisioning or managing servers,
  responding to end users at the lowest network latency. You just upload
  your Node.js code to AWS Lambda and configure your function to be
  triggered in response to Amazon CloudFront requests (i.e., when a
  viewer request lands, when a request is forwarded to or received back
  from the origin, and right before responding back to the end user).
  The code is then ready to execute across AWS locations globally when a
  request for content is received, and scales with the volume of
  CloudFront requests globally. Learn more in our documentation.

Usecase, minimizing latency for globally distributed users

Q: When should I use Lambda@Edge? Lambda@Edge is optimized for latency
  sensitive use cases where your end viewers are distributed globally.
  Ideally, all the information you need to make a decision is available
  at the CloudFront edge, within the function and the request. This
  means that use cases where you are looking to make decisions on how to
  serve content based on user characteristics (e.g., location, client
  device, etc) can now be executed and served right from the edge in
  Node.js-6.10 without having to be routed back to a centralized server.


Is Fermat's Last Theorem really proven by Prof. Wiles?

Question: The Prof. Wiles uses axioms, postulates and assumptions of the Set Theory. They can not be proven, thus, the Fermat's Last Theorem is not rigorously proven, but only confirmed by Set Theory? Source of worry:
Colin McLarty. What does it take to prove Fermat's last theorem? Grothendieck and the logic of number theory // Bulletin of Symbolic Logic. 2010. Vol.16, Number 3, 359-377.
Comment: I think you might have misunderstood something; it's true that Wiles' proof of Fermat's Last Theorem uses an axiom (existence of an uncountable Grothendieck universe) which is independent of ZFC (the usual axioms for set theory) - but it's generally thought that this is convenient rather than an essential part of the proof. This is separate from the more philosophical question of what it means to prove stuff anyways.
Comment: I don't think there's cause to pile on the downvotes... this question is founded on some misconceptions, but I think deserves the presumption of good faith.
Comment: Every proof in math (and everywhere) uses axioms. Nothing can be "proved from nothing".
Comment: If you don't want to assume any logic theory whose consistency is sloppy then you won't be able to prove there are infinitely many primes
Comment: This is exactly what I thought. May be some people think it is a troll (and they may be right). However using some axioms or not is a huge topic for a lot of people, you cannot sweep the problem away. @spaceisdarkgreen
Answer: You can't prove anything without assumptions and a proof that uses set theory (correctly) is considered rigorous by modern mathematical standards.
But there are a few things to think about here.
First, the proof has not been formalized (i.e. written down in a computer-checkable way). This is par for the course for modern mathematics and not considered problematic by most people... it is a lot of hard work to formalize an elaborate proof and generally mathematicians are content to pore over the details and convince themselves that the reasoning of every step is sound.
This does however open up the question of whether we know precisely which set theoretical axioms it would take to formalize the proof. For instance, can it be done in ZFC, or does it require some mild large cardinal assumptions? Many mathematicians would accept it either way, although some are uncomfortable with assuming large cardinals. In any event it's something to think about, and suggests some directions for further research. This is generally what the paper you cite is exploring, and he seems to indicate that the consensus is that it is formalizable in ZFC.
(I doubt McLarty is skeptical of the proof in any sense. At the very least, on a quick skim, that doesn't seem to be the point of the paper.)
Another concern touched on in the paper is that the theorem certainly doesn't require any set theoretical assumptions to state, so shouldn't there be a more elementary proof that doesn't need set theory? Well, perhaps there should, but one wasn't discovered in hundreds of years... discovery of an elementary proof would certainly be considered a major achievement, even many years after the theorem is accepted as fact.
But perhaps sometimes big ideas are needed to prove simple things. (However, see Friedman's Grand Conjecture.) Also, case of the prime number theorem might give some perspective here too: an elementary proof was found years after the original non-elementary proof, and although it is considered a major achievement, it was much less enlightening than the original and substantially fewer people bother to learn it today.
I don't any of these issues are as important as the possibility that the proof is simply wrong and the error has just not been discovered yet. It's a long and complicated proof, and it's not unheard of for errors in big important proofs to be discovered years after the fact (though I don't know offhand of any cases where the error turned out to not be fixable). In fact, there was a major error in Wiles' original proof, though this was found and fixed relatively quickly.
However, it's probably pretty unlikely that an error remains after 25 years cause of how well-studied the proof is, but I think it's still more likely than mathematicians deciding set theoretical methods used are unsound, e.g. if it were discovered that ZFC plus Grothendieck universe is inconsistent and that the proof can't be done in a consistent fragment. (At least the former is more likely in this lifetime - there could be a major sea change in methodology down the line.)
Comment: For those who are interested : it took a year to fix Wiles's mistake.


Varnish as Reverse Proxy Server for Rubygems

Question: I want to setup a cache server for Rubygems, as I'm currently based in Vietnam and the international internet connections are pretty slow. I have been trying to get this done via Varnish, but after hours of googling and trying various things I'm still stuck and can't get it to work properly.
My goal
This a sample request group when I'm installing a gem:
GET http://api.rubygems.org/latest_specs.4.8.gz
302 Moved Temporarily
GET http://s3.amazonaws.com/production.s3.rubygems.org/latest_specs.4.8.gz
200 OK

I want to setup a reverse proxy cache server (e.g. rubygems.mydomain.com) where I can perform the following request and the cache server would follow any redirects internally.
rubygems.mydomain.com/latest_specs.4.8.gz

The redirect location will link to various domains (some rubygems subdomains, Amazon S3, rubygems mirror).
Current State
After fiddling around with nginx, I found this blog post which is pretty close what I wanna achieve. However, I have too little knowledge about how Varnish works to get it working properly.
That's my current config file
import std;

backend rubygems {
    .host = "rubygems.org";
    .port = "80";
}

sub vcl_recv {
    std.syslog(180, "RECV: " + req.http.host + req.url);
    if (!req.url  ~ "^http") {
      std.syslog(180, "FETCH");
      set req.backend = rubygems;
      return (lookup);
    }
}

sub vcl_fetch {
    if (beresp.status == 302) {
        set beresp.http.X-Magic-Redirect = "1";
        return(deliver);
    }
}

sub vcl_hit {
    if (obj.http.X-Magic-Redirect == "1") {
        set req.url = obj.http.Location;
        return (restart);
    }
}

sub vcl_deliver {
    if (resp.http.X-Magic-Redirect == "1") {
        unset resp.http.X-Magic-Redirect;
        return(restart);
    }
    return(deliver);
}

I can perform a request, but it responds with an error:
curl -is http://localhost:8080/latest_specs.4.8.gz
HTTP/1.1 302 Found
Server: Varnish
Content-Type: text/html; charset=utf-8
Retry-After: 5
Content-Length: 376
Accept-Ranges: bytes
Date: Sat, 01 Feb 2014 02:33:47 GMT
X-Varnish: 933109322
Age: 1
Via: 1.1 varnish
Connection: close

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <title>302 Found</title>

Error 302 Found

Found

Guru Meditation:

XID: 933109322

Varnish cache server

and that's the corresponding syslog output for the request:
Jan 31 18:33:46 precise64 varnishd[2387]: RECV: localhost:8080/latest_specs.4.8.gz
Jan 31 18:33:46 precise64 varnishd[2387]: FETCH
Jan 31 18:33:47 precise64 varnishd[2387]: RECV: localhost:8080/latest_specs.4.8.gz
Jan 31 18:33:47 precise64 varnishd[2387]: FETCH
Jan 31 18:33:47 precise64 varnishd[2387]: RECV: localhost:8080http://production.s3.rubygems.org/latest_specs.4.8.gz

So, the request to Rubygems is working fine, but following the redirect does not work as expected. I would be glad if somebody could point me in the right direction.
Comment: I think you're missing an adequate backend once the request have been restarted.

Anyway, you should also change fill req.http.host and req.url appropiately when following the redirect
Answer: At this point when you will receive a 302 status from your rubygems backend, you have to make a request again at the new location specify by the HTTP header Location in the response.
You should end up with something like that:
vcl_fetch {
   if (beresp.status == 302) {  /* The content is on another location */

      /* First change the host of the request*/
      set req.http.host = regsub(regsub(beresp.http.Location, "^http://", ""), "^([^/]+)/.*$", "\1");

      /* Then change the url of the request */
      set req.url = regsub(beresp.http.Location, "^http://[^/]+/(.*)$", "/\1");
      return (restart);
   }
}

Answer: When I contacted the author of angry-caching-proxy, she responded:

Unfortunately your concern is correct. I have left the company two years ago for which I wrote it for - meaning my interest in maintaining it is fairly low. And it seems that nobody else has picked it up there...
Answer: If you get that working, please share.
Especially whether it works with the bundler dependency protocol.
There is some good information here
Alternatively, you may want to take a look at geminabox
Answer: Another approach is https://www.npmjs.org/package/angry-caching-proxy which provides a proxy that will cache the gems on the way through.


Filter Where-Object on variable property

Question: Read the following answers:
(Where object based on a variable content), (Use array of strings for comparing in Where-Object in PowerShell)
$allgroups
DisplayName
--------
Group1
Group2
Group3

$mailgroups
DisplayName
--------
Group1
Group3

$newgroup = $allgroups | ? ($_.DisplayName -notin $mailgroups)
$newgroup = $allgroups | ? ($_.DisplayName -notin ($mailgroups | Select DisplayName))

$newgroup should = "DisplayName: Group2", above commands return null. Tried other operators:
-ne, -cnotin, -eq, -notcontains

Answer: Your syntax is wrong:
$newgroup = $allgroups | ? DisplayName -notin $mailgroups.DisplayName

or if you want to keep your way:
$newgroup = $allgroups | Where-Object { $PSItem.DisplayName -notin $mailgroups.DisplayName }

alternatively, for v2:
$newgroup = $allgroups | Where-Object {
    ($mailgroups | Select-Object -ExpandProperty DisplayName) -notcontains $_.DisplayName
}

footnote: $PSItem and $_ are the same; $PSItem introduced in v3. Additionally, ? is the default alias for Where-Object.
Comment: Perfect, realized my mistake substituting () for {}. Thank you!
Comment: @009 Great, if my answer solved your problem, kindly vote on it and mark it as the answer.


HTML Views (UserControl) for Knockout.js

Question: In a single page application, how to use Knockout.js effectively to achieve MVVM. Is there a way to create views (Html files) and viewmodels (javascript files) separately? That can be referred in another HTML master file.
I tried iframe, but it allows user to navigate to individual views. Is there any other way?
Thanks in advance.
Answer: Yes, I think this is possible. If you create each view as a template in a separate html file and then load and append the appropriate template to the documents body when you instantiate you viewmodel.
in pseudo-code you'd get something like:

//your javascript
function yourViewModel (){
    this.loadedTemplate = ko.observable();

    //Load template from server with a get and append to document body
    //when loaded and appended do: loadedTemplate("idForTemplate");
}

this way you could load your views/templates using ajax and just load the view you'd need.
Comment: Thanks for the answer. How to link the html file which contains "idForTemplate" in main page?
Comment: [reading this](http://api.jquery.com/jQuery.get/) and [reading this](https://api.jquery.com/append/) should get you on your way.


How can I bootstrap?

Question: How can I bootstrap Drupal 8 from an external script?
This an example script from the RabbitMQ Work Queues tutorial.
require_once __DIR__ . '/vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;

$connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
$channel = $connection->channel();
$channel->queue_declare('task_queue', false, true, false, false);
echo " [*] Waiting for messages. To exit press CTRL+C\n";
$callback = function ($msg) {
  echo ' [x] Received ', $msg->body, "\n";
  sleep(substr_count($msg->body, '.'));
  echo " [x] Done\n";
  $msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']);
};

$channel->basic_qos(null, 1, null);
$channel->basic_consume('task_queue', '', false, false, false, false, $callback);

while (count($channel->callbacks)) {
  $channel->wait();
}

$channel->close();
$connection->close();

Within a worker script like this, I need to be able to create nodes.
How can I bootstrap Drupal 8 in this script?
Php Access User Data from external script? and Bootstrap from external script bootstraps passing a fake request to the kernel, which to me looks like a work-around.
In Drupal 7 you could do something like this, apparently.
// Bootstrap Drupal.
include_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

Comment: Have you investigated the probable usage of Drush commands? Modules like Devel generate content, users, etc.. with drush commands
Comment: Maybe do some reading up on "headless" and REST. It can be used for both the front end and backend of a site
Comment: @LittleCoding Yes, using a worker that only consumes messages from the queue and sends HTTP requests to Drupal has been considered as well. However, I am more interested to learn if this approach can work as well.
Comment: What about the opposite order? Have Drupal make an HTTP request to check the queue for new/updated messages and process them accordingly. This would be managed by the CRON system in Drupal. And a real server CRON can be setup to trigger Drupal's CRON system rather then being triggered by user visits.
Answer: I ended up inheriting the kernel and will adjust it as needed be.
Something like:
namespace Drupal\Core;

use Drupal\Core\Site\Settings;

class DrupalCliKernel extends DrupalKernel {

  public function bootstrap() {
    static::bootEnvironment();
    $this->setSitePath('sites/default');
    Settings::initialize($this->root, 'sites/default', $this->classLoader);
    $this->boot();
  }

}

And then:
use Drupal\Core\DrupalCliKernel;

$autoloader = require_once 'autoload.php';

$kernel = new DrupalCliKernel('prod', $autoloader);
$kernel->bootstrap();

// Drupal is bootstrapped now.

Not yet sure if I miss something important, but I am most likely not using this, but instead relying on using HTTP requests that the worker will use as Drupal is too coupled to the HTTP request. Just putting it out if someone come here to try to accomplish something similar and want a jump-start.

How can I bootstrap?


Add a reference cell formula in to a code

Question: enter image description here

This is what would be the output

I have this formula in cell "C1" To average the values in column2 with respected to column1 values.It gives what I need to do. But I want to get this work into a vba code.
Can anyone help to put this into a code. Is it possible when we have reference cells in the formula?? or do we need to go to more complex code??
=IF(A2<>A1,AVERAGEIF(A2:INDEX($A2:INDEX(A:A,MATCH(1E+99,A:A)+1),MATCH(TRUE,(INDEX($A2:INDEX(A:A,MATCH(1E+99,A:A)+1)<>A2,)),0)),A2,B2:INDEX($B2:INDEX(B:B,MATCH(1E+99,A:A)+1),MATCH(TRUE,(INDEX($A2:INDEX(A:A,MATCH(1E+99,A:A)+1)<>A2,)),0))),"")

Comment: The macro recorder will only help if you want to *enter the formula* by using VBA. I think, he wants to *perform the calculation* in VBA; that's not possible with the macro recorder. A possible solution which is analogous to the formula approach would be to use the `WorksheetFunction` object: https://msdn.microsoft.com/en-us/library/office/ff834434.aspx
Comment: Possible duplicate of [Average column value based on other column value vba code](http://stackoverflow.com/questions/36921899/average-column-value-based-on-other-column-value-vba-code)
Comment: Record it with the macro recorder?
Comment: @vacip It's not just a duplicate, it's the same person with the same question. Apparently not happy with the Answer, so trying again...
Answer: Here is one way to do C1's calculation is VBA:

Sub DoingC1Job()
    Dim s As String, s2 as string
    s = "=IF(A2<>A1,AVERAGEIF(A2:INDEX($A2:INDEX(A:A,MATCH(1E+99,A:A)+1),MATCH(TRUE,(INDEX($A2:INDEX(A:A,MATCH(1E+99,A:A)+1)<>A2,)),0)),A2,B2:INDEX($B2:INDEX(B:B,MATCH(1E+99,A:A)+1),MATCH(TRUE,(INDEX($A2:INDEX(A:A,MATCH(1E+99,A:A)+1)<>A2,)),0))),??)"
    s = Replace(s, "??", Chr(34) & Chr(34))
    s2 = Evaluate(s)
    MsgBox s2
End Sub

The ?? is just an easy way to get the double-quotes into the string.

As improved by Leviathan:
Sub DoingC1Job()
    Dim s As String, v As Variant
    s = "=IF(A2<>A1,AVERAGEIF(A2:INDEX($A2:INDEX(A:A,MATCH(1E+99,A:A)+1),MATCH(TRUE,(INDEX($A2:INDEX(A:A,MATCH(1E+99,A:A)+1)<>A2,)),0)),A2,B2:INDEX($B2:INDEX(B:B,MATCH(1E+99,A:A)+1),MATCH(TRUE,(INDEX($A2:INDEX(A:A,MATCH(1E+99,A:A)+1)<>A2,)),0))),"""")"
    v = Evaluate(s)
    MsgBox v
End Sub

Comment: `TEXT(,)` replaces `""` in a string formula nicely as well.
Comment: S Hi Thanks, it gives the answer for my first set, can we copy "S" down to other cells and get the answers in the Column C at respective cells.?? please see the picture?
Comment: Yes, but we would modify **s** in a loop to change the **1** and **2** cell references
Comment: @ Gary's Thank you, I will go from that.
Comment: "*The ?? is just an easy way to get the double-quotes into the string.*" -- Why not just use `s = "=IF(A2<>A1, ... <>A2,)),0))),"""")"`, why the `Replace()`?
Comment: @Leviathan  My personal mental problem...........I have trouble keeping track of the number of double quotes
Comment: @Gary's Student: Mhmm... well, I don't think it is a good idea to show this kind of workaround in an answer. Since it will only work if no other question marks are present in the string, this can easily introduce new errors. If you get confused by doubling all quotes (you could use the search&replace feature of your favourite text editor to automate this), instead of replacing them by question marks, directly replace them by `" & Chr(34) & "`. Also see http://stackoverflow.com/a/9024764/6216216 for handling double quotes in strings.
Comment: @Leviathan  I am forced to agree with you and I will edit my answer.........thank you for your help.........
Comment: Thanks, now it's +1. :)


Send node as HTML formatted email to all users of a role

Question: I have a RULE that works well:

After saving a new content of type DEMO
Send node as HTML formatted email
Parameter: Send email to:email@example.com,firstname.lastname@example.com

What I need is to send the same Action but to a "users of a role", something like

After saving a new content of type DEMO
Send node as HTML formatted email
Parameter: Send email to: Roles: Editor ---Rules does not allow to add roles here---

Is there any module that can expand this function in RULES? Or is there some way to achieve this directly within RULES?
Thanks
Comment: I did try and it didn't work as need it. I'm still looking...
Comment: You could use tokens to load your node body and set Mime Mail to use your site css ...
Answer: It may depend on your config. Here's a solution relying on Mime Mail and Mail System, as Mime Mail integrates smoothly with Rules.
Download and enable these 2 modules. Then you'll have a few steps configuring it :

Mail System: select MimeMailSystem in both "Site-wide default MailSystemInterface class" and "Mime Mail module class" drop-down list.
Mime Mail: change it from "Plain text" to "Filter HTML".

Now when you edit your rule, you'll see an action "Send HTML mail to all users of a role". Select editor role. You're done :)
Find even more details in this step by step tutorial: How to Send HTML Emails in D7 using Rules
EDIT : Alternative solution.

Download simplenews and enable both simplenews and simplenews rules. Set up the module.
Create a editors newsletter. Deactivate Subscription block
Enable "Use as simplenews newsletter" in the content type options you wish to send as HTML formatted email.
Create a rule : after editing a user account, condition user has role editor, subscribe user to newsletter editors  (and reverse rule to unsubscribe)
Create a rule : after saving a node, condition content-type is..., send newsletter :The newsletter node to be sent.: [node]
Comment: @user28697 I added another solution I've tested. I've got these modules installed on a test site, and the rule part itself is peanuts to set ut. Before you'll have to configure correctly your simplenews module and Mime Mail but this is quite easy and well documented
Answer: Not exactly the same scenario, but this has step by step instructions on how to do something similar - might help guide you in the right direction.
Email users on node creation based on taxonomy reference
Answer: You can use Mime Mail module for this.
Add action rule as "Send HTML mail to all users of a role" and select the editor role from the dropdown.
Refer: https://www.webwash.net/how-to-send-html-emails-in-drupal-7-using-rules/
Answer: You could use the Views Rules to get this to work. Here is a blueprint of how to do so:

Create a view of all users with role "Editor" (as in your question).
Improve your existing rule to create a "Views loop", which is similar to a regular Rules loop, but allows looping over rows of view results.
Within that "Views loop", perform a Rules Action to Send node as HTML formatted (similar to what you already have in your existing rule).

For way more details on this, refer to ("Option 2" of) my answer to "How to use Rules to send an E-mail after saving a new comment, to users who checked a boolean in their profile?"


Prove a geometry question about angles and radii in five collinear circles?

Question: Our teacher give us this question and I worked on it but I couldn't find a way to prove that. Is it possible to help me to prove that?
Thanks.
Comment: It's just about **similar triangles**. Triangles ABC, AGD, AHE, AIF, AKJ are all similar. Hence their sidelengths are in ratio. The result follows directly.
Comment: $R_i$ are the radii, not angles. Also, your circles are collinear. I edited the title for you.
Comment: The geometry of geometric mean.
Answer: Hint: Consider the uniform scaling (i.e., similarity transformation) of the entire plane about point $A$ that takes $K$ to $H$. Argue that this transformation takes $H$ to $B$, $J$ to $E$, and $E$ to $C$. Once you see this, it's clear that
$$
\frac{R_5}{R_3} = \frac{R_3}{R_1}
$$
If the language of transformations isn't familiar to you, try instead noting that the segments labelled $R_1, R_3, R_5$ are all parallel (being orthogonal to the upper ray), and hence that $AKJ$ is similar to $AHE$, and work from there.
Answer: That is a immediate consequence of Thales Theorem.
$$\frac{BG}{GH}=\frac{CD}{DE} \Rightarrow \frac{R_1+R_2}{R_2+R_3}=\frac{\sqrt{4R_1R_2}}{\sqrt{4R_2R_3}} \Rightarrow R_1R_3=(R_2)^2 (*)$$
We get $CD=\sqrt{4R_1R_2}$ by a Pythagoras Theorem at $BCDG$. The relation $(*)$ means that those radius are in a geometric sequence and so
$$R_1R_5=(R_3)^2$$
Comment: This is total overkill. It's just similar triangles. Compare the ratio of sides.
Answer: Hint. Start by proving that $R_{i-1} R_{i+1}=R_{i}^2$ by noting that
$$\frac{x}{R_i}=\frac{x-R_{i}-R_{i-1}}{R_{i-1}}=\frac{x+R_{i}+R_{i+1}}{R_{i+1}}.$$
where $x$ is distance of the center of the $i$-th circle from $A$.
Answer: Let $c_n$ denote the distance of $A$ to the center of the circle with radius $R_n$.
Since the triangles formed by the radius and $A$ contain the same angles, you have
$R_n = k \cdot c_n$ for some constant $k$.
Now since the neighboring circles intersect in exactly one point on the line connecting the centers and $A$, we can come up with the following recursive formula for $c_n$:
$c_{n+1} = c_n + R_n + R_{n+1} = c_n + k \cdot c_n + k \cdot c_{n+1}$
Solve for $c_{n+1}$ to get
$c_{n+1} = c_n \cdot \frac{k+1}{1-k}$ which is the recursive form of a geometric sequence and hence
$c_{n} = c_1 \cdot \left(\frac{k+1}{1-k}\right)^{n-1}$
Proving the claim now is trivial. (use $R_n = k \cdot c_n$)
Answer: By the similarity $R_{i+1}/R_i = \mathrm{const.}$ , hence $R_5/R_3 = R_3/R_1$.
Answer: Assumptions
I'm assuming that the following are true:

$A$, $B$, $G$, $H$, $I$, $K$ are collinear
$B$, $G$, $H$, $I$, $K$ are the centres of their respective circles
$A$, $C$, $D$, $E$, $F$, $J$ are collinear and the line on which they lie is tangent to all the circles.

Definitions
We know these angles:

$\angle CAB$ = $\angle DAG$ = $\angle EAH$ = $\angle FAI$ = $\angle JAK$. Call this angle $\theta$.
$\angle ACB$ = $\angle ADG$ = $\angle AEH$ = $\angle AFI$ = $\angle AJK$ = $90^{\circ}$.

And we can define some lengths. Let:

$R_1$, $R_2$, etc. be the lengths of $CB$, $DG$, etc.
$H_1$, $H_2$, etc. be the lengths of $AB$, $AG$, etc.

Known Information

For right angled trianges, we know that $\sin(\text{angle}) = \frac{\text{opposite}}{\text{hypoteneuse}}$, so:

$$\forall n \in \{1, \dots, 5\}, \sin\theta = \frac{R_n}{H_n} \Rightarrow H_n = \frac{R_n}{\sin\theta}$$

Looking at the diagram, we can also see that:

$$\forall n \in \{1, \dots, 4 \}, H_{n+1} = H_n + (R_n + R_{n+1})$$
Forming a Rule
We can substitute for $H_n$ from the first equation into the second and rearrange:
\begin{align}
&& \frac{R_{n+1}}{\sin\theta} &= \frac{R_n}{\sin\theta} + R_n + R_{n+1} \\
\Rightarrow && R_{n+1} \left(\frac{1}{\sin\theta} - 1\right) &= R_n \left(\frac{1}{\sin\theta} + 1\right) \\
\Rightarrow && R_{n+1} \left(1 - \sin\theta\right) &= R_n \left(1 + \sin\theta \right) \\
\Rightarrow && R_{n+1} &= R_n \left(\frac{1 + \sin\theta}{1 - \sin\theta}\right) \\
\Rightarrow &&R_{n+k} &= R_n {\left(\frac{1 + \sin\theta}{1 - \sin\theta}\right)}^k \\
\end{align}
The result
This means that:
\begin{align}
R_1 \cdot R_5 &= R_1 \cdot \left(R_1 \cdot \left(\frac{1 + \sin\theta}{1 - \sin\theta}\right)^4\right) \\
&= \left(R_1 \cdot \left(\frac{1 + \sin\theta}{1 - \sin\theta}\right)^2\right) \cdot \left(R_1 \cdot \left(\frac{1 + \sin\theta}{1 - \sin\theta}\right)^2\right) \\
&= R_3 \cdot R_3
\end{align}
Extra results
This rule, coupled with the fact that there's nothing special about $R_1$ (it could just as easily have been called $R_0$ or $R_{1000}$) means that if we take any two collections of integers $A = \{A_1, A_2, \dots\}$ and $B = \{B_1, B_2, \dots\}$ and define $S_A = \sum_{a \in A}a$ and $S_B = \sum_{b \in B}b$ we get:
\begin{align}
\prod_{a \in A} R_{a} &= R_0^{|A|} \left(\frac{1 + \sin\theta}{1 - \sin\theta}\right)^{S_A} \\
&= R_0^{|A| - |B|} \left(\frac{1 + \sin\theta}{1 - \sin\theta}\right)^{S_A - S_B} R_0^{|B|} \left(\frac{1 + \sin\theta}{1 - \sin\theta}\right)^{S_B} \\
&= R_0^{|A| - |B|} \left(\frac{1 + \sin\theta}{1 - \sin\theta}\right)^{S_A - S_B} \prod_{b \in B} R_{b}
\end{align}
If $|A| \neq |B|$ and $z = \frac{S_A - S_B}{|A|-|B|}$ is an integer, this simplifies to:
$$
\prod_{a \in A} R_{a} = R_z^{|A| - |B|} \prod_{b \in B} R_{b}
$$
Or if $|A| = |B|$ and $S_A = S_B$ (i.e. two equal sized collections with equal sums), we end up with:
$$
\prod_{a \in A} R_{a} = \prod_{b \in B} R_{b}
$$
and your question is a special case of this where $A = \{1,5\}$ and $B = \{3,3\}$.


Definition of "invariant in a module"

Question: What does it mean if someone say that the class of an ideal $I$ in a ring $R$ is an invariant of a module $M$?
Comment: I can't make sense of it. It seems strange that the statement about *ideals* should be an invariant of *modules*. It would really be helpful if you provided the full context of where you encountered the statement.
Comment: I found this expression here: http://www.jstor.org/stable/1993702   in Lemma 1.4
Comment: Thank you! That helps immensely.
Answer: In the reference you gave, it expresses $M$ as $$M\cong\sum(\overline{\theta}-\theta)^{e_i}U_iR$$ where the $U_i$ are ideals of $R_0$. It then says "the class of $\prod U_i$ is an invariant of $M$."
My best guess is that this means that if there is another representation
$$\sum(\overline{\theta}-\theta)^{e_i}V_iR$$ for ideals $V_i$ in $R_0$, then $\prod V_i$ and $\prod U_i$ have the same class.
I can't be 100% sure since it's possible they are using "invariant" in some specialized sense specific to this subtopic. There is certainly a lot of notation to catch up to at that point in the paper :)

Definition of "invariant in a module"


With $(AB^{-1})^T$, what comes first, the multiplication or the transpose?

Question: In part of the question we have $(AB^{-1})^T$.
My first thought was that I multiply $A$ and $B^{-1}$, then apply the transpose.
But according to theory $(AB)^T = (B)^T(A)^T,$ so this says I should get the transpose first, then multiply.
I'm confused about either sticking to the theory or what I did was right.
Comment: A seemingly common misunderstanding when learning identities (like $(AB)^T=B^TA^T$) is that you *must* use them.  All it's giving you is a manipulation that you *can* do.  Don't confuse "is" with "ought"!  (Knowing them can save you a whole lot of work, like say in calculating $B^T(AB^{-1})^T$.  But it's just that you *can* save work.  No one says you must!  It can be good trying things in multiple ways to make sure you didn't make a mistake, though.)
Comment: Either way would be right, they're the same.
Comment: @sarah23 you should show us what you did, or use a computer software to verify your calculations - I suggest Symbolab for having visual matrices you can enter elements into, but WolframAlpha is the typical choice for this sort of thing
Comment: @FShrike yup you're right I re-calculated the whole thing and my calculation had an extra negative sign, thank you for the help
Comment: @KyleMiller but I got two different answers and its a true or false question so using it is giving me false and not using it is giving me true
Comment: If you use an identity and get two different answers, then at least one of three things must be true: (1) you did the first calculation wrong, (2) you did the second calculation wrong, or (3) the identity is wrong.  This identity is not wrong, so that leaves (1) or (2).
Answer: The order is unimportant from a principles standpoint, but in some situations one formula may be more useful than the other. The identity $(AB)^T=B^TA^T$ is an algebraic tool to prove theorems and solve equations, it isn't necessarily a computational tool. $(B^{-1})^TA^T=(AB^{-1})^T$, calculate whichever feels more natural (I'd go for the RHS myself).
Comment: and was what you did respectful of the fact that matrix multiplication isn't in general commutative? $AB^{-1}\neq B^{-1}A$ in general
Comment: Show us what you did @sarah23
Comment: but I'm getting different answers that's why I'm confused


Integral of a non-negative but non-zero real-valued continuous function is strictly positive?

Question: Let $C(X)$ be the collection of all continuous real-valued functions defined on a compact metric space $X \subset \mathbb{R}$.
Let $C(X)_+$ be the positive cone of $C(X)$
(i.e., $C(X)_+ := \{ f \in C(X) \colon f \geq \theta \}$, where $\theta(x)\equiv 0$ for all $x \in X$ is the zero vector in $C(X)$.).
Let $\nu$ be a probability measure on the measurable space $(X, \mathcal{B}(X))$, where $\mathcal{B}(X)$ denotes its Borel $\sigma$-algebra of $X$.
It is well known from the elementary property of integral that $$ \int_X f(x) \nu (\mathrm{d} x) \geq 0$$ whenever $f \geq \theta$.
Furthermore, $ \int_X f(x) \nu (\mathrm{d} x) > 0$ holds true if $f$ is strictly positive (i.e., $f(x) >0$ for all $x \in X$).

I am wondering that what if $f$ is just non-zero element of the positive cone $C(X)_+$ (i.e., $f \in C(X)_+ \setminus \{\theta\}$), can we still conclude that its integral is strictly positive
  $$ \int_X f(x) \nu (\mathrm{d} x) > 0 \qquad ?$$

I guess that the answer is yes, since $f$ is continuous rather than just Borel measurable. But I have been struggling with this question for a while, so could any kind person help me out please?
Thank you very much in advance! Any idea or suggestions are much appreciated!
Answer: First of all there is no such thing as normal distribution on a compact metric space. Normal/Gaussian distribution id defined on Euclidean spaces or topological vector spaces but not on metric spaces. Your conclusion is true for Borel measures $nu $ on $X$ such that $\nu (U)>0$ for every non-empty open set $U$. A counter example to your statement is obtained by taking $\nu $ to be a delta measure at a point.
Comment: I have given a counter example already. Suppose $\nu (A)=1$ if $x \in A$, $0$ otherwise, where $x \in X$ is fixed. Then $\int f \, d\nu =f(x)$. If $f$ is non-negative and not identically $0$ we cannot say that $f(x) >0$ for any $x$, right? So what you are trying to prove is simply not true.
Comment: I have answered this point also: if $\nu (U)>0$ for every non-empty open set $U$ the the conclusion is true. I  particular if $\nu $ has a strictly positive density f (where $\nu $ is a Borel measure on $\mathbb R$) then the conclusion holds. In particular it is true for normal distribution. It is not true for exponential distribution (whose density is $0$ on $(-\infty ,0)$.
Comment: Thanks so much for your kind advice, @Kavi Rama Murthy . I learned it. But I am still curious how to prove my statement above for a general probability measure? (I've changed my description a bit) Since I am quite keen on understanding this point and I am just a beginner in this area. Would you mind to provide me more details in explanation please? I really appreciate :-)
Comment: Thanks for your reply @Kavi Rama Murthy . It's a huge help to me. I understand the counterexample now. But I still confused that why the statement holds true if $\nu$ is normal distribution? Generally speaking, under which kind of probability measures, such integral (expectations) will be strictly positive? Sorry for bothering you, but I am sincerely keen on getting this point. Could you explain this please? Thanks again :-)
Comment: Thanks for your kind explanation @kavi rama murthy . It's very helpful to me and I learned from it. Thank you so much again:-)


IIS rewriting location header before ARR

Question: We have a rewrite configuration that treats ARR as a reverse proxy in a configuration like this:
Browser client (OriginA) <-> IIS/ARR (OriginB) <-> Server

The client is any number of web browsers. We cannot change this configuration.

The client requests http://originb/return with a URL such as http://origina/done.html in the request.
ARR then forwards the request to http://server/return.
The server responds with the Location header set to http://origina/done.html and HTTP 302. I've verified this with Wireshark.
IIS somewhere in the pipeline is changing the Location header to http://originb/done.html. This is where the problems begin.
ARR sees the originb URL in a PATTERN_MATCH step for the Location header.
ARR reports the originb URL as the Location header in the GENERAL_RESPONSE_HEADERS step.
The client blindly accepts the URL and redirects to the non-existent http://originb/done.html instead of http://origina/done.html

I've cranked up Failed Request Tracing and thats how I saw steps 5 and 6.
What could be causing IIS to rewrite the Location header before ARR? Are there any other IIS tools I can use to figure this out?
Answer: My Googlefu was failing me today.
In the Server Proxy Settings pane of IIS Manager, I needed to uncheck "Reverse rewrite host in response headers".
Comment: Thanks, I was searching for this all over website settings, but it turns out it is global setting
Answer: In IIS 7, click the server that runs the AAR/does the rewriting (above sites, application pools, etc) - then open "Application Request Routing Cache". In the "Actions" menu on the right hand "Actions" pane, under "Proxy", click "Server Proxy Settings". In the resulting dialogue, ensure "Reverse rewrite host in response headers" is unchecked (see image).
dialogue with tickbox image


how to access parents scope from ng-click

Question: I need to pass the value of $scope.correct into the checkAnswer function but it keeps coming up undefined. ng-click only seems to understand it's own scope. What am I doing wrong?
angular.module('Tutorials', ['functions']).controller('getAnswers', function ($scope, $element){
    $scope.verbs = conjugate(conjugationsets[tutorial_number][questionnum]);
    $scope.correct = $scope.verbs.conjugations[0].text;
    $scope.randomizeAnswers = function () {

      fisherYates($scope.verbs.conjugations);
    }();

    $scope.checkAnswer = function (answer, correct){
        checkanswer($scope, answer, correct);
    }
});

Comment: You can use `$scope.$parent` to access the parent scope.
Comment: you legend, I should have posted on here about 2 hours ago!
Comment: Can you create a demo of the problem at http://plnkr.co/edit/?p=preview
Comment: http://plnkr.co/edit/Rs4BwMMnKqfC7MIsWB2Q
Comment: sorry, make that http://plnkr.co/edit/Rs4BwMMnKqfC7MIsWB2Q?p=preview
Comment: You should avoid explicitly calling the parent scope with scope.$parent. It makes your code brittle as it will break silently if you add another scope in between.
Comment: Your `$scope.checkAnswer` should be `$scope.checkAnswer = function (answer){`. The `$scope` will be available in the function through `closure`
Comment: Anders, I need to compare the answer that was clicked on (and thus triggered the click and controls scope) to the correct answer which also exists within the same object and has a correct property of "correct". I'm having trouble understanding scope in Angular.
Comment: ok finally I got it working thanks guys, sorry about the noob question but this is the forst MVC framework I've ever used and its taking a whil eto get out of the jQuery mindset!
Answer: You can use $scope.$parent to access the parent scope.
$scope.checkAnswer = function (answer){
    checkanswer($scope, answer, $scope.$parent.correct);
}

Note: I haven't gone through the complete problem to see whether there is an better way to solve the problem


Tipo de dado char precisa de espaço após aspas no scanf()

Question: #include <stdio.h>
#include <stdlib.h>

void main(){

  char elevador;
  int cod=0, a=0, b=0, c=0;

  while(cod == 0){
    printf("\nElevador utilizado (a/b/c)? ");
    scanf("%c", &elevador);

    switch(elevador){
      case 'a':
        a++;
        break;
      case 'b':
        b++;
        break;
      case 'c':
        c++;
        break;
      default:
        printf("opcao inválida!");
    }
  }
}

Por que quando utilizo o tipo de dado char e utilizo o scanf() preciso dar um espaço após a primeira aspas?
Desta forma:

scanf(" %c", &elevador); << Espaço após "_%c"

Pois se não utilizar assim meu programa conforme código no inicio irá funcionar de forma "anormal" podem testar, irá executar desta maneira:
Answer: Porque o scanf() trata a entrada com uma quebra de linha no final e isto pode causar problemas de buffer. Este espaço indica que haverá uma substituição da quebra de linha que é espúrio aí. Normalmente só dá problema quando há repetição de leitura onde a quebra de linha acaba ficando para a próxima entrada.
Relacionado.
Comment: Tu manja de mais amigo, obrigado mais uma vez. O outro tópico me ajudo a entender melhor ainda.

Grato.


illegalStateException on nested lock

Question: i' m getting this exception but i don't understand why.
public Test() {
        globalLock = new ReentrantLock();
        condition = globalLock.newCondition();
    }

public void increaseRow(Integer row) {
    matrixLock.lock();
    try {
        while (countIncreasingColumn > 0)
            condition.await();
        countIncreasingRow++;
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
       condition.notifyAll();
        matrixLock.unlock();
        synchronized (rows.get(row)) {
            for (int j = 0; j < column; j++)
                matrix[row][j] += 1;
            countIncreasingRow--;
        }
    }
}

thread class:
public void run() {
        while (true) {
            test.function(new Random().nextInt(10));
        }
    }

stackTrace:
Exception in thread "Thread-0" waiting thread for test 18
java.lang.IllegalMonitorStateException
    at java.lang.Object.notifyAll(Native Method)

i' m getting thie exception on notifyAll(). The thread that execute the global.lock() block is the owner,so why i'm getting this?
Comment: And what is this mysterious exception? Do we guess? Provide the full stack trace.
Comment: @BoristheSpider wait a bit.
Answer: It seems you are confused with Monitor Lock(Object#notifyAll & synchronized-statements) and Condition Variable(Condition#signalAll & Condition#await).
If you wait on Condition#await, you must use Condition#signalAll instead of Object#notifyAll.
UPDATE:
Please see notifyAll() throws IllegalMonitorStateException to solve OP's question.
Comment: thanks for the answer, i changed the snippet, can you see updates?
Comment: i' m still getting illegalMonitorExeception on notifyAll(), can you explain me why?

illegalStateException on nested lock


Adjusting for zero mean (standardizing) in a multiple regression model

Question: A friend of mine was telling me today about the need to mean adjust input variables to zero in order to "get rid of implicit intercept" or scale terms in the slope coefficients and to make their interpretation easier. He was stressing its use and even standardization by the weighted mean in a weighted regression. Both of these I had never quite heard of other than when the inputs are of a very different scale (like 6 digit dollar values and single digit times or something) for stability of the estimation. Is it sensible what I am hearing? And that this "mean shifting" increases correlation between the slope coefficients? If so where can I read more about this?
The argument I was given goes something like this:
If i have the model
$$y = ax + b + \epsilon$$
and then I shift $x$ by $D$, I will have $y = a' + b(x+D) + \epsilon$ where the estimate for $b$ does not change (and neither do the residuals) but the estimate for the intercept should be shifted accordingly. Thus we can equate $y - \epsilon$ to see that $a' = a - bD$ suggesting that shifting $x$ makes estimates of the intercept more correlated with $b$ than before. It feels to me like no new information has been added at all and there is nothing better about the coefficient estimates with shifts than with no shifts.
Comment: In linear regression, "mean shifting" should not affect correlation
Answer: I don't know how representative my experience is, but I've met several people with somewhat strong opinions on centering.  (Which is weird, really, because who cares?)  It may be that you have run into this yourself.  Often, centering is discussed in the context of multicollinearity.  In general, I don't think centering really does much; if $x_1$ & $x_2$ are correlated, so will the centered versions of them, as @Henry points out.  The one case I know of where it can make a difference is when fitting polynomial terms.  For example, if your predictor variable, $x$, ranges from 2 to 4, and you want to add an $x^2$ term to capture a possible curvilinear trend, $x$ & $x^2$ can be awfully hard to distinguish.  On the other hand, if you center $x$ first (and the quadratic was concave up) $x^2$ would be going down on the left and up on the right, which makes them much more distinguishable.  I'm not aware of much beyond that.  There are what I would call 'cosmetic' changes, though.  For instance, sometimes it just doesn't make much sense to talk about the effect when $x$ is 0, but you are interested in the predicted $y$ value at the mean of $x$.  In such a case, centering causes the regression intercept to reflect that value.  Note that this hasn't actually changed anything, however; it is just as possible to get a predicted value at $-\bar{x}$ with your new model, and you could have easily gotten the predicted value at $\bar{x}$ with your old one.


Copying no of files from one folder to another in Mac using terminal

Question: I am trying to follow a blog about machine learning. In the blog, author transferred/copy the certain number of files from one folder to another using linux command. I am working on Mac, I tried to run the commands by modifying them according to the mac environment (with my limited knowledge) but could not able to copy them to other folder. Here is the Linux command copied from the blog
#Transfer data into the specific directory
echo "---Parasitized---"
cd Parasitized_all
cp `ls Parasitized_all | head -5000` ../Parasitized_train
cp `ls Parasitized | tail -n+5001 | head -5000 | wc -l` ..Parasitized_validation
cp `ls Parasitized | tail -n+5001 | tail -3779 | wc -l` ..Parasitized_test

For instance, I tried to copy the first copy command of above statements into mac as follow:
cp `Documents/folder_directory/Parasitized_all | head -5000` Documents/folder_directory/Parasitized_train

However, it did not work. Is there anyone who could guide me in identifying the mistake I am making?
Comment: Based on the examples you've given, you should treat this blog with care.  Follow it at your own risk.  Many bad practices are exhibited above.
Comment: Please note: [Why *not* parse `ls`?](http://unix.stackexchange.com/questions/128985/why-not-parse-ls)
Answer: The point of failure comes when you run this:
cp `Documents/folder_directory/Parasitized_all | head -5000`

Because you are trying to do one thing and the shell is understanding another one. By running that head 5000 you want to read that file Documents/folder_directory/Parasitized_all and take that list as source to then copy those files that coincide with the first 5.000 lines of it, but cp does not work like that, it only understands copy SOURCE (to) DESTINATION. Also, it is not even a file but a directory.
The difference between that command and ls Parasitized_all | head -5000 is that the output from this last command will be a list of files, which can be used as a source for copying them to their destination path.
That said, note that in the command you run you are missing the ls at the beginning of it, so that list of files is not coming up. So, try running this instead (I changed from ls to find just because I prefer using it):
cp $(find Documents/folder_directory/Parasitized_all -type f | head -5000) Documents/folder_directory/Parasitized_train/

Or if you face an error like argument list too long:
for FILE in $(find Documents/folder_directory/Parasitized_all -type f | head -5000); do
    cp $FILE Documents/folder_directory/Parasitized_train/
done

Comment: Thanks for the answer, When I ran the command it throws me this message: -bash: /bin/cp: Argument list too long
Comment: In that case, you could try running a loop: `for FILE in $(find Documents/folder_directory/Parasitized_all -type f | head -5000); do cp $FILE Documents/folder_directory/Parasitized_train/; done`


Degree of cut equal to degree of source in digraph

Question: Let $D$ be a digraph and $s, t \in V (D)$. Suppose that $d_D^+(v)=d_D^-(v)$ for all $v \in
V(D) \backslash  \{s,t\} $. Let $S \subseteq V(D)$ with $s \in S$ and $t \in V (D) \backslash S $. Let $d_D^+(S)= |A_D^+(S) \cap A_D^-(V(D) \backslash  S)| $be the number of arcs from $S$ to $V(D) \backslash  S$, and $d_D^-(S)= |A_D^+(V(D)\backslash (S) \cap A_D^-(S)| $
the number of arcs from $V (D) \backslash S$ to $S$. How can I show that $d_D^+(s)-d_D^-(s)=d_D^+(S)-d_D^-(S)$. I undestand it intuitively (i.e. every vertex other than $s$ contributes nothing to the indegree and outdegree of $S$) but I think I'm missing an intermediate step or at least some rigor. I also thought to use the handshaking dilemma to show $d_D^+(s)-d_D^-(s)=-d_D^+(t)+d_D^-(t)$, but I don't see where to go from this. Maybe an inductive proof would work (start from two vertices and add one vertex to either $S$ or $T$ for the inductive step).
Answer: You should look at $$\sum_{v \in S} d^+(v)  - \sum_{v \in S} d^-(v) = \sum_{v\in S} \left(d^+(v) - d^-(v)\right).$$
The right-hand side simplifies to $d^+(s) - d^-(s)$ without too much work.
The left-hand side should simplify to $d^+(S) - d^-(S)$, with the number of arcs within $S$ canceling between the two sums. That argument still may or may not feel rigorous to you; to take it to the next level of formality, write $$d^+(v) = \sum_{w : (v,w) \in A(D)} 1$$ (and similarly for $d^-(v)$) then interchange some sums.


Radiobutton e Checkbox Soma

Question: Galera eu aqui um codigo em js que ao selecionar um checkbox ele exibe o valor do checkbox em um input e se eu selecionar mais de um ele soma os checkbox selecionados e exibe o valor total também na mesma input
o meu problema tá sendo o seguinte, na hora que selecionar as radiobutton ele soma a radiobutton selecionada mas quando eu marco outra radiobutton ele simplesmente não subtrai
EXEMPLO:
RADIO1 = 10 REAIS
RADIO2 = 15 REAIS
RADIO3 = 40 REAIS
se eu selecionar a RADIO1 ele soma 10 reais, mas se por acaso eu mudar da RADIO1 para RADIO3 ele não subtrai a RADIO1 ele só soma a RADIO3 ai o valor total fica 50 ao invés de 40...
Segue abaixo o codigo..

function checkChoice(whichbox) {
  with(whichbox.form) {
    if (whichbox.checked == false)
      hiddentotal.value = eval(hiddentotal.value) - eval(whichbox.value);
    else
      hiddentotal.value = eval(hiddentotal.value) + eval(whichbox.value);
    return (formatCurrency(hiddentotal.value));
  }
}

function formatCurrency(num) {
  num = num.toString().replace(/\$|\,/g, '');
  if (isNaN(num)) num = "0";
  cents = Math.floor((num * 100 + 0.5) % 100);
  num = Math.floor((num * 100 + 0.5) / 100).toString();
  if (cents < 10) cents = "0" + cents;
  for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
    num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
  return ("" + num + "." + cents);
}

// funcoes somas de checkds

function checkChoice(whichbox) {
  with(whichbox.form) {
    if (whichbox.checked == false)
      hiddentotal.value = eval(hiddentotal.value) - eval(whichbox.value);
    else
      hiddentotal.value = eval(hiddentotal.value) + eval(whichbox.value);
    return (formatCurrency(hiddentotal.value));

  }
}
<form name=myform class="noformat">

    <input type="radio" name="tamanho" id="option1" value="9.25" autocomplete="off" onchange="this.form.total.value=checkChoice(this);">250GR

    <input type="radio" name="tamanho" id="option2" value="11.25" autocomplete="off" onchange="this.form.total.value=checkChoice(this);">400GR

    <input type="radio" name="tamanho" id="option3" value="14.25" autocomplete="off" onchange="this.form.total.value=checkChoice(this);">600GR

      <input type="checkbox" autocomplete="off" name="valor" value="2" onClick="this.form.total.value=checkChoice(this);">L. Ninho

      <input type="checkbox" autocomplete="off" name="valor" value="3" onClick="this.form.total.value=checkChoice(this);">Nutella

      <input type="checkbox" autocomplete="off" name="valor" value="3" onClick="this.form.total.value=checkChoice(this);">Chantilly

      <input type="checkbox" autocomplete="off" name="valor" value="1.5" onClick="this.form.total.value=checkChoice(this);">L. Condensado

      <input type="checkbox" autocomplete="off" name="valor" value="1.5" onClick="this.form.total.value=checkChoice(this);">S. Valsa

      <input type="checkbox" autocomplete="off" name="valor" value="2.5" onClick="this.form.total.value=checkChoice(this);">Sorvete

    Valor Total:
    <input class="form-control input-lg" id="disabledInput" name="total" type="text" placeholder="" readonly disabled>
    <input type=hidden name=hiddentotal value=0>
    R$

</form>

Alguém me ajuda falta isso pra eu completar esse sistema.
Eu não sei o que aconteceu mas o código aqui no site ele funciona mas quando eu coloco em algum pagina online, ele não exibe o resultado.
Caso queira dar um olhada aqui acessa aqui: http://acaiamarena.com.br/modulos/teste.php
Comment: dicas: não utilize a função `eval()`, não é uma boa prática; utilize todas as chaves mesmo para instruções de apenas uma linha para facilitar a leitura
Answer: A estrutura do seu código não considera quando um radio é desmarcado ao selecionar outro radio, isso que causa o problema de não subtrair. Como acho que seria complexo controlar os campos que já foram somados é mais simples somar todos os valores quando algum checkbox ou radio for modificado.
Observações:

"limpei" o HTML para deixar somente o que importa para o problema
utilizei a função nativa addEventListener() para atribuir os eventos ao invés do atributo onclick
utilizei o seletor nativo querySelectorAll() para selecionar os <input>

function formatCurrency(num) { // função original - sem modificação
  num = num.toString().replace(/\$|\,/g, '');
  if (isNaN(num)) num = "0";
  cents = Math.floor((num * 100 + 0.5) % 100);
  num = Math.floor((num * 100 + 0.5) / 100).toString();
  if (cents < 10) cents = "0" + cents;
  for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
    num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
  return ("" + num + "." + cents);
}

var form = document.forms[0];
var inputs = form.querySelectorAll('input[type=checkbox],input[type=radio]');
// iterar todos os inputs
for (var i = 0; i < inputs.length; i++) {
  // vincular função ao evento "change"
  inputs[i].addEventListener('change', function() {
    var soma = 0;
    for (var j = 0; j < inputs.length; j++) {
      if (inputs[j].checked) {
        // interpreta como float, usando parseFloat ao invés de eval
        soma += parseFloat(inputs[j].value);
      }
    }
    form.hiddentotal.value = soma; // atribui valor ao campo oculto
    form.total.value = formatCurrency(soma) // exibe valor formatado
  }, false);
}
label {
  display: inline-block;
  width: 210px;
  float: left;
}
<form name="myform">
  <input type="radio" name="tamanho" value="9.25">250GR
  <input type="radio" name="tamanho" value="11.25">400GR
  <input type="radio" name="tamanho" value="14.25">600GR
  <input type="checkbox" name="valor" value="2">L. Ninho
  <input type="checkbox" name="valor" value="3">Nutella
  <input type="checkbox" name="valor" value="3">Chantilly
  <input type="checkbox" name="valor" value="1.5">L. Condensado
  <input type="checkbox" name="valor" value="1.5">S. Valsa
  <input type="checkbox" name="valor" value="2.5">Sorvete

    Valor Total:
    <input name="total" type="text" readonly disabled>
    <input type="hidden" name="hiddentotal" value="0">

</form>
Comment: eu não sei o que aconteceu mas o codigo aqui no site ele funciona mas quando eu coloco em algum pagina online, ele não exibe o resultado

caso queira dar um olhada aqui acessa aqui

http://acaiamarena.com.br/modulos/teste.php
Comment: @AlfredoLima coloque a tag `
Comment: coloquei mesmo asism não funcionou... :(
Comment: Olá, por favor me ajuda, estou com o mesmo problema já faz meses...
Comment: @AlfredoLima coloque a tag `
Comment: Agora deu certo kkk valeu

Radiobutton e Checkbox Soma


Bootstrap: How to close an open collapsed navbar when clicking outside of the MENU?

Question: I want to have my menu closed when the user clicks outside the menu, not only outside the navbar element. Because I have more collapses in my menu, this solution did not work for me: How to close an open collapsed navbar when clicking outside of the navbar element in Bootstrap 3?
The menu disapeares when I click outside the menu, but when I click on the link with a dropdown, the whole menu collapses.

            Webshop

                Industriële verpakkingen
                Promotionele verpakkingen
                Gelamineerde verpakkingen
                Enveloppen &verzend verpakkingen
                Medische verpakkingen
                Co-packing

Comment: Can you create a fiddle or bootply of this
Comment: post the rest of your html
Answer: You can use this to collapse if not clicking a link: fiddle
$(document).click(function(e) {
    if (!$(e.target).is('a')) {
        $('.collapse').collapse('hide');
    }
});

Comment: I fixed the issue by adding navbar- to .collapse. Thanks for your help!
Comment: You can add the class `in` to the `collapse` to keep hidden ;)
Comment: when clicking on the search  field, the menu hides... how can I fix this?
Comment: add another condition to this like so: `if (!$(e.target).is('a') && !$(e.target).is('input')) { ...`
Comment: I have got this working but when I click a sub menu link and it opens a modal window it also closes the submenu.

Any ideas?
Answer: another alternative, you can add code below :

another example : dtc-eng
Answer: Here is my take on this:
$(document).on('click', function(event){
  var $clickedOn = $(event.target),
      $collapsableItems = $('.collapse'),
      isToggleButton = ($clickedOn.closest('.navbar-toggle').length == 1),
      isLink = ($clickedOn.closest('a').length == 1),
      isOutsideNavbar = ($clickedOn.parents('.navbar').length == 0);

  if( (!isToggleButton && isLink) || isOutsideNavbar ) {
    $collapsableItems.each(function(){
      $(this).collapse('hide');
    });
  }
});

This solution handles:

single page website/applications (and will work on multi-pages too).
clicks on:

.navbar-toggle elements (could be <buttons> or , and it handles clicks on potential inner elements like  or  or whatever).
on simple  elements (again, it handles clicks on inner elements).
just outside some particular parent (ie. .navbar).

multiple collapsable (.collapse) elements that might be open (indistinct to where they are placed in the DOM).

Not enough for you? No problem. You can customize most of the selectors passed to jQuery (document, .collapse, .navbar, etc) to suit your needs or even add more conditions.


Retorno de consulta gerar Array

Question: Tenho uma consulta em MySQL.
foreach($resultado as $row)
{
$lat = $row['lat'];
$lon = $row['lon'];
$horario = $row['horario'];
}

Preciso que o resultado monte um array semelhante à este abaixo.
$markers = array(
array("latitude" => $lat, "longitude" => $lon, "conteudo" => $horario),
array("latitude" => $lat, "longitude" => $lon, "conteudo" => 'aaaaa'),
array("latitude" => -22.688211, "longitude" => -47.311065, "conteudo" =>
$horario),
);

Answer: É necessário criar uma array antes do foreach e depois ir criando um array multidimensional.
<?php

$resultado = [
["lat" => 0.0,"lon" => 0.0,"horario" => "00:00",],
["lat" => 0.0,"lon" => 0.0,"horario" => "06:00",],
["lat" => 0.0,"lon" => 0.0,"horario" => "12:00",],
["lat" => 0.0,"lon" => 0.0,"horario" => "18:00",],
["lat" => 0.0,"lon" => 0.0,"horario" => "24:00",]];

$result = [];

foreach($resultado as $row)
{
    $result[] = [
        "latitude" => $row["lat"],
        "longitude" => $row["lon"],
        "conteudo" => $row["horario"]
    ];
}

var_export( $result );

Demonstração
Comment: Obrigado, perfeito!!

Retorno de consulta gerar Array


Why are the two events independent of each other in this case?

Question: For the following problem, the two events are said to be independent of each other.

Intuitively, I would think that the outcome of 10 depends on getting 5 on both rolls, which gives a YES answer.  Can someone explain this to me?
Comment: As you say, knowing your sum is 10 clearly changes the probability of getting at least one 5, which says the events are DEPENDENT, i.e. a NO answer to the question.
Comment: Use the mathematical definition of independence.
Comment: Thank you!  Figured out my error.
Answer: Letting $A$ be the sum is $10$ (as in OP's statement), and letting $B$ be the event of at least one $5$, then:
$P(A)=\frac{5}{25}$
$P(B)=\frac{9}{25}$
and $P(A\cap B)=P(A)=\frac{1}{25}$.
Since $P(A\cap B)\ne P(A)\cdot P(B)$, the events are not independent.
One could also reason that event $A$ is a subset of event $B$.  So $P(B|A)=1\ne P(B)$
Answer: You simply mixed up the linguistics of the question, by ignoring a negation. Inititally you say

For the following problem, the two events are said to be independent
  of each other.

That is not what is indicated in the picture. The question asks if the events are $\color{red}{\rm in}\rm dependent$, and "No" is presented as correct. That's the same as saying they are dependent.
Which is what your intuition told you and which paw88789 proved in their answer.
Your inituition and the answer (from an online test, I presume) agree. They are just worded differently ("dependent" vs. "not independent").
Comment: Thank you!  I was absent-minded.


PersistGate causes the app to stop rendering

Question: I am in the process of configuring a React Native app with Redux store and PersistGate. The Redux store is configured and working as expected, but the PersistGate is causing the app to stop rendering even the first screen. Without PersistGate the app renders fine.
Here is the App.js code:
    import React, {Component} from 'react';
    import { Provider } from 'react-redux';
    import { createStore, applyMiddleware } from 'redux';
    import thunk from 'redux-thunk';
    import { persistStore, autoRehydrate } from 'redux-persist';
    import { PersistGate } from 'redux-persist/integration/react';
    import AppNavigator from './AppNavigator';
    import SplashScreen from 'react-native-splash-screen';
    import allReducers from './store/reducers/index';

    const store = createStore(
      allReducers,
      applyMiddleware(thunk),
      //compose(applyMiddleware(thunk), autoRehydrate()),
    );

    // This line makes store persistent.
    const persistor = persistStore(store);

    type Props = {};
    export default class App extends Component<Props> {
      componentDidMount() {
        if (SplashScreen) {
          SplashScreen.hide();
        }
      }
      render() {
        return (
          <Provider store={ store }>
            <PersistGate persistor={persistor}>
                <AppNavigator />
            </PersistGate>
          </Provider>
        );
      }
    }

The Reducer index file:
    import {combineReducers} from 'redux';
    import userReducer from './UserReducer';
    const allReducers= combineReducers({
      user: userReducer,
    });
    export default allReducers;

If I remove the <PersistGate persistor={persistor}> tag from App.js file, the app works fine. But when I use the PersistGate, I just see a white screen without any crash.
What am I missing which causes this weird output?
Answer: You also need to call the persistReducer function:
const persistConfig = {
  key: 'root',
  storage,
}

const persistedReducer = persistReducer(persistConfig, rootReducer)
let store = createStore(persistedReducer)
let persistor = persistStore(store)

More info in their doc: https://github.com/rt2zz/redux-persist
Comment: That worked, but the store still loses the values after reload
Comment: Maybe check the persistConfig storage options, I never did it in React Native only in React


Add date field to drupal entity registration

Question: I created an event with a fieldset of dates. You're able to register to this event, but I would like to add an extra field with one of the dates of the event.
How can this be done (with the entity registrations module)?
Answer: Goto Strcuture->Registrations->YourRegistrationType and add a new field of type date.
You can use Field Validation Module to make sure that the entered field is between the selected date range of the content type on which you have the registrations enabled.
Note : You could also use the tokens module to make sure that this datefiled in registration type has default value of the starting date of the date field in parent content type.


Question about Functional analysis and coresponding f

Question: Hi guys I have been looking at the theorem.
Let x be in an normed vector space X. Then there is a bounded linear functional f on X such that $f(x)=||x||||f||$
such that the norm of f is 1.
I was thinking about the converse. For every f there exists and x with $||x||=1.$  such that f(x)=||x||
First is this true?
I think it is not because f on C[0,1] assigns each x from the space C[0,1] the value x(0) of x at 0. It has the norm 1 on the C so we can use the Hahn Banach to extend it to linear functional to $L^{\infty}[0,1]$, but now there is no element y in L^1 such that $F(x)= \int_0 ^1 xy dt$ for all x in C[0,1]
Comment: Try simple cases first. Take $f(x) = {1 \over 2} x$. Then $|f(x)| = {1 \over 2}$ for all $|x|=1$.
Comment: If I am following correctly this shows that $f(x)=||x|| $ is $f(x)=1$ which is contradiction to us defining f to be $f(x)=1/2x$ The problem I am having is hod do we know no such x exists. PS Thanks for the comment
Answer: By definition, if $\|f\| <1$ then there can be no unit length $x$ such that $|f(x)| = 1$.
Even if $\|f\| = 1$, it is possible that $|f(x)| < \|f\|$ for all $\|x\| = 1$.
An example on $C[0,1]$ is $\phi(f) = \int_0^{1 \over 2} f(t) dt - \int_{1 \over 2}^1 f(t) dt$, we have $\|\phi\| = 1$, but we have
$|\phi(f)| < 1$ for all $\|f\| = 1$.


Drupal 8 multi fields in one fields

Question: can Someone explain how can i make one field in Drupal 8 that can contain multiple fields in it... I am not allowed to use Paragraph module. I want to make it full programmatically, By the way i know how to make simple field in Drupal 8 but don't know how to set schema or form form dynamic field that can have multiple fields in it.
 For Example when we want to add some field in user or in node, we go to ~/fields/add-field and then select the field type, after in the field setting i want to have one form element that says add filed and the type of the field. and after saving setting, i will generate the field widget and formater depending on the field type selection that i made before.
Is there a solution for this problem (only programmatically)?
Comment: You're best off just using Paragraphs or Field Collections where the problem is already solved.
Comment: Thank you @kevin but i can't use this modules... only programmatically
Comment: If you just need a compound field Paragraphs and Field Collection (especially) are probably unnecessary overhead. Have a look at how the core text fields work, they have multiple columns and multiple form elements. For example: https://api.drupal.org/api/drupal/core%21modules%21text%21src%21Plugin%21Field%21FieldType%21TextWithSummaryItem.php/function/TextWithSummaryItem%3A%3Aschema/8.0.x
Comment: thanks Clive but that way it has to be predefined, i want something more dynamic
Comment: What do you mean by "dynamic" exactly? The schema has to be predefined, it's responsible for which columns get added to the table that stores the data
Comment: i mean that i want to use the same field in multiple content types but with completely different settings, for example in one content type the field will contain a date and a text and on another an entity reference field and a float
Comment: that is not possible on a field level. That's exactly what paragraphs does and how it does what it does, by having separate multiple paragraph types with different fields and the field itself is just a reference
Answer: If you prefer another approach, a little more clean and following the Drupal structure, you can use Inline Entity Form to do that.
I don't like Paragraphs and Field Collection for just one reason. They don't follow the way that Drupal storages data in DB. If you open your database and search for the tables that this modules create, you will be able to see some strange patterns.
https://www.drupal.org/project/inline_entity_form
Comment: "you will be able to see some strange patterns." No idea what makes you think that. There are no strange patterns with paragraphs. IEF and paragraphs is exactly the same, just a different widget. Both use entity reference (entity reference revisions in case of paragraphs because that is the only way that embedded entities with  revisions work) and separate entities to store the data. Paragraphs provides its own type that is optimized for embedded and also works well with e.g. previews, with IEF you need to use an existing entity type.
Comment: That doesn't mean that you can't use IEF, I just disagree with the argumentation. Try both, use what makes more sense for your use case. IEF is more optimized towards re-using existing entities and not too specifically optimized for content-building like the paragraphs widget is, especially with the improvements we're working on in the experimental widget with drag and drop, duplicating, summaries and so on.
Comment: "Paragraphs provides its own type that is optimized for embedded and also works well with e.g. previews, with IEF you need to use an existing entity type.". That is exactly the problem for me. I've been faced some troubles with that custom type, especial with some relationships in views. And I agree too, that work with IEF is a little more difficult, but prevents this kind of problem.
Answer: Content Entity Builder module: https://www.drupal.org/project/content_entity_builder
Allow you add multiple base field to entity by config. it store all base fields in one table.
If you don't like the way : one field 2 tables. You can have a try with this module.

Drupal 8 multi fields in one fields


Show that the set of points that are nearer $a$ than $b$ with respect to $\lVert \cdot \rVert_2$ is convex

Question: I am trying to show the above statement:

Show that the set of points that are nearer $a$ than $b$ in the sense
  of Euclidean $\lVert\cdot\rVert_2$ are convex.

My attempt
This follows from the Proposition:
The convex hull of $M \subset \mathbf R^2$ is convex, indeed the smallest convex set that contains $M$. Moreover, co($M$) is the set of all convex combinations of points of $M$,
\begin{equation}
\text{co}(M) := \{x \in \mathbf R^2 | \exists x_1, x_2, ... , x_N \in M \text{ such that } x = \sum\limits_{i=1}^{N} \lambda_i x_i,\\
\text{ for some } \lambda_1, \lambda_2, ..., \lambda_N, \text{ where } \lambda_1 \geq 0 \forall i, \sum\limits_{i=1}^{N} \lambda_i = 1 \}.
\end{equation}
The main idea is based on the idea about the corollary 1.14 in
http://www.math.udel.edu/~angell/ch1.pdf:

The convex hull of a compact set in $\mathbf R^n$ is compact.

Assume $C \subset \mathbf R^n$ be compact.
See the original source for the skipped steps.
The sequence $\{A\}_{k=1}^{\infty}$ has a subsequence $\{AA\}_{j=1}^{\infty}$ which converges to a point of co $(C)$ which shows that this latter set is compact.
If $C$ is closed and convex, it has a smallest/nearest element in a certain sense.
It is a simple result for analysis that involves the fact that the function $x \to \lVert x\rVert$ is a continuous map from $\mathbf R^n \to \mathbf R$ and the fact that Cauchy sequences in $\mathbf R^n$ converges.
We need also the theorem:
Every closed convex subset of $\mathbf R^n$ has a unique element of minimum norm.
See the proof in the source above.
There must be also a simpler way to prove the statement.
Is there any sense in my attempt?
How can you show the statement?
Answer: The set is a hyperplane. I think you are over-thinking the problem.
The set in question is
$$
\left||a-x\right|| \lt \left ||b-x\right|| \Leftrightarrow\left||a-x\right||^2 \lt \left ||b-x\right||^2$$
Writing out the norms we get
$$
(a\cdot a) - 2 (a \cdot x) + (x \cdot x) < (b\cdot b) - 2 (b \cdot x) + (x \cdot x)$$
Cancelling $(x \cdot x)$ and rearranging
$$
 (c \cdot x) < (b\cdot b) - (a\cdot a) ~\text{ where $c = 2(b-a)$}$$
Let us write the above inequality as
$$(c \cdot x) < d$$
This is clearly a convex set: If $x$ and $y$ are in the set then
$$
(c \cdot (\lambda x + (1-\lambda) y ) = \lambda (c \cdot x) + (1-\lambda) (c \cdot y)<
\lambda d + (1-\lambda) d = d $$
Comment: Not a hyperplane, but a halfspace.
Answer: Let $\phi(x) = \|x-a\|^2-\|x-b\|^2= \|a\|^2-\|b\|^2+2 \langle b-a, x \rangle$. $\phi$ is affine (that is, linear plus a constant) hence convex, and so $\{ x | \phi(x) < 0\}$ is convex.
Note: Since it also follows from the above that $\{ x | \phi(x) > 0\}$ is convex, we see that the sets are open half-spaces separated by the hyperplane $\{ x | \phi(x) = 0\}$.
Comment: It means the set of $x$ that satisfy the inequality $\phi(x) <0$, where $\phi$ is the function defined on the first line.
Comment: What do you mean by this $\{x|\Phi(x) < 0\}$?


What is the expamapi.dll in windows folder?

Question: I'm getting a virus message related to expamapi.dll in c:\Windows (windows xp).  When I used ProcessExplorer, this dll is related to a bunch of processes, which isn't making sense. Some of the processes listed are:

explorer.exe
svchost.exe
MOM.exe
CTDVDDET.exe
CTSysVol.exe
DLLML.exe
CTHELPER.EXE
Dropbox.exe

So, does this make sense? Or do I need to do some deep cleaning?
Comment: are you 100% certain thats the file name ? the only google result for expamapi.dll is this page, which is really Odd...
Comment: Agreed - I was just about to post that exact question for Greg.
Comment: Yeah, I'm sure. And this is what is causing me confusion as well...what the hell is this thing? That file is in the Windows folder and apparently associated with all of those processes, according to ProcessExplorer.
Answer: I posted a related question on the BitDefender forum and they confirmed that this is a malicious file. A deep scan removed it.
http://forum.bitdefender.com/index.php?showtopic=21462&st=0&gopid=93849&#entry93849


finding text in a string and replacing whole string with another string + R

Question: I have this vector/array in R programming that I would like to find "WIND" (upercase or lower case) and replace the whole text with "WIND"
> b
 [1] "TORNADO"                   "TSTM WIND"                 "HAIL"
 [4] "FREEZING RAIN"             "SNOW"                      "ICE STORM/FLASH FLOOD"
 [7] "SNOW/ICE"                  "WINDTER STORM"             "HURRICANE OPAL/HIGH WINDS"
[10] "THUNDERSTORM WINDS"

Fo r  example "TSTM WIND"  would be come "WIND". So would "WINDTER STORM" and "HURRICANE OPAL/HIGH WINDS"...etc
I have tried this but no joy
> gsub("*WIND*","WIND",b,ignore.case=T)
 [1] "TORNADO"                   "TSTM WIND"                 "HAIL"
 [4] "FREEZING RAIN"             "SNOW"                      "ICE STORM/FLASH FLOOD"
 [7] "SNOW/ICE"                  "WINDTER STORM"             "HURRICANE OPAL/HIGH WINDS"
[10] "THUNDERSTORM WINDS"
>

this show the ones that meet my criteria
> grepl("*WIND*",b,ignore.case=T)
 [1] FALSE  TRUE FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE  TRUE

Answer: Since you're replacing all matches with the same string, you can use [<-
b[grepl("WIND", b)] <- "WIND"

You can also use sub
sub(".*(WIND).*", "\\1", b)

Both resulting in
 [1] "TORNADO"               "WIND"                  "HAIL"
 [4] "FREEZING RAIN"         "SNOW"                  "ICE STORM/FLASH FLOOD"
 [7] "SNOW/ICE"              "WIND"                  "WIND"
[10] "WIND"

Comment: thaks and perfect, what are the `dots` in `".*WIND.*"`
Comment: `.*` in regex basically says, "match everything".  So this matches everything up to and including `WIND` and then everything after it.  I believe the `.` by itself means "any character"
Comment: Here's a good reference http://en.wikibooks.org/wiki/R_Programming/Text_Processing
Comment: How would I insert a variable in place of "WIND", say looping through an array /Is it something like `list<-gsub(".*"+i+".*",i,list,ignore.case=T)`
Comment: to answer my own Q i usesd `pattern<-paste(".*",i,".*",sep="")  list<-gsub(pattern,i,list,ignore.case=T)`
Answer: The simplest solution is in the stringr package.
require(stringr)
str_replace_all(b, ignore.case(".*WIND.*"), "WIND")

This should do what you're looking for. Cases like these are why stringr was made.


Newton Raphson method to find intersection points

Question: I'm supposed to use N-R method to find intersection point near $(4,-4)$ of $x^2+y^2=16$ and $e^{1/3x} + (1/5)y =1 .$
So, I equated these two functions, and got $f(x) = 5- (5*\exp(x/3)) + (16- x^2)^{1/2}$
and $f'(x)= (-5/3)*\exp(x/3) - (16-x^2)^{-1/2}$.
As stated in my assignment, I'm supposed to start with point $(4,-4)$ , but as you can see...this would give me $-\infty$ for $f'(x).$
So I can't even go on to the next iteration.
What am I doing wrong?
Comment: I would square the exponential and equate $y^2$, so that your derivative doesn't get that square root in the denominator.
Comment: I suspect you were intended to locate the point of intersection by finding a "root" of a system of two equations in two unknowns.   Newton-Raphson is the name we usually call Newton's method for a multivariable system of equations.  That said, it is possible to eliminate one variable and proceed by the single variable Newton's method.  You may have to pick a different starting point to avoid a singularity.  What kind of explanation would you prefer?
Answer: Way 1: use 2D Newton's method on the original system. Based on how the problem was formulated, this was probably the intent.
Way 2: Work with $u+v=16,e^{\sqrt{u}/3}-\sqrt{v}/5=1$, which is effectively working with $(x^2,y^2)$ as your variables under the assumption $x>0,y<0$. Then you can eliminate one variable without triggering any singularity.
Way 3: Do what you said, but start somewhere else and hope you get the right intersection. For instance you could start at $(\sqrt{8},-\sqrt{8})$ which is on the circle (and not on the axes) and will thus remove the singularity. (This might have actually been the point where they wanted you to start, i.e. $(4,-4)$ might have just been a mistake.)
Answer: As said in answers, they (more than likely) wanted you to use Newton-Raphson method with two varaibles.
However, you idea of eliminating $y$ and just solve for $x$ was good and works.
You have two equations
$$e^{x/3}+\frac{y}{5}-1=0 \tag 1$$ $$x^2+y^2-16=0 \tag 2$$
Frm $(1)$, $y=5-5 e^{x/3}$. Plug it in $(2)$ to get
$$x^2-50 e^{x/3}+25 e^{2 x/3}+9=0$$ So, you look for the zero of
$$f(x)=x^2-50 e^{x/3}+25 e^{2 x/3}+9$$
$$f'(x)=2 x-\frac{50 }{3}e^{x/3}+\frac{50}{3} e^{2 x/3}$$ Now, Newton iterates using $x_0=4$
$$\left(
\begin{array}{cc}
 n & x_n \\
 0 & 4.000000000 \\
 1 & 2.943256168 \\
 2 & 2.166300869 \\
 3 & 1.755176003 \\
 4 & 1.649488097 \\
 5 & 1.643297711 \\
 6 & 1.643277453
\end{array}
\right)$$ which is the solution for ten significant figures.


join and orwhere ends to AND

Question: I have the follwing code:
$_duplicates = $this->find()
    ->innerJoin(
        ['c' => 'contacts'],    //alias
        [
            'Contacts.contactname != ' => '',
            'Contacts.id < c.id',
            'c.id > ' => 0
        ]
        )
    ->select(['Contacts.id', 'Contacts.contactname', 'Contacts.legalname',
              'c.id', 'c.contactname', 'c.legalname'])
    ->orWhere([
        'LEVENSHTEIN(Contacts.contactname, c.contactname) <= ' => $distance,
        'LEVENSHTEIN(Contacts.contactname, c.legalname) <= ' => $distance,
        'LEVENSHTEIN(Contacts.legalname, c.contactname) <= ' => $distance,
        'LEVENSHTEIN(Contacts.legalname, c.legalname) <= ' => $distance
        ]);
debug($_duplicates);

The debug there gives this output:
SELECT Contacts.id AS `Contacts__id`, Contacts.contactname AS `Contacts__contactname`,
  Contacts.legalname AS `Contacts__legalname`, c.id AS `c__id`,
  c.contactname AS `c__contactname`, c.legalname AS `c__legalname`
FROM contacts Contacts
INNER JOIN contacts c
ON (Contacts.contactname != :c0 AND Contacts.id < c.id AND c.id > :c1)
WHERE (
   Contacts.active = :c2
   AND (
      LEVENSHTEIN(Contacts.contactname, c.contactname) <= :c3
      AND LEVENSHTEIN(Contacts.contactname, c.legalname) <= :c4
      AND LEVENSHTEIN(Contacts.legalname, c.contactname) <= :c5
      AND LEVENSHTEIN(Contacts.legalname, c.legalname) <= :c6
    )
  )

Any ide why I get AND-s at LEVENSHTEIN calls and not OR? orWhere supposed to create OR relations there, right?
Answer: Because that's not how orWhere() is supposed to work, the OR condition is being used for combining with the previous conditions that have been defined via where/andWhere/orWhere(), ie
->where(['a' => 'b'])
->orWhere(['c' => 'd', 'e' => 'f'])

results in
(c = d AND e = f) OR a = b

If you need to combine all your conditions via OR, then you could either use multiple orWhere() calls
->orWhere(['a' => 'b'])
->orWhere(['c' => 'd'])
->orWhere(['e' => 'f'])

the OR key
->where([
    'OR' => [
        'a' => 'b'
        'c' => 'd'
        'e' => 'f'
    ]
])

or expressions
->where(function (\Cake\Database\Expression\QueryExpression $exp) {
    return
        $exp->or_([
            'a' => 'b'
            'c' => 'd'
            'e' => 'f'
        ]);
})

See also Cookbook > Database Access & ORM > Query Builder > Advanced Conditions

join and orwhere ends to AND


How do I display a taxonomy term if another term is active for a node?

Question: I have a content type that has taxonomy terms for Category, like Blog, Publication, and Project. Depending on which term is selected, the content is displayed under blogs, publications or projects. If the category selected is Project, then the user has to select the focus area from another vocabulary (not a child vocabulary) - Focus Area 1, Focus Area 2... through to Focus Area 10.
Currently, my pathauto pattern displays the Category/Node_Title - [node:field_post_category:entity]/[node:title]
My objective is that I also want to display the Focus Area term in the node url, but ONLY if the category chosen is 'Project'. In that case, I want the url to be project/focus_area_n/node_title. So the focus area is displayed in the node url only if the category is project. Is there a Pathauto pattern, or any other method that I can use to accomplish this?
I need to do this so that I can control the display of a few blocks in the sidebar that will show up depending on what the URL is.
Thanks in advance...
Comment: You'll need to code a custom token for that
Answer: It was actually quite easy! No custom-coding required. I just added the token for the other vocabulary to the URL alias pattern, and it now appears, when it's present. When not present, the regular URL is formed.
So now the new pattern is [node:field_post_category:entity]/[field_focus_area:entity]/[node:title]
Drupal is great!


Setting Up How to Take The Limit of a Sequence?

Question: I am taking a Calculus II course and we have just started Series and Sequences. Here is the problem:
A sequence {an} is defined as:
$$a_1 = 2,  \,\,
a_{n+1} = \frac{a_n}{2} + \frac{1}{a_n}
$$
Assuming that $\{a_n\}$ is convergent find its limit.
How do I make an expression to then take the limit given this? Thank you in advance!
Comment: I have calculated it and I see the answers underneath. My problem was the condition and where it fit into everything. Thank you!
Comment: Could you say what you know about finding limits of any sequence? What techniques do you have?
Comment: Bare minimum. I understand the concepts of limits.
We have the Continuity and Convergence Theorem
Monotonic Sequence Theorem
Possibly a few others but the examples have a lot of variables that I think are causing me to over complicate it
Comment: Have you experimented to see what the limit might be? Knowing the value of the limit can be helpful in proving convergence.
Answer: Let $L$ be the limit of $a_n$, as $n\to +\infty$ (which you know it exists by assumption). Then, the limit of $a_{n+1}$ would be $L$, too (why?). Thereofre, taking the limit of both sides of
$a_{n+1} = \dfrac{a_n}{2}+\dfrac{1}{a_n}$
yields (why?)
$L = \dfrac{L}{2}+\dfrac{1}{L}$
At this point you can just solve the equation and find $L$. The initial condition is given so you can rule out one of the two possible values you get out of the equation.
Answer: Suppose $a$ is the limit of $\{a_n\}$. Then it must be the case that
$$
a = \frac{a}{2} + \frac{1}{a}
$$
So $a^2 = 2 \Rightarrow a = \pm \sqrt{2}$. Notice that the initial condition is positive and if $a_n$ is positive then $a_{n+1}$ is as well. Thus
$$
\lim_{n\to\infty} a_n = \sqrt{2}
$$
Comment: Yes this makes sense! Thank you!


Is Safe JWT Store in Req. Session?

Question: i have a question about MERN Stack (Mysql,Express,React,Node). I confused about storing Jwt token (in Cookies,Localstorage or as session in request).
 What iam asking is Is Safe Storing JWT On Request Session ?
 Can someone explain how to store token in Single Page App ?
 Thanks Anyway ...
Comment: i would choose cookie > localstorage. the reason is that you can turn on `httpOnly` on the cookie witch simply means that javascript on the client side cannot read the cookie only the server. you can also set an expire date on the cookie witch you cant on localstorage, you need to manually delete it. if you are using things like Nuxt.js or Next.js that has server side rendering, you will have a scenario where you need to access the token from the server side, and therefore you can read it out of the request headers.
Comment: i personaly use nuxt.js so i dont know exactly the ecosystem of next.js but it should be similar. i do it like this: when i refresh the page, and i am on the server side, i grab the token out of the cookie and store it into the vuex storage (in your case redux i guess) because its httponly and i cannot read it from the client side. saving your token in a store like vuex is ok. a token should not contain sensitive data it can be decoded easely. in my app i just store the mongoDB objectId of the user. thats enough information for my backend to know witch operation the user is allowed to do
Comment: a token has a expire date. that means till that date the token is valid. if somebody steals your token and you log off you usually erase that token from your cookie. but the problem is that the attacker has your token and that token is still valid. people decide to create a blacklist. its just a simple storage on the server. if you log out of your app, you store that token to the blacklist. now if the attacker tries to do something with your token, you need to check first if that token is in that blacklist. if it is you reject the request
Comment: and also, if somebody goes to your computer, opens your devtools and checks the cookies its the fault of the user and not the dev. usually users have a computer password.
Comment: httpOnly simply means javascript (the client side) cannot read that cookie. so its not easelie stealable with XSS attacks
Comment: Thanks for answer, i already use next js too. But i have a problem on backBehaviour (Browser). When that action is triggered, ReactComp has not rendered on the server side (Ex, So when is already logged In, When i press back. Back to login screen (Logic in server side has not triggered).
I Have an idea for that issues, i can store logic in frontend (But I have a problem with storing the sensitive data).
Cookies HttpOnly is Recommended for store the token ?
Comment: @Ifaruki when it comes to SSR the token would be refresh token right? Because we only get the processed html to the client side.
Comment: @Ifaruki Are you for each request need token jwt ? you mean store that token in cookies but httpOnly right ? And you need some information stored in redux. (Are store is persisted or only each request is storing ) ?
Comment: @Ifaruki Oh i see, if cookies already httpOnly flag attacked can't be steals the cookie right ?
Comment: Ouh, ok.
Appreciated your answer, Thankyou verymuch. That information is very usefull for me
Answer: When we do a successful login we get an access token. In this case, it is a JWT token. When we get this we need to keep it somewhere to use it for the future use of the user. We normally store that in LocalStorage. You can find more info about LocalStorage here. We also can use SessioStorage, Cookies as well. But Cookies only can contain 4KB of data and SessionStorage will go away when the browser is closed. That is the reason for me to go with LocalStorage. But you can choose it depending on your application requirement.
When sending a request with a token, I use the Authorization header.
Comment: People can take it and read it easily. That's why we need to make sure we aren't storing any sensitive data in it. Only data that we need to bootstrap the user flow. May be user name, user id, user role kind of things. And that token is short lived. About 15 mins. In that way we are less vulnerable to the outside. That's when the refresh token comes into play. That can be stored in cookie with http only and secured flags. That will also contain expiration date. But a larger one around 30 days. We need to clear both when logout.
Comment: Thanks for the answer, is safe to store token in localstorage ? When that storage can be access to other people.Best way store in cookies httpOnly (Maybe storing only jwt will be less than 4Kb) ?
Comment: Ouh ok, so the only one choices is storing Jwt in cookies But must be turn (httpOnly and Secure flag. Https Access) ya ? Thankyou verymuch for the answer bro
Comment: for refresh token, yes go for cookie. for access token, it is fine to go with localstorage since it is short-lived.
Answer: It's safe to store JWT cookie at the client and even more in this day and age it necessary for scalability.
What should you use?

Session - This is the "old" way of doing things and no in use anymore. The session saves a state on the API server and that is a bad thing for scaling.
Localstorage - A good choice for mobile and web applications. The idea here is that you as the client developer are responsible for keeping track of JWT (save it on login, remove it on logout)
JWT-Cookie - is the best for ONLY web application. It's the same idea of Localstorage but now the server is responsible for setting and removing the JWT from the client using the Set-Cookie header.

Note: You can implement both Localstorage and JWT-Cookie side by side.
Comment: `Set-Cookie` works regardless of `httpOnly`. Having said that `httpOnly` is the more secure because  JS won't be able to access it and it the correct way to set a JWT-Cookie
Comment: Thankyou for the answer, `Set-Cookie` in the server that you mean is httpOnly flag ?
So is the best choices is store Jwt in cookies but httpOnly flag MUST be turned on ya ?
Comment: Ouh ok, so the best way is Cookies httpOnly. Thankyou anyway
Comment: @Daniel localstorage is the not the secured way, can you tell any other way?
Comment: @RohanDevaki try `JWT-Cookie`. Cookies are more secured
Comment: @daniel,  ok , i will try

Is Safe JWT Store in Req. Session?