问:
Why do some online Python compilers not allow me to enter an input?
I found quite a few examples of how to use input in Python 3. I even directly copied examples from videos to online python compilers and I always get an EOF error on the input line.

For example:

```<code>password = input("please enter password... ")
</code>```

it won't even let me put an input and end the program. Did a rule change?

答:
No, the input rules did not change.

It's just those type of online Python interpreters expect you to provide the input values before you actually run the program. There is no prompt for the input value, where they wait for you to enter something. Instead, they automatically read what you put for STDIN and then pass it to your program.

In https://onecompiler.com:

OneCompiler's python online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab.

In https://www.tutorialspoint.com:

I would say it's better to learn how to run your programs locally, especially if you are writing programs that get or read multiple user inputs. For example, in the images above, you'll have to add some unnecessary code to print out the name on a separate line or to handle multiple input's. On local, the same code works (and looks) better:

$ cat main.py
name = input("What's your name? ")
print(name)

$ python3 main.py
What's your name? gino
gino
```

Body:
I found quite a few examples of how to use input in Python 3. I even directly copied examples from videos to online python compilers and I always get an EOF error on the input line.

For example:

password = input("please enter password... ")

it won't even let me put an input and end the program. Did a rule change?


来源: stackexchange

问:
React Ionic Modal not closing when button clicked
I used the Ionic docs' guide on using boolean state to determine when to open or close my modal.
When card is clicked, it sets state to open the modal, but when the close icon is pressed it does not change the state back to false or close the modal.
Would it be possible if I created a separate component to handle this behaviour?</p>
```<code>import { useState } from "react";
import {
  IonCard,
  IonGrid,
  IonCardHeader,
  IonCardTitle,
  IonCardSubtitle,
  IonText,
  IonCardContent,
  IonImg,
  IonRow,
  IonCol,
  IonAvatar,
  IonModal,
  IonHeader,
  IonToolbar,
  IonIcon,
  IonTitle,
} from "@ionic/react";
import { closeOutline, closeSharp } from "ionicons/icons";

import "./UserCard.css";

type UserCardProps = {
  id: number;
  name: string;
  icon: string;
  email: string;
  country: string;
  image: string;
  description: string;
};

export const UserCard = (props: UserCardProps) => {
  const [detailModal, setDetailModal] = useState({ isOpen: false });

  const handleClose = () => {
    console.log(`Value before setDetailModal: ${detailModal.isOpen}`);
    setDetailModal({ isOpen: false });
    console.log(`Value after setDetailModal: ${detailModal.isOpen}`);
  };
  return (
    <IonCard
      onClick={() => setDetailModal({ isOpen: true })}
      id={`${props.name}Modal`}
    >
      {/* When card clicked, open modal */}
      <IonModal isOpen={detailModal.isOpen}>
        <IonHeader>
          <IonToolbar mode="ios" className="ion-padding">
            <IonIcon
              slot="start"
              ios={closeOutline}
              md={closeSharp}
              onClick={handleClose} // Modal currently does not close when clicked
            />
            <IonTitle className="ionTextCenter">{props.name}</IonTitle>
          </IonToolbar>
        </IonHeader>

        {/* Detailed Modal component */}
        <IonCard id="detailModal">
          <IonCardHeader>
            <IonImg src={props.image} />
            <IonGrid>
              <IonRow>
                <IonCol size="3">
                  <IonAvatar>
                    <img src={props.icon} />
                  </IonAvatar>
                </IonCol>
                <IonCol size="9">
                  <IonCardTitle>{props.name}</IonCardTitle>
                  <IonCardSubtitle>{props.email}</IonCardSubtitle>
                </IonCol>
              </IonRow>
            </IonGrid>
          </IonCardHeader>
          <IonCardContent>
            <IonText>
              <p>This photo was taken in: {props.country}</p>
            </IonText>
          </IonCardContent>
        </IonCard>
      </IonModal>
      {/* Detailed Modal component end */}

      {/* Card component */}
      <IonCardHeader className="card-header">
        <IonGrid>
          <IonRow>
            <IonCol size="3">
              <IonAvatar>
                <img src={props.icon} />
              </IonAvatar>
            </IonCol>
            <IonCol size="9">
              <IonCardTitle>{props.name}</IonCardTitle>
              <IonCardSubtitle>{props.email}</IonCardSubtitle>
            </IonCol>
          </IonRow>
        </IonGrid>
      </IonCardHeader>
      <IonCardContent>
        <img src={props.image} className="center-img" />
        <IonText className="ion-text-center ion-margin">
          <h2 className="subheading">{props.country}</h2>
        </IonText>
        <IonImg className="character-img"></IonImg>
        {props.description}
      </IonCardContent>
      {/* Card component end */}
    </IonCard>
  );
};
</code>```

答:
Can you try to use an arrow function with handle close?

Check out
https://reactjs.org/docs/faq-functions.html

```<code><IonIcon
              slot="start"
              ios={closeOutline}
              md={closeSharp}
              onClick={() => handleClose()}
            />
