java8 – GraphQL authorization directive with exceptions

I am trying to apply restrictions on a graphQL schema on a Java application, based on domain. I would like the whole schema to be restricted to the domain “admin.org”.

However, I also want to be able to expose any query or mutation to “user.org”, by excluding the particular query or mutation from the global restriction.

The only way I found yet, is to restrict each query with the FIELD_DEFINITION directive. That is something I would like to avoid since I don’t want to add a rule in every new query I add to the API.

  1. Is this possible to implement with GraphQL directives?
  2. If it is not, is there another way to accomplish the desired result?

python 3.x – Handling exceptions

I had a blast to get a awesome code reviewer yesterday who taught me very much and I do hope I have done a pretty good job on improving my knowledge both with exceptions and in general.

Currently I have been working on to get a nice exception/more correctly way to do the exceptions as well.

For now I have done something like this:

from typing import Iterable

import requests
from requests.exceptions import ConnectionError, ConnectTimeout, HTTPError, ProxyError, ReadTimeout, RequestException, 
    Timeout


# ----------------------------------------------------
# Exceptions
# ----------------------------------------------------
class RequestsException(Exception):
    """
    Base exception class for Requests
    """


class TooManyFailedRequests(RequestsException):
    """
    Raise an exception for FailedRequests
    """


class TooManyTimedOut(RequestsException):
    """
    Raise an exception for TimedOut
    """


# ----------------------------------------------------
# Counter Exception
# ----------------------------------------------------
class ExceptionCounter:
    """
    Counter to check if we get exceptions x times in a row.
    """

    def __init__(self, limits):
        self.limits = limits
        self.exception_counts: DefaultDict(Type(Exception), int) = defaultdict(int)

    def check(self, exception):
        allowed_count = self.limits.get(type(exception), 3)

        self.exception_counts(type(exception)) += 1

        if self.exception_counts(type(exception)) >= allowed_count:
            raise

    def reset(self):
        self.exception_counts.clear()


simple_exception = ExceptionCounter({})


# ----------------------------------------------------
# Run requests
# ----------------------------------------------------
def run_request(site_url: str, session: requests) -> Iterable(requests.Response):
    try:
        return get(
            site_url=site_url,
            session=session
        )

    except HTTPError as err:
        raise TooManyFailedRequests("Too many response status err", err)

    except (ReadTimeout, Timeout, ConnectionError, ProxyError) as err:
        raise TooManyTimedOut("Msg", err)

    except Exception as err:
        print("We dont know")
        raise Exception("We dont know")


# ----------------------------------------------------
# Do the request
# ----------------------------------------------------

def get(site_url, session) -> Iterable(requests.Response):
    while True:

        try:
            response = session.get(site_url, timeout=10)
            if response.ok or response.status_code == 404:
                return response

            response.raise_for_status()

        except HTTPError as http_error:
            # In the event of the rare invalid HTTP response, Requests will raise an HTTPError exception. Response.raise_for_status() will raise an HTTPError if the HTTP request returned an unsuccessful status code.
            print(f'HTTP Error | URL -> {site_url} | Exception -> {http_error}')
            simple_exception.check(exception=http_error)

        except ProxyError as proxy_error:
            print(f'Proxy Error | URL -> {site_url} | Exception -> {proxy_error}')

            # Manage Proxy Error. Re-try if proxy returns 503
            if "503 Service Unavailable" not in str(proxy_error):
                print("Unknown Proxy error")
                simple_exception.check(exception=proxy_error)

        except (ReadTimeout, Timeout, ConnectTimeout, ConnectionError) as err:
            # Manage Read timeouts, Timeouts, Connection error
            print(f'Timeout/Connection | URL -> {site_url} | Exception -> {err}')
            simple_exception.check(exception=err)

        except RequestException as uncaught_req_error:
            # All exceptions that Requests explicitly raises inherit from requests.exceptions.RequestException. So a base handler can look like,
            print(f'RequestException | URL -> {site_url} | Exception -> {uncaught_req_error}')
            simple_exception.check(exception=uncaught_req_error)

        except Exception as unexpected_error:
            print(f'Unexpected caught | URL -> {site_url} | Exception -> {unexpected_error}')
            simple_exception.check(exception=unexpected_error)


def main():
    session = requests.session()
    test = run_request("https://stackoverflow.com/testing123", session=session)
    print(test)


if __name__ == '__main__':
    main()

I wonder if i’m doing it correct or if there is anything I can improve 🙂

