typescript – RxJs – Flat nested swithMaps and pass variables on Http interceptor

How can the following method be flattened? I tried to pipe all the operators to the first pipe (from(this.fireAuth.currentUser)) but I lost access to the previous variables. It’s an Angular HTTP interceptor that adds a Bearer Token when the user has logged in, the chain should continue as usual when the user has not logged in yet.

  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    const isApiUrl = request.url.startsWith(apiCloudURL);
    return from(this.fireAuth.currentUser).pipe(
      switchMap(user => {
        if (!user) return next.handle(request);
        return from(user.getIdToken()).pipe(
          switchMap(token => {
            if (isApiUrl) request = this.addToken(request, token);
            return next.handle(request).pipe(
              catchError(error => {
                if ( isApiUrl && token && error instanceof HttpErrorResponse && error.status === 403) {
                  return this.handle403Error(request, next);
                }
                else{
                  return throwError(error); 
                }
              })
            );
          })
        )
      })
    );
  }

Piping to the first observable… I have no access to the token var in the catchError block 😥

  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    const isApiUrl = request.url.startsWith(apiCloudURL);
    return from(this.fireAuth.currentUser).pipe(
      switchMap(user => {
        if (!user) return next.handle(request);
        return from(user.getIdToken());
      }),
      filter<string>(x => typeof(x) === "string"), //x can be string to HttpEvent<any>
      switchMap(token => {
        if (isApiUrl) request = this.addToken(request, token);
        return next.handle(request)
      }),
      catchError(error => {
        if ( isApiUrl && error instanceof HttpErrorResponse && error.status === 403) {
          return this.handle403Error(request, next);
        }
        else{
          return throwError(error); 
        }
      })
    );
  }

I’m also wondering what’s happening in the scenario where user is falsy, does it mean the request will be canceled because it does not pass the filter?

Thanks.

python – Access nested dictionary from list of values

I have a json output like this :

input= {"username": 'user_1',
       "data": [{"id": 4,"name": "email", "updated_data": {"score":5}},
        {"id": 7, "name": "Spread","updated_data": {"assigned": "user_2"}},
        {"id": 6,"name": "Losses", "updated_data": {"assigned": "user_3","score":5}}]}

Now i want to get a dictionary output from these data based on assigned key, i.e, if there is assigned value in updated data then my output dictionary would like this

output ={'Spread': {'user_1': -1, 'user_2': 1}, 'Losses': {'user_1': -1, 'user_3': 1}}

Is there any way where i acn create dictionary in the above given format

Nested URL with categories, sub categories and pages in between

I’m a bit new to wordpress and would like to know how to achieve the following structure. Essentially I’m creating a website for a store that carries multiple products. For example:

site.com/brand/<brand1>/products/<product1>
site.com/brand/<brand1>/products/<product2>
site.com/brand/<brand2>/products/<product3>

also as part of the requirement:

site.com/brand loads a page that will display all available brands
site.com/brand/<brand1>/products loads a page that will display all available products for brand 1

Is there a way for me to achieve this without using any plugin? I prefer to create a custom code instead.

information architecture – How can I simplify this highly nested data structure?

Trying to layer multiple levels of tab controls can get messy, fast.

I would suggest you stick with something more simple such as a navigation menu. You could also make it an accordion menu if you don’t want all sub-categories to be visible at the same time.

Here is an example of a simple menu:

enter image description here

It isn’t clear what “medium” and “language” are in your question. So this idea works on the basis that they are field sets and fields. Therefore, you have the navigation menu for categories, and then a single (scrollable) view that will hold all the data for the selected sub-category.

arrays – Replacing nested loops in Python using NumPy

So I have these 6 nested loops, and their purpose is only to multiply and add arrays X and Y over different indices to get array Z.

import numpy as np

dim_a = 5
dim_b = 9
Z = np.zeros((dim_a,dim_b,dim_b,dim_a))
X = np.arange(2025).reshape(dim_a,dim_b,dim_b,dim_a)
Y = np.arange(2025).reshape(dim_a,dim_b,dim_b,dim_a)

for i in range(0, dim_a):
    for j in range(0,dim_a):
        for a in range(0, dim_b):
            for b in range(0, dim_b):
                for m in range(0,dim_a):
                    for e in range(0,dim_b):
                        Z(i,a,b,j) += X(m,e,b,j) * Y(m,e,a,i) * 2

Is there a way to write it using just a few lines of code using NumPy? The computational effort of these nested loops is enormous. I have a feeling that NumPy can optimize it significantly.

postgresql – Find nested related users

From this SQL schemas, I want to find all users related by contest.id

enter image description here

I try this req :