</code>```

Check out this link too!
https://reactjs.org/docs/handling-events.html

ContentLicense: CC BY-SA 4.0

Body:
I used the Ionic docs' guide on using boolean state to determine when to open or close my modal.
When card is clicked, it sets state to open the modal, but when the close icon is pressed it does not change the state back to false or close the modal.
Would it be possible if I created a separate component to handle this behaviour?

import { useState } from "react";
import {
  IonCard,
  IonGrid,
  IonCardHeader,
  IonCardTitle,
  IonCardSubtitle,
  IonText,
  IonCardContent,
  IonImg,
  IonRow,
  IonCol,
  IonAvatar,
  IonModal,
  IonHeader,
  IonToolbar,
  IonIcon,
  IonTitle,
} from "@ionic/react";
import { closeOutline, closeSharp } from "ionicons/icons";

import "./UserCard.css";

type UserCardProps = {
  id: number;
  name: string;
  icon: string;
  email: string;
  country: string;
  image: string;
  description: string;
};

export const UserCard = (props: UserCardProps) => {
  const [detailModal, setDetailModal] = useState({ isOpen: false });

  const handleClose = () => {
    console.log(`Value before setDetailModal: ${detailModal.isOpen}`);
    setDetailModal({ isOpen: false });
    console.log(`Value after setDetailModal: ${detailModal.isOpen}`);
  };
  return (
    <IonCard
      onClick={() => setDetailModal({ isOpen: true })}
      id={`${props.name}Modal`}
    >
      {/* When card clicked, open modal */}
      <IonModal isOpen={detailModal.isOpen}>
        <IonHeader>
          <IonToolbar mode="ios" className="ion-padding">
            <IonIcon
              slot="start"
              ios={closeOutline}
              md={closeSharp}
              onClick={handleClose} // Modal currently does not close when clicked
            />
            <IonTitle className="ionTextCenter">{props.name}</IonTitle>
          </IonToolbar>
        </IonHeader>

        {/* Detailed Modal component */}
        <IonCard id="detailModal">
          <IonCardHeader>
            <IonImg src={props.image} />
            <IonGrid>
              <IonRow>
                <IonCol size="3">
                  <IonAvatar>

                  </IonAvatar>
                </IonCol>
                <IonCol size="9">
                  <IonCardTitle>{props.name}</IonCardTitle>
                  <IonCardSubtitle>{props.email}</IonCardSubtitle>
                </IonCol>
              </IonRow>
            </IonGrid>
          </IonCardHeader>
          <IonCardContent>
            <IonText>

This photo was taken in: {props.country}

            </IonText>
          </IonCardContent>
        </IonCard>
      </IonModal>
      {/* Detailed Modal component end */}

      {/* Card component */}
      <IonCardHeader className="card-header">
        <IonGrid>
          <IonRow>
            <IonCol size="3">
              <IonAvatar>

              </IonAvatar>
            </IonCol>
            <IonCol size="9">
              <IonCardTitle>{props.name}</IonCardTitle>
              <IonCardSubtitle>{props.email}</IonCardSubtitle>
            </IonCol>
          </IonRow>
        </IonGrid>
      </IonCardHeader>
      <IonCardContent>

        <IonText className="ion-text-center ion-margin">

{props.country}

        </IonText>
        <IonImg className="character-img"></IonImg>
        {props.description}
      </IonCardContent>
      {/* Card component end */}
    </IonCard>
  );
};

Body:
Can you try to use an arrow function with handle close?

Check out
https://reactjs.org/docs/faq-functions.html

<IonIcon
              slot="start"
              ios={closeOutline}
              md={closeSharp}
              onClick={() => handleClose()}
            />

Check out this link too!
https://reactjs.org/docs/handling-events.html


问:
Android studio not showing project files
Please I have been working on a flutter project on android studio, and at one point I found myself with this situation, the project files on the left is not showing, there is this loading icon

enter image description here

答: Android Studio started opening my Flutter project as an Android-only project for some reason. Deleting the .idea folder at the Flutter project root removes all the IDE settings. Reopening the project after that fixed it for me.


问:
Where can one find the C89/C90 standards in PDF format?
I’m looking for a free copy version of the C89/C90 standard, but I can’t find it anywhere! Why is so hard to find it?

C99 and C11 standards are very easy to get a copy of on Internet. Even in the Stack Overflow questions Where do I find the current C or C++ standard documents? and The C Standard, Obtaining the Standard don’t contain what I’m looking for.

Web searches didn’t helped either, nor did Open Standards.

答:
C89/C90:

https://www.yodaiken.com/wp-content/uploads/2021/05/ansi-iso-9899-1990-1.pdf

https://web.archive.org/web/20200909074736/https://www.pdf-archive.com/2014/10/02/ansi-iso-9899-1990-1/ansi-iso-9899-1990-1.pdf

https://web.archive.org/web/20190210174230/http://read.pudn.com/downloads133/doc/565041/ANSI_ISO%2B9899-1990%2B[1].pdf

C99:

http://open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf

C11:

http://open-std.org/JTC1/SC22/WG14/www/docs/n1570.pdf

C17:

http://open-std.org/JTC1/SC22/WG14/www/docs/n2310.pdf

Other documents:

http://open-std.org/JTC1/SC22/WG14/www/projects#9899


问:
How to create "credential" object needed by Firebase web user.reauthenticateWithCredential() method?
The (unclear) example in the new docs:

```<code>var user = firebase.auth().currentUser;
var credential;
// Prompt the user to re-provide their sign-in credentials
user.reauthenticateWithCredential(credential).then(function() {
</code>```

How should I create this credential object?

I tried:

reauthenticateWithCredential(email, password) (like the login method)

reauthenticateWithCredential({ email, password }) (the docs mention one argument only)

No luck :(

PS: I don't count the hours wasted searching for relevant info in the new docs... I miss so much the fabulous firebase.com docs, but wanted to switch to v3 or superior for firebase.storage...

答:
With the new firebase version 9.*</p>
```<code>import {
  EmailAuthProvider,
  getAuth,
  reauthenticateWithCredential,
} from "firebase/auth";

const auth = getAuth();

let credential = EmailAuthProvider.credential(
                  auth.currentUser.email,
                  password
                );

reauthenticateWithCredential(auth.currentUser, credential)
.then(result => {
      // User successfully reauthenticated. New ID tokens should be valid.
    })
</code>```

Body:
The (unclear) example in the new docs:

var user = firebase.auth().currentUser;
var credential;
// Prompt the user to re-provide their sign-in credentials
user.reauthenticateWithCredential(credential).then(function() {

How should I create this credential object?

I tried:

reauthenticateWithCredential(email, password) (like the login method)

reauthenticateWithCredential({ email, password }) (the docs mention one argument only)

No luck :(

PS: I don't count the hours wasted searching for relevant info in the new docs... I miss so much the fabulous firebase.com docs, but wanted to switch to v3 or superior for firebase.storage...

Body:
With the new firebase version 9.*

import {
  EmailAuthProvider,
  getAuth,
  reauthenticateWithCredential,
} from "firebase/auth";

const auth = getAuth();

let credential = EmailAuthProvider.credential(
                  auth.currentUser.email,
                  password
                );

reauthenticateWithCredential(auth.currentUser, credential)
.then(result => {
      // User successfully reauthenticated. New ID tokens should be valid.
    })


问:
Angular: How to pass an inline style to component
I have created a custom component. The component's HTML scaffolding contains very simple HTML.

```<code><!-- Generated template for the MyComponent component -->
<div>
  {{text}}
</div>
</code>```

But adding a style like this did not work.

```<code><my-component style="height:300px; background:gray;"></my-component>
</code>```

I think I need to pass that style to the
. But how?

答:
You can also use Variable/Prop inside the styling like this:

```<code><button [ngStyle]="{backgroundColor: variableNameOrPropNameHere}">{{text}}</button>
</code>```

Note, you can also MIX them in the same code:

```<code><button style="padding: 10px" [ngStyle]="{backgroundColor: variableNameOrPropNameHere}">{{text}}</button>
</code>```

because default inline styling is a bit standard and faster to type and is similar to standard CSS, while ngStyle is more like React inline styling.

Just to have couple of options  =)

ContentLicense: CC BY-SA 3.0

Body:
I have created a custom component. The component's HTML scaffolding contains very simple HTML.

  {{text}}

But adding a style like this did not work.

<my-component style="height:300px; background:gray;"></my-component>

I think I need to pass that style to the
. But how?

Body:
You can also use Variable/Prop inside the styling like this:

<button [ngStyle]="{backgroundColor: variableNameOrPropNameHere}">{{text}}</button>

Note, you can also MIX them in the same code:

<button style="padding: 10px" [ngStyle]="{backgroundColor: variableNameOrPropNameHere}">{{text}}</button>

because default inline styling is a bit standard and faster to type and is similar to standard CSS, while ngStyle is more like React inline styling.

Just to have couple of options  =)


问:
Combine row values into character vector by condition
I have a data.frame where values are repeated in col1.

```<code>col1 <- c("A", "A", "B", "B", "C")
col2 <- c(1995, 1997, 1999, 2000, 2005)

df <- data.frame(col1, col2)
</code>```

I want to combine values in col2 that correspond to the same letter in col1 into one cell, so that col2 shows a range of values for a particular letter in col1. I do this by splitting the data.frame by col1, applying fun, and binding the split data.frames back together.

```<code>library(tidyverse)

split_df <- split(df, df$col1)

fun <- function(df) {

  if (length(unique(df$col2)) > 1) {

    df$col2 <- paste(min(df$col2),
                     max(df$col2),
                     sep = "-")

    df <- distinct(df)

  }

  return(df)
}

split_df <- lapply(split_df, fun)

df <- do.call(rbind, split_df)
</code>```

This works, but I am wondering if there is a more intuitive or more efficient solution?

答:
One option would be the tidyverse, where you can accomplish this a little more succinctly. The basic idea is the same:

```<code>library(tidyverse)

new.result <- df %>%
  group_by(col1) %>%
  summarize(
    col2 = ifelse(n() == 1, as.character(col2), paste(min(col2), max(col2), sep = '-'))
  )

  col1  col2
  <chr> <chr>
1 A     1995-1997
2 B     1999-2000
3 C     2005
</code>```

A different (but possibly overcomplicated) approach assumes that you have at most two years per grouping. We can pivot the start and end years into their own columns, and then paste them together directly. This requires a little more data transformation but avoids having to check explicitly for groups with 1 year:

```<code>df %>%
  group_by(col1) %>%
  mutate(n = row_number()) %>%
  pivot_wider(names_from = n, values_from = col2) %>%
  rowwise() %>%
  mutate(
    vec = list(c(`1`, `2`)),
    col2 = paste(vec[!is.na(vec)], collapse = '-')
  ) %>%
  select(col1, col2)
</code>```

Body:
I have a data.frame where values are repeated in col1.

col1 <- c("A", "A", "B", "B", "C")
col2 <- c(1995, 1997, 1999, 2000, 2005)

df <- data.frame(col1, col2)

I want to combine values in col2 that correspond to the same letter in col1 into one cell, so that col2 shows a range of values for a particular letter in col1. I do this by splitting the data.frame by col1, applying fun, and binding the split data.frames back together.

library(tidyverse)

split_df <- split(df, df$col1)

fun <- function(df) {

  if (length(unique(df$col2)) > 1) {

    df$col2 <- paste(min(df$col2),
                     max(df$col2),
                     sep = "-")

    df <- distinct(df)

  }

  return(df)
}

split_df <- lapply(split_df, fun)

df <- do.call(rbind, split_df)

This works, but I am wondering if there is a more intuitive or more efficient solution?

Body:
One option would be the tidyverse, where you can accomplish this a little more succinctly. The basic idea is the same:

library(tidyverse)

new.result <- df %>%
  group_by(col1) %>%
  summarize(
    col2 = ifelse(n() == 1, as.character(col2), paste(min(col2), max(col2), sep = '-'))
  )

  col1  col2
  <chr> <chr>
1 A     1995-1997
2 B     1999-2000
3 C     2005

A different (but possibly overcomplicated) approach assumes that you have at most two years per grouping. We can pivot the start and end years into their own columns, and then paste them together directly. This requires a little more data transformation but avoids having to check explicitly for groups with 1 year:

df %>%
  group_by(col1) %>%
  mutate(n = row_number()) %>%
  pivot_wider(names_from = n, values_from = col2) %>%
  rowwise() %>%
  mutate(
    vec = list(c(`1`, `2`)),
    col2 = paste(vec[!is.na(vec)], collapse = '-')
  ) %>%
  select(col1, col2)


问:
Python Multiply Matrix by Vector of Matrices
Does anybody know of a way (preferably using numpy or something similar) to multiply a matrix by a vector of matrices and obtain the desired product shown below? Basically the idea is to follow the normal rules of matrix multplication of a matrix and a vector, only the elements of the vector are matrices themselves and not numbers.

答:
Is this what you want to calculate:

```<code># Define two matrices
A = np.arange(9).reshape(3, 3)
B = np.arange(9, 18).reshape(3, 3)

# First calculate the desired result:
rows = []
for i in range(3):
    rows.append([A[i, j] * B for j in range(3)])
result = np.stack(rows).sum(axis=1)
assert(result.shape == (3, 3, 3))
print(result)

[[[ 27  30  33]
  [ 36  39  42]
  [ 45  48  51]]

 [[108 120 132]
  [144 156 168]
  [180 192 204]]

 [[189 210 231]
  [252 273 294]
  [315 336 357]]]
</code>```

Is this correct?

If so, then here is the same calculation using numpy's einsum function:

```<code>C = np.array([B] * 3)  # shape (3, 3, 3)
result = np.einsum("ij,jkl->ikl", A, C)
</code>```

Body:
Is this what you want to calculate:

# Define two matrices
A = np.arange(9).reshape(3, 3)
B = np.arange(9, 18).reshape(3, 3)

# First calculate the desired result:
rows = []
for i in range(3):
    rows.append([A[i, j] * B for j in range(3)])
result = np.stack(rows).sum(axis=1)
assert(result.shape == (3, 3, 3))
print(result)

[[[ 27  30  33]
  [ 36  39  42]
  [ 45  48  51]]

 [[108 120 132]
  [144 156 168]
  [180 192 204]]

 [[189 210 231]
  [252 273 294]
  [315 336 357]]]

Is this correct?

If so, then here is the same calculation using numpy's einsum function:

C = np.array([B] * 3)  # shape (3, 3, 3)
result = np.einsum("ij,jkl->ikl", A, C)


问:
How to find all nodes and their links to other nodes by traversing them in both directions (fathers and children)?
I have a client application consuming data from an external API based on a configuration during startup.

Since calculating the necessary data is not easy for me, I tried to fake the implementation and calculate it locally for now.

There are many WorkItems linked to each other and the configuration only knows about the relations to consider.

Some explanations:

Workitem

A workitem has a unique id and a type

e.g.

```<code>{
    id: 1,
    type: "person"
}
</code>```

so you know that Workitem 1 is of type person

Linkrole

A linkrole is a composite key of three keys

The parrent workitem type

The child workitem type

The name of the role

e.g.

```<code>{
    parentWorkItemType: "person",
    childWorkItemType: "house",
    name: "owns",
}
</code>```

which represents Person owns House

Links

The backend knows about the relations, a link between workitems might look like

```<code>{
    /* each link is unique */
    linkRole: {
        parentWorkItemType: "person",
        childWorkItemType: "house",
        name: "owns",
    },
    parentId: 1,
    childId: 2
}
</code>```

so you know that Person 1 owns House 2

Fake prerequisites:

Fake backend

I created some fake data for my calculations. The file backend.js represents the backend / database

```<code>// backend.js

export const workItems = [{
    id: 1,
    type: "car"
}, {
    id: 2,
    type: "car"
}, {
    id: 3,
    type: "bird"
}, {
    id: 4,
    type: "bird"
}, {
    id: 5,
    type: "bird"
}, {
    id: 6,
    type: "invalid"
}, {
    id: 7,
    type: "house"
}, {
    id: 8,
    type: "house"
}, {
    id: 9,
    type: "house",
}, {
    id: 10,
    type: "person",
}];

export const workItemLinks = [{
    linkRole: {
        parentWorkItemType: "car",
        childWorkItemType: "bird",
        name: "isChildOf",
    },
    parentId: 1,
    childId: 3
}, {
    linkRole: {
        parentWorkItemType: "car",
        childWorkItemType: "bird",
        name: "isChildOf",
    },
    parentId: 1,
    childId: 4
}, {
    linkRole: {
        parentWorkItemType: "bird",
        childWorkItemType: "house",
        name: "with",
    },
    parentId: 3,
    childId: 7
}, {
    linkRole: {
        parentWorkItemType: "bird",
        childWorkItemType: "house",
        name: "with",
    },
    parentId: 3,
    childId: 8
}, {
    linkRole: {
        parentWorkItemType: "person",
        childWorkItemType: "car",
        name: "owns",
    },
    parentId: 10,
    childId: 1
}, {
    linkRole: {
        parentWorkItemType: "car",
        childWorkItemType: "car",
        name: "references",
    },
    parentId: 1,
    childId: 2
}];
</code>```

Fake API

I created some methods inside the file api.js to fake an API asking the backend for data.

Important sidenote: These methods just help me to find the data I need. I can add more "helpers" if needed (In the real world I can ask to add more API endpoints) so everything can be queried. Please feel free to modify the "Fake API".

```<code>// api.js

import { workItems, workItemLinks } from "./backend.js";

export function getWorkItemsByType(workItemType) {
    return workItems.filter(workItem => workItem.type === workItemType);
}

export function getWorkItemsByIds(workItemIds) {
    return workItems.filter(workItem => workItemIds.some(workItemId => workItemId === workItem.id));
}

export function getWorkItemLinksByLinkRoleAndLeftSideIds(linkRole, leftSideIds, leftSideIsParentSide) {
    return workItemLinks.filter(workItemLink => {

        // Pseudo equality check

        if (workItemLink.linkRole.parentWorkItemType === linkRole.parentWorkItemType &&
            workItemLink.linkRole.childWorkItemType === linkRole.childWorkItemType &&
            workItemLink.linkRole.name === linkRole.name) {
            const leftSideIdInLink = leftSideIsParentSide ? workItemLink.parentId : workItemLink.childId;

            // Return this link if it matches with the left side id ( you're looking for the right side id )

            return leftSideIds.some(leftSideId => leftSideId === leftSideIdInLink);
        }

        return false;
    });
}
</code>```

Fake configuration

I created definitions inside configuration.js to start the calculations based on those

```<code>// configuration.js

export const definitions = [
    {                                           // fetch linked birds from every root car
        linkRole: {
            parentWorkItemType: "car",
            childWorkItemType: "bird",
            name: "isChildOf",
        }
    },
    {                                           // !! Root Element !! Fetch work items based on type
        workItemType: "car",
        isRootWorkItem: true
    },
    {                                            // fetch linked houses from every bird ( car - bird - house )
        linkRole: {
            parentWorkItemType: "bird",
            childWorkItemType: "house",
            name: "with",
        }
    },
    {                                             // fetch every person from every car ( person - car )
        linkRole: {
            parentWorkItemType: "person",
            childWorkItemType: "car",
            name: "owns",
        }
    },
    {                                          // Self reference, fetch linked cars from every root car
        linkRole: {
            parentWorkItemType: "car",
            childWorkItemType: "car",
            name: "references",
        }
    },
];
</code>```

Problem to solve:

I am looking for a performant way to fetch every related link and workitem from the backend based on the chain of relations starting with each root item.

Expected output based on the configuration:

```<code>export const workItems = [{
    id: 1,
    type: "car"
}, {
    id: 2,
    type: "car"
}, {
    id: 3,
    type: "bird"
}, {
    id: 4,
    type: "bird"
}, /* no car is linked to bird 5, no links for invalid 6 */ {
    id: 7,
    type: "house"
}, {
    id: 8,
    type: "house"
}, /* no bird is linked to house 9 */ {
    id: 10,
    type: "person",
}];

/* based on the configuration every workItemLink from the backend got fetched */
</code>```

My first implementation approach:

```<code>import { inspect } from "util";

import { getWorkItemsByType, getWorkItemsByIds, getWorkItemLinksByLinkRoleAndLeftSideIds } from "./api.js";
import { definitions } from "./configuration.js";

// Find the root definition

const { workItemType: rootWorkItemType } = definitions.find(definition => definition.isRootWorkItem);

// Fetch all the root workitems and initialize the store holding unique workitems

const workItems = getWorkItemsByType(rootWorkItemType); // will hold car 1 and car 2

const initialWorkItemIds = workItems.map(workItem => workItem.id);

const workItemIdsToLoad = []; // try to read all missing ids from fetched links and fetch all the workitems at once later on

const workItemLinks = []; // global store for links

const definitionsToTraverse = definitions.filter(definition => definition.linkRole !== undefined); // do not consider the root definition

run(initialWorkItemIds, rootWorkItemType, definitionsToTraverse, workItemIdsToLoad, workItemLinks);

const missingWorkItemIdsToLoad = workItemIdsToLoad.filter(workItemIdToLoad => !rootWorkItemIds.some(rootWorkItemId => rootWorkItemId === workItemIdToLoad)); // filter out all the existing root item ids

const workItemsToAdd = getWorkItemsByIds(missingWorkItemIdsToLoad); // fetch all the missing workitems at once

workItems.push(...workItemsToAdd); // add them to the global store

console.log(inspect({
    workItems,
    workItemLinks
}, false, null, true))

function run(leftSideWorkItemIds, leftSideWorkItemType, definitionsToTraverse, workItemIdsToLoad, workItemLinks) {
    /*

        consider all the defitions from "definitionsToTraverse" directly related to "leftSideWorkItemType"
        remove them from "definitionsToTraverse" to prevent endless loops
        loop backwards so splice won't struggle with the indices

    */

    for (let definitionIndex = definitionsToTraverse.length - 1; definitionIndex >= 0; definitionIndex--) {
        const currentDefinition = definitionsToTraverse[definitionIndex];
        const { linkRole } = currentDefinition;
        const { parentWorkItemType, childWorkItemType } = linkRole;

        const leftSideWorkItemTypeIsParent = parentWorkItemType === leftSideWorkItemType;
        const leftSideWorkItemTypeIsChild = childWorkItemType === leftSideWorkItemType;

        // Check the direct relation

        if (leftSideWorkItemTypeIsParent || leftSideWorkItemTypeIsChild) {
            // Remove the inspected definition

            definitionsToTraverse.splice(definitionIndex, 1);

            const relatedWorkItemLinks = getWorkItemLinksByLinkRoleAndLeftSideIds(linkRole, leftSideWorkItemIds, leftSideWorkItemTypeIsParent);

            // store all the right side workitem IDs for the next run

            const rightSideWorkItemIds = [];

            for (let relatedWorkItemLinkIndex = 0; relatedWorkItemLinkIndex < relatedWorkItemLinks.length; relatedWorkItemLinkIndex++) {
                const relatedWorkItemLink = relatedWorkItemLinks[relatedWorkItemLinkIndex];

                // Process the link if not processed yet

                if (!workItemLinks.some(workItemLink => /* !!! pseudo equality check !!! */
                        workItemLink.linkRole.parentWorkItemType === relatedWorkItemLink.linkRole.parentWorkItemType &&
                        workItemLink.linkRole.childWorkItemType === relatedWorkItemLink.linkRole.childWorkItemType &&
                        workItemLink.linkRole.name === relatedWorkItemLink.linkRole.name &&
                        workItemLink.parentId === relatedWorkItemLink.parentId &&
                        workItemLink.childId === relatedWorkItemLink.childId)) {

                    // Push the link to the store

                    workItemLinks.push(relatedWorkItemLink);

                    // Get the right side id from the link

                    const rightSideWorkItemId = leftSideWorkItemTypeIsParent ? relatedWorkItemLink.childId : relatedWorkItemLink.parentId;

                    rightSideWorkItemIds.push(rightSideWorkItemId);

                    // Push the id to the store if it doesn't exist

                    if (!workItemIdsToLoad.some(workItemIdToLoad => workItemIdToLoad === rightSideWorkItemId)) {
                        workItemIdsToLoad.push(rightSideWorkItemId);
                    }
                }
            }

            // Find the opposite workitem type of the current definition

            const rightSideWorkItemType = leftSideWorkItemTypeIsParent ? childWorkItemType : parentWorkItemType;

            // Run again but use this definition as the previous one

            run(rightSideWorkItemIds, rightSideWorkItemType, definitionsToTraverse, workItemIdsToLoad, workItemLinks);
        }
    }
}
</code>```

The problem is that my approach crashes because the backwards loop even runs if definitionsToTraverse is empty. And I'm mutating the arrays from the parameters directly, I think I shouldn't do that.

So any help would be appreciated a lot!

答:
General Considerations

Suggest pushing most of the work onto the server, as presumably the workItems and workItemLinks will be comprised of a large number of records.  If the work of traversing the tree of workItems is left to the client making individual API calls, then network latency comes into play...

Data Structure

Suggest normalizing the data as follows:

WorkItems - No change.

WorkItemLinks - Reduce attributes to parentId and childId, which is essentially a many-to-many entity with the WorkItems entity.

Definitions - Flatten to parentWorkItemType, childWorkItemType, and name.  Root entries are handled by setting parentWorkItemType to null.

Note also that realistically, the need for Definitions is likely not necessary when traversing WorkItemLinks, as presumably the entries within the WorkItemLinks, when created, were only permitted to be created if the relationship between the parentId type and childId type conformed to the Defintions.  If indeed this is the case, then the proposed code can likely be simplified further...

Proposed APIs

The solution below proposes two (2) APIs:

getDefinitionChain( rootWorkItemType ) - Given a rootWorkItemType (eg, "car"), this API traverses the children and parents of the Definition entity, and returns all the related workItemTypes.

getWorkItemChain( rootWorkItemType ) - Initially calls getDefinitionChain to identify the related workItemTypes, and then traverses workItems starting with the rootWorkItemType.

Again, the concept being that these APIs are server side, reducing the chattiness between the client and server...

const workItems = [{"id":1,"type":"car"},{"id":2,"type":"car"},{"id":3,"type":"bird"},{"id":4,"type":"bird"},{"id":5,"type":"bird"},{"id":6,"type":"invalid"},{"id":7,"type":"house"},{"id":8,"type":"house"},{"id":9,"type":"house"},{"id":10,"type":"person"}];

const workItemLinks = [
  {
    "parentId": 1,
    "childId": 3
  },
  {
    "parentId": 1,
    "childId": 4
  },
  {
    "parentId": 3,
    "childId": 7
  },
  {
    "parentId": 3,
    "childId": 8
  },
  {
    "parentId": 10,
    "childId": 1
  },
  {
    "parentId": 1,
    "childId": 2
  }
];

const definitions = [
  {
    "parentWorkItemType": "car",
    "childWorkItemType": "bird",
    "name": "isChildOf"
  },
  {
    "parentWorkItemType": null,
    "childWorkItemType": "car",
    "name": "root"
  },
  {
    "parentWorkItemType": "bird",
    "childWorkItemType": "house",
    "name": "with"
  },
  {
    "parentWorkItemType": "person",
    "childWorkItemType": "car",
    "name": "owns"
  },
  {
    "parentWorkItemType": "car",
    "childWorkItemType": "car",
    "name": "references"
  }
];

function getDefinitionChain( rootWorkItemType ) {

  let alreadyVisitedType = new Set();
  let definitionChain = [];

  function recurse( workItemType ) {

    // Visit the children types...
    let nodeTypeChildList = definitions.filter( def => def.parentWorkItemType === workItemType );

    for ( let childType of nodeTypeChildList ) {
      if ( !alreadyVisitedType.has( childType.childWorkItemType ) ) {
        alreadyVisitedType.add( childType.childWorkItemType );
        definitionChain.push( childType.childWorkItemType );
        recurse( childType.childWorkItemType );
      }
    }

    // Visit the parent types...
    let nodeTypeParentList = definitions.filter( def => def.childWorkItemType === workItemType );

    for ( let parentType of nodeTypeParentList ) {
      // Don't go up the definition chain if parent is null.
      if ( parentType.parentWorkItemType && !alreadyVisitedType.has( parentType.parentWorkItemType ) ) {
        alreadyVisitedType.add( parentType.parentWorkItemType );
        definitionChain.push( parentType.parentWorkItemType );
        recurse( parentType.parentWorkItemType );
      }
    }

  }

  recurse( rootWorkItemType )
  if ( !alreadyVisitedType.has( rootWorkItemType ) ) {
    definitionChain.push( rootWorkItemType );
  }

  return definitionChain;

}

function getWorkItemChain( rootWorkItemType ) {

  // Get the list of allowable definitions...
  let allowableDefinitions = new Set( getDefinitionChain( rootWorkItemType ) );

  // Now, traverse the WorkItems tree, ensuring that they are in the WorkItemType list...
  let wim = new Map();

  function recurse( workItemCandidates ) {

    for ( let workItem of workItemCandidates ) {
      // Is this a workItemType that conforms to our allowable definitions?
      if ( allowableDefinitions.has( workItem.type ) ) {
        // If never having traversed this WorkItem, then let's traverse the children and parents.
        if ( !wim.has( workItem.id ) ) {
          wim.set( workItem.id, workItem );

          // Get the list of WorkItems that are children to the workItem.id.
          recurse( workItemLinks.filter( wix => wix.parentId === workItem.id ).map( wil => workItems.find( wif => wif.id === wil.childId )) );

          // Get the list of WorkItems that are parents to the workItem.id.
          recurse( workItemLinks.filter( wix => wix.childId === workItem.id ).map( wil => workItems.find( wif => wif.id === wil.parentId )) );
        }
      }
    }

  }

  // Start with all the workItems that are of type rootWorkItemType.
  recurse( workItems.filter( wi => wi.type === rootWorkItemType ) );

  return [...wim.values()];

}

console.log( 'WorkItem Types in Definitions with a root of "car".' );
let definitionChain = getDefinitionChain( 'car' );
console.log( definitionChain );

console.log( 'WorkItems with a root of "car"' );
let workItemChain = getWorkItemChain( 'car' );
console.log( workItemChain );```

Body:
I have a client application consuming data from an external API based on a configuration during startup.

Since calculating the necessary data is not easy for me, I tried to fake the implementation and calculate it locally for now.

There are many WorkItems linked to each other and the configuration only knows about the relations to consider.

Some explanations:

Workitem

A workitem has a unique id and a type

e.g.

{
    id: 1,
    type: "person"
}

so you know that Workitem 1 is of type person

Linkrole

A linkrole is a composite key of three keys

The parrent workitem type

The child workitem type

The name of the role

e.g.

{
    parentWorkItemType: "person",
    childWorkItemType: "house",
    name: "owns",
}

which represents Person owns House

Links

The backend knows about the relations, a link between workitems might look like

{
    /* each link is unique */
    linkRole: {
        parentWorkItemType: "person",
        childWorkItemType: "house",
        name: "owns",
    },
    parentId: 1,
    childId: 2
}

so you know that Person 1 owns House 2

Fake prerequisites:

Fake backend

I created some fake data for my calculations. The file backend.js represents the backend / database

// backend.js

export const workItems = [{
    id: 1,
    type: "car"
}, {
    id: 2,
    type: "car"
}, {
    id: 3,
    type: "bird"
}, {
    id: 4,
    type: "bird"
}, {
    id: 5,
    type: "bird"
}, {
    id: 6,
    type: "invalid"
}, {
    id: 7,
    type: "house"
}, {
    id: 8,
    type: "house"
}, {
    id: 9,
    type: "house",
}, {
    id: 10,
    type: "person",
}];

export const workItemLinks = [{
    linkRole: {
        parentWorkItemType: "car",
        childWorkItemType: "bird",
        name: "isChildOf",
    },
    parentId: 1,
    childId: 3
}, {
    linkRole: {
        parentWorkItemType: "car",
        childWorkItemType: "bird",
        name: "isChildOf",
    },
    parentId: 1,
    childId: 4
}, {
    linkRole: {
        parentWorkItemType: "bird",
        childWorkItemType: "house",
        name: "with",
    },
    parentId: 3,
    childId: 7
}, {
    linkRole: {
        parentWorkItemType: "bird",
        childWorkItemType: "house",
        name: "with",
    },
    parentId: 3,
    childId: 8
}, {
    linkRole: {
        parentWorkItemType: "person",
        childWorkItemType: "car",
        name: "owns",
    },
    parentId: 10,
    childId: 1
}, {
    linkRole: {
        parentWorkItemType: "car",
        childWorkItemType: "car",
        name: "references",
    },
    parentId: 1,
    childId: 2
}];

Fake API

I created some methods inside the file api.js to fake an API asking the backend for data.

Important sidenote: These methods just help me to find the data I need. I can add more "helpers" if needed (In the real world I can ask to add more API endpoints) so everything can be queried. Please feel free to modify the "Fake API".

// api.js

import { workItems, workItemLinks } from "./backend.js";

export function getWorkItemsByType(workItemType) {
    return workItems.filter(workItem => workItem.type === workItemType);
}

export function getWorkItemsByIds(workItemIds) {
    return workItems.filter(workItem => workItemIds.some(workItemId => workItemId === workItem.id));
}

export function getWorkItemLinksByLinkRoleAndLeftSideIds(linkRole, leftSideIds, leftSideIsParentSide) {
    return workItemLinks.filter(workItemLink => {

        // Pseudo equality check

        if (workItemLink.linkRole.parentWorkItemType === linkRole.parentWorkItemType &&
            workItemLink.linkRole.childWorkItemType === linkRole.childWorkItemType &&
            workItemLink.linkRole.name === linkRole.name) {
            const leftSideIdInLink = leftSideIsParentSide ? workItemLink.parentId : workItemLink.childId;

            // Return this link if it matches with the left side id ( you're looking for the right side id )

            return leftSideIds.some(leftSideId => leftSideId === leftSideIdInLink);
        }

        return false;
    });
}

Fake configuration

I created definitions inside configuration.js to start the calculations based on those

// configuration.js

export const definitions = [
    {                                           // fetch linked birds from every root car
        linkRole: {
            parentWorkItemType: "car",
            childWorkItemType: "bird",
            name: "isChildOf",
        }
    },
    {                                           // !! Root Element !! Fetch work items based on type
        workItemType: "car",
        isRootWorkItem: true
    },
    {                                            // fetch linked houses from every bird ( car - bird - house )
        linkRole: {
            parentWorkItemType: "bird",
            childWorkItemType: "house",
            name: "with",
        }
    },
    {                                             // fetch every person from every car ( person - car )
        linkRole: {
            parentWorkItemType: "person",
            childWorkItemType: "car",
            name: "owns",
        }
    },
    {                                          // Self reference, fetch linked cars from every root car
        linkRole: {
            parentWorkItemType: "car",
            childWorkItemType: "car",
            name: "references",
        }
    },
];

Problem to solve:

I am looking for a performant way to fetch every related link and workitem from the backend based on the chain of relations starting with each root item.

Expected output based on the configuration:

export const workItems = [{
    id: 1,
    type: "car"
}, {
    id: 2,
    type: "car"
}, {
    id: 3,
    type: "bird"
}, {
    id: 4,
    type: "bird"
}, /* no car is linked to bird 5, no links for invalid 6 */ {
    id: 7,
    type: "house"
}, {
    id: 8,
    type: "house"
}, /* no bird is linked to house 9 */ {
    id: 10,
    type: "person",
}];

/* based on the configuration every workItemLink from the backend got fetched */

My first implementation approach:

import { inspect } from "util";

import { getWorkItemsByType, getWorkItemsByIds, getWorkItemLinksByLinkRoleAndLeftSideIds } from "./api.js";
import { definitions } from "./configuration.js";

// Find the root definition

const { workItemType: rootWorkItemType } = definitions.find(definition => definition.isRootWorkItem);

// Fetch all the root workitems and initialize the store holding unique workitems

const workItems = getWorkItemsByType(rootWorkItemType); // will hold car 1 and car 2

const initialWorkItemIds = workItems.map(workItem => workItem.id);

const workItemIdsToLoad = []; // try to read all missing ids from fetched links and fetch all the workitems at once later on

const workItemLinks = []; // global store for links

const definitionsToTraverse = definitions.filter(definition => definition.linkRole !== undefined); // do not consider the root definition

run(initialWorkItemIds, rootWorkItemType, definitionsToTraverse, workItemIdsToLoad, workItemLinks);

const missingWorkItemIdsToLoad = workItemIdsToLoad.filter(workItemIdToLoad => !rootWorkItemIds.some(rootWorkItemId => rootWorkItemId === workItemIdToLoad)); // filter out all the existing root item ids

const workItemsToAdd = getWorkItemsByIds(missingWorkItemIdsToLoad); // fetch all the missing workitems at once

workItems.push(...workItemsToAdd); // add them to the global store

console.log(inspect({
    workItems,
    workItemLinks
}, false, null, true))

function run(leftSideWorkItemIds, leftSideWorkItemType, definitionsToTraverse, workItemIdsToLoad, workItemLinks) {
    /*

        consider all the defitions from "definitionsToTraverse" directly related to "leftSideWorkItemType"
        remove them from "definitionsToTraverse" to prevent endless loops
        loop backwards so splice won't struggle with the indices

    */

    for (let definitionIndex = definitionsToTraverse.length - 1; definitionIndex >= 0; definitionIndex--) {
        const currentDefinition = definitionsToTraverse[definitionIndex];
        const { linkRole } = currentDefinition;
        const { parentWorkItemType, childWorkItemType } = linkRole;

        const leftSideWorkItemTypeIsParent = parentWorkItemType === leftSideWorkItemType;
        const leftSideWorkItemTypeIsChild = childWorkItemType === leftSideWorkItemType;

        // Check the direct relation

        if (leftSideWorkItemTypeIsParent || leftSideWorkItemTypeIsChild) {
            // Remove the inspected definition

            definitionsToTraverse.splice(definitionIndex, 1);

            const relatedWorkItemLinks = getWorkItemLinksByLinkRoleAndLeftSideIds(linkRole, leftSideWorkItemIds, leftSideWorkItemTypeIsParent);

            // store all the right side workitem IDs for the next run

            const rightSideWorkItemIds = [];

            for (let relatedWorkItemLinkIndex = 0; relatedWorkItemLinkIndex < relatedWorkItemLinks.length; relatedWorkItemLinkIndex++) {
                const relatedWorkItemLink = relatedWorkItemLinks[relatedWorkItemLinkIndex];

                // Process the link if not processed yet

                if (!workItemLinks.some(workItemLink => /* !!! pseudo equality check !!! */
                        workItemLink.linkRole.parentWorkItemType === relatedWorkItemLink.linkRole.parentWorkItemType &&
                        workItemLink.linkRole.childWorkItemType === relatedWorkItemLink.linkRole.childWorkItemType &&
                        workItemLink.linkRole.name === relatedWorkItemLink.linkRole.name &&
                        workItemLink.parentId === relatedWorkItemLink.parentId &&
                        workItemLink.childId === relatedWorkItemLink.childId)) {

                    // Push the link to the store

                    workItemLinks.push(relatedWorkItemLink);

                    // Get the right side id from the link

                    const rightSideWorkItemId = leftSideWorkItemTypeIsParent ? relatedWorkItemLink.childId : relatedWorkItemLink.parentId;

                    rightSideWorkItemIds.push(rightSideWorkItemId);

                    // Push the id to the store if it doesn't exist

                    if (!workItemIdsToLoad.some(workItemIdToLoad => workItemIdToLoad === rightSideWorkItemId)) {
                        workItemIdsToLoad.push(rightSideWorkItemId);
                    }
                }
            }

            // Find the opposite workitem type of the current definition

            const rightSideWorkItemType = leftSideWorkItemTypeIsParent ? childWorkItemType : parentWorkItemType;

            // Run again but use this definition as the previous one

            run(rightSideWorkItemIds, rightSideWorkItemType, definitionsToTraverse, workItemIdsToLoad, workItemLinks);
        }
    }
}

The problem is that my approach crashes because the backwards loop even runs if definitionsToTraverse is empty. And I'm mutating the arrays from the parameters directly, I think I shouldn't do that.

So any help would be appreciated a lot!


问:
What is the difference between var and val in Kotlin?
What is the difference between var and val in Kotlin?

I have gone through this link:

KotlinLang: Properties and Fields

As stated on this link:

The full syntax of a read-only property declaration differs from a
mutable one in two ways: it starts with val instead of var and does
not allow a setter.

But just before there is an example which uses a setter.

```<code>fun copyAddress(address: Address): Address {
    val result = Address() // there's no 'new' keyword in Kotlin
    result.name = address.name // accessors are called
    result.street = address.street
    // ...
    return result
}
</code>```

What is the exact difference between var and val?

Why do we need both?

This is not a duplicate of Variables in Kotlin, differences with Java: 'var' vs. 'val'? as I am asking about the doubt related to the particular example in the documentation and not just in general.

答:
Var is a mutable variable. It is a variable that can be changed to another value. It's similar to declaring a variable in Java.

Val is a read-only thing. It's similar to final in java. A val must be initialized when it is created. This is because it cannot be changed after it is created.

```<code>var test1Var = "Hello"
println(test1Var)
test1Var = "GoodBye"
println(test1Var)
val test2Val = "FinalTestForVal";
println(test2Val);
</code>```

Body:
What is the difference between var and val in Kotlin?

I have gone through this link:

KotlinLang: Properties and Fields

As stated on this link:

The full syntax of a read-only property declaration differs from a
mutable one in two ways: it starts with val instead of var and does
not allow a setter.

But just before there is an example which uses a setter.

fun copyAddress(address: Address): Address {
    val result = Address() // there's no 'new' keyword in Kotlin
    result.name = address.name // accessors are called
    result.street = address.street
    // ...
    return result
}

What is the exact difference between var and val?

Why do we need both?

This is not a duplicate of Variables in Kotlin, differences with Java: 'var' vs. 'val'? as I am asking about the doubt related to the particular example in the documentation and not just in general.

Body:
Var is a mutable variable. It is a variable that can be changed to another value. It's similar to declaring a variable in Java.

Val is a read-only thing. It's similar to final in java. A val must be initialized when it is created. This is because it cannot be changed after it is created.

var test1Var = "Hello"
println(test1Var)
test1Var = "GoodBye"
println(test1Var)
val test2Val = "FinalTestForVal";
println(test2Val);


问:
JSLint Character Unexpected '.'
Atoms's JSLint report is complaining about an unexpected dot of the .toFixed function:

```<code>subTotal = (Math.round(subTotal * 100) / 100).toFixed(2);
</code>```

at line 113, character 50 Unexpected '.'

The code works fine,

Question: Is this a fault with JSLint or have I coded something wrong?

Thanks

答:
jslint doesn't like the dot "." after a naked, parenthesized expression.  adding a Number in front of ( should fix the warning.  the other common-case is adding a String in front of (.

```<code>subTotal = Number(Math.round(subTotal * 100) / 100).toFixed(2);
</code>```

Title: JSLint Character Unexpected '.'

Body:
Atoms's JSLint report is complaining about an unexpected dot of the .toFixed function:

subTotal = (Math.round(subTotal * 100) / 100).toFixed(2);

at line 113, character 50 Unexpected '.'

The code works fine,

Question: Is this a fault with JSLint or have I coded something wrong?

Thanks

Body:
jslint doesn't like the dot "." after a naked, parenthesized expression.  adding a Number in front of ( should fix the warning.  the other common-case is adding a String in front of (.

subTotal = Number(Math.round(subTotal * 100) / 100).toFixed(2);


问:
SQL Query based on value of another table
Suppose That I have Table A and Table B as follow. How would I get my expected outcome ? The filtering should be dynamically based on values in Table A as follow

```<code>SELECT * FROM TableB
WHERE
(Start = 'A' AND End = 'B')
OR (Start = 'C' AND End = 'D')
OR (Start = 'B' AND End = 'A')
</code>```

Table A

```<code>Start End
A     B
C     D
B     A
</code>```

Table B

```<code>ID Start End  Date
1  A     B    2021-01-01
2  A     B    2021-01-01
3  C     D    2021-01-01
4  B     A    2021-01-01
5  C     D    2021-01-01
6  E     A    2021-01-01
6  D     C    2021-01-01
</code>```

Expected Result

```<code>ID Start End  Date
1  A     B    2021-01-01
2  A     B    2021-01-01
3  C     D    2021-01-01
4  B     A    2021-01-01
5  C     D    2021-01-01
</code>```

答:
It's seems a simple join is all that is required?</p>
```<code>select *
from TableB B
inner join TableA A on
    A.Start = B.Start
    and A.End = B.End
</code>```

Body:
Suppose That I have Table A and Table B as follow. How would I get my expected outcome ? The filtering should be dynamically based on values in Table A as follow

SELECT * FROM TableB
WHERE
(Start = 'A' AND End = 'B')
OR (Start = 'C' AND End = 'D')
OR (Start = 'B' AND End = 'A')

Table A

Start End
A     B
C     D
B     A

Table B

ID Start End  Date
1  A     B    2021-01-01
2  A     B    2021-01-01
3  C     D    2021-01-01
4  B     A    2021-01-01
5  C     D    2021-01-01
6  E     A    2021-01-01
6  D     C    2021-01-01

Expected Result

ID Start End  Date
1  A     B    2021-01-01
2  A     B    2021-01-01
3  C     D    2021-01-01
4  B     A    2021-01-01
5  C     D    2021-01-01

Body:
It's seems a simple join is all that is required?

select *
from TableB B
inner join TableA A on
    A.Start = B.Start
    and A.End = B.End


问:
Question about #define statement in Objective-C project
I'm not experienced in C, so I'm not comfortable with this statement in this C / objective-C project.

```<code>#define CBLog(...) NSLog(@"%s [%ld]: %@", basename(__FILE__), __LINE__, [NSString stringWithFormat:__VA_ARGS__])
</code>```

Questions:

the 3 dots (...) are used to indicate CBLog() is a method with parameters ? What do they mean ?

%ld stands for line format ? what's the d in %ld for ?

FILE , LINE and VA_ARGS are default replacement tokens for the C debugger ?

thanks

答:
The ... means the macro accepts any number of arguments.

%ld is a string formatter meaning 'long decimal', where decimal really means integer.

__FILE__ expands to the current file name

__LINE__ expands to the current line number

__VA_ARGS__ expands to the arguments passed to the macro.

The debugger has nothing to do with it.  All of this is the preprocessor, except %ld which is string formatting.

Body:
I'm not experienced in C, so I'm not comfortable with this statement in this C / objective-C project.

#define CBLog(...) NSLog(@"%s [%ld]: %@", basename(__FILE__), __LINE__, [NSString stringWithFormat:__VA_ARGS__])

Questions:

the 3 dots (...) are used to indicate CBLog() is a method with parameters ? What do they mean ?

%ld stands for line format ? what's the d in %ld for ?

FILE , LINE and VA_ARGS are default replacement tokens for the C debugger ?

thanks


问:
How to show hidden pseudo-element with JavaScript
I'm using CSS to hide form elements:

```<code>#main_form #form-field-email, #form-field-realtor_select { display: none;}
#main_form .elementor-select-wrapper::before { display: none; }
</code>```

Then JavaScript to show them with:

```<code>document.getElementById("form-field-first_name").onclick = function(){
document.getElementById('form-field-email').style.display = 'block';
document.getElementById('form-field-realtor_select').style.display = 'block';
</code>```

The problem is with the pseudo-element .elementor-select-wrapper::before which is needed to hide the down arrow in the select element. I need to get the arrow to display using the JavaScript onclick event. I tried document.getElementsByClassName() but that did not work.

You can see the test page here: Test Page. Click First Name or Last Name to reveal fields (more than listed above) and you'll see the down arrow is mission from the select element.

答:
So, it's not possible to select a pseudo element directly, but you can create a set of CSS styles like the following, which will change the ::before element using a "toggleable" class on the parent:

#main_form .elementor-select-wrapper::before {
    display: none;
}

#main_form .elementor-select-wrapper.show-chevron::before {
    display: block;
}
```

When you add (or remove) the .show-chevron class to .elementor-select-wrapper, it should toggle the ::before element.

document.getElementsByClassName('elementor-select-wrapper')[0].classList.add('show-chevron')

Let me know if this works! If not, I can take another look

Body:
I'm using CSS to hide form elements:

#main_form #form-field-email, #form-field-realtor_select { display: none;}
#main_form .elementor-select-wrapper::before { display: none; }

Then JavaScript to show them with:

document.getElementById("form-field-first_name").onclick = function(){
document.getElementById('form-field-email').style.display = 'block';
document.getElementById('form-field-realtor_select').style.display = 'block';

The problem is with the pseudo-element .elementor-select-wrapper::before which is needed to hide the down arrow in the select element. I need to get the arrow to display using the JavaScript onclick event. I tried document.getElementsByClassName() but that did not work.

You can see the test page here: Test Page. Click First Name or Last Name to reveal fields (more than listed above) and you'll see the down arrow is mission from the select element.

Body:
So, it's not possible to select a pseudo element directly, but you can create a set of CSS styles like the following, which will change the ::before element using a "toggleable" class on the parent:

#main_form .elementor-select-wrapper::before {
    display: none;
}

#main_form .elementor-select-wrapper.show-chevron::before {
    display: block;
}

When you add (or remove) the .show-chevron class to .elementor-select-wrapper, it should toggle the ::before element.

document.getElementsByClassName('elementor-select-wrapper')[0].classList.add('show-chevron')

Let me know if this works! If not, I can take another look


问:
Msal4j browser login window never opens
Java Version - OpenJDK 17
OS - Linux Mint 20.1 Ulyssa

I'm trying to implement interactive token acquisition from a JavaFX desktop app and running into some trouble getting the browser window to open in order to login.

MRE (just make sure to update PUBLIC_CLIENT_ID in HelloApplication.java to a valid client id)

In the start function in HelloApplication.java I've setup this example in the docs in my Controller's constructor

```<code>public HelloController() throws MalformedURLException, URISyntaxException {
    PublicClientApplication publicClientApplication =
        PublicClientApplication
        .builder(CLIENT_ID)
        .authority(AUTHORITY)
        .build();

    InteractiveRequestParameters parameters = InteractiveRequestParameters
        .builder(new URI("http://localhost"))
        .scopes(scope)
        .build();

    IAuthenticationResult result = publicClientApplication.acquireToken(parameters).join();
}
</code>```

I would expect that a browser window would open that I could then login with my MS credentials, what actually happens is it never opens a browser window and the .join() on the CompletableFuture never returns.

Is there anything else that needs to be setup in order to get the browser window to open?

答:
I don’t know the Microsoft lib at all, but from looking at the Java sample in this documentation, it says the join() method will:

Try to acquire a token interactively with system browser.

If successful, you should see the token and account information printed out to console.

So your current code would freeze your app until that occurs as you are waiting on the JavaFX thread.

You should acquire the token in a JavaFX Task (research JavaFX concurrency) or some other means (which I don’t know at the moment).

Perhaps you also want to customize the open browser action using either

The JavaFX api HostServices.show() to show the page in an external web browser

OR

Load the content into a WebView to embed it in your app.

Title: Msal4j browser login window never opens

Body:
Java Version - OpenJDK 17
OS - Linux Mint 20.1 Ulyssa

I'm trying to implement interactive token acquisition from a JavaFX desktop app and running into some trouble getting the browser window to open in order to login.

MRE (just make sure to update PUBLIC_CLIENT_ID in HelloApplication.java to a valid client id)

In the start function in HelloApplication.java I've setup this example in the docs in my Controller's constructor

public HelloController() throws MalformedURLException, URISyntaxException {
    PublicClientApplication publicClientApplication =
        PublicClientApplication
        .builder(CLIENT_ID)
        .authority(AUTHORITY)
        .build();

    InteractiveRequestParameters parameters = InteractiveRequestParameters
        .builder(new URI("http://localhost"))
        .scopes(scope)
        .build();

    IAuthenticationResult result = publicClientApplication.acquireToken(parameters).join();
}

I would expect that a browser window would open that I could then login with my MS credentials, what actually happens is it never opens a browser window and the .join() on the CompletableFuture never returns.

Is there anything else that needs to be setup in order to get the browser window to open?


问:
How to simulate "multi-versioning" regarding database MVCC in JavaScript?
Here is a demo which demonstrates the problem with not having transaction "locking". It sort of simulates async / concurrency using setTimeout. I have never dealt with concurrency in languages like C, Go, or Rust, so I am not really sure how it works in implementation detail, but I am trying to grasp the concept of MVCC.

const db = {
  table1: {
    records: [
      { id: 1, name: 'foo', other: 'hello' },
      { id: 2, name: 'bar', other: 'world' },
    ]
  }
}

function readTable1(id) {
  return db.table1.records.find(x => x.id === id)
}

function writeTable1(id) {
  const record = readTable1(id)
  return new Promise((res, rej) => {
    console.log('transaction 1 start')
    setTimeout(() => {
      record.other = 'qwerty'

      setTimeout(() => {
        record.name = 'asdf'
        console.log('transaction 1 done')
        res()
      }, 1000)
    }, 1000)
  })
}

function wait(ms) {
  return new Promise((res) => setTimeout(res, ms))
}

async function test1() {
  writeTable1(1)
  console.log(readTable1(1))
  await wait(1100)
  console.log(readTable1(1))
  await wait(2200)
  console.log(readTable1(1))
}

test1()```
</div>
</div>
</p>
<p>It logs</p>
```transaction 1 start
{ id: 1, name: 'foo', other: 'hello' } // read
{ id: 1, name: 'foo', other: 'qwerty' } // read
transaction 1 done
{ id: 1, name: 'asdf', other: 'qwerty' } // read
```
<p>In the middle while the transaction is processing the record, it changes the real record which can be concurrently read. There are no locks on it, or however MVCC does it without locks (using multiple versions of records). I next try to implement how I think MVCC works, with hopes that you can correct my understanding. Here is that.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const db = {
  table1: {
    records: [
      [{ id: 1, name: 'foo', other: 'hello' }],
      [{ id: 2, name: 'bar', other: 'world' }],
    ]
  }
}

