text:
Q: Where can I read about elliptic operators on manifolds? In Voisin's beautiful book on Hodge theory she gives a proof that every cohomology class can be represented by a harmonic form by referring to the the following theorem on elliptic operators:
Let $P : E → F \ $  be an elliptic differential operator on a compact
manifold. Assume that $E$ and $F$ are of the same rank, and are equipped with
metrics. Then $\operatorname{ker} P \subset C^{\infty}(E)\ $ is finite-dimensional, $P( C^{\infty}(E)) \subset C^{\infty}(F) \ $ is closed and of finite codimension, and we have a decomposition as an orthogonal direct sum (for the $L^2$ metric) $$ C^{\infty}(E) = \operatorname{ker}  P \oplus P^{\ast}( C^{\infty}(F)), $$
which she then applies to the Laplace operator.
Unfortunately, her reference for this (Demailly - Théorie de Hodge L2 et Théor`emes d'annulation) is in French, which I don't understand.
I am primarily hoping for a reference on elliptic operators which proves this theorem; however, at the same time I also feel like I should know more about elliptic operators in general, and 'how they can be used in geometry' (can they, actually? I'm thinking about Atiyah-Singer here, which I don't understand at all, so I'm not sure.), so if you can give me a reference about that, it would be much appreciated, too.

A: One more suggestion: Wells Differential Geometry on Complex Manifolds has a complete proof, and focuses on the sort of examples which will interest someone who is reading Voisin's book.

A: The book   Topology and Analysis: Atiyah-Singer Index Formula and Gauge-theoretic Physics by Booss and Bleecker (Springer , Universitxt) seems to be exactly what you are loooking for.
It is an introduction to the Atiyah-Singer index formula, with all prerequisites carefully developed :Fredholm operators, (pseudo-)differential operators on manifolds, Sobolev spaces, vector bundles and much more.
The style is quite friendly, with many examples,remarks, exercises,  interspersed throughout the text.
To sum up, I find the blend of analysis, manifold theory  and topology in this book quite remarkable and unusual.
I am only really familiar with the German original version, written by Booss alone. The English translation I refer to is enriched by about 100 pages due to Bleecker and devoted to applications in mathematical physics: they seem very interesting but I haven't looked at them seriously .

A: Unfortunately, I am not an exert in this area, but I have collected for my purposes some links about that, so I would like to share.
First of all, I would take a look to "Lectures on pseudodifferential operators" of Richard Melrose, Chapter 6 is dedicated to ellipticity, where you can try to find some proofs that you are after.
Next, I would refer to the classical source of this subject, the book of R.Melrose "The Atiyah-Patodi-Singer Index Theorem", a copy is generously provided by the author here.
Another very interesting online resource is Michael E. Taylor's "Pseudodifferential operators. Four Lectures at MSRI, September 2008"
And if you want a quick yet brilliant introduction to the topic don't miss out Rafe Mazzeo's presentation "The Atiyah–Singer Index Theorem: What it is and why you should care"
Some additional googling revealed a plenitude of various texts on the topic. For instance, this one: Nigel Higson and John Roe, Lectures on Operator K-Theory and the Atiyah-Singer Index Theorem
"Notes on the Atiyah-Singer Index Theorem" by Liviu I. Nicolaescu also deserves a very good mention! (just google it!)
I hope that this will be more than enough to satisfy your curiosity.
EDIT. And I forgot to mention Victor Guillemin's homepage where you can find notes on elliptic operators!


text:
Q: Finding nearest point in an efficient way I've got a point in 2d plane for example (x0,y0) and a set of n points (x1,y1)...(xn,yn) and I want to find nearest point to (x0,y0) in a way better than  trying all points. Any solutions?
I should also say that my points are sorted in this way:
bool less(point a,point b){
  if(a.x!=b.x)
     return a.x<b.x;
  else
     return a.y<b.y;
 }

A: For efficient nearest neighbour search you need to use a spatial partitioning scheme, for example a kd-tree.

A: If you aren't using any sort of tree data structure to help limit the range of values you have to query, you are going to have to check each point in your range of potential "neighbors".  One way to limit the comparisons would be to check the squared distance from your given point for the smallest value:
Point myPoint = {x, y};
std::vector<Point> otherPoints; // given list of points to check

struct PointDistance
{
    Point pt;
    float dist;
};

std::vector<PointDistance> squaredDistances(otherPoints.size()); // will be filled in with squared distances

float CalculateDistance(const Point& pt1, const Point& pt2)
{
    float deltaX = pt1.x - pt2.x;
    float deltaY = pt1.y - pt2.y;
    return (deltaX * deltaX) + (deltaY * deltaY);
}

// should be changed to use an algorithm, but for clarity done as a loop here
for (int i = 0; i < otherPoints.size(); ++i)
{
    PointDistance pd;
    pd.pt = otherPoints[i];
    pd.dist = CalculateDistance(myPoint, pd.pt);
    squaredDistances.push_back(pd);
}

bool DistanceLess(const PointDistance& lhs, const PointDistance& rhs)
{
    return lhs.dist < rhs.dist;
}

std::sort(squaredDistances.begin(), squaredDistances.end(), DistanceLess);

// squaredDistances[0].pt will be your closest point.

A: Voronoi diagram is designed specifically for finding nearest point very fast. Although it's quite a pain to implement, you might find some existing library/implementation.
There's also an option to of repeatedly dividing plane in squares, thus building some kind of tree where each non-leaf node has 4 children (top-right square, bottom-right square, etc.). Then, of four squares you find the one your point is in and proceed with it recursively. Often this yields point close enough, so you may eliminate the need to check other squares.
But it's easy to create a 'counter-example' for this strategy which will result in linear time.
But there's not much you can do with your sorted array to speed up the process. You'll need a special data structure.
edit
Second structure is called Quadtree, thanks to VGE for providing the name.

A: Use a quad-tree for 2D
http://en.wikipedia.org/wiki/Quadtree

A: If you are creating the set of N points then instead of just pushing them into a set, you can hash and map them based on their linear distance from the point under consideration . So points with same linear distance will be in the same bucket. Then fetching the point(s) based on distance will be a constant time operation.

A: A particularly nice solution is ANN: A Library for Approximate Nearest Neighbor Searching. I've used it for point location in triangulations. You initialize a data structure with points, in my case I used the center points of my triangles. Then you can pass in another point and get back list of the approximate closest neighbour points. Even the number of points returned is selectable as a parameter. Anyway ANN was a great library for my purposes, I'd suggest you check it out.
Good luck!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using nested while loops to create a sum or powers list, python I recently posted about this before but I am still not getting it to work properly. Here is a better description of what I need:
If your bases list is [1, 2, 3] and your exponents list is [2, 4], then the list your will return has two elements, one for each exponent, and is this: [1^2 + 2^2 + 3^2, 1^4 + 2^4 + 3^4].  Your mission is to calculate these elements using nested while loops and store the results in a list so you can return it at the end.
def sum_of_powers(base_list, expo_list):

    end = []
    j = 0
    i = 0
    while j < len(expo_list):
        sub_accum = []
        while i < len(base_list):
            sub_accum.append(base_list[i]**expo_list[j])
            i += 1
            end.append(sub_accum)
        j += 1

    return end

>>>base_list = [1, 2, 3]
>>>>expo_list = [1, 2]
>>>>print(sum_of_powers(base_list, expo_list))
[[1,2,3],[1,2,3],[1,2,3]]

The desired outcome is:
    [6, 14]
which is (obviously)
[1^1 + 2^1 + 3^1, 1^2 + 2^2 + 3^2]]
I dont think "j" is being added to properly and I cant figure out how to add up the elements in "sub_accum". I just cant figure this one out! Any help is welcomed! Thanks guys!

A: Why don't try this one:
def sum_of_powers(base_list, expo_list):
    exp_sum = lambda lst, n: reduce(lambda x,y: x + y**n, lst)
    return [exp_sum(base_list, e) for e in expo_list]

base_list = [1, 2, 3]
expo_list = [1, 2]
print(sum_of_powers(base_list, expo_list))

It's more functional and simple, using:

*

*list comprehension

*map and reduce

A: append does not calculate the data when you put it in a list
thus you need to add the data instead of appending it
and you didn't re-initialize the value of i so it only runs through once
def sum_of_powers(base_list, expo_list):

        end = []
        sum = 0 #added sum
        j = 0
        i = 0
        k = 0 #added for loop in getting sum

        while j < len(expo_list):
            sum = 0 #re-initialize value to 0 for the next loop
            i = 0 #re-initialize value to 0 for the next loop
            k = 0 #re-initialize value to 0 for the next loop
            sub_accum = []

            while i < len(base_list):
                sub_accum.append(base_list[i]**expo_list[j])
                i += 1

            while k < len(sub_accum): #loop though temporary list to add its values
                sum = sum + sub_accum[k]
                k += 1

            end.append(sum) #end should be at level of 1st layer when all have been calculated and should only insert the sum of 'sub_accum'

            j += 1

        return end

please use for loops next time so you wont forget to re-initialize your inner values

A: Here you go. This does what you need with small modifications to your current code:
def sum_of_powers(base_list, expo_list):

    end = []
    endsum = []
    j = 0
    while j < len(expo_list):
        sub_accum = []
        i = 0
        while i < len(base_list):
            sub_accum.append(base_list[i]**expo_list[j])
            i += 1
        end.append(sub_accum)
        j += 1

    for i in range(len(end)):
        endsum.append(sum(end[i]))

    return endsum

base_list = [1, 2, 3]
expo_list = [1, 2]
print(sum_of_powers(base_list, expo_list))
[6, 14]

The main things were the placement of your i = 0 re-initialization, and your end.append.


text:
Q: How to find if a Wordpress Hook is valid I found an interesting blog post from 2015 with the following containing the "single-{$type}_template" hook:
add_filter( 'single-hats_template', function( $template ) [
    if ( ! $template ) {
        $template = dirname( __FILE__ ) . '/templates/default-hats-single.php';
    }

    return $template;
});

https://wpshout.com/hacking-the-wordpress-template-hierarchy/
That would be perfect for me as I am writing a plugin that only needs to override the template for a certain type of post.
However, I added a filter for this hook, added a breakpoint and got nothing. I couldn't find this hook in any documentation and I wonder if its since been removed?

*

*I searched the source code, but couldn't find it being called.

*I checked the global $wp_filter in the debugger and it wasn't listed.
is there a definitive way to check if a hook exists?
I am using Wordpress Version  5.6.1


text:
Q: apache server 2.4: is there a way to hook into thread init event? I'm developing an apache module on version 2.4 and using the power of MPM workers/events.
I want each thread to have it's own libcurl handle (the module is creating an http request using curl) so that no curl handle will be shared on more than one thread (as mentioned in libcurl docs this is bad).
I'm trying to hook into the thread initialisation process to define a handle on each thread, something like:
apr_status init_worker_thread(apr_pool_t *p, void *thread_local) {
   thread_local->curl_handle = curl_easy_init();
   ...

}
I could not find any documentation on this kind of hook, is that possible? If not, is there a work around? how can I reuse my curl handle for better performance (mainly connection persistence) through multi threading (calling curl_easy_cleanup on each request is not a good idea).
BTW: I'm aware of making this module only relevant for MPM module supported versions.


text:
Q: touchend event not firing on iphone I am trying to have a counter based on an image. the onclick event works fine in desktop browsers and ipad safari but not in iphone. so i am trying to add event listener for 'touchend'. it still doesn't fire in iphone. what is missing? thank you.
<!DOCTYPE html>

    <title>Counter</title>

         0

A: Use elmt.ontouchend=function(){};


text:
Q: Python 2.7.2 doesn't properly iterate through logger's handlers the following code is very simple, but for some reason, for-loop does not iterate through all handlers of the logger. however, for-loop does iterate through all handlers if we remove my_logger.removeHandler( handler ) in the else clause. any idea if I'm doing anything wrong?
import logging
import sys

stdf = logging.Formatter( "%(message)s" )
filef = logging.Formatter( "%(message)s" )
my_logger = logging.getLogger( "file std logger" )
stdh = logging.StreamHandler( sys.stdout )
stdh.setFormatter( stdf )
my_logger.addHandler( stdh )
fileh = logging.FileHandler( "run.log", mode = 'w', encoding = "utf-16-le", delay = True )
fileh.setLevel( logging.DEBUG )
fileh.setFormatter( filef )
my_logger.addHandler( fileh )

my_logger.info("wow1")
my_logger.info("test string1")
my_logger.info("wow2")
my_logger.info("test string2")
my_logger.info("wow3")
my_logger.info("test string3")

for handler in my_logger.handlers:
    print(handler)
    if handler.__class__.__name__ == "FileHandler":
        handler.flush()
        handler.close()
        my_logger.removeHandler( handler )
    else:
        handler.flush()
        my_logger.removeHandler( handler )

my_logger.handlers

A: This is a classic destructive iteration. What you are doing is:
>>> l= [0, 1, 2, 3, 4]
>>> for n in l:
...     l.remove(n)
...
>>> l
[1, 3]

In this example only every second element is removed. Why? Well the for...in syntax obscures what's actually happening, which is the same as in a traditional C-style for-index loop:
>>> l= [0, 1, 2, 3, 4]
>>> i= 0
>>> while i<len(l):
...     del l[i]
...     i+= 1
...
>>> l
[1, 3]

So first time round the loop i is 0. Item 0 gets removed, moving items 1–4 down one place to be the new items 0–3. Next time round the loop i is 1 so the current item 1, which is 2, is removed. The original 1 has been jumped and remains in the loop.
A simple workaround to avoid destructive iteration is to take a copy of the list and iterate the copy whilst changing the original:
for handler in list(my_logger.handlers):

Using filter or list comprehensions is typically a simpler route when you are trying to remove certain items from a list.


text:
Q: is $a \circ b \circ a=a$ when $[A,\circ]$ is a semi-group Let $[A,\circ]$ be a semi-group. Further $\forall a,b$ if $a \neq b$, then $a\circ b \neq b \circ a$. Now show that
$a\circ b\circ a=a$
My argument is as follows:
since in semi-group we have Associativity property,
So, we have $(a\circ b)\circ a=a \\ a\circ(b\circ a)=a$
So, seems like we have en identity element for this semi-group and that is $a\circ b=b\circ a$.
Hence, $a\circ b \circ a=a$
Am I correct in my argument?

A: Let $a \in A$ and let $b = a^2$. Then $ab = ba$ and hence $b = a$, that is, $a^2 = a$. Thus your semigroup is a band or, if you prefer, an idempotent semigroup. Now, consider $c = aba$. Then $ac = aaba = aba = c$ and $ca = abaa = aba = c$. Thus $ac = ca$, whence $a = c = aba$.


text:
Q: What happens when you initialize a const reference by conversion constructor? What happens when you initialize a const reference by conversion constructor? Is it any different from an ordinary assignment? Look at this code:
void func(const char* cstr) {
    std::string S1 = cstr;
    const std::string& S2 = cstr;
}

Is there any practical difference between S1 and S2? Why would you want to use the second expression?

A:
Is there any practical difference between S1 and S2?

In terms of performance, the answer is no. Both instructions invoke converting constructor and allocate memory, then copy the the char array in the internal dynamic memory of std::string instance.
In term of syntax, the answer is obviously the const-ness: in the successive block of the function the object handled by S2 cannot be modified.

A: *

*With std::string S1 = cstr;
S1 is move-constructed from a temporary. That move-construct should probably be elided, but should be accessible. As not const, S1 can be modified.

*With const std::string& S2 = cstr;
S2 is a const reference to a temporary string, with extended lifetime. As const, S2 cannot be modified.
For type without move/copy constructor as
struct S {
    S() = default;
    S(const S&) = delete;
    S& operator =(const S&) = delete;
};

You may use the second form, but not the first one:
 S s1 = S{}; // Invalid
 const S& s2 = S{}; // Valid
 S&& s3 = S{}; // Valid too.

A: You get a const reference to the S1 string, and the compiler enforces the const of the value. If you try to modify S2 it will not compile. For local variables it doesn't make much sense, except when you don't trust yourself to not modify S2, or when you are doing code refactorings moving things around and you want to be sure that S2 is never changed.
But if you pass a string as an argument to a function you can use a const reference to avoid a costly copy:
void f(const std::string& S2) { ... }

const in general won't help the compiler to perform optimizations to the code since you can always use const_cast to remove the const of a variable.


text:
Q: Invalid Launch Image error uploading IPA with Application Loader ERROR ITMS-90094 I'm trying to upload an .ipa file via Apple's Application Loader utility on my Mac. When I do, I get this error:

ERROR ITMS-90094: "Invalid Launch Image - Your app contains a launch
  image with a size modifier that is only supported for apps built with
  the iOS 6.0 SDK or later."

The app is built using the iOS 8.2 SDK in Embarcadero RAD Studio XE7 / C++ Builder. I have created a valid Adhoc Distribution mobile provision, which is on my Mac and used by PAServer 15.0 & Xcode 6.2 to compile the app. I have properly defined that in my Project Properties | Provisioning for Adhoc distribution on the iOS platform. I have changed to Release mode, and under Configuration I choose Adhoc via the Project Manager. I clean the app first, then Build it, and then Deploy it. When I'm done, I get a valid .ipa file that runs perfect on my test devices.
According to Apple this issue occurs when you build your app with iOS SDK 5.1 or earlier, but include the Default-568h@2x.png image (for iPhone 5's 4-inch retina display support). It says to resolve this issue build your app against the iOS 6.0 SDK or greater. But as I stated, I am using the iOS 8.2 SDK. I've also tried 8.1, and those are the only 2 iOS SDK versions I even have installed on my system.
It says if you do not intend to build your app against iOS 6 SDK, then remove the Default-568h@2x.png from your project. I tried removing this file, and the error goes away but then you get another error: "iPhone 5 Optimization Requirement - Your binary is not optimized for iPhone 5."
It must somehow be detecting the wrong version from the IPA file (which I can only assume is somehow an issue on the RAD Studio side of the equation, as opposed to Xcode or a ton of other people would be having this issue). Other posts use terms like "Deployment Target", "Base SDK" and "Target SDK".
I believe I have set all of these correctly, but how can I fix it so the IPA generated by XE7 is properly detected by Application Loader as being built with a later SDK than iOS 6.0?
Resolutions I've tried (without success):
Most of the search results say to build with a newer version of Xcode (at least 5 or later), but I'm using the latest Xcode version 6.2. Note: Everywhere it says ver 6.0, I also tried 7.0. Project Options refers to Target: All configurations - iOS Device platform.

*

*http://207.211.86.211/index.php/answers/my-discussion/upload-to-itunesconnect
This guy had the same problem, and says to verify all your Project Options | Application images are the correct sizes. I've verified that mine are. He also recommends that you ensure you are building with release versions of Apple's iOS SDKs. Via Tools | Options | Environment Options | SDK Manager, select the iPhoneOS 8.x and click "Update Local File Cache". This also didn't help.

*https://pjstrnad.com/submitting-application-apple-store-delphi/
First he recommends you create a custom Info.plist file under Project | Deployment. Then to fix the invalid image problem, he says you need to add the MinimumOSVersion key and set it 6.0.Add to Custom.info.plist:<key>MinimumOSVersion</key>
<string>6.0</string>

*Since I can only post 2 links, this next one you will have to search at community.embarcadero.com under Answers for "Problems deploying for iOs 8.1" for the original post.
Here they recommend you install Hotfix 30036 "Hotfix for Submitting iOS Applications to Apple AppStore" - which I did. They also suggested on Project Options | Delphi Compiler | Compiling, adding "--ios-version-min:6.0" to Additional options to pass to the compiler. Not sure if that would affect me since I'm using BCB, but I tried it too.

*An article on stackoverflow describes how to use otool and grep on the .IPA file to determine version info. So I unzipped my ipa file, ran otool w/ grep on it, which returned this output:cmd = LC_VERSION_MIN_IPHONEOScmdsize = 16version = 7.0sdk = 7.1While it doesn't say 8.1 or 8.2 as I'd expect, both versions are 7+. This is definitely newer than 6.0, so there must be somewhere else Application Loader is getting the version from.

*Changed Project Options | C++ Linker: Advanced: Minimum iOS version supported to 6.0.

*Changed Project Options | Delphi Compiler | Linking: Minimum iOS version supported to 6.0.

*Tried creating a brand new blank Multi-Device Application, provisioning it and uploading it via Application Loader. This fails with the same exact error.

A: Answer:
Between Embarcadero support and error messages/docs from Apple I finally figured out what the problem was. It turns out Apple will allow you to try and submit an Ad hoc app to iTunes Connect, even though it must be an App Store mobile provision. Despite the fact that you are not distributing to the public App Store yet, but are deploying a private beta test version to a select group of users, you still submit it as an App Store provision. The difference is the beta entitlement that it has.
I took Ad hoc to mean it was going to a select number of devices outside of the App Store via TestFlight - but this is not the case (at least with TestFlight anyway). The problem stems from the fact that Apple's error message was completely useless. The error should have said something like "You must use an App Store provision, and not an Ad hoc or Development provision" instead of "You are including an invalid launch image for 6.0 SDK".
To make matters worse, when TestFlight was a 3rd-party service the instructions were to submit it as Ad hoc. So our team got confused, as that changed when Apple bought it (but this was not made obvious, or at least clear in any Embarcadero docs).
Also terminology is another issue. The terms CERTIFICATE and PROVISION sometimes seem to get used interchangeably or accidentally from one or the other - and the distinction is quite important.
So the solution is to use an App Store Mobile Provision (signed with a Distribution certificate) instead of an Ad hoc one. The app has been submitted successfully to iTunes Connect now.


text:
Q: How to empty price of simple and variable product when product changed into out off stock I want to empty price of simple product and variable product when product changed into out off stock. I have added one code for that its working well. But when adding this code on my site then when i uploading images into media library images are uploaded into wrong folder. If i upload image in 10th October 2019 then image is uploaded into /uploads/2019/04/ actually image need to upload into /uploads/2019/10/ folder. That issue due to my empty price code. so with out this conflict how i can empty price of out off stock product. My current code is following.
function wph_empty_price1() {

    $args = array(
        'posts_per_page' => -1,
        'post_type'      => 'product',
        'meta_query' => array(
        array(
            'key' => '_stock_status',
            'value' => 'outofstock',
            'compare' => '=',
        )
    )
    );

    $loop = new WP_Query( $args ); // get all out of stock products
//var_dump($query);
   if ( $loop->have_posts() ) {
    while ( $loop->have_posts() ) : $loop->the_post();
        $args_variable = array(
            'post_type'     => 'product_variation',
            'post_status'   => array( 'publish' ),
            'numberposts'   => -1,
            'orderby'       => 'menu_order',
            'order'         => 'asc',
            'post_parent'   => get_the_ID(),
            'meta_query' => array(
            array(
                    'key' => '_regular_price',
                    'value' => '',
                    'compare' => '!=',
                )
            )
        );

    $args_simple = array(
    'post_type'     => 'product',
    'post_status'   => array( 'publish' ),
    'numberposts'   => -1,
    'p'             => get_the_ID(),
    'orderby'       => 'menu_order',
    'order'         => 'asc',
    'meta_query' => array(
    array(
            'key' => '_regular_price',
            'value' => '',
            'compare' => '!=',
        )
    )
);

$variations = get_posts( $args_variable ); // get all variations of out of stock product
$simples = get_posts( $args_simple ); // get all simple product of out of stock product
foreach ( $variations as $variation ) {
    $variation_id = $variation->ID;
    // empty price fields in backend
    update_post_meta( $variation_id, '_price', '');
    update_post_meta( $variation_id, '_regular_price', '');
    update_post_meta( $variation_id, '_sale_price', '');
}
foreach ( $simples as $simple ) {
    $simple_id = $simple->ID;
    // empty price fields in backend
    update_post_meta( $simple_id, '_price', '');
    update_post_meta( $simple_id, '_regular_price', '');
    update_post_meta( $simple_id, '_sale_price', '');
}

        endwhile;
    }else {
            echo __( 'No products found' );
    }

wp_reset_postdata();
}

add_action( 'init', 'wph_empty_price1' );


text:
Q: Get ODataQueryOptions in HTTPPOST method I am using HTTP POST for getting the data from the ODataController. But I m not able to query my service
[HttpPost]
[EnableQuery]
public IQueryable<MyDataObject> FetchCCMNewIssueLogViewGridData()
{
     var result = CCMModelDataContext.MyDataObject.AsQueryable();
     return result ;
}

How I can send request from the client side to accept as ODataQueryOptions object?
[HttpPost]
public IQueryable<MyDataObject> FetchGridData(ODataQueryOptions<MyDataObject> options)
{
    var result = options.ApplyTo(CCMModelDataContext.MyDataObject.AsQueryable(), new ODataQuerySettings());
    return result as IQueryable<MyDataObject>;
}

But here in ODataQueryOptions object, I m getting 'Filter' and 'OrderBy' in the ODataQueryOptions  object as null.
Here is my kendo parameter map method for creating the request
parameterMap: function (data, type) {
    var newData = customFilterOptions.grdParameterMap(data, type);
    return JSON.stringify(newData );
},

How I can achieve this?
No need to modify query options in the API Controller.
In which format I can send data to API for accepting it as ODataQueryOPtions object.
As of now my 'Request payload' is
{$top: 20, $orderby: "field1 desc", $filter: "(field1 eq 2 and field2 eq 385)", $count: true, $skip : 20}

How I can do this? will this EnableQuery work with 'HTTP POST'?
Thanks in advance


text:
Q: Is there any way to close meet from jitsy meet wrapper? I wonder, can i somehow programically close the meet incoming via jitsi meet wrapper?
I checked the documentation of package but no word about it. There is no available function as I see. So I wonder, any possible way for it?
Thank u in advance

A: NO.
Jitsi Meet plugin has JitsiMeet.closeMeeting();
They have not included this in Jitsi Meet Wrapper plugin.


text:
Q: can not run all tests with ant and java does anyone know how I can run all of tests with ant and java(build.xml) without eclipse through  script.
I created a build.xml from eclipse then I want to run all the tests in the project build by ant through command prompt, and have one report for all of them with each test sepcified in the report if passed or failed.
Pleas help

A: Just cd into the directory that contains the build.xml file and run the command ant.  It will expect to find a build.xml file and then will execute the default target.


text:
Q: Import with condition clause (query) in parfile - Oracle12c I'm trying to import specific rows from a full '.dmp' file using the parfile parameter.
Import command:
IMP userid=user/password@db parfile=parfile.dat
parfile.dat file:

But I'm receiving the error below when executing the IMP command:

What can be the problem?
Is it possible to use a condition using the old IMP command?
If yes, why it is not working?
Thank you for your help,

A: As long as PARFILE is a valid parameter for the original IMP utility, QUERY is not - which answers your question:

is it possible to use a condition using the old IMP command?

No, it is not.

If yes, why is it not working?

Because it is not supported.
As you're on 12c, here's the Original Import documentation. Have a look at its Parameters section - you won't find QUERY in there (to see the list of all parameters, expand the tree node on the left hand side of the screen).
So, what to do?

*

*Use Data Pump instead, if possible

*If all you have is the DMP file created with the original EXP (and you can't obtain a new, data pump one), import the whole table and write a query which will select data from it, using WHERE clause you meant to use in the PARFILE.

*

*Alternatively, delete all rows that don't satisfy that condition.


text:
Q: In protractor how to click on column based on other column value I need to click on button in a row based on other associated value for that button in same row .
Need to click on :
   button ng-if="ctrl.showEdit"
based on text contain 'abc' in following td or class
    class="width-25 ng-binding"
Both above attributes are in a same row
HTML Table
this.EditByName = function (input) {
        element.all(by.className('table pagination-table-margin ng-scope ng-table')).then(function (rows) {
            rows.forEach(function (row) {
                row.all(by.className('ng-binding')).then(function (columns) {
                     element.all(by.cssContainingText(input)).then(function () {
                        element(by.className('btn-grid ng-scope')).click();
                        console.log(input);
                    });
                });
            });
        });
    };

A: You need to use XPATHs selectors, so you can backtrack once you have found the columns with the value you want to use as reference, like this:
element(by.cssContainingText("td", "abc"))
  .element(by.xpath("..")) // This selects the parent <tr>
  .all(by.css("button[ng-if='ctr.showEdit']"))


text:
Q: scipy linregress: computing support and resistance trendlines on timeseries I would like to compute the trendlines (support and resistance) on timeseries charts (like stocks).
I have manage to assemble something fairly simple that works in many cases, but not in all.
In  my example for the stocks 'ENZ' and 'ARTL' we could imagine better trendlines.
Could anyone familiar with scipy linregress help me improve it / find what goes wrong for some stocks?
The full code is below:
import pandas as pd
import pandas_datareader as pdr
import yfinance as yf
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import linregress
import time
import datetime as dt
from datetime import timedelta

df = pd.DataFrame()

for ticker in ['SNN','AAPL', 'ENZ', 'ARTL']:

    #1# Get data
    print('Processing ticker '+ str(ticker))
    df = pdr.get_data_yahoo(ticker, start = '2020-09-01', end = '2021-09-01', interval = "d")
    df['Ticker'] = ticker #adds the ticker name
    print(df)

    #2# Compute support and resistence trendlines based on df['Close']
    df_len = len(df)
    df['Number'] = np.arange(df_len)+1
    df_high = df.copy() #resistance
    df_low = df.copy()  #support
    #resistance
    while len(df_high)>2:
        slope, intercept, r_value, p_value, std_err = linregress(x=df_high['Number'], y=df_high['Close'])
        df_high = df_high.loc[df_high['Close'] > slope * df_high['Number'] + intercept]
    df['resistance'] = slope * df['Number'] + intercept
    print( '\tresistance:\t' + ' slope: ' + str(round(slope, 3)) + '\tintercept: '+ str(round(intercept,3)))
    #support
    while len(df_low)>2:
        slope, intercept, r_value, p_value, std_err = linregress(x=df_low['Number'], y=df_low['Close'])
        df_low = df_low.loc[df_low['Close'] < slope * df_low['Number'] + intercept]
    df['support'] = slope * df['Number'] + intercept
    print( '\tsupport:\t' + ' slope: ' + str(round(slope,3)) +'\tintercept: '+ str(round(intercept,3)))

    #3# Plot
    fig, ax1 = plt.subplots(figsize=(8,5))
    color = 'tab:green'
    xdate = [x.date() for x in df.index]
    ax1.set_xlabel('Date', color=color)
    ax1.plot(xdate, df.Close, label="indi", color=color)
    ax1.tick_params(axis='x', labelcolor=color)
    ax1.legend()
    ax2 = ax1.twiny()
    ax2.plot(df.Number, df.resistance, label="resistance")
    ax2.plot(df.Number, df.support, label="support")
    plt.title(label=df['Ticker'][1])
    plt.legend()
    plt.grid()
    plt.show()

A: I have the same code in my stock algo. I was having some problems with this line:
df_high = df_high.loc[df_high['Close'] > slope * df_high['Number'] + intercept]

because df_high was reducing down to only one row. Scipy won't calculate a slope for only one record so NaN was returned. I solved it like this:
if len(df_high.loc[df_high['Close'] > slope * df_high['Number'] + intercept]) > 1:
    df_high = df_high.loc[df_high['Close'] > slope * df_high['Number'] + intercept]
else:
    break

Also, I don't use yahoofinance, but make sure you're not getting current day values equal to zero. That'll mess up a slope quickly. It happened to me when pulling live data from TDAmeritrade if the market hasn't opened yet.


text:
Q: References for depth of field implementation in a raytracer? I have a basic raytracer and I want to implement depth of field. Can you please
recommend me resources I can use, books and code?
Thanks

A: I figured it out from the little bit of information on this page: http://cg.skeelogy.com/depth-of-field-using-raytracing/, specifically the diagrams near the bottom. I think I did it a little bit differently then how it's shown, but the concept is pretty simple.
I can explain the general idea of what is going on and how to implement it (I'll try to be concise). Light reflects off of any given point in all directions (generally speaking), so it's not actually a single ray going between the render-pt and your eye, it's a cone of light leaving the render-pt and expanding towards the eye. The lens of your eye/camera will tend to bend these light rays such that the cone stops expanding and starts contracting again. For things to be perfectly in focus, the cone should contract to a point on your retina/frame, but this only works at one specific distance from the lens: a distance indicated by the "focal plane" in the referenced page (though I think it should really be a sphere centered on the eye, not a plane).
For anything in front of the focal plane, the cone of light will be bent more: it will focus to a point in front of the retina/frame, and then start expanding again so by the time it reaches the frame, it is no longer a point, but a circle. Similarly, for points behind the focal plane, the cone will be bent less and will not yet have converged to a point when it reaches the frame. In both cases, the effect is that a single point is the scene ends up smeared out across multiple pixels.
For implementation, you can kind of turn this idea on it's head: in stead of rendering every point in the scene to several pixels, you can render several nearby points to a single pixel, which is of course what would really happen since the "smeared out" light circles from neighboring points will end up overlapping and therefore each contribute to a pixel.
So here's how I implemented it:
First, define an aperture: a planar area center on your eye and parallel to the retina/frame. The bigger the aperture, the more DOF effect will be evident. Aperture's are typically just circles, in which case it is easily defined by its radius. Other shapes can lead to different lighting effects.
Also define a "focal distance". I don't think that's actually the correct term for it, but it's the distance from the eye at which things will be perfectly in focus.
To render each pixel:

*

*Start by casting a ray like normal from the eye through the pixel out into the scene. Instead of intersecting it with objects in the scene, though, you just want to find the point on the ray for which the distance from the eye is equal to the selected focal distance. Call this point the focal point for the pixel.

*Now select a random starting point on the aperture. For a circular aperture, it's pretty easy, you can select a random polar angle and a random radius (no greater than the radius of the aperture). You want a uniform distribution over the entire aperture, don't try to bias it towards the center or anything.

*Cast a ray from your selected point on the aperture through the focal point. Note that it will not necessarily pass through the same pixel, that's ok.

*Render this ray the way your normally would (e.g., path tracing, or just finding the nearest point of intersection, etc.).

*Repeat steps 2, 3, and 4 some number of times, using different a random starting point on the aperture each time, but always casting it through the focal point. Sum up the rendered color values from all of the rays and use that as the value for this pixel (as usual, divide by a constant attenuation factor if necessary).

The more rays you use for each pixel, the better the quality will be, of course. I've been using about 150 rays per pixel to get decent but not great quality. You can see the effect with quite a bite fewer (say like 50 or 60 rays), but fewer rays will tend to produce a graininess in the image, especially for things that are very out of focus. The number of rays you need also depends on the aperture size: a smaller aperture won't require as many rays, but you won't get as much blurring effect.
Obviously, you're greatly increasing your work load by doing this, essentially multiplying it by the number of rays per pixel, so if you have any optimizations left to make in your raytracer, now would be a good time to do it. The good news if you happen to have multiple processors available, is that this is embarrassingly parallel once you found the focal point for a pixel.
A little more explanation
The image below should give you an idea of what's happening, and why it works out to be equivalent to what really occurs in an eye or camera. It shows two pixels being rendered, one pixel illustrated in red, the other in blue. The dashed lines extending from the eye through each pixel to the focal "plane" are the rays you cast at the beginning to determine the focal point for the pixel. The semi-transparent cones indicate the complete set of rays which could possibly be selected at random to render each pixel (red cone for pixel-1, blue cone for pixel 2). Notice that since all rays pass through the focal point, each cone converges to a point exactly at the focal point.
The overlapping areas of the cones represent points in the scene which could end up being rendered to both pixel-1 and pixel-2: in other words, smeared out. Since every cone is a point on the focal "plane", there is no overlap between cones here, so points at this distance are only rendered to a single pixel: they are perfectly in focus. Meanwhile, the further you get away from the focal "plane" (either forwards or backwards), the more the cones spread out, so the more cones will overlap at any given point. Therefore, points that are very close or very far away will tend to be rendered to a large number of different pixels, so they will be very out of focus.


text:
Q: authentication error on WS2012 (trust relationship failed) Given the following lab setup:
HOST1 on Windows Server 2012 R2 (host running Hyper-V, joined test.local domain, static IP)
DC1 on Windows Server 2012 (VM under Hyper-V on HOST1, AD and DNS roles, all defaults with test.local domain)
DC2 on Windows Server 2012 (VM under Hyper-V on HOST1, secondary AD)
DHCP1 on Windows Server 2012 (VM under Hyper-V on HOST1, DHCP role)
HOST2 on Windows Server 2012 R2 (host running Hyper-V, joined test.local domain, static IP)
DC3 on Windows Server 2012 (VM under Hyper-V on HOST2, secondary AD)
DHCP2 on Windows Server 2012 (VM under Hyper-V on HOST2, DHCP role)

Both hosts on the same subnet and home router, all firewalls off.
First installed the physical hosts, then the VMs. Installed roles, created new domain, joined all VMs, joined the hosts, restarted a few times, all good.
Problem: When trying to RDP to HOST1 yesterday from my Windows 8.1 box, as usual with the Domain Admin user (test\Administrator), no joy. The connection is accepted but i get to accept the certificate, the RDP connection opens, and a message in the remote machine saying: "Other user The trust relationship between this workstation and the primary domain failed." and disconnects in 30 seconds or so.
If I go with the local administrator account (HOST1\Administrator) I can login just fine. Also, logging on HOST2 with the same Domain Admin user (test\Administrator) is allowed.
Able to fix it (sometimes!) by rebooting both hosts a couple of times. So it looks like the computers and accounts are still allright within the AD (no need to rejoin or reset passwords).
Why does this happen ? Where to start with the troubleshooting ? Trying to get to understand the root cause, rather than just a quick fix.

A: Check the simple things first. Make sure the times match on all the computers (They should since it is Hyper-V, but it's a quick thing to check). Kerberos authentication can fail if they don't, and a failed login by the computer could be sending the trust message when trust isn't really the issue. Also, make sure the DNS servers specified in the host IP settings that you statically configured are the DCs, for the same reason.
After that, try launching your RDP session connecting by IP address instead of host name. If this works, then you have either a problem with certificates, or negotiating the security protocol that is used in the connection.
You said you have to accept the certificate before connecting. Can you supply the reason you are getting prompted to accept it? If the certificate is issued by the domain, it should already be trusted.


text:
Q: Java creating a waveform with samples I have loaded a sound file into a bytearray. I am confused at what I have to do next to get the information to plot the points for a waveform. From what I have found online I have to create another array? Can someone explain to me how this would work as I don't quite understand how the samples would be gathered.

A: The samples are gathered according to the file format.
Lets just say, your audio format is a 8 bit one channel audio file.
This is the simplest case. You can just iterate trough your byte[] and draw the stored values as amplitude.
When your file is a 16bit audio file, each sample consists of 2 bytes, so you'll have to take a look at two bytes for each sample. You can do this by calling the following method:
private int getSixteenBitSample(int high, int low) {
    return (high << 8) + (low & 0x00ff);
}

It will concatinate the first and the second byte of your bytearray for each sample.
So your loop would look somehow like this:
int sampleArray[] = new int[numSamples];

for(int i = 0, j=0;i < bytearray.length;)
{
    int iLow = bytearray[i];
    i++;
    int iHigh = bytearray[i];
    i++;

    sampleArray[j] = getSixteenBitSample(iHigh, iLow);
    j++;
}

The third case could be, that your file is a 16 bit stereo audio file. In that case each sample has two bytes, and after each byte the channel changes.
For example:
First read sample 1 from byte 0 and byte 1. -> First sample of channel 1
Second read sample 2 from byte 2 and byte 3 -> First sample of channel 2
Third read sample 3 from byte 4 and byte 5 -> Second sample of channel 1
Forth read sample 4 from byte 6 and byte 7 -> Second sample of channel 2

For further and mor detailed description, take a look at this page


text:
Q: how to use the first 3 values of a column in each chunk of dataframe to label each group I have a dataframe shown below
 df = pd.DataFrame({'type':[1]*15, 'key':['a','b','c','d','e'] * 3,
 'value':['Tom', 'car','truck', 7,7, 'Steve','car','truck', 4,6,
 'Jason', 'car', 'truck', 2, 10] })

Here is the Input.
    type    key         value
     1      a           Tom
     1      b           car
     1      c           truck
     1      d             7
     1      e             7
     1      a           Steve
     1      b           car
     1      c           truck
     1      d             4
     1      e             6
     1      a           Jason
     1      b           car
     1      c           truck
     1      d             2
     1      e             10

I want to make change this dataframe like below:
   type       concatenated_first3_value     d     e
    1           Tom_car_truck               7     7
    1            Steve_car_truck            4     6
    1            Jason_car_truck            2     10

How should I do this?

A: I am using cumsum create another key for help pivot , here I am using unstack , you can also using pivot or pivot_table
df['New Key']=df.key.eq('a').cumsum()
#noted here I assuming you only have one type if not you need
#df.key.eq('a').groupby(df['Type']).cumsum(),for the key creation
s=df.set_index(['type','New Key','key'])['value'].unstack()
#s=df.pivot_table(index=['type','New Key'],columns='key',values='value',aggfunc='first')

s['New col']=s[list('abc')].apply('_'.join,1)
s.drop(list('abc'),1,inplace=True)
s#You can add reset_index at the end
key           d   e          New col
type New Key
1    1        7   7    Tom_car_truck
     2        4   6  Steve_car_truck
     3        2  10  Jason_car_truck


text:
Q: Total number of DNA string alignments with spaces I'm trying to create formula for the approximation of the total number of alignments between two DNA strings before beginning experimentation. I couldn't find literature that derives a formula to calculate all possible alignments including spaces for strings of unequal length.
Suppose I'm trying to align two strings: AAAAA, CCCCC
In the most extreme case, I can have an alignment of
 AAAAA-----
 -----CCCCC

I do not allow for aligned spaces. I do not have to have the maximum number of spaces in any individual alignment. Some other valid alignment cases:
 -AAAAA   --AAA---A   A-----AAAA    AA-AAA
 C-CCCC   CC---CCC-   -CCCCC----    C-CCCC

From what I could find about equal-length strings, for string of length n I can have at most r=n spaces, and n+r CHOOSE r ways to arrange the spaces in that string. The second string will have at most n CHOOSE r alignments as its spaces cannot be aligned to spaces on the first string.
So the total number of alignments would be:
$\sum\limits_{r=0}^{n}{n+r \choose r}{n \choose r}$.
Is it possible to derive a similar equation for strings of differing length? On the shorter string of length $m$ there would be a minimum of $n-m$ spaces to make up for the insufficient characters.

A: One straightforward way to count these is to organize by the number of positions where both strings are non-spaces, call it $k$.  The minimum value of $k$ is $0$ and the maximum is $m$ (retaining the assumption from the OP that $m \le n$).  The total length of the alignment will be $m + n - k$.  From these we can choose the $m$ positions where the second string has a non-space: there are $\binom{m+n-k}{m}$ ways to do this, and this fully determines the $n-k$ places where only the first string has a non-space.
Within the $m$ positions we selected, $k$ of them have two non-spaces and $m-k$ have a space in the first string.  There are $\binom{m}{k}$ ways to arrange these, so the total number of alignments is:
$$\sum_{k=0}^m \binom{m+n-k}{m} \binom{m}{k}$$
(if you're familiar with multinomial coefficients, the summand can also be written as $\binom{n+m-k}{k,n-k,m-k}$).
This agrees with your analysis when $m=n$, making the simple observation that in that case $k = n-r$ so that $m+n-k = n + r$ (and of course using the horizontal symmetry of Pascal's triangle).


text:
Q: cannot ssh into Elastic MapReduce I'm using elastic-mapreduce to spun new clusters from the command line. After reading this tutorial, I have:
elastic-mapreduce --create --alive \
--instance-type m1.xlarge\
--num-instances 5 \
--supported-product mapr \
--name m7 \
--args "--edition,m7"

a new cluster with 6 nodes(1 master + 5 slaves) will be created. So I try to ssh into the master:
elastic-mapreduce --jobflow j-3FLVMX9CYE5L6 --ssh

and I get Permission denied (publickey)
The permissions.json file is in the elastic_mapreduce home, and also the path to the my_key.pem file.
Also, by doing:
ssh -i my_key.pem hadoop@masternode

I also get Permission denied (publickey). my_key.pem has been given 400 permissions. I honestly don't know what can I try next ... any clues?
When I go to the EC2 console, and I click in Connect, I get the following error message:
Instance is not associated with a key pair.
This instance is not associated with a Key Pair. Without a Key Pair you will need to log into this instance using a valid username and password combination.

A: When you create your EMR cluster make sure you enable a key pair. On EMR console you can see it like below:

A: To augment Rico's comment, above; I would add that you can pull down the key on the command line when you --create the cluster:  for your example:
elastic-mapreduce --create --alive \
--instance-type m1.xlarge\
--num-instances 5 \
--supported-product mapr \
--name m7 \
--args "--edition,m7"
--key-pair hadoopKey

Were "hadoopKey" is the name given to a keypair created via the AWS console.
When you SSH in, you are providing this key as "identity"--this means that the host server must have the private key (PEM file in this case).  This action parameter (or Rico's example above) will push that key file onto the (and ONLY the) Master EC2 server.
N.B., if you want to SSH from the Master to one of the Worker boxen, you need to push the same PEM file to the master and then proceed as usual from there.
E.g.,
you@devbox:$ scp -i hadoopKey.pem hadoopKey.pem hadoop@ec2-the-master-server:
you@devbox:$ssh -i hadoopKey.pem hadoop@ec2-the-master-server:
<figure out the IP of a worker from w/in that Master
hadoop@ec2-the-master-server:$ ssh -i ~/hadoopKey.pem hadoop@the.worker.box.ip

Hope that helps.


text:
Q: return early from some method when full computation is not needed I have a function simillar to this:
void fillset(std::set<int>& myset)
{

while(...) {
object[i]->fillset(myset);
}

if(...)
    otherfillset(myset)

}

now I notice that often this function is used like this:
bool isAllowed() {

std::set<int> myset;

fillset(myset);

return !myset.empty();

}

Now, calling the whole fillset() method is useless for this case, as it takes some time to execute.
I could in this case return as soon as one element is found.
Is there a simple way to refactor this without having to duplicate the code of fillset?
I was thinking of something like this:
template<bool return_as_soon_as_not_empty>

void fillset(std::set<int>& myset)
{

while(...) {
object[i]->fillset(myset);
if( return_as_soon_as_not_empty && !myset.empty()) {
return;
}
}

if(...)
    otherfillset(myset)

}

how do you feel about this? any other idea is welcome

A: What you actually want to do, is to create a new function canFillSet() and call that instead.
All approaches to 'fix' the fillSet() method will cause it to do something that is not obvious from its name and signature => these methods are roads to disaster, they will cause bugs when the program is modified later on.

A: Doing this changes the meaning of fillset(). It is no longer filling the set with all elements, it fills it with only the first.
A better solution would be to cascade the isAllowed() through the objects
bool isAllowed() {
    while (...) {
        if (object[i]->isAllowed())
            return true;
    }
    return false;
}

A: If you can truly guarantee that there are no side-effects of filling the set, you could make your recommended change. But if that set needs to get filled for something else to work properly, you risk changing that behavior.
You could call the early-return variable something like single_fill or something to imply that you are only looking for one object to fill with instead of the whole possible set. You should also consider making that variable optional and default to false.


text:
Q: @appdynamics/react-native-agent throws Task :appdynamics_react-native-agent:compileDebugKotlin FAILED in android react native I am trying to integrate app dynamics in my react native project. we have upgraded react native version in our project from 0.66.4 to 0.70.0
App dynamics is working fine in android with previous version of react but does not works with upgraded version and throws error as below while running the application in android studio.
Task :appdynamics_react-native-agent:compileDebugKotlin FAILED
@appdynamics/react-native-agent version is 22.5.0
react native version: 0.70.0
Android gradle plugin version: 7.2.1
Gradle version: 7.5.1
Please help me on this issue


text:
Q: Display only needed decimals from double I want to convert a double to a string and only display needed decimals.
So I cannot use
d := 123.4
s := Format('%.2f', [d]);

As it display as the result is 123.40 when I want 123.4.
Here is a table of samples and expected result
|Double|Result as string|
-------------------------
|5     |5               |
|5.1   |5.1             |
|5.12  |5.12            |
|5.123 |5.123           |

A: You can use the %g format string:

General: The argument must be a floating-point value. The value is converted to the shortest possible decimal string using fixed or
  scientific format. The number of significant digits in the resulting
  string is given by the precision specifier in the format string; a
  default precision of 15 is assumed if no precision specifier is
  present. Trailing zeros are removed from the resulting string, and a
  decimal point appears only if necessary. The resulting string uses the
  fixed-point format if the number of digits to the left of the decimal
  point in the value is less than or equal to the specified precision,
  and if the value is greater than or equal to 0.00001. Otherwise the
  resulting string uses scientific format.

A: This is not as simple as you think. It all boils down to representability.
Let's consider a simple example of 0.1. That value is not exactly representable in double. This is because double is a binary representation rather than a decimal representation.
A double value is stored in the form s*2^e, where s and e are the significand and exponent respectively, both integers.
Back to 0.1. That value cannot be exactly represented as a binary floating point value. No combination of significand and exponent exist that represent it. Instead the closest representable value will be used:
0.10000 00000 00000 00555 11151 23125 78270 21181 58340 45410 15625

If this comes as a shock I suggest the following references:

*

*Is floating point math broken?

*http://download.oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html

*http://floating-point-gui.de/
So, what to do? An obvious option is to switch to a decimal rather than binary representation. In Delphi that typically means using the Currency type. Depending on your application that might be a good choice, or it might be a terrible choice. If you wish to perform scientific or engineering calculations efficiently, for instance, then a decimal type is not appropriate.
Another option would be to look at how Python handles this. The repr function is meant, where possible, to yield a string with the property that eval(repr(x)) == x. In older versions of Python repr produced very long strings of the form 1.1000000000000001 when in fact 1.1 would suffice. Python adopted an algorithm that finds the shortest decimal expression that represents the floating point value. You could adopt the same approach. The snag is that the algorithm is very complex.


text:
Q: Does MySQL or MariaDB support double literals (double precision)? MySQL seems to support double precision

The FLOAT and DOUBLE types represent approximate numeric data values. MySQL uses four bytes for single-precision values and eight bytes for double-precision values.

Is there a method to declare that a literal is a double precision and not a float, decimal or anything else? I don't see this mentioned in the docs on Numeric Literals. In PostgreSQL, I could coerce a literal to a double precision with
SELECT 1::double precision,
  double precision '1',
  CAST(1 AS double precision);

A: Though not in the docs explicitly on Numeric Literals. You can make a double precision literal with scientific notation (using e0) which seems to work,
MariaDB [test]> CREATE TABLE foo AS SELECT 1.0e0 AS "se_decimal", 1e0 AS "se_nodecimal", 1.0 AS "decimal";
Query OK, 1 row affected (0.03 sec)
Records: 1  Duplicates: 0  Warnings: 0

MariaDB [test]> SHOW CREATE TABLE foo;
+-------+------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table                                                                                |
+-------+------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| foo   | CREATE TABLE `foo` (
  `se_decimal` double NOT NULL,
  `se_nodecimal` double NOT NULL,
  `decimal` decimal(2,1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 |
+-------+------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

This is actually supported by the SQL Spec, which shifts the literal from <exact numeric literal> to <approximate numeric literal> when it sees the e or E. From SQL 2011n spec,
<approximate numeric literal> ::=
  <mantissa> E <exponent>

This is what the docs on Numeric Literals presumably refer to when it says,

Approximate-value numeric literals are represented in scientific notation with a mantissa and exponent. Either or both parts may be signed. Examples: 1.2E3, 1.2E-3, -1.2E3, -1.2E-3.

Though the docs don't say the type, it's double (see above).
See also,

*

*How does the SQL Spec specify literals with a decimal should be handled?


text:
Q: Google APIs Console - missing client secret I tried to create a testing client id for an android app which uses OAUTH 2.0 as login for retrieving user profile. I followed the steps to complete the creation of the client id on google console, but I do not see anywhere the client secret. I'm trying to help my employer with getting google credentials for it's app. I know how to implement OAUTH 2.0 in android, but I need client secret to exchange the code with access token.
First, I selected "Google+ API" from Services tab.
Then followed the on screen steps from API Access tab.

A: Since almost everything from the accepted answer has been deprecated, I thought I'd share what I've found.
I needed the People API which requires a client secret. What Google recommends for using People API with Android is,

Select the application type Other, enter the
  name "People API Quickstart", and click the Create button.

Found here: https://developers.google.com/people/quickstart/java
(Step 1 part e)
So if you need a client secret, you might consider using the Other type. Of course, follow the documentation for your specific API  first.

A: It seems that Google finally ditched the unnecessary client_secret for installable applications and is not yet up-to-date with their documentation.
You should check if you already get an access_token in the initial OAuth request like it's handled on Facebook.
Another possibility would be to fall back to using a Simple API Access key.
Update:
First method seems to not work with Google.
The recommended way for Android is to use AccountManager instead of baking your own requests. Follow this example to see how this is implemented and how you get an AuthToken using a Simple API Access key. Instead of using the Tasks API you can then include the OAuth2 API library to retrieve the userinfo.

A: Just today I found out that on the new Cloud Console we can see the client secret for android apps - while in the old google console we just can't.
To use the new Cloud console, just click on the message "We are improving the experience. Try the new Cloud Console." Google will ask for a SMS confirmation. Now you'll be redirected to the new cloud console

Now, just select your project, click on "Registered Apps" on the left menu, selected your android app, and voilá, on oAuth 2.0 Client Id you'll see your client secret. No idea why on the old google console it's not displayed, but if you really need a client secret key, it's there.

A: Click on "Download JSON "
Is it what you're looking for ?

A: Now that the type Other is unavailable, I used type Desktop since I wish to upload using Visual Studio which is a Desktop app. That worked, I got the client id and client secret.

A: When you update any changes in the credential, make sure you could see the client ID and secret in the dashboard before downloading.
Google cloud takes at the least 10 seconds to regenerate the client id and add it in the json.
Once json is downloaded you can check for client_secret to be present.

A: Another solution is that you have to create a client ID with the type of "Installed Application" then you will have the Client secret

A: source said that :
Visit the Google Developers Console to obtain OAuth 2.0 credentials such as a client ID and client secret that are known to both Google and your application. The set of values varies based on what type of application you are building. For example, a JavaScript application does not require a secret, but a web server application does.


text:
Q: Period of fractions, general formula for primes? So I stumbled on this by accident. Turns out that for example 1/17 has a period of 16 decimals, 1/19 has 18, 1/23 has 22 and lastly 1/97 has 96. So is it a general rule that for 1/n, if n is prime then the length of the period is n-1? If so why? It also works for 1/7 which is 6 repeating decimals. Thank you so much!

A: $\frac1{11}$ repeats with period only $2$ in base $10$. The correct formula for the repeat length of $\frac1p$ is the order of $10$ modulo $p$, i.e. the least $k$ with $10^k\equiv1\bmod p$. This is equal to $p-1$ precisely when $10$ is a primitive root modulo $p$.


text:
Q: Real-world applications of mathematics, by arxiv subject area? What are the most important applications outside of mathematics of each of the major fields of mathematics? For concreteness, let's divide up mathematics according to arxiv mathematics categories, e.g. math.AT, math.QA, math.CO, etc.
This is a community-wiki question, so please edit and improve pre-existing answers: let's keep it to a single answer for each subject area.
(This is inspired by Terry Tao's recent post about a periodic table of the elements listing commercial applications. He suggested it might be fun to have such a summary for either the MSC top-level subjects or the arxiv subjects.)
I'd like to propose that for areas in which the applications are either numerous, non-obvious, or generally worthy of discussion, someone volunteers to open up a new question specifically about that subject area, and takes care of providing a summary here of the best answers produced there.

A: math.MP Mathematical Physics: this subject already uses several of the other already mentioned categories, like group theory, functional analysis, applied to physical theories like quantum field theory. But since the intention is to see concrete applications to the real world taken from a mathematically rigorous framework, then we could mention

*

*In the first place Noether's theorem: "every differentiable symmetry of the action of a physical system has a corresponding conservation law".

*Onsager reciprocal relations: They "express the equality of certain ratios between flows and forces in thermodynamic systems out of equilibrium, but where a notion of local equilibrium exists". Onsager's contribution was to demonstrate that not only is $L_{\alpha \beta}$ positive semi-definite (the Onsanger matrix of phenomenological coefficientes), it is also symmetric, except in cases where time-reversal symmetry is broken.

*

*The issues about proving thermodynamical statements strictly from statistical mechanics. This became one the biggest discussions in mathematical physics on its time, between Ludwig Boltzmann and Ernst Zermelo (see the book of the colleted works of Ernst Zermelo, volume II, edited by Herausgegeben von, Heinz-Dieter Ebbinghaus and Akihiro Kanamori, Springer, 2013).

*The existence of anti-particles by P.A.M. Dirac, which was first a mathematical result. Dirac realised that his relativistic version of the Schrödinger wave equation for electrons predicted the possibility of antielectrons, themselves discovered four years latter, by Carl D. Anderson.

*The Universality of the Feigenbaum constants, proven by Landorf ( Lanford III, Oscar (1982). "A computer-assisted proof of the Feigenbaum conjectures". Bull. Amer. Math. Soc 6 (3): 427–434.), with some corrections by Eckmann and Wittwer (Eckmann, J. P.; Wittwer, P. (1987). "A complete proof of the Feigenbaum conjectures". Journal of Statistical Physics 46 (3–4): 455).

*The very concept of Universality, together with scaling, introduced by Kadanoff (see for example, Physica A 163 (1990) 1-14 "Scaling and Universality in Statistical Physics"). Roughly speaking, scaling is about the description of changes in the behavior of physical phenomena, in terms of adimensional constants, and how do they scale with them, as is the case of the Reynolds number. Universality concerns the invariance of properties for different dynamical systems, independently of some other physical details. For example, (see the aforementioned paper of Kadanoff), any perturbation which does not drive away a Hamiltonian near a critical point is deemed irrelevant, and all the Hamiltonians with any such kind of perturbations are said to belong to the same Universality class.

*In the speculative region (as of today), the prediction of a possible second Island of Stability, where some new stable chemical elements might be found, with possibly interesting physical properties (see, for example, Zeitschrift für Physik 1969, Volume 228, Issue 5, pp 371-386 "Investigation of the stability of superheavy nuclei around Z=114 and Z=164", by Jens Grumann, Ulrich Mosel, Bernd Fink, Walter Greiner).

*Even more speculative, but still valid mathematical results, some solutions from Einstein's General Relativity equations, allowing for closed timelike curves (i.e. time machines to the past), such as Gödel Spacetime (see, Review of Modern Physics, volume 21, Number 3, July 1949, "An example of a new type of cosmological solutions of Einstein's field equations of gravitation", Kurt Gödel).

*Not yet published as mathematically solved, the strict mathematical derivation of turbulence, from the Navier-Stokes equation, or otherwise (turbulence does not have a complete mathematical theory, to the extent of my knowledge). Navier-Stokes does not even have a theorem for the following problem: "Prove or give a counter-example of the following statement: In three space dimensions and time, given an initial velocity field, there exists a vector velocity and a scalar pressure field, which are both smooth and globally defined, that solve the Navier–Stokes equations."

*Along similar lines for mathematical completeness, is the Yang-Mills existence and mass gap: "Prove that for any compact simple gauge group $G$, a non-trivial quantum Yang–Mills theory exists on $\mathbb{R}^4$ and has a mass gap $\Delta > 0$. Its importance comes from the fact that it is the simplest Quantum Field Theory available (as far as I know), and it does not need to assume the existence of quarks.

A: math.KT K-Theory and Homology
Used for the purposes (edit: image processing and computational dynamics) in this book and in the Chomp project.

A: math.AC Commutative algebra

*

*Reed-Solomon codes (a type of error correction codes based on polynomials over finite fields - this is why CDs and DVDs still work even after being scratched!)

A: math.GM General Mathematics

*

*The cosmic distance ladder is largely built using elementary geometry (although for some legs of the ladder, more advanced mathematics, e.g. relativity and probability, play a role).

*Mathematics considered as general is
the model of precise reasoning, which
is widely ( not so widely as it could
be or even should be probably...) used
in various branches of everyday
living as law, economics, psychology,
rhetoric etc. Person who do not know
mathematics at all usually have small
chances to solve his problems in
abstract way, which means that every
problem may only certain solution
related to defined example, without
generalisation.

A: math.GT Geometric Topology: used for topological quantum field theory (TQFT). There is information on applications of this subject area: here. In chapter 6 of Topological Quantum Computation edited by Zhengan Wang CBMS 112 availabe at http://www.ams.org/bookstore/pspdf/cbms-112-prev.pdf It is argued that TQFT is relevant to the real world due to emergence phenomenon.
Also at this site: http://web.ornl.gov/sci/ortep/topology.html geometric topology is used in crystallography. (Carroll K. Johnson and Michael N. Burnett: Crystallographic Topology - The Topology of Crystallographic Groups and Simple Crystal Structures. Here is a link to a Wayback Machine snapshot.)

A: math.GR Group Theory

*

*Group theory provides methods for understanding the Rubik's cube, and for generating algorithms for solving the cube remarkably quickly from any state the cube may be in.

*Groups find various applications in chemistry, eg. in the study of crystal structures and spectroscopy.

*Cryptography - various hard algorithmic problems about groups are used to design crypto-systems.

*Groups of symmetries are used to reduce the dimension of parameter spaces in engineering models to make model verification more tractable.

*Potentially fast matrix multiplication; see this MO question.

*Card tricks that don't work by sleight of hand, but via the arrangements of the cards. e.g. Sim Sala Bim, see this site for a description. If you think about it, the symmetric group explains the trick and shows you how you to extend it past three piles of seven cards, but to N piles of M cards.

A: math.DG Differential geometry

*

*Lie groups are used in robotics (to find the most efficient way to maneuver a robotic arm, for instance).

*Spherical trigonometry is essential for navigation (a few centuries ago, this was THE application of mathematics to the real world - naval empires were built upon this!)

*Finsler geometry can be used in planning shipping routes when ocean currents and winds (as well as the earth's curvature) need to be taken into account to conserve fuel.

*Differential geometry (Riemann metrics + stress tensors) is used in mechanical engineering to study the properties of large membranes, for example, how one should go about building a large tent.  Keyword for literature search "elastic membrane", "continuum mechanics".

*Without taking into account the effects of general relativity on the orbiting satellites that make up the GPS system, the locations reported by GPS receivers would accumulate errors of around 10km each day, rendering the system useless.

*Nonlinear control theory makes heavy use of differential geometry

*[Quantum theory of atoms in molecules] 3 is an application of Morse theory in quantum chemistry.

A: math.AT Algebraic Topology

*

*Algebraic Topology finds applications in sensor network design, coverage analysis for sensor networks, and in expanding data analysis techniques to give better visualizations for large data sets.

*It has also been applied to computer vision, pattern recognition algorithms (for instance here), and topological data analysis.

*Algebraic Topology can be used in robotics. Motion planning and behavioral algorithms for robotics have been studied with topological tools.

*Knot theory is used when dealing with protein folding and other analysis of DNA function. There are enzymes called 'topoisomerases' that change the knottedness of loops of DNA. In fact, when bacteria (which have circular 'chromosomes' called plasmids) reproduce, they make use of an enzyme whose specific role to to unlink Hopf links! There are antibiotics that target this enzyme.

*Model categories have been used in the study of concurrency. See this paper by Gaucher.

*Nash's proof (Ann. of Math, Vol. 54, No.2; 1951) that every finite non-cooperative game has an equilibrium point in mixed strategies is a direct application of Brouwer's fixed point theorem, and spurred a great deal of interest in applications of game theory to economics (cf. this survey article).  Game theory itself has applications in computer science and mathematical finance.

A: math.RT Representation Theory

*

*Much of modern particle physics is related to representations of Lie algebras. For instance, Gell-Mann's "Eightfold Way" comes from the representation theory of SU(3) and its associated algebra.

*

*Almost every application of theoretic
physics in solid state physics
extensively uses representation
theory in description of periodic and
quasi-periodic media as crystals,
semiconductors etc. In fact solutions
of Schroedinger Equation in such
cases, numerical or analytical has to
be carried in accordance with
representation of crystal/quasi
cristal symmetry group.

*There are applications of representation theory to three-dimensional Cryo-Electron Microscopy - there is a recent paper of Hadani and Singer about this in the Annals.

*The study of the orbits of the permanent and the determinant (thought of as points in the space of polynomials) is the central idea in Valiant's algebraic version of P vs NP, and the representation theory of the relevant coordinate rings of the orbit closures is a leading approach by Mulmuley and Sohoni.  There are many references, but here are two for starters: report, ICM paper

A: math.CO Combinatorics

*

*Combinatorics finds applications in computer science, especially in the run-time analysis of algorithms.  It has also in recent years found applications in physics, at least in part via its relationship to quantum theory.

*Combinatorial group testing allows one to quickly isolated defects in a large collection of samples by testing batches of samples at a time.

*Combinatorial designs are routinely used to design experiments in applied statistics and quality control.

*Combinatorial optimization in Logistics and Operations research.

*Graphs are used as models for networks (e.g., internet server connections). Applications include searches for least expensive plane tickets, optimizing garbage pickup routes.

*Graph models are used in machine learning.

*combinatorial properties of
permutation group was the fundamental
part of Enigma cipher breaking by
Marian Rejewski before II-nd WW.
It is dated now but it was one of the
first application of higher
mathematic reasoning to cipher
breaking, because before usually
linguistic reasoning was used
instead.

*Finite projective spaces and Galois geometry are used in random network coding and cryptography.

A: Math.AP Analysis of PDE

*

*Partial differential equations are used a lot for modelling systems in biology and medicine, and help describe e.g. animal coat pattern formation (zebras, leopards...), wound healing, tumor growth, spread of a virus in a population, predator-prey systems in ecology, predicting the variations of concentrations of chemicals (hormones, drugs...) within an organ over time...

*PDEs are used in climate modelling, from atmospheric dynamics to ocean currents.

*Radar imaging is based on solving an inverse problem.  The recent buzz about metamaterials and invisibility is based on understanding variable-coefficient elliptic problems.

A: math.ST Statistics

*

*almost everywhere

*Accurate polling

*Fraud detection: whether financial (e.g. via Benford's law) or voter fraud.

*Used in the world of finance, economics and gambling on a daily basis.

*Predicting consumer preferences (e.g. Netflix prize)

*Experimental design and hypothesis testing (e.g. testing of medical hypotheses)

*Machine learning

*Quality control

A: math.AG Algebraic geometry

*

*Elliptic curve cryptography

*Motion planning: Configuration spaces of robot arms are semi-algebraic sets, and algebraic geometry (especially the Cylindrical Algebraic Decomposition) has been used to understand their geometry and design algorithms.

*Algebraic geometry over finite fields is used to construct error correcting codes.

*Statistical models are often semi-algebraic sets, and algebraic geometry can be used to devise tests for the correctness of the model or to fit parameters.

*Birational geometry can be used in the design of NURBS and CAD tools.

*Projective geometry and implicitization is used in 3D image reconstruction from multiple camera views.

*Geometry and Representation theory of tensors can be used in Physics, Computer Science, Statistics, Phylogenetics, Psycometrics and more. Here is a summary from 2008: report

A: math.CT Category Theory

*

*Category Theory helps design modern and novel programming languages, that end up being able to do optimizations based on mathematical theorems, and even allow provably correct code with less effort than using other techniques. For example, the language Haskell makes use of many ideas from category theory.

*There are deep connections between category theory and logic, in the sense of computer science.

*Feynman diagrams form a (monoidal) category.

A: math.CV Complex Variables

*

*Conformal mapping simplifies various problems about heat conduction and fluid flow, such as calculating steady temperatures. Modelling the flow of fluids around solid bodies (for example aircraft wings!) can also be simplified by appropriate conformal mappings.

*Tools from complex analysis (phasors, argument principle, conformal mapping) are widely used in analyzing electrical circuits, and stress and strain analysis in mechanical engineering.

*The uniformization theorem for discrete complex analysis (circle packings) allows for efficient and pleasant visualization of geometric data that can be related to surface triangulations.

*With the emergence of SLE (Schramm-Loewner evolution, conformally invariant curves), we can model the critical interfaces of various systems such as Ising and Percolation.

*Evaluation of complicated real integrals that show up in engineering and physics via contour integration.

A: math.CA Classical Analysis

*

*Fourier analysis allows one to precisely divide up the electromagnetic spectrum, leading of course to radio, television, wireless, and so forth.

*The fast Fourier transform (and relatives, such as the fast Wavelet transform) is an essential component of many signal processing algorithms.

*MRI is based on inverting the Radon transform.

*Wavelets are used in signal processing (e.g. image compression, edge detection).

The picture is of a Hilbert spectrometer.

A: math.RA  Rings and Algebras

*

*Google's Pagerank algorithm is based, in part, on the singular value decomposition.

*Fourier analysis / transforms and linear algebra is at work in the world millions of times per second (video, audio). In particular, creating or displaying a JPEG image requires the discrete Fourier transform.

*Quaternions are used in 3D modeling and animation software to represent rotations in a more robust form than Euler angles (helping to avoid transition issues like gimbal lock).

*Every simulation using Finite Element
Method uses algebra in very extensive
way.

*Tropical algebra has been used to design product-mix auctions and to calculate demand (see Baldwin-Klemperer).

A: math.PR Probability

*

*Probability theory is used in information theory, error-correcting codes, compression algorithms, machine learning, probabilistic algorithms

*Physicists use probability in Quantum Mechanics and Statistic Mechanics

*Queuing theory is used to analyze telecommunication networks.

*Stochastic processes such as branching processes and HMMs are used to model speciation and extinction (the Tree of Life), evolution of molecular sequences, cell proliferation, and other things in biology. For example, see `Branching Processes in Biology' by Kimmel and Axelrod.

*Here's a somewhat frivolous one (but one that casinos greatly care about): the number of times one needs to shuffle a deck before it truly randomizes.

*used in the world of finance, economics and gambling on a daily basis.

*Random number generation is a key component of many efficient algorithms, and also plays an important role in cryptography.

*Stochastic calculus is used to price options (Black-Scholes formula) and to hedge against risk.  (Of course, it is not always applied wisely...)

*Markov chains are used to find uniformly random objects. This, among other things, makes designing an experiment fairest and crypto-systems based on designs securest.

A: math.NA Numerical analysis

*

*Linear programming algorithms are used in compressed sensing, which is now being used in MRI and imaging to increase resolution and/or decrease the number of measurements required.

*Numerical analysis is what makes calculators work. (And so much more!)

*We use numerical linear algebra to approximate solutions to discretized versions of complicated PDEs.

*At the heart of Google's Pagerank algorithm is a relatively simple numerical eigenvector computation called the Power Method. The study of large complicated networks (e.g. Facebook) is done using tools from graph theory which again comes back to using the tools of numerical linear algebra.

*Finite elements method (a version of multigrid numerical aanalysis) is all pervasive in construction and achitectural stability analysis, and also in other fields of engineering like engine design).