SELECT u.id, u.firstname, u.lastname, u.avatar FROM contests c
LEFT JOIN trials AS t ON (t.contest_id = c.id)
LEFT JOIN trials_has_users AS tu ON (tu.trial_id = t.id)
LEFT JOIN users AS u ON (u.id = tu.trial_id)
WHERE c.id = '7a101d23-a1d5-457c-821e-14321ae3bb64'
GROUP BY u.id;

but it does not work, u.id, u.firstname, u.lastname, u.avatar is NULL, and I only have one result 😅

postgresql – Count deep nested tables

since this SQL schemas I want to count the number of times a user is in a contest.

schema SQL user has trials

SELECT * FROM users u
LEFT JOIN trials_has_users tu ON (tu.users_id = '1')
LEFT JOIN trials AS t ON (t.id = tu.trials_id)
WHERE u.id = '1';

Previously, I have the expected number of lines, but I want to make a count

SELECT contests FROM users u
LEFT JOIN trials_has_users tu ON (tu.users_id = '1')
LEFT JOIN (
    SELECT
        contest_id,
        COUNT(*) AS contests    
    FROM
        trials
    WHERE deleted_at IS NULL
    GROUP BY
        (contest_id)
) AS t ON (t.id = tu.trials_id)
WHERE u.id = '1';

Error

ERROR:  column t.id does not exist
LINE 12: ) AS t ON (t.id = tu.trials_id)

I would like to receive the number of contests in which the user has participated.

time complexity – Theta bound for runtime analysis of nested while loops

I am trying to fully analyze the running time of $texttt{nestedLoops}$ in terms of $n$ with a Theta bound.

The Java code I have is as follows:

public void nestedLoops(int n) {
     int i = 1;
     while (i < n) {
          int j = i;
          while (j > 1) {
               int k = 0;
               while (k < n) {
                    k += 2;
               }
               j = j // 2
          }
          i *= 2
     }
}

I know that the innermost while loop has an obvious runtime of $lceil frac{n}{2} rceil$.
But I get stuck on the next while loops. I think the middle while loop has a runtime of $lfloor
log_2texttt{i} rfloor$
, but that is very confusing for me.

Any help would be taken with much gratitude.

MVC architecture – communication between nested components

I’m working on a rich client desktop application. I’m trying to use MVC to decouple the model, view and controller responsabilities.
Problem is I can’t seem to find a clean solution for handling communication between nested components.

Most of the answers I’ve read online were either confusing or were dealing with “web MVC” architecture rather than real MVC.

I do not mind ending up using another MVC flavor (MVP, MVVM etc…) if it helps me creating a clean a maintainable architecture.

Scenario

The codebase is small and contains two classes: MainView, and MainController. So far the view and controller responsabilities are decoupled and the code is clean.

At some point the codebase grows and I need a SecondaryView with a button. When the button is clicked, the program needs to access the file system to perform operations.

Problem

How to handle the button click in a nested component (one level deep or more) without making a mess in my code?

What I tried so far

1 – One controller owning the nested view and a chain of observer/observables: unmaintainable code

MainController has a reference to MainView. MainView has a reference to SecondaryView.

When SecondaryViewButton is clicked, SecondaryView notifies its listener MainView which notifies its listener MainController which performs the file system operations.

This solution is even less maintainable when we nest components into components into components…

2 – Still one controller, but the main view now owns its nested views AND the controller

MainView has a reference to MainController and SecondaryView.

When SecondaryViewButton is clicked, SecondaryView notifies its listener MainView which directly calls performOperation() method on MainController.

This solution seems slightly better but it wouldn’t work if the clicked button is nested several levels deep.
Plus I suspect having a view reference BOTH controllers and other views is not a good idea?

3 – Multiple controllers, and each view has a reference to its controller

This solution seems better, but now all the controllers have to be able to access the file system (which is a common operation in this application) instead of a unique entry point when we just had MainController.
I’m not sure whether this would be a good idea in the long run.

The real problem however is I don’t have a clear understanding of how to nest components in a MVC architecture? Should I nest the views together and each view reference its own controller?

How would you solve the component nesting problem while maintaining a clean architecture?

rest – POSTing a nested object – returning the created nested object inside the parent

Suppose that we have a Post resource (this is just a dummy example):

GET /api/posts/1

{
  "id": 1,
  "header": null,
  "content": null
}

And now we’d like to create a Header inside the Post#1.

POST /api/posts/1/header

{
  "color": "blue",
  "title": "Some title"
}

Now, is it okay for the POST request above to return the following response?

{
  "id": 1,
  "header": {
    "id": 1,
    "color": "blue",
    "title": "Some title"
  },
  "content": null
}

So, basically, a Header was created inside the Post and returned as part of the Post.

Also, if we need to GET the header for Post#1:

GET api/posts/1/header

 {
   "id": 1,
   "color": "blue",
   "title": "Some title"
}

So here only the Header is returned.