function readTable1(id) {
  const idx = db.table1.records.findIndex(x => x[0].id === id)
  return [idx, db.table1.records[idx][0]]
}

// this is a long transaction.
function writeTable1(id) {
  const [idx, record] = readTable1(id)
  // create a new version of record for transaction to act on.
  const newRecordVersion = {}
  Object.keys(record).forEach(key => newRecordVersion[key] = record[key])
  db.table1.records[idx].push(newRecordVersion)

  return new Promise((res, rej) => {
    console.log('transaction 2 start')
    setTimeout(() => {
      newRecordVersion.other = 'qwerty'

      setTimeout(() => {
        newRecordVersion.name = 'asdf'
        console.log('transaction 2 done')

        // now "commit" the changes
        commit()

        res();
      }, 1000)
    }, 1000)
  })

  function commit() {
    db.table1.records[idx].shift()
  }
}

function wait(ms) {
  return new Promise((res) => setTimeout(res, ms))
}

async function test1() {
  writeTable1(1)
  console.log(readTable1(1)[1])
  await wait(1100)
  console.log(readTable1(1)[1])
  await wait(2200)
  console.log(readTable1(1)[1])
  console.log(db.table1.records)
}

test1()</code>```

That outputs this, which seems correct.

```<code>transaction 2 start
{ id: 1, name: 'foo', other: 'hello' }
{ id: 1, name: 'foo', other: 'hello' }
transaction 2 done
{ id: 1, name: 'asdf', other: 'qwerty' }
[
  [ { id: 1, name: 'asdf', other: 'qwerty' } ],
  [ { id: 2, name: 'bar', other: 'world' } ]
]
</code>```

Is this correct, generally how it works? Mainly, how many versions per record are created in a real implementation? Can there be more than 2 versions at a time? If so, in what situations does that occur generally speaking? And how do the timestamps work? I read about the timestamps on the wiki page, but it doesn't really register to me how to implement it. Also the incrementing transaction IDs. So basically how those 3 pieces fit together (versioning, timestamps, and transaction IDs).

I am looking for some sort of simulation of the timestamps and versioning in JavaScript, so I can make sure I understand the general concepts at a high level, yet at a sort of rough approximation of an implementation level. Just knowing what MVCC is and reading a few papers isn't enough in the weeds to know how to implement it.

In my example there will only ever be 2 versions of a record during a transaction. I am not sure if there are cases where you would need more than that. And I am not sure how to plug in the timestamps.

答:
Short answer: Multiversion concurrency control in "databases" involves several different things; different vendors implement each of these things in several different ways.

Here's a list of databases using MVCC (both RDBMs and No-SQL DBs), and which versions first supported MVCC: https://en.wikipedia.org/wiki/List_of_databases_using_MVCC

Here's a good response for MSSQL (Microsoft's enterprise RDBMS database):

https://dba.stackexchange.com/questions/174791/does-sql-server-use-multiversion-concurrency-control-mvcc

Does SQL Server really implement MVCC anywhere

Yes, since SQL Server 2005.

The SQL Server terminology is "row-versioning isolation levels". See
the product documentation tree starting at Locking and Row
Versioning.
Note in particular that there are two separate "MVCC" implementations,
read committed isolation using row versioning (RCSI) and snapshot
isolation (SI).

and how does that reconcile with the idea of with (tablock, holdlock) if it does?

Using that combination of hints serializes access to whole table(s).
It is the least concurrent option available, so using these hints
should be very rare. Whether a particular use could be replaced with
RCSI or SI isolation depends on the specific circumstances. You could
ask a follow-up question with a specific example if you want us to
address that aspect in detail.

You might also like to read my series of
articles
on SQL Server isolation levels.

Here is another good link: Well-known Databases Use Different Approaches for MVCC.  It discusses things like:

rollback segments (Oracle)

row versioning (Microsoft)

Finally, here is a good paper from Microsoft Research:

https://www.microsoft.com/en-us/research/wp-content/uploads/2011/12/MVCC-published-revised.pdf

It's a big topic, with no short, simple "one size fits all" reply.

As far as "simulating MVCC in JavaScript":

Javascript is inherently single-threaded; there is no concept of "threads" or "locking" in the language itself.

"Promises" (as you're using) are an excellent way to "order" asynchronous callbacks

We'd need more details on exactly what you're trying to accomplish.

Body:
Here is a demo which demonstrates the problem with not having transaction "locking". It sort of simulates async / concurrency using setTimeout. I have never dealt with concurrency in languages like C, Go, or Rust, so I am not really sure how it works in implementation detail, but I am trying to grasp the concept of MVCC.

const db = {
  table1: {
    records: [
      { id: 1, name: 'foo', other: 'hello' },
      { id: 2, name: 'bar', other: 'world' },
    ]
  }
}

function readTable1(id) {
  return db.table1.records.find(x => x.id === id)
}

function writeTable1(id) {
  const record = readTable1(id)
  return new Promise((res, rej) => {
    console.log('transaction 1 start')
    setTimeout(() => {
      record.other = 'qwerty'

      setTimeout(() => {
        record.name = 'asdf'
        console.log('transaction 1 done')
        res()
      }, 1000)
    }, 1000)
  })
}

function wait(ms) {
  return new Promise((res) => setTimeout(res, ms))
}

async function test1() {
  writeTable1(1)
  console.log(readTable1(1))
  await wait(1100)
  console.log(readTable1(1))
  await wait(2200)
  console.log(readTable1(1))
}

test1()

It logs

transaction 1 start
{ id: 1, name: 'foo', other: 'hello' } // read
{ id: 1, name: 'foo', other: 'qwerty' } // read
transaction 1 done
{ id: 1, name: 'asdf', other: 'qwerty' } // read

In the middle while the transaction is processing the record, it changes the real record which can be concurrently read. There are no locks on it, or however MVCC does it without locks (using multiple versions of records). I next try to implement how I think MVCC works, with hopes that you can correct my understanding. Here is that.

const db = {
  table1: {
    records: [
      [{ id: 1, name: 'foo', other: 'hello' }],
      [{ id: 2, name: 'bar', other: 'world' }],
    ]
  }
}

function readTable1(id) {
  const idx = db.table1.records.findIndex(x => x[0].id === id)
  return [idx, db.table1.records[idx][0]]
}

// this is a long transaction.
function writeTable1(id) {
  const [idx, record] = readTable1(id)
  // create a new version of record for transaction to act on.
  const newRecordVersion = {}
  Object.keys(record).forEach(key => newRecordVersion[key] = record[key])
  db.table1.records[idx].push(newRecordVersion)

  return new Promise((res, rej) => {
    console.log('transaction 2 start')
    setTimeout(() => {
      newRecordVersion.other = 'qwerty'

      setTimeout(() => {
        newRecordVersion.name = 'asdf'
        console.log('transaction 2 done')

        // now "commit" the changes
        commit()

        res();
      }, 1000)
    }, 1000)
  })

  function commit() {
    db.table1.records[idx].shift()
  }
}

function wait(ms) {
  return new Promise((res) => setTimeout(res, ms))
}

async function test1() {
  writeTable1(1)
  console.log(readTable1(1)[1])
  await wait(1100)
  console.log(readTable1(1)[1])
  await wait(2200)
  console.log(readTable1(1)[1])
  console.log(db.table1.records)
}

test1()

That outputs this, which seems correct.

transaction 2 start
{ id: 1, name: 'foo', other: 'hello' }
{ id: 1, name: 'foo', other: 'hello' }
transaction 2 done
{ id: 1, name: 'asdf', other: 'qwerty' }
[
  [ { id: 1, name: 'asdf', other: 'qwerty' } ],
  [ { id: 2, name: 'bar', other: 'world' } ]
]

Is this correct, generally how it works? Mainly, how many versions per record are created in a real implementation? Can there be more than 2 versions at a time? If so, in what situations does that occur generally speaking? And how do the timestamps work? I read about the timestamps on the wiki page, but it doesn't really register to me how to implement it. Also the incrementing transaction IDs. So basically how those 3 pieces fit together (versioning, timestamps, and transaction IDs).

I am looking for some sort of simulation of the timestamps and versioning in JavaScript, so I can make sure I understand the general concepts at a high level, yet at a sort of rough approximation of an implementation level. Just knowing what MVCC is and reading a few papers isn't enough in the weeds to know how to implement it.

In my example there will only ever be 2 versions of a record during a transaction. I am not sure if there are cases where you would need more than that. And I am not sure how to plug in the timestamps.


问:
Android LiveData - how to reuse the same ViewModel on different activities?
Example ViewModel:

```<code>public class NameViewModel extends ViewModel {
    // Create a LiveData with a String
    private MutableLiveData<String> mCurrentName;

    public MutableLiveData<String> getCurrentName() {
        if (mCurrentName == null) {
            mCurrentName = new MutableLiveData<>();
        }
        return mCurrentName;
    }

}
</code>```

Main activity:

```<code>mModel = ViewModelProviders.of(this).get(NameViewModel.class);