A: Math.DS: Dynamical systems

*

*Modeling flow of liquids, like the animated flow of lava in the movie "Volcano"

*Solving classical few-body problems, though it doesn't help with the modern notorious "two-body problem"

*Heteroclinic trajectories are used in space mission design

*Heteroclinic tangles are used by chemical engineers to get well-mixed reactants

*Pseudo-Anosov braids are used to design efficient methods for stirring viscous liquids (see for example http://arxiv.org/pdf/nlin/0603003.pdf)

A: math.NT Number Theory

*

*From Number Theory comes the ideas and theoretical basis for modern cryptography, used to secure communications everywhere from banking to cellphones.

*A more quirky one is SETI (the primes in binary would be a very clear indication of a signal non-natural origin, and would be a starting point for communication).

*There is a gamma ray telescope design using mod p quadratic residues to construct a mask.  Gamma rays cannot be focused, so this design uses a redundant array of detectors separated from the mask to reconstruct directional information.

A: math.SP Spectral theory

*

*Spectroscopy (of course)

*To avoid bridge collapse, knowing where the resonant frequencies are is extremely important. :-)

*Shape and model recognition

*Network analysis and security (spectral graph theory)

*The design of quantum wave guides

A: math.FA Functional Analysis

*

*Used in signal processing for modeling and design.