What is the meaning of “[*.]” in the Chrome cookie exceptions dialog?

enter image description here
Screenshot of the add-to-cookie-whitelist pop up (chrome://settings/cookies?search=cookies)

I am always entering the metacharacters (*.) here, what is their meaning? Do i correctly guess that () means zero or one, * means one or more letters from “a” to “z”, and . means the literal “.”?

(some 300+ points owner: would you be so kind to append metacharacter to the tags of this question and then delete this paragraph?)

algebra precalculus – Are there any exceptions to the upper and lower bounds theorem?

Hi there 🙂 I’m new to this site so please let me know if there’s anything wrong with my question.

I was trying to find the roots of the polynomial expression $P(x) = 8x^5 – 14x^4 – 22x^3 +57x^2 – 35x + 6$. I first found $(x+2)$ using the Rational Zeros Theorem and synthetic division. Since the result of $frac{P(x)}{x+2}$ is $Q(x) = 8x^4 – 30x^3 + 38x^2 – 19x + 3$, I assumed $-2$ is a lower bound, because of the alternating signs. And from the graph I can see that’s true, since there are no x-intercepts smaller than $-2$.

graph of P(x)

Then, I found $(x – 1)$ as a root. The result $frac{Q(x)}{x-1} = 8x^3-22x^2+16x-3 = R(x)$ implies that, according to the theorem, 1 is a lower bound of $Q(x)$, but this time, according to the graph, that is not true. I supposed that roots themselves cannot be considered upper and lower bounds.

graph of Q(x)

However, when dividing $R(x)$ by $(x-1)$ I get $8x^2-14x+2 – frac{1}{x-1}$, which is not a root, but should be a lower bound according to the theorem, and that does not make sense looking at the graph.

graph of R(x)

Am I doing something wrong? Or maybe this is indeed an exception to the theorem? Also, can you tell me whether roots can or cannot be considered as bounds themselves?

Thank you in advance! 🙂

c# – Rethrowing unhandled exceptions later in the catching method

I have a worker class that catches uncaught exceptions and logs them for tracking purposes. However, I do NOT want to swallow those exceptions, nor do I want to abstract them (i.e. losing the stack trace). I believe the best practice in the industry is to throw a new exception and set the inner exception to the caught exception.

With that in mind, I would like a peer review of my implementation in a stripped down form that can be reproduced in a console application:

private static void ExecuteAction(Action action) {
    Exception uncaughtException = null;
    try {
        action();
    } catch (Exception e) {
        Console.WriteLine(e.Message); // In reality this logs to a database.
        uncaughtException = e;
    }

    // Some fake extra work for sample purposes.
    for (int i = 0; i < 1000; i += 3)
        i -= 2;

    if (uncaughtException != null)
        throw new Exception("An uncaught exception was detected by the worker. Check the inner exception for details.", uncaughtException);
}

To test it out, in your main method of a console application:

try {
    int maxValue = int.MaxValue;
    ExecuteAction(() => {
        Console.WriteLine("This is a test.");
        Console.WriteLine(checked(maxValue + 1));
    });
}
catch (Exception e) {
    Console.WriteLine(e.Message);
    if (e.InnerException != null)
        Console.WriteLine($"Inner Exception: {e.InnerException.Message}");
}

The expected output is:

This is a test.

Arithmetic operation resulted in an overflow.

An uncaught exception was detected by the worker. Check the inner exception for details.

Inner Exception: Arithmetic operation resulted in an overflow.

Are there some scenarios that may not be covered by this? Are there any gotchas to this implementation?

database design – How to model local exceptions to distributed tables

I am looking for possible ways to model a distributed table(s) and provide local exceptions to that table. Consider a situation where head office publishes a list of products/prices that is distributed to branches and they load this price list into their local database. Now sometimes these branches want to change the head office price to a local price. Clearly we can simply update the price in the local database, but then it gets lost when the next head office update is applied. We also only want to block that single column(s), not changes to other fields in the row.

EG. Head office send
| Name | Price |
|——|——-|
| ABC | $5 |
| DEF | $8 |

In one database (out of say 100) we want ABC to have a price of $3. And this $3 should continue to apply even as future updates from head office are received. Head office are not aware of this local exeception.

In the past we’ve done this in two ways. The first was to maintain a second LocalProducts table with the changes to be applied – then when the head office version was applied, any local changes would then be read from LocalProducts and replace the distributed value.
This works OK, but suffers as the table sizes go up.

The second method we tried was to duplicate the column and use coalesce
eg rather than select price where name='abc' we would use select coalesce(localprice,price) where name='abc' This works ok, but had the overhead that we had to change every SQL and remember to do it on future development too.

Are there any other better methods? I am looking for a database agnostic solution, the target databases are ODBC (90% sql/server), SQL-Lite or MS-Access. Access can be ignored if it helps, it is being actively phased out. Engine specific solutions are ok, we can detect the engine and use a different technique, but would prefer not to have a different technique for each engine.

Other notes

  • The data is distributed by the application, not built in replication. This means we can have code/logic during the loading phase
  • Multiple tables are require this feature, not just one as the example above
  • Some of the tables have a reasonable number of columns that could be involved, but typically not.
  • Most of the tables aren’t large, perhaps 50M rows in the biggest, and only 7 rows in the smallest case.

(please feel free to retag this question – not exactly sure which tags are relevant. And yes I have spent many hours over the years investigating this)

google analytics – Exceptions of different scope combinations in GA

I am studying about the scope in Google Analytics and, obviously, I have read that we shouldn’t combine different scope metrics and dimensions. However, I have some questions regarding the exceptions allowed.

For example, we have the following combination:

Bounce Rate by Page (session-level metric by hit-level dimension)

I have also read that we should never combine session-level metrics and hit-level dimensions, because when combining any session-level metric with a hit-level dimension, the metric will only contain data from the first hit of the session. So, even though there are some exceptions, this shouldn’t be one. However, in this case we do have such a combination. Why?

Exceptions of different scope combinations in Google Analytics

I am studying about the scope in Google Analytics and, obviously, I have read that we shouldn’t combine different scope metrics and dimensions. However, I have some questions regarding the exceptions allowed. I will give some examples:

A. Users by Page (user-level metric by hit-level dimension)

I would expect to get a table that shows how many users visited each page of my site. Based on my research, this combination can be used because hits do contain user information (the client id).

B. Pageviews by Source / Medium (hit-level metric by session-level dimension)

Are, and if yes why, are we allowed to use this combination if we want to calculate the number of pageviews generated from users arriving from a specific source/medium?

C. Bounce Rate by Page (session-level metric by hit-level dimension)

Regarding this combination, I have read that we should never combine session-level metrics and hit-level dimensions, because when combining any session-level metric with a hit-level dimension, the metric will only contain data from the first hit of the session. However, in this case we do have such a combination. Why?

Exceptions of different scope combinations in Google Analytics

I am studying about the scope in Google Analytics and, obviously, I have read that we shouldn’t combine different scope metrics and dimensions. However, I have some questions regarding the exceptions allowed. I will give some examples:

A. Users by Page (user-level metric by hit-level dimension)

I would expect to get a table that shows how many users visited each page of my site. Based on my research, this combination can be used because hits do contain user information (the client id).

B. Pageviews by Source / Medium (hit-level metric by session-level dimension)

Are, and if yes why, are we allowed to use this combination if we want to calculate the number of pageviews generated from users arriving from a specific source/medium?

C. Bounce Rate by Page (session-level metric by hit-level dimension)

Regarding this combination, I have read that we should never combine session-level metrics and hit-level dimensions, because when combining any session-level metric with a hit-level dimension, the metric will only contain data from the first hit of the session. However, in this case we do have such a combination. Why?

language design – Why do “checked exceptions”, i.e., “value-or-error return values”, work well in Rust and Go but not in Java?

From a scientific point of view, checked exceptions can be seen as alternative return values, e.g.

Exactly. They can be seen that way, and they should be but they aren’t.

Using an Error type like is common in Rust, Elm, Haskell, and in some sub-communities in Scala or a special error value as in Go is just an alternative return value indicated in the type system. A checked exception is like an alternative return value, but it doesn’t use the normal way of returning values, it is a completely separate, very different way of “returning values”. It also sits outside of the type system, and bolts on a completely separate “checked exception” system onto the type system.

But most importantly, it is not just an alternative return value, it is also an alternative control flow.

Another problem with the specific way checked exceptions are implemented in Java, is that they are anti-modular. That is, however, not a fundamental problem of checked exceptions, unlike the ones I mentioned above. There is an idea of Modular Anchored Exceptions, for example, where you can specify something like

int foo() throws like bar { return bar(); }

And you don’t have to know (and leak!) which precise exceptions bar can throw. You can even do something like throws like bar except ArrayOutOfBoundsException when you are handling some errors yourself.