// Create the observer which updates the UI.
final Observer<String> nameObserver = textView::setText;

// Observe the LiveData, passing in this activity as the LifecycleOwner and the observer.
mModel.getCurrentName().observe(this, nameObserver);
</code>```

I want to call mModel.getCurrentName().setValue(anotherName); in second activity and make MainActivity receive changes. Is that possible?

答:
ViewModel scope/lifecycle is tied to an activity simply because the ViewModelStoreOwner that you pass to the ViewModelProvider constructor happens to be the activity.

Since you get to provide the ViewModelStoreOwner, you can just as easily provide one that has a longer lifecycle, such as the application.

You can

Provide your own subclass of Application and make it implement ViewModelStoreOwner (and have a ViewModelStore)

In ViewModelProvider constructor calls, pass activity.application rather than activity.

This will cause the ViewModelProvider to interact with the application-level ViewModelStore, allowing you to create ViewModel instances that will have application scope.

Body:
Example ViewModel:

public class NameViewModel extends ViewModel {
    // Create a LiveData with a String
    private MutableLiveData<String> mCurrentName;

    public MutableLiveData<String> getCurrentName() {
        if (mCurrentName == null) {
            mCurrentName = new MutableLiveData<>();
        }
        return mCurrentName;
    }

}

Main activity:

mModel = ViewModelProviders.of(this).get(NameViewModel.class);

// Create the observer which updates the UI.
final Observer<String> nameObserver = textView::setText;

// Observe the LiveData, passing in this activity as the LifecycleOwner and the observer.
mModel.getCurrentName().observe(this, nameObserver);

I want to call mModel.getCurrentName().setValue(anotherName); in second activity and make MainActivity receive changes. Is that possible?


问:
Fill Javascript 2d Array with passed Variable
I have an 2d array created thats 50 by 2 and want to fill it with a passed array. I know the array works and the passed variables. But I can't get the passed variable to fill up the array, it just fills with plain text. Is my syntax wrong?

```<code>for (i=0; i <50; i++){
basket[i]=new Array(2);
}