*Used in machine learning in the design of classifiers (e.g. spam filters)

A: math.OA Operator Algebras

*

*(In "Nature") Operator algebras, and, more broadly, operator theory, appear in mathematical models for quantum phenomena.

*(In Engineering) Completely positive maps are used in quantum information theory. There are also many connections between operator algebras and wavelets, which is useful in electrical engineering.

A: math.IT Information theory

*

*Compression; efficient use of bandwidth

*Error-correcting codes protect against digital data corruption from noise, packet loss, physical damage, etc.

*Used in machine learning

A: Math.HO: History and overview: used for

*

*understanding mathematics as a social and human endeavor

*considering alternative approaches that historically have been used to explore quantifiable relationships

*to teach us that no mathematical
ideas appear in empty social space:
every idea is a child of its time. It is application of HO to mathematics itself

One real-world application of mathematics is set forth in Bill Thurston's far-sighted essay On Proof and Progress in Mathematics, that purpose being, to provide foundations for social enterprise.
With more than 300 references, On Proof and Progress in Mathematics is among the most-cited of all the arxiv's [math.HO] articles.
Nowadays many influential essays in systems engineering (for example) draw implicitly upon Thurston's influential ideas regarding the central role of mathematics in social enterprises ... it is not only mathematicians who are reading and reflecting upon these ideas.

A: math.LO Logic

*

*Lambda calculus, the theoretical basis for functional programming (Lisp in particular), was developed by Alonzo Church in the 1930's as part of his research on recursion and the foundations of mathematics.

*Formal verification is used to verify software and hardware in which failure rates need to be as close to zero as possible (e.g. avionics)

*Finite Model Theory is used to design and improve database query systems.

*logical reasoning is widely and sometime non-trivial used in
law application in courts, and in
should be in parliaments during
setting a law systems

A: math.MG Metric Geometry

*

*Discrete sphere packing solutions lead to error-correcting codes.

*The earthmover metric is used in image recognition and classification.

*Triangulation using the Euclidean metric is used for navigation (and nowadays, in GPS systems)

The Banach fixed point theorem for contraction mappings has a beautiful application in image compression, called fractal compression. One starts with a complete metric space $X$ of images with Hausdorff metric. Then for a given image $x \in X$ one finds a contraction mapping $A: X \to X$ with (unique) fixed point $x$. To do this, one considers self-similarities in the picture (that's why it is called fractal compression).
Then we get rid of the original image and store the map $A$ only.
To reconstruct the image, one starts with any $x_0 \in X$ (for example an image which is all black or all white), and applies $A$ several times. The result will be close to $x$.
When I (Evgeny Shinder) first learnt this in high school (my friend and I implemented fractal compression as a final project for a programming class), I was fascinated how such abstract math can be applied to such a concrete problem as image compression!

A: math.SG Symplectic Geometry
Symplectic integrators are used for numerical simulation of Hamiltonian mechanics.  Prominent applications include molecular dynamics, solar system dynamics, computer animation, and a wide variety of problems in mechanical engineering.

A: math.OC Optimization and Control

*

*Optimization is heavily used in medicine for cancer treatment, in a technique of radiation therapy called Intensity Modulated Radiotherapy (IMRT) Take a look at this presentation of one of the main researchers in the field.

*Used everywhere in almost every electro-mechanical system (cars, planes, the power grid)

*Kalman filtering and the like are used to enable (e.g.) radar tracking.

*Optimization (and more generally, operations research) is used for management in logistics and analyses/feasibility studies.