function addtobasket(itemname, itemvalue){
    basket[itemcount][itemcount]='itemname itemvalue;'
}
</code>```

TIA!

答:
```<code>for (i=0; i <50; i++){
    basket[i]=new Array(2);
}

function addtobasket(itemname, itemvalue){
    basket[itemcount][itemcount]= itemname + " " + itemvalue;
}
</code>```

I believe that's what you want, assuming you're trying to get the items into the array in the format "itemname itemvalue" as in your example code.

The reason you're currently seeing the names of the variables in your array, rather than their values, is that you're using the string literal "itemname itemvalue".  Anything within a string literal - that is, inside the quotation marks - is left unchanged when the code executes.

Body:
I have an 2d array created thats 50 by 2 and want to fill it with a passed array. I know the array works and the passed variables. But I can't get the passed variable to fill up the array, it just fills with plain text. Is my syntax wrong?

for (i=0; i <50; i++){
basket[i]=new Array(2);
}

function addtobasket(itemname, itemvalue){
    basket[itemcount][itemcount]='itemname itemvalue;'
}

TIA!

Body:
for (i=0; i <50; i++){
    basket[i]=new Array(2);
}

function addtobasket(itemname, itemvalue){
    basket[itemcount][itemcount]= itemname + " " + itemvalue;
}

I believe that's what you want, assuming you're trying to get the items into the array in the format "itemname itemvalue" as in your example code.

The reason you're currently seeing the names of the variables in your array, rather than their values, is that you're using the string literal "itemname itemvalue".  Anything within a string literal - that is, inside the quotation marks - is left unchanged when the code executes.


问:
Checking if an internal tester in Playstore has installed the app or not
I have set up an internal testing channel on the Google Play Store. I have added a few testers for my app but could not find a way to check if a particular tester from the list has installed the app or not.

I think this can be found out in Appstore.
We would like to know who has installed the app.
I attempted using the firebase analytics dashboard and play console dashboard for the app as well, app statistics etc, but with no luck.
Is there a way to find this in Playstore?

答:
The signup for internal testing requires the Google Play email address the user will use to install the app. While I have never found anything more than a count of testers who installed, you can retrieve the current account of the user using the app. It isn't exactly a neat and autonomous process, but you could craft a means to compare the list of potential users to the installed account.

The permission required is GET_ACCOUNTS and then you would use AccountManager to retrieve a list of accounts and iterate through them to see if any match a list of testers.


问:
Reduce boolean Iterator
How can I reduce an Iterator of booleans using the && operator? Here is an example (just the relevant part):

let row: Vec<(u32, bool)> = vec![(12, true), (13, false), (15, true)];

row.iter()
    .map(|it| {
        let (_, marked) = it;
        marked
    })
    .reduce(|acc, mk | acc && mk);
```

The compiler recommends dereferencing acc first, then dereferencing mk, and finally borrowing the whole expression. It's a quite simple operation but I'm unable to find the Rustacean way to do it.

答:
After trying things the best solution I found is dereferencing value returned in previous map, so instead of returning a reference to boolean returns an owned copy. Here is the modified question code:

let row: Vec<(u32, bool)> = vec![(12, true), (13, false), (15, true)];

row.iter()
    .map(|it| {
        let (_, marked) = it;
        *marked // Dereference here
    })
    .reduce(|acc, mk | acc && mk);
```

Title: Reduce boolean Iterator

Body:
How can I reduce an Iterator of booleans using the && operator? Here is an example (just the relevant part):

let row: Vec<(u32, bool)> = vec![(12, true), (13, false), (15, true)];

row.iter()
    .map(|it| {
        let (_, marked) = it;
        marked
    })
    .reduce(|acc, mk | acc && mk);

The compiler recommends dereferencing acc first, then dereferencing mk, and finally borrowing the whole expression. It's a quite simple operation but I'm unable to find the Rustacean way to do it.