问:
KeyError:'image_path' while executing Google Vision API using python
I am trying to extract text data from images using Google Cloud Vision API. My Initial starting point was here After Enabling Vision API and Creating service account,generating json file, I created a script by referring this example.

Here's my code

```<code>from google.cloud import vision
from google.cloud.vision_v1 import types
import os

os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'generated_after_creating_sec_key.json'
image_path = 'images\\image_1.png'
vision_client = vision.ImageAnnotatorClient()
print(vision_client)
image = types.Image()
image.source.image_path = image_path

response = vision_client.text_detection(image=image)
for text in response.text_annotations:
    print(text.description)
</code>```

The only difference between the example shown in google page and my code is that the image uploaded in the example is on gcloud while mine happens to be on local storage.

Here's the complete stacktrace.

```<code><google.cloud.vision_v1.ImageAnnotatorClient object at 0x000001DF861D7970>
Traceback (most recent call last):
  File "text_detection.py", line 10, in <module>
    image.source.image_path = image_path
  File "C:\Users\user\ProjectFolder\ProjName\venv\lib\site-packages\proto\message.py", line 677, in __setattr__
    pb_type = self._meta.fields[key].pb_type
KeyError: 'image_path'
</code>```

What is the root cause of this error? Please help!

答: Per the Google Cloud Vision docs, you want image.source.image_uri instead.

Body:
I am trying to extract text data from images using Google Cloud Vision API. My Initial starting point was here After Enabling Vision API and Creating service account,generating json file, I created a script by referring this example.

Here's my code

from google.cloud import vision
from google.cloud.vision_v1 import types
import os

os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'generated_after_creating_sec_key.json'
image_path = 'images\\image_1.png'
vision_client = vision.ImageAnnotatorClient()
print(vision_client)
image = types.Image()
image.source.image_path = image_path

response = vision_client.text_detection(image=image)
for text in response.text_annotations:
    print(text.description)

The only difference between the example shown in google page and my code is that the image uploaded in the example is on gcloud while mine happens to be on local storage.

Here's the complete stacktrace.

<google.cloud.vision_v1.ImageAnnotatorClient object at 0x000001DF861D7970>
Traceback (most recent call last):
  File "text_detection.py", line 10, in <module>
    image.source.image_path = image_path
  File "C:\Users\user\ProjectFolder\ProjName\venv\lib\site-packages\proto\message.py", line 677, in __setattr__
    pb_type = self._meta.fields[key].pb_type
KeyError: 'image_path'

What is the root cause of this error? Please help!


来源: stackexchange

问:
Select price record if record for a customer exists, otherwise select general price record
Suppose i have the following MySQL prices table:

ID
item
from_date
to_date
customer
price

1
1
2021-10-10
2021-12-14
NULL
103.25

2
1
2021-12-15
NULL
NULL
100.25

3
5
2022-01-01
NULL
NULL
201.50

4
1
2022-01-05
NULL
3
80.75

The idea is that for there will be a price record for each item and if there are special price deals for a customer, also a record for that item with a different price. Looking for the price, the price should be taken from the record that is for the item and that specific customer. if there is none, it should return the default price which is valid for all customers.

So, I am trying to get the price that is valid at today's date (2022-02-02). Having those records selected, if there is a most recent record for my specific customer (3) it takes precedence, return that (record ID 4). If there is none for this customer, return the most recent price (record ID 2)

So, today = 2022-02-02, my item is 1 AND my customer is 3. Using the table above the result should be:

ID
item
from_date
to_date
customer
price

4
1
2022-01-05
NULL
3
80.75

If the record with ID = 4 is not there the result should be:

ID
item
from_date
to_date
customer
price

2
1
2021-12-15
NULL
NULL
100.25

I tried several select queries but still don’t see what i should do and google didn’t help me much.

Any help would be appreciated greatly!

答:
Ok, i think i wasn't in the right mind when i asked this question. See things much clearer now.

I solved it via this simple query:

SELECT ISP.gross_price, ISP.disc_amount, ISP.disc_percentage, I.Name FROM item_salesprices ISP

JOIN Items I ON I.ID = ISP.item

WHERE I.Item=‘ZZ1’

AND (ISP.Customer=(SELECT ID FROM Customers WHERE Customer=‘Cust3’) OR ISP.Customer IS NULL)

AND (ISP.from_date <= NOW() OR ISP.from_date IS NULL)  AND (ISP.to_date >= NOW() OR ISP.to_date IS NULL)

ORDER BY ISP.Customer DESC, ISP.from_date DESC LIMIT 1

The result is that if there's a price record for item = 1 and customer = 3, it will output only that row. Thus, record ID = 4, price = 80.75.

If there's not, it will output the default price row for item = 1 (and essentially customer IS null). Thus, record ID = 2, price = 100.25.

ContentLicense: CC BY-SA 4.0


问:
Replacing multiple special characters in oracle
I have a requirement in oracle to replace the special characters at first and last position of the column data.

Requirement: only [][.,$'*&!%^{}-?] and alphanumberic characters are allowed to stay in the address data and rest of the characters has to be replaced with space.I have tried in below way in different probabilities but its not working as expected. Please help me in resolving this.

SELECT emp_address,
       REGEXP_REPLACE(
         emp_address,
         '^[^[[][.,$'\*&!%^{}-?\]]]|[^[[][.,$'\*&!%^{}-?\]]]$'
       ) AS simplified_emp_address
FROM   table_name
```

答:
You do not need regular expressions, because they will have cumbersome escape sequences. Use substrings and translate function:

```<code>with a as (
  select
    'some [data ]' as val
  from dual
  union all
  select '{test $' from dual
  union all
  select 'clean $%&* value' from dual
  union all
  select 's' from dual
)
select
  translate(substr(val, 1, 1), q'{ [][.,$'*&!%^{}-?]}', ' ')
  || substr(val, 2, lengthc(val) - 2)
  || case
       when lengthc(val) > 1
       then translate(substr(val, -1), q'{ [][.,$'*&!%^{}-?]}', ' ')
     end
  as value_replaced
from a
</code>```
```
| VALUE_REPLACED   |
| :--------------- |
| some [data       |
| test             |
| clean $%&* value |
| s                |
```

db<>fiddle here

Body:
You do not need regular expressions, because they will have cumbersome escape sequences. Use substrings and translate function:

with a as (
  select
    'some [data ]' as val
  from dual
  union all
  select '{test $' from dual
  union all
  select 'clean $%&* value' from dual
  union all
  select 's' from dual
)
select
  translate(substr(val, 1, 1), q'{ [][.,$'*&!%^{}-?]}', ' ')
  || substr(val, 2, lengthc(val) - 2)
  || case
       when lengthc(val) > 1
       then translate(substr(val, -1), q'{ [][.,$'*&!%^{}-?]}', ' ')
     end
  as value_replaced
from a

| VALUE_REPLACED   |
| :--------------- |
| some [data       |
| test             |
| clean $%&* value |
| s                |

db<>fiddle here


问:
Java JEditorPane - Trying to edit an html tag value and getting Exception
I have a JEditorPane and I'm trying to edit one fo the html element attributes, basically changing the the src x value in  to a custom value

The code I have is:

```<code>// Get <img src="..."> tag
RunElement imageTagElement = getImageTagElement(htmlDocument);

// Print src attribute value
System.out.println("src : " + runElement.getAttribute(HTML.Attribute.SRC));

// Replace existing src value
runElement.removeAttribute(HTML.Attribute.SRC);
runElement.addAttribute(HTML.Attribute.SRC, "customValue");
</code>```

I get the following exception in the before last line when I try to remove the existing attribute (because you can't replace):

```<code>javax.swing.text.StateInvariantError: Illegal cast to MutableAttributeSet
</code>```

I read a few places that you can use writeLock, but that's a protected method, which means I can't call it from this code...

So basically my question is that if you've found the element you want, how do you edit it's attributes?

答:
```<code>## Use the  htmlDoc.setCharacterAttributes (...);##
ElementIterator it = new ElementIterator(htmlDoc);
Element elem;
 while ((elem = it.next()) != null) {
   if (elem.getName().equals("img")) {
      AttributeSet atts = elem.getAttributes();
       // Modifiable
      SimpleAttributeSet simple = new SimpleAttributeSet(atts);
      String s = (String) simple.getAttribute(HTML.Attribute.SRC);
      if (s != null) {
           System.out.println(s); // testing
           int len = elem.getEndOffset() - elem.getStartOffset();
           //simple.removeAttribute(HTML.Attribute.SRC);
           simple.addAttribute( HTML.Attribute.SRC, **newSRC_URL_String** );
           //
           //  The doc takes care of the locks
           //
           htmlDoc.setCharacterAttributes(
             elem.getStartOffset(),len,simple,true);
 }
 }
 }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a JEditorPane and I'm trying to edit one fo the html element attributes, basically changing the the src x value in  to a custom value

The code I have is:

// Get  tag
RunElement imageTagElement = getImageTagElement(htmlDocument);

// Print src attribute value
System.out.println("src : " + runElement.getAttribute(HTML.Attribute.SRC));

// Replace existing src value
runElement.removeAttribute(HTML.Attribute.SRC);
runElement.addAttribute(HTML.Attribute.SRC, "customValue");

I get the following exception in the before last line when I try to remove the existing attribute (because you can't replace):

javax.swing.text.StateInvariantError: Illegal cast to MutableAttributeSet

I read a few places that you can use writeLock, but that's a protected method, which means I can't call it from this code...

So basically my question is that if you've found the element you want, how do you edit it's attributes?


问:
Maximum Stack Size for C/C+ Program?
I've tried the below program. The intent by which this program was created is to discover more about stack sizes.

```<code>int main()
{
    int nStack[100000000];
    return 0;
}
</code>```

After executing the above code, the program crashes due to huge stack size allocation.
What is the maximum possible size of the stack? Is it fixed for every program/computer? Can it be increased?

I want to know for the sake of knowledge. If anyone can provide examples in C/C++, it would be very helpful.

答:
For this type, you can allocate the dynamic memory allocation for this
and use Generic Representation of Stack for Memory allocation. If requiring a huge amount of memory, you can use a Linked List in the form of a Stack. For C/C++, Dynamic Memory allocation for Malloc/New. Hope you understand.</p>

Title: Maximum Stack Size for C/C+ Program?

Body:
I've tried the below program. The intent by which this program was created is to discover more about stack sizes.

int main()
{
    int nStack[100000000];
    return 0;
}

After executing the above code, the program crashes due to huge stack size allocation.
What is the maximum possible size of the stack? Is it fixed for every program/computer? Can it be increased?

I want to know for the sake of knowledge. If anyone can provide examples in C/C++, it would be very helpful.


问:
How to iteratively apply a function (pdf_text()) across pdf files in a folder in R?
I have a large folder of pdf documents. I am trying to extract the text from each document iteratively (such that the only input is the folder pathway). It seems one can approach this with a imap/map and a for loop. Below is an attempt mapping a function onto a vector in which all files in the folder reside.

```<code>files <- list.files(path = "foldername", pattern = "*.pdf")

text_vector = c()

df <- files %>% map(function(x) {
    text <- pdf_text(x))
    text_vector <- append(text)})

</code>```

I welcome alternative methods to the same end of extracting the text across all files in a folder.

答:
You could use sapply followed by rbind to join the results together.

```<code>library(pdftools)
pdfs <- list.files('foldername', pattern = 'pdf', full.names = T)
text <- sapply(pdfs, pdf_text)
all_text <- do.call(rbind, text)
</code>```

Body:
I have a large folder of pdf documents. I am trying to extract the text from each document iteratively (such that the only input is the folder pathway). It seems one can approach this with a imap/map and a for loop. Below is an attempt mapping a function onto a vector in which all files in the folder reside.

files <- list.files(path = "foldername", pattern = "*.pdf")

text_vector = c()

df <- files %>% map(function(x) {
    text <- pdf_text(x))
    text_vector <- append(text)})

I welcome alternative methods to the same end of extracting the text across all files in a folder.

Body:
You could use sapply followed by rbind to join the results together.

library(pdftools)
pdfs <- list.files('foldername', pattern = 'pdf', full.names = T)
text <- sapply(pdfs, pdf_text)
all_text <- do.call(rbind, text)


问:
Group the two rows but Last 2 columns value is different
I have the below table in which I got the data from different tables.

Policy_Number
Name_Of_Client
Email
Phone

BEI/BGAMMQ/0000431
Test, Lda
t@t.com
NULL

BEI/BGAMMQ/0000431
Test, Lda
NULL
1212121212

Can someone please help me to get the result as below?

Policy_Number
Name_Of_Client
Email
Phone

BEI/BGAMMQ/0000431
Test, Lda
t@t.com
1212121212

Thank you in advance

答:
Aggregate by policy number and name of client, then select the max of the email and phone.

SELECT Policy_Number, Name_Of_Client, MAX(Email) AS Email, MAX(Phone) AS Phone
FROM yourTable
GROUP BY Policy_Number, Name_Of_Client;
```

By the way, your table in its current state might imply that there is some sort of design or data gathering problem.  The output you want is the version you probably should be using.

Body:
Aggregate by policy number and name of client, then select the max of the email and phone.

SELECT Policy_Number, Name_Of_Client, MAX(Email) AS Email, MAX(Phone) AS Phone
FROM yourTable
GROUP BY Policy_Number, Name_Of_Client;

By the way, your table in its current state might imply that there is some sort of design or data gathering problem.  The output you want is the version you probably should be using.


问:
Rock Paper Scissors game loop
I'm working on a task to build a Stone,Paper,Scissors Game.
The game is supposed to run in 3 possible modes. best of 3 / best of 5 and endless games.

My code works fine until the point where I reset the game to begin a new game.
For a reason which I can not figure out, it plays multiple instances of my game, each time I call the game() function.
(after the game is over - a reset game button appears and the game mode needs to be reseleted)

I've added the entire project to this https://jsfiddle.net/vydkg3bz/, since I don't manage to pinpoint where the issue is.

I believe, due to all the extra logging I added, that the problem is somewhere in the game() function, as I tried to replace most of the code around it, with the same result.

Maybe someone has a moment to review my code and give me a hint where I should look?

```<code>// global variables
var choicesObj = {
  Rock: "url('./img/stone.png')",
  Paper: "url('./img/paper.png')",
  Scissors: "url('./img/scissors.png')",
}
var choices = Object.keys(choicesObj);
var moveAI;
var movePlayer;
var winnerRound;
var winnerGame;
var roundCount = 0;

// actual game
function game(requiredWins) {
  console.log("game");
  enabler()

  var inputs = document.querySelectorAll(".inputButton");
  console.log(inputs);
  for (var i = 0; i < inputs.length; i++) {
    inputs[i].addEventListener("click", function() {
    movePlayer = this.id
    handleClick(movePlayer)
    });
  }

  // checking choice, display choice IMG, call compareChoices function
  function handleClick(buttonID) {
    console.log("handleClick");
    moveAIfunc()
    movePlayer = buttonID;
    console.log('movePlayer: ' + movePlayer);
    console.log('moveAI: ' + moveAI);
    document.getElementById("mainImgPlayer").style.backgroundImage = choicesObj[movePlayer];
    document.getElementById("mainImgAI").style.backgroundImage = choicesObj[moveAI];
    compareChoices(moveAI,movePlayer);
    console.log("requiredWins", requiredWins);
    gameEnd();
    displays();
  }

  // AI control
  function moveAIfunc() {
    moveAI = choices[Math.floor(Math.random() * choices.length)]
  }

  // compare choices
  function compareChoices(a, b) {
    console.log("compareChoices");
    a = choices.indexOf(a);
    b = choices.indexOf(b);
    console.log("requiredWins", requiredWins);
    roundCount++;
    if (a == b) {
      winnerNone()
      return;
    }
    if (a == choices.length - 1 && b == 0) {
      winnerPlayer()
      return;
    }
    if (b == choices.length - 1 && a == 0) {
      winnerAI()
      return;
    }
    if (a > b) {
      winnerAI()
      return;
    }
    else {
      winnerPlayer()
      return;
    }
  }

  // game end
  function gameEnd() {
    console.log("gameEnd");
    console.log(requiredWins,winsPlayer,winsAI);
    if (winsPlayer == requiredWins) {
      console.log(requiredWins,winsPlayer,winsAI);
      winnerGame = "Player";
      disabler()
      createEndButton()
      return;
    }
    if (winsAI == requiredWins) {
      console.log(requiredWins,winsPlayer,winsAI);
      winnerGame = "AI";
      disabler()
      createEndButton()
      return;
    }
  }
}```

```

答:
Your code seems to be pretty complicated. The state of the wins/required wins etc. is not saved adequately in it. For playing you add event listeners per game (click), which is pretty inefficient imho.

I have created a mockup (a minimal reproducable example) for the handling of games, using data attributes to remember the state of a game and event delegation for the handling. Maybe it's useful for you.

Not related, but here's my take on RPS.

document.addEventListener(`click`, handle);

function handle(evt) {
  if (evt.target.id === `play`) {
    return play(evt.target);
  }

  if (evt.target.name === `nWins`) {
    return reset(evt.target);
  }
}

function reset(radio) {
    const value = radio === `none`
      ? Number.MAX_SAFE_INTEGER : +radio.value;
    const bttn = document.querySelector(`#play`);
    const result = document.querySelector(`#result`);
    result.textContent = `(Re)start initiated, click [Play]`;
    result.dataset.wins = bttn.dataset.wins = 0;
    bttn.dataset.plays = 0;
    return bttn.dataset.winsrequired = value;
}

function play(bttn) {
    if (+bttn.dataset.winsrequired < 1) {
      return document.querySelector(`#result`)
        .textContent = `Select best of to start playing ...`;
    }

    const result = document.querySelector(`#result`);
    bttn.dataset.plays = +bttn.dataset.plays + 1;
    const won = Math.floor(Math.random() * 2);
    const wins = +result.dataset.wins + won;
    result.textContent = `${won ? `You win` : `You loose`} (plays: ${
      bttn.dataset.plays}, wins ${wins})`;
    result.dataset.wins = wins;

    if (+bttn.dataset.plays === +bttn.dataset.winsrequired) {
      result.textContent = `You won ${wins} of ${
        bttn.dataset.winsrequired} games. Choose 'Best of'
          to start another game`;
      bttn.dataset.plays = bttn.dataset.winsrequired = 0;
      result.dataset.wins = 0;
      document.querySelectorAll(`[name="nWins"]`)
        .forEach(r => r.checked = false);
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Best of
<input type="radio" name="nWins" value="3"> 3
<input type="radio" name="nWins" value="5"> 5
<input type="radio" name="nWins" value="none"> indefinite

<button id="play" data-winsrequired="0" data-plays="0" >Play</button>

<p id="result" data-wins="0"></p></code>```

Title: Rock Paper Scissors game loop

Body:
I'm working on a task to build a Stone,Paper,Scissors Game.
The game is supposed to run in 3 possible modes. best of 3 / best of 5 and endless games.

My code works fine until the point where I reset the game to begin a new game.
For a reason which I can not figure out, it plays multiple instances of my game, each time I call the game() function.
(after the game is over - a reset game button appears and the game mode needs to be reseleted)

I've added the entire project to this https://jsfiddle.net/vydkg3bz/, since I don't manage to pinpoint where the issue is.

I believe, due to all the extra logging I added, that the problem is somewhere in the game() function, as I tried to replace most of the code around it, with the same result.

Maybe someone has a moment to review my code and give me a hint where I should look?

// global variables
var choicesObj = {
  Rock: "url('./img/stone.png')",
  Paper: "url('./img/paper.png')",
  Scissors: "url('./img/scissors.png')",
}
var choices = Object.keys(choicesObj);
var moveAI;
var movePlayer;
var winnerRound;
var winnerGame;
var roundCount = 0;

// actual game
function game(requiredWins) {
  console.log("game");
  enabler()

  var inputs = document.querySelectorAll(".inputButton");
  console.log(inputs);
  for (var i = 0; i < inputs.length; i++) {
    inputs[i].addEventListener("click", function() {
    movePlayer = this.id
    handleClick(movePlayer)
    });
  }

  // checking choice, display choice IMG, call compareChoices function
  function handleClick(buttonID) {
    console.log("handleClick");
    moveAIfunc()
    movePlayer = buttonID;
    console.log('movePlayer: ' + movePlayer);
    console.log('moveAI: ' + moveAI);
    document.getElementById("mainImgPlayer").style.backgroundImage = choicesObj[movePlayer];
    document.getElementById("mainImgAI").style.backgroundImage = choicesObj[moveAI];
    compareChoices(moveAI,movePlayer);
    console.log("requiredWins", requiredWins);
    gameEnd();
    displays();
  }

  // AI control
  function moveAIfunc() {
    moveAI = choices[Math.floor(Math.random() * choices.length)]
  }

  // compare choices
  function compareChoices(a, b) {
    console.log("compareChoices");
    a = choices.indexOf(a);
    b = choices.indexOf(b);
    console.log("requiredWins", requiredWins);
    roundCount++;
    if (a == b) {
      winnerNone()
      return;
    }
    if (a == choices.length - 1 && b == 0) {
      winnerPlayer()
      return;
    }
    if (b == choices.length - 1 && a == 0) {
      winnerAI()
      return;
    }
    if (a > b) {
      winnerAI()
      return;
    }
    else {
      winnerPlayer()
      return;
    }
  }

  // game end
  function gameEnd() {
    console.log("gameEnd");
    console.log(requiredWins,winsPlayer,winsAI);
    if (winsPlayer == requiredWins) {
      console.log(requiredWins,winsPlayer,winsAI);
      winnerGame = "Player";
      disabler()
      createEndButton()
      return;
    }
    if (winsAI == requiredWins) {
      console.log(requiredWins,winsPlayer,winsAI);
      winnerGame = "AI";
      disabler()
      createEndButton()
      return;
    }
  }
}```

Body:
Your code seems to be pretty complicated. The state of the wins/required wins etc. is not saved adequately in it. For playing you add event listeners per game (click), which is pretty inefficient imho.

I have created a mockup (a minimal reproducable example) for the handling of games, using data attributes to remember the state of a game and event delegation for the handling. Maybe it's useful for you.

Not related, but here's my take on RPS.

document.addEventListener(`click`, handle);

function handle(evt) {
  if (evt.target.id === `play`) {
    return play(evt.target);
  }

  if (evt.target.name === `nWins`) {
    return reset(evt.target);
  }
}

function reset(radio) {
    const value = radio === `none`
      ? Number.MAX_SAFE_INTEGER : +radio.value;
    const bttn = document.querySelector(`#play`);
    const result = document.querySelector(`#result`);
    result.textContent = `(Re)start initiated, click [Play]`;
    result.dataset.wins = bttn.dataset.wins = 0;
    bttn.dataset.plays = 0;
    return bttn.dataset.winsrequired = value;
}

function play(bttn) {
    if (+bttn.dataset.winsrequired < 1) {
      return document.querySelector(`#result`)
        .textContent = `Select best of to start playing ...`;
    }

    const result = document.querySelector(`#result`);
    bttn.dataset.plays = +bttn.dataset.plays + 1;
    const won = Math.floor(Math.random() * 2);
    const wins = +result.dataset.wins + won;
    result.textContent = `${won ? `You win` : `You loose`} (plays: ${
      bttn.dataset.plays}, wins ${wins})`;
    result.dataset.wins = wins;

    if (+bttn.dataset.plays === +bttn.dataset.winsrequired) {
      result.textContent = `You won ${wins} of ${
        bttn.dataset.winsrequired} games. Choose 'Best of'
          to start another game`;
      bttn.dataset.plays = bttn.dataset.winsrequired = 0;
      result.dataset.wins = 0;
      document.querySelectorAll(`[name="nWins"]`)
        .forEach(r => r.checked = false);
    }
}

Best of
<input type="radio" name="nWins" value="3"> 3
<input type="radio" name="nWins" value="5"> 5
<input type="radio" name="nWins" value="none"> indefinite

<button id="play" data-winsrequired="0" data-plays="0" >Play</button>

<p id="result" data-wins="0"></p>


问:
Remove user while also removing unused tags in many-to-many relationship in GraphQL?
I'm using Hasura for this.

Say for example I have a users, tags and users_tags table in a many-to-many relationship.

User's can define multiple tags (like a persons hobbies) and each tag can belong to multiple people.

```<code>Table users {
  id int [pk increment]
}

Table tags {
  id int [pk increment]
  name text
}

Table users_tags {
  id int [pk increment]
  user [ref: - user.id]
  tag [ref: - tags.id]
}
</code>```

The users_tags table is a many-to-many table.

When a new user is created, I can create new tags and associate them with users just fine.

But when a user is deleted, what GraphQL mutation can I use to remove tags from both tags and users_tags if they don't point to other users.

答:
This depends on your desired data model. If a tag is always associated with one user only, you can get rid of the users_tags table and add the user to the tags table.

Then, if you've set up a foreign key on the tag table that references the id field on the user table then this can be done automatically.

You will be given 4 options on deletion:

restrict:  Does not allow you to delete a user that is referenced on a tag

cascade: Deletes the tag if the user is deleted

set null: Sets this row as null if the user is deleted

set default: Sets this row as the default value if the user is deleted

You'll want to select the cascade option here.

If you want to keep your current data model you will be able to do this cascading on the users_tags table if the tag or user is deleted but will need some process in place to delete tags that have no users associated to them.

The easiest way would probably be to add a custom SQL function but you could also have the following graphql query to find the tags that have 0 users_tags associated with them and then provide a list of primary keys to a delete tags mutation.

```<code>query CountOfUsersTagsForTag {
  tags {
    id
    users_tags_aggregate {
      aggregate {
        count
      }
    }
  }
}
</code>```

Body:
I'm using Hasura for this.

Say for example I have a users, tags and users_tags table in a many-to-many relationship.

User's can define multiple tags (like a persons hobbies) and each tag can belong to multiple people.

Table users {
  id int [pk increment]
}

Table tags {
  id int [pk increment]
  name text
}

Table users_tags {
  id int [pk increment]
  user [ref: - user.id]
  tag [ref: - tags.id]
}

The users_tags table is a many-to-many table.

When a new user is created, I can create new tags and associate them with users just fine.

But when a user is deleted, what GraphQL mutation can I use to remove tags from both tags and users_tags if they don't point to other users.

Body:
This depends on your desired data model. If a tag is always associated with one user only, you can get rid of the users_tags table and add the user to the tags table.

Then, if you've set up a foreign key on the tag table that references the id field on the user table then this can be done automatically.

You will be given 4 options on deletion:

restrict:  Does not allow you to delete a user that is referenced on a tag

cascade: Deletes the tag if the user is deleted

set null: Sets this row as null if the user is deleted

set default: Sets this row as the default value if the user is deleted

You'll want to select the cascade option here.

If you want to keep your current data model you will be able to do this cascading on the users_tags table if the tag or user is deleted but will need some process in place to delete tags that have no users associated to them.

The easiest way would probably be to add a custom SQL function but you could also have the following graphql query to find the tags that have 0 users_tags associated with them and then provide a list of primary keys to a delete tags mutation.

query CountOfUsersTagsForTag {
  tags {
    id
    users_tags_aggregate {
      aggregate {
        count
      }
    }
  }
}


问:
ASP.NET Core app does not use setting from the appsettings.json, after trying to publish to Azure
My app when executed locally does not read ConnectionString from the appsettings.json.
I had configured "Connected Services" in VS2019 for my ASP.NET Core 3.1 app. Where the SQL DB connection got a wrong DB name (probably got autogenerated). I then have deleted this configuration and ignored it from my profile.
But now when I'm trying to execute this app locally - it is still trying to use DB from that config.

Microsoft.Data.SqlClient.SqlException (0x80131904): Cannot open
database "aspnet-53bc9b9d-9d6a-45d4-1122-2a2761773502" requested by
the login. The login failed.

1. Is there a place it is got cached at or where I need to remove it
manually from?

2. Also why it does not read from my appsettings.json?

appsettings.json:

```<code>**{
  "Serilog": {
    "Using": [
      "Serilog.Sinks.Console",
      "Serilog.Sinks.File",
      "Serilog.Sinks.Seq",
      "Serilog.Sinks.Loggly"
    ],
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "Microsoft": "Debug",
        "System": "Debug"
      }
    },
    "Enrich": [
      "FromLogContext",
      "WithMachineName",
      "WithProcessId",
      "WithThreadId"
    ],
    "WriteTo": [
      {
        "Name": "Console"
      },
      {
        "Name": "File",
        "Args": {
          "path": "C:\\ODATA\\Logs\\log.json"
        },
        "formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog"
      }
    ],
    "Properties": {
      "Application": "ODataTestApp"
    }
  },
  "ConnectionStrings": {
    "Database": "Data Source=*MyDBConnectionString*"
  },
  "AllowedHosts": "*",
  "ApplicationInsights": {
    "ConnectionString": "InstrumentationKey=*my-key*/"
  }
}**
</code>```

P.S. I added those Connected Services as part of the Publish to Azure steps. I have tried to Publish my app to Azure, but it failed (for different reasons).

答:
By running locally I am taking it that you mean in debug mode from Visual Studio. Doing the following two things should fix the issue:

Search the solution for "aspnet-53bc9b9d-9d6a-45d4-1122-2a2761773502" and correct anywhere that is set (settings files or otherwise).

Delete the debug and obj folders in the project directory. Clean and rebuild the solution.

The other possibility is that there is an environment variable set on your machine for the connection string, but it seems unlikely that this would be there without you already being aware.

Body:
My app when executed locally does not read ConnectionString from the appsettings.json.
I had configured "Connected Services" in VS2019 for my ASP.NET Core 3.1 app. Where the SQL DB connection got a wrong DB name (probably got autogenerated). I then have deleted this configuration and ignored it from my profile.
But now when I'm trying to execute this app locally - it is still trying to use DB from that config.

Microsoft.Data.SqlClient.SqlException (0x80131904): Cannot open
database "aspnet-53bc9b9d-9d6a-45d4-1122-2a2761773502" requested by
the login. The login failed.

1. Is there a place it is got cached at or where I need to remove it
manually from?

2. Also why it does not read from my appsettings.json?

appsettings.json:

**{
  "Serilog": {
    "Using": [
      "Serilog.Sinks.Console",
      "Serilog.Sinks.File",
      "Serilog.Sinks.Seq",
      "Serilog.Sinks.Loggly"
    ],
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "Microsoft": "Debug",
        "System": "Debug"
      }
    },
    "Enrich": [
      "FromLogContext",
      "WithMachineName",
      "WithProcessId",
      "WithThreadId"
    ],
    "WriteTo": [
      {
        "Name": "Console"
      },
      {
        "Name": "File",
        "Args": {
          "path": "C:\\ODATA\\Logs\\log.json"
        },
        "formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog"
      }
    ],
    "Properties": {
      "Application": "ODataTestApp"
    }
  },
  "ConnectionStrings": {
    "Database": "Data Source=*MyDBConnectionString*"
  },
  "AllowedHosts": "*",
  "ApplicationInsights": {
    "ConnectionString": "InstrumentationKey=*my-key*/"
  }
}**

P.S. I added those Connected Services as part of the Publish to Azure steps. I have tried to Publish my app to Azure, but it failed (for different reasons).


问:
why do pipenv install uwsgi with different version of python?
I am trying to install uwsgi library with pipenv

my environment is below and I run on pipenv.

```<code>(docker_test) ubuntu@ip-10-213-27-94:~/docker_test$ python --version
Python 3.9.10
(docker_test) ubuntu@ip-10-213-27-94:~/docker_test$ pip --version
pip 22.0.3 from /home/ubuntu/.local/share/virtualenvs/docker_test-zaCE99f5/lib/python3.9/site-packages/pip (python 3.9)
</code>```

But when I try to install uwsgi with a command pipenv install uwsgi
it seems working with different version of python and only to fail...

```<code>(docker_test) ubuntu@ip-10-213-27-94:~/docker_test$ pipenv install uwsgi
/home/ubuntu/.local/lib/python3.6/site-packages/pkg_resources/__init__.py:119: PkgResourcesDeprecationWarning: 0.18ubuntu0.18.04.1 is an invalid version and will not be supported in a future release
  PkgResourcesDeprecationWarning,
Installing uwsgi...
Error:  An error occurred while installing uwsgi!
</code>```

I don't understand why.... :-(

答:
this may be because of differnet python version associated with the pip and pipenv.

do use python -m <pip/pipenv> install uwsgi

Body:
I am trying to install uwsgi library with pipenv

my environment is below and I run on pipenv.

(docker_test) ubuntu@ip-10-213-27-94:~/docker_test$ python --version
Python 3.9.10
(docker_test) ubuntu@ip-10-213-27-94:~/docker_test$ pip --version
pip 22.0.3 from /home/ubuntu/.local/share/virtualenvs/docker_test-zaCE99f5/lib/python3.9/site-packages/pip (python 3.9)

But when I try to install uwsgi with a command pipenv install uwsgi
it seems working with different version of python and only to fail...

(docker_test) ubuntu@ip-10-213-27-94:~/docker_test$ pipenv install uwsgi
/home/ubuntu/.local/lib/python3.6/site-packages/pkg_resources/__init__.py:119: PkgResourcesDeprecationWarning: 0.18ubuntu0.18.04.1 is an invalid version and will not be supported in a future release
  PkgResourcesDeprecationWarning,
Installing uwsgi...
Error:  An error occurred while installing uwsgi!

I don't understand why.... :-(


问:
java.lang.ClassNotFoundException: scala.Product$class
I am trying to  connect to an elasticsearch database using spark and my code snippet looks like this:

```<code>spark = SparkSession.builder.master("local").appName("Spark").getOrCreate()
reader = spark.read.format("org.elasticsearch.spark.sql").option("es.read.metadata", "true").option("es.nodes.wan.only","true").option("es.port","9200").option("es.net.ssl","false").option("es.nodes", "here-ip-adress")
df = reader.load("my_index")
</code>```

When calling df = reader.load("my_index") I get the following error:

```<code>py4j.protocol.Py4JJavaError: An error occurred while calling o45.load.: java.lang.NoClassDefFoundError: scala/Product$class
    at org.elasticsearch.spark.sql.ElasticsearchRelation.<init>(DefaultSource.scala:191)
    at org.elasticsearch.spark.sql.DefaultSource.createRelation(DefaultSource.scala:93)
    at org.apache.spark.sql.execution.datasources.DataSource.resolveRelation(DataSource.scala:350)
    at org.apache.spark.sql.DataFrameReader.loadV1Source(DataFrameReader.scala:274)
    at org.apache.spark.sql.DataFrameReader.$anonfun$load$3(DataFrameReader.scala:245)
    at scala.Option.getOrElse(Option.scala:189)
    at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:245)
    at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:188)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:282)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.ClientServerConnection.waitForCommands(ClientServerConnection.java:182)
    at py4j.ClientServerConnection.run(ClientServerConnection.java:106)
    at java.lang.Thread.run(Thread.java:748)

Caused by: java.lang.ClassNotFoundException: scala.Product$class
        at java.net.URLClassLoader.findClass(URLClassLoader.java:387)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
        ... 20 more
</code>```

There are some other solutions here on stackoverflow, but for some reason none of them have helped. I am using Spark version 3.2.0, Scala version 2.12.15 (OpenJDK 64-Bit Server VM, Java 1.8.0_312) and running the code with spark-submit --packages org.elasticsearch:elasticsearch-hadoop:6.1.0

Thanks in advance!

答:
It looks like you are using different Scala version binaries.

please check again you imported spark compiled with the right Scala version.

according to maven dependencies, https://mvnrepository.com/artifact/org.elasticsearch/elasticsearch-hadoop/6.1.0

elasticsearch-hadoop:6.1.0 depends on the spark compiled with Scala 2.11, so you should choose a compatible spark version.

Body:
I am trying to  connect to an elasticsearch database using spark and my code snippet looks like this:

spark = SparkSession.builder.master("local").appName("Spark").getOrCreate()
reader = spark.read.format("org.elasticsearch.spark.sql").option("es.read.metadata", "true").option("es.nodes.wan.only","true").option("es.port","9200").option("es.net.ssl","false").option("es.nodes", "here-ip-adress")
df = reader.load("my_index")

When calling df = reader.load("my_index") I get the following error:

py4j.protocol.Py4JJavaError: An error occurred while calling o45.load.: java.lang.NoClassDefFoundError: scala/Product$class
    at org.elasticsearch.spark.sql.ElasticsearchRelation.<init>(DefaultSource.scala:191)
    at org.elasticsearch.spark.sql.DefaultSource.createRelation(DefaultSource.scala:93)
    at org.apache.spark.sql.execution.datasources.DataSource.resolveRelation(DataSource.scala:350)
    at org.apache.spark.sql.DataFrameReader.loadV1Source(DataFrameReader.scala:274)
    at org.apache.spark.sql.DataFrameReader.$anonfun$load$3(DataFrameReader.scala:245)
    at scala.Option.getOrElse(Option.scala:189)
    at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:245)
    at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:188)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:282)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.ClientServerConnection.waitForCommands(ClientServerConnection.java:182)
    at py4j.ClientServerConnection.run(ClientServerConnection.java:106)
    at java.lang.Thread.run(Thread.java:748)

Caused by: java.lang.ClassNotFoundException: scala.Product$class
        at java.net.URLClassLoader.findClass(URLClassLoader.java:387)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
        ... 20 more

There are some other solutions here on stackoverflow, but for some reason none of them have helped. I am using Spark version 3.2.0, Scala version 2.12.15 (OpenJDK 64-Bit Server VM, Java 1.8.0_312) and running the code with spark-submit --packages org.elasticsearch:elasticsearch-hadoop:6.1.0

Thanks in advance!


问:
MockMvc result returns null for GET request in Spring Boot
I have a problem with testing my Spring Boot Controller. I'm trying to test one of Controller put methods, but all I'm getting is Status expected:<200> but was:<400> error message.

My Controller:

```<code>@PutMapping(value = "/update", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> updateFields(@RequestBody List<UpdateModel> model) throws JsonProcessingException {
    return new ResponseEntity<>(vaultService.updateFields(model), HttpStatus.OK);
}
</code>```

My ControllerTest:
The URL is ok, and I have a list just like in the get method in my controller.

```<code>@Test
void updateFieldsTest() throws Exception {
    List<UpdateModel> response = new ArrayList<>();
    UpdateModel updateModel = new UpdateModel();
    response.add(updateModel);
    when(vaultService.updateFields(anyList()))
            .thenReturn(String.valueOf(response));

mockMvc.perform(
        MockMvcRequestBuilders.put("/api/update")
        .contentType(MediaType.APPLICATION_JSON_VALUE)
        .accept("application/json"))
        .andExpect(MockMvcResultMatchers.status().isOk());
}
</code>```

And here's an error message:

```<code>MockHttpServletRequest:
      HTTP Method = PUT
      Request URI = /api/update
       Parameters = {}
          Headers = [Content-Type:"application/json;charset=UTF-8", Accept:"application/json"]
             Body = null
    Session Attrs = {}

Handler:
             Type = hr.ogcs.ltt.api.lttapi.controller.LttController
           Method = hr.ogcs.ltt.api.lttapi.controller.LttController#updateFields(List)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = org.springframework.http.converter.HttpMessageNotReadableException

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 400
    Error message = null
          Headers = [Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers"]
     Content type = null
             Body =
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

Status expected:<200> but was:<400>
Expected :200
Actual   :400
<Click to see difference>
java.lang.AssertionError: Status expected:<200> but was:<400>
    at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:59)
    at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:122)
    at org.springframework.test.web.servlet.result.StatusResultMatchers.lambda$matcher$9(StatusResultMatchers.java:627)
    at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:212)
   at hr.ogcs.ltt.api.apicontroller.ControllerTest.updateFieldsTest(ControllerTest.java:113) <31 internal lines>
   at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)<9 internal lines>
   at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)<48 internal lines>
</code>```

I guess it has to be something with sending the required parameter, but I'm not sure what exactly causes this 400 error.

答:
You do not have content in the request</p>
```<code>mockMvc.perform(
        MockMvcRequestBuilders.put("/api/update")
        .contentType(MediaType.APPLICATION_JSON_VALUE)
        .content(jsonString)
        .accept("application/json"))
        .andExpect(MockMvcResultMatchers.status().isOk());
}
</code>```

Body:
I have a problem with testing my Spring Boot Controller. I'm trying to test one of Controller put methods, but all I'm getting is Status expected:<200> but was:<400> error message.

My Controller:

@PutMapping(value = "/update", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> updateFields(@RequestBody List<UpdateModel> model) throws JsonProcessingException {
    return new ResponseEntity<>(vaultService.updateFields(model), HttpStatus.OK);
}

My ControllerTest:
The URL is ok, and I have a list just like in the get method in my controller.

@Test
void updateFieldsTest() throws Exception {
    List<UpdateModel> response = new ArrayList<>();
    UpdateModel updateModel = new UpdateModel();
    response.add(updateModel);
    when(vaultService.updateFields(anyList()))
            .thenReturn(String.valueOf(response));

mockMvc.perform(
        MockMvcRequestBuilders.put("/api/update")
        .contentType(MediaType.APPLICATION_JSON_VALUE)
        .accept("application/json"))
        .andExpect(MockMvcResultMatchers.status().isOk());
}

And here's an error message:

MockHttpServletRequest:
      HTTP Method = PUT
      Request URI = /api/update
       Parameters = {}
          Headers = [Content-Type:"application/json;charset=UTF-8", Accept:"application/json"]
             Body = null
    Session Attrs = {}

Handler:
             Type = hr.ogcs.ltt.api.lttapi.controller.LttController
           Method = hr.ogcs.ltt.api.lttapi.controller.LttController#updateFields(List)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = org.springframework.http.converter.HttpMessageNotReadableException

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 400
    Error message = null
          Headers = [Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers"]
     Content type = null
             Body =
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

Status expected:<200> but was:<400>
Expected :200
Actual   :400
<Click to see difference>
java.lang.AssertionError: Status expected:<200> but was:<400>
    at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:59)
    at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:122)
    at org.springframework.test.web.servlet.result.StatusResultMatchers.lambda$matcher$9(StatusResultMatchers.java:627)
    at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:212)
   at hr.ogcs.ltt.api.apicontroller.ControllerTest.updateFieldsTest(ControllerTest.java:113) <31 internal lines>
   at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)<9 internal lines>
   at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)<48 internal lines>

I guess it has to be something with sending the required parameter, but I'm not sure what exactly causes this 400 error.

Body:
You do not have content in the request

mockMvc.perform(
        MockMvcRequestBuilders.put("/api/update")
        .contentType(MediaType.APPLICATION_JSON_VALUE)
        .content(jsonString)
        .accept("application/json"))
        .andExpect(MockMvcResultMatchers.status().isOk());
}


问:
TypeError: 'ABCMeta' object is not subscriptable
Here is my code:

```<code>from collecionts.abc import Sequence
from typing import TypeVar

T = TypeVar('T')
def first(a: Sequence[T]) -> T:
    return a[0]
</code>```

In my understanding, I can pass any Sequence-like object as parameter into first function, like:

```<code>first([1,2,3])
</code>```

and it returns 1

However, it raises a TypeError:' ABCMeta' object is not subscriptable. What is going on here? How can I make it work that I have a function using typing module which can take first element whatever its type?

UPDATE

If I use from typing import Sequence,it runs alright,what is the difference between from collections.abc import Sequence and from typing import Sequence

答:
two things.

The first one is that the typing module will not raise errors at runtime if you pass arguments that do not respect the type you indicated. Typing module helps for general clarity and for intellisense or stuff like that.

Regarding the error that you encounter is probably beacuse of the python version you are using. Try to upgrade to python >= 3.9

Body:
Here is my code:

from collecionts.abc import Sequence
from typing import TypeVar

T = TypeVar('T')
def first(a: Sequence[T]) -> T:
    return a[0]

In my understanding, I can pass any Sequence-like object as parameter into first function, like:

first([1,2,3])

and it returns 1

However, it raises a TypeError:' ABCMeta' object is not subscriptable. What is going on here? How can I make it work that I have a function using typing module which can take first element whatever its type?

UPDATE

If I use from typing import Sequence,it runs alright,what is the difference between from collections.abc import Sequence and from typing import Sequence


问:
Can i let user to select which screen they want to load when they open app next time?
Initially when the user log in and go settings page can we let user to select which screen they want to be the home screen next time when the use logs in.
Example:

Splash Screen > Checks user is logged in> if logged in Home screen else Log in Screen.

Let user select which screen they want to be landed next time when logs in or reopening the app let's say products screen.

答:
```<code>You have to specify the user login id in the splash screen when the app is open it will check user login or not if the user login you can route it to whatever you want otherwise you can redirect to the login screen.

    I Used firebase for user authentication you can get an idea of how to save user id and get user id on splacescren using the shared preference plugin

        ///firebase login function
          static Future<User?> fireLogin({String ?email, String ?password,bool ?isManager,context}) async {
            SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
            FirebaseAuth _auth = FirebaseAuth.instance;
            try {
              final loggedInUser = await _auth.signInWithEmailAndPassword(
                  email: email.toString(), password: password.toString());
              print(_auth.currentUser!.uid);
              sharedPreferences.setString("User UID",_auth.currentUser!.uid );
             var  userId = sharedPreferences.getString("User UID");
             sharedPreferences.setBool("isManager", isManager!);
             sharedPreferences.getBool("isManager");
             var isManagerValue = sharedPreferences.getBool("isManager");
              print("userId------"+isManagerValue.toString());
              if (loggedInUser != null) {
                isManager == false
                    ? Navigator.pushReplacement(
                    context!,
                    MaterialPageRoute(
                        builder: (context) => EmployeeBottomNavBar()))
                    : Navigator.pushReplacement(
                    context!,
                    MaterialPageRoute(
                        builder: (context) => ManagerBottomNavBar()));
              }
            } on FirebaseAuthException catch (e) {

              if (e.code == 'user-not-found') {
                showToast(msg: "User not found!");
              } else if (e.code == 'wrong-password!') {
               showToast(msg: "Wrong password provided!");

              }
            }catch (e) {
              print(e);
              showToast(msg: "Please verify email and password!");
             /* final snackBar =
              SnackBar(
                  content: Text(e.toString()));
              ScaffoldMessenger.of(context).showSnackBar(snackBar);*/
            }
          }
    ///Placed these function into SplashScreen
        ///to check userID
         Future<dynamic>geFunction()async{
            SharedPreferences sharedPreferences= await  SharedPreferences.getInstance();
            userId = sharedPreferences.getString("User UID");
            print("user id -----------"+userId.toString());
            sharedPreferences.getBool("isManager");
            isManagerValue = sharedPreferences.getBool("isManager");
            print("userId------"+isManagerValue.toString());
            navigatePage();
         }
        /// Place these method into your splash screen
         Future<void>navigatePage()async{
            if(userId ==null){
              Future.delayed(Duration(seconds: 2), () {
                Navigator.pushNamedAndRemoveUntil(
                    context, RoutePath.selectUser, (route) => false);
              });
            }else{
              isManagerValue==true?Future.delayed(Duration(seconds: 2), () {
                Navigator.pushNamedAndRemoveUntil(
                    context, RoutePath.managerBottomNavBar, (route) => false);
              })
              : Future.delayed(Duration(seconds: 2), () {
                Navigator.pushNamedAndRemoveUntil(
                    context,RoutePath.employeeBottomNavBar, (route) => false);
              })
              ;

            }

         }
      Put getfunction into initstate in splash screen
         @override
          void initState() {
            super.initState();
             getFunction();

          }
</code>```


问:
Looping over related (M2M) items in the order specified by the intermediatry relationship
Using the example from the docs:
https://docs.djangoproject.com/en/1.2/topics/db/models/#intermediary-manytomany

I can loop over the groups and show the people in each:

```<code>{% for group in group_list %}
 {{ group.name }}:
 {% for member in group.members.all %}
  {{ member.name }}
 {% endfor %}
{% endfor %}
</code>```

But I can't figure out how to show the members in the order they joined (i.e., by membership.date_joined). Using dictsort after the all like so:

```<code>{% for member in group.members.all|dictsort:"date_joined" %}
</code>```

results in an empty member list. And I've tried using members.through, but can't seem to get any data from that, either.

答:
Found a work around:

In the model for class Group, I added a method

```<code>def members_by_date(self):
 return Membership.objects.filter(group = self).order_by('date_joined')
</code>```

And in the template:

```<code>{% for membership in group.members_by_date %}
 {{ membership.person.name }}
</code>```

I would still like to know how to do on-the-fly ordering in the template, though, using dictsort or otherwise, if anyone has a hint for that.

Body:
Using the example from the docs:
https://docs.djangoproject.com/en/1.2/topics/db/models/#intermediary-manytomany

I can loop over the groups and show the people in each:

{% for group in group_list %}
 {{ group.name }}:
 {% for member in group.members.all %}
  {{ member.name }}
 {% endfor %}
{% endfor %}

But I can't figure out how to show the members in the order they joined (i.e., by membership.date_joined). Using dictsort after the all like so:

{% for member in group.members.all|dictsort:"date_joined" %}

results in an empty member list. And I've tried using members.through, but can't seem to get any data from that, either.

Body:
Found a work around:

In the model for class Group, I added a method

def members_by_date(self):
 return Membership.objects.filter(group = self).order_by('date_joined')

And in the template:

{% for membership in group.members_by_date %}
 {{ membership.person.name }}

I would still like to know how to do on-the-fly ordering in the template, though, using dictsort or otherwise, if anyone has a hint for that.


问:
How to manage multiple state on same screen using flutter bloc
i have a screen with three widget [widgetA, widgetB, widgetC]
and i have a bloc[BlocA] which is responsible for the data fetching and displaying on this screen
i have three event [eventA, eventB, eventC] which render the widget [widgetA, widgetB, widgetC]
and i have three state [stateA, stateB, stateC] which are responsible for managing state of widget [widgetA, widgetB, widgetC]
i have attached all code to reproduce and test the case.

I am only able to display one state and their respective widget at a time whereas i want to display all three state and its widget based on their event.
any help would be highly appreciated.

only way i tried to achieve the same is by making separate bloc and event class for each widget, but somehow i am not satisfied with this approach.

what would be the best approach to achieve this use case.

TestScreen

```<code>import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:locus/blocs/test/testbloc.dart';

class TestScreen extends StatelessWidget {
  const TestScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
        create: (context) => TestBloc()..add(const TestEvent1()),
        child: Scaffold(
          appBar: AppBar(
            title: const Text('Test'),
          ),
          body: Stack(
            children: [
              Builder(builder: (context) {
                return Padding(
                  padding: const EdgeInsets.only(top: 0),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      ElevatedButton(
                          onPressed: () =>
                              context.read<TestBloc>().add(const TestEvent1()),
                          child: const Text("Event1")),
                      const SizedBox(width: 10),
                      ElevatedButton(
                          onPressed: () => context
                              .read<TestBloc>()
                              .add(const TestEvent2(" event 2")),
                          child: const Text("Event2")),
                      const SizedBox(width: 10),
                      ElevatedButton(
                          onPressed: () => context
                              .read<TestBloc>()
                              .add(const TestEvent3(false)),
                          child: const Text("Event3")),
                    ],
                  ),
                );
              }),
              BlocBuilder<TestBloc, TestState>(
                builder: (context, state) {
                  if (state is TestState1) {
                    return const Center(child: Text("I am state 1"));
                  }
                  return const SizedBox.shrink();
                },
              ),
              Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  BlocBuilder<TestBloc, TestState>(
                    builder: (context, state) {
                      if (state is TestState2) {
                        return Center(
                            child: Text("I am state 2 ${state.message}"));
                      }
                      return const SizedBox.shrink();
                    },
                  ),
                  BlocBuilder<TestBloc, TestState>(
                    builder: (context, state) {
                      if (state is TestState3) {
                        return Center(
                            child: Text("I am state 3 ${state.check}"));
                      }
                      return const SizedBox.shrink();
                    },
                  ),
                ],
              ),
            ],
          ),
        ));
  }
}
</code>```

TestBloc

```<code>
import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:bloc/bloc.dart';
part 'test_state.dart';
part 'test_event.dart';

class TestBloc extends Bloc<TestEvent, TestState> {
  TestBloc() : super(TestInitializing()) {
    on<TestEvent1>((event, emit) => test1(event, emit));
    on<TestEvent2>((event, emit) => test2(event, emit));
    on<TestEvent3>((event, emit) => test3(event, emit));
  }

  Future test1(TestEvent1 event, Emitter<TestState> emit) async {
    try {
      emit(const TestState1());
    } catch (_) {}
  }

  Future test2(TestEvent2 event, Emitter<TestState> emit) async {
    try {
      emit(const TestState2(message: "Hello"));
    } catch (_) {}
  }

  Future test3(TestEvent3 event, Emitter<TestState> emit) async {
    try {
      emit(const TestState3(check: true));
    } catch (_) {}
  }
}
</code>```

TestEvent

```<code>
@immutable
abstract class TestEvent extends Equatable {
  const TestEvent();
}

class TestEvent1 extends TestEvent {
  const TestEvent1();
  @override
  List<Object> get props => [];
}

class TestEvent2 extends TestEvent {
  final String message;
  const TestEvent2(this.message);
  @override
  List<Object> get props => [message];
}

class TestEvent3 extends TestEvent {
  final bool check;
  const TestEvent3(this.check);
  @override
  List<Object> get props => [check];
}
</code>```

TestState

```<code>
@immutable
abstract class TestState extends Equatable {
  const TestState();
}

class TestInitializing extends TestState {
  @override
  List<Object> get props => [];
}

class TestState1 extends TestState {
  const TestState1();
  @override
  List<Object?> get props => [];
}

class TestState2 extends TestState {
  final String message;
  const TestState2({
    required this.message,
  });
  @override
  List<Object> get props => [message];
}

class TestState3 extends TestState {
  final bool check;
  const TestState3({
    required this.check,
  });
  @override
  List<Object> get props => [check];
}
</code>```

testbloc barrel class

```<code>export 'test_bloc.dart';
</code>```

答:
A bloc can only have one state at a time. If you want more states than that you'll have to either maintain a custom internal state mechanism inside TestBloc or create 3 separate TestBlocs and then provide each BlocBuilder with each TestBloc like so:

```<code>class TestScreen extends StatelessWidget {
  TestScreen({Key? key}) : super(key: key) {
  }

  final TestBloc bloc1 = TestBloc();
  final TestBloc bloc2 = TestBloc();
  final TestBloc bloc3 = TestBloc();

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
        create: (context) => TestBloc()..add(const TestEvent1()),
        child: Scaffold(
          appBar: AppBar(
            title: const Text('Test'),
          ),
          body: Stack(
            children: [
              Builder(builder: (context) {
                return Padding(
                  padding: const EdgeInsets.only(top: 0),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      ElevatedButton(
                          onPressed: () =>
                              bloc1.add(const TestEvent1()),
                          child: const Text("Event1")),
                      const SizedBox(width: 10),
                      ElevatedButton(
                          onPressed: () => bloc2.add(const TestEvent2(" event 2")),
                          child: const Text("Event2")),
                      const SizedBox(width: 10),
                      ElevatedButton(
                          onPressed: () => bloc3.add(const TestEvent3(false)),
                          child: const Text("Event3")),
                    ],
                  ),
                );
              }),
              BlocBuilder<TestBloc, TestState>(
                bloc: bloc1,
                builder: (context, state) {
                  if (state is TestState1) {
                    return const Center(child: Text("I am state 1"));
                  }
                  return const SizedBox.shrink();
                },
              ),
              Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  BlocBuilder<TestBloc, TestState>(
                    bloc: bloc2,
                    builder: (context, state) {
                      if (state is TestState2) {
                        return Center(
                            child: Text("I am state 2 ${state.message}"));
                      }
                      return const SizedBox.shrink();
                    },
                  ),
                  BlocBuilder<TestBloc, TestState>(
                    bloc: bloc3,
                    builder: (context, state) {
                      if (state is TestState3) {
                        return Center(
                            child: Text("I am state 3 ${state.check}"));
                      }
                      return const SizedBox.shrink();
                    },
                  ),
                ],
              ),
            ],
          ),
        ));
  }
}
</code>```

However making 3 separate blocs (TestBloc1, TestBloc2, TestBloc3) isn't necessaryly a bad way to go in regards to speration of concerns.

Body:
i have a screen with three widget [widgetA, widgetB, widgetC]
and i have a bloc[BlocA] which is responsible for the data fetching and displaying on this screen
i have three event [eventA, eventB, eventC] which render the widget [widgetA, widgetB, widgetC]
and i have three state [stateA, stateB, stateC] which are responsible for managing state of widget [widgetA, widgetB, widgetC]
i have attached all code to reproduce and test the case.

I am only able to display one state and their respective widget at a time whereas i want to display all three state and its widget based on their event.
any help would be highly appreciated.

only way i tried to achieve the same is by making separate bloc and event class for each widget, but somehow i am not satisfied with this approach.

what would be the best approach to achieve this use case.

TestScreen

import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:locus/blocs/test/testbloc.dart';

class TestScreen extends StatelessWidget {
  const TestScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
        create: (context) => TestBloc()..add(const TestEvent1()),
        child: Scaffold(
          appBar: AppBar(
            title: const Text('Test'),
          ),
          body: Stack(
            children: [
              Builder(builder: (context) {
                return Padding(
                  padding: const EdgeInsets.only(top: 0),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      ElevatedButton(
                          onPressed: () =>
                              context.read<TestBloc>().add(const TestEvent1()),
                          child: const Text("Event1")),
                      const SizedBox(width: 10),
                      ElevatedButton(
                          onPressed: () => context
                              .read<TestBloc>()
                              .add(const TestEvent2(" event 2")),
                          child: const Text("Event2")),
                      const SizedBox(width: 10),
                      ElevatedButton(
                          onPressed: () => context
                              .read<TestBloc>()
                              .add(const TestEvent3(false)),
                          child: const Text("Event3")),
                    ],
                  ),
                );
              }),
              BlocBuilder<TestBloc, TestState>(
                builder: (context, state) {
                  if (state is TestState1) {
                    return const Center(child: Text("I am state 1"));
                  }
                  return const SizedBox.shrink();
                },
              ),
              Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  BlocBuilder<TestBloc, TestState>(
                    builder: (context, state) {
                      if (state is TestState2) {
                        return Center(
                            child: Text("I am state 2 ${state.message}"));
                      }
                      return const SizedBox.shrink();
                    },
                  ),
                  BlocBuilder<TestBloc, TestState>(
                    builder: (context, state) {
                      if (state is TestState3) {
                        return Center(
                            child: Text("I am state 3 ${state.check}"));
                      }
                      return const SizedBox.shrink();
                    },
                  ),
                ],
              ),
            ],
          ),
        ));
  }
}

TestBloc

import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:bloc/bloc.dart';
part 'test_state.dart';
part 'test_event.dart';

class TestBloc extends Bloc<TestEvent, TestState> {
  TestBloc() : super(TestInitializing()) {
    on<TestEvent1>((event, emit) => test1(event, emit));
    on<TestEvent2>((event, emit) => test2(event, emit));
    on<TestEvent3>((event, emit) => test3(event, emit));
  }

  Future test1(TestEvent1 event, Emitter<TestState> emit) async {
    try {
      emit(const TestState1());
    } catch (_) {}
  }

  Future test2(TestEvent2 event, Emitter<TestState> emit) async {
    try {
      emit(const TestState2(message: "Hello"));
    } catch (_) {}
  }

  Future test3(TestEvent3 event, Emitter<TestState> emit) async {
    try {
      emit(const TestState3(check: true));
    } catch (_) {}
  }
}

TestEvent

@immutable
abstract class TestEvent extends Equatable {
  const TestEvent();
}

class TestEvent1 extends TestEvent {
  const TestEvent1();
  @override
  List<Object> get props => [];
}

class TestEvent2 extends TestEvent {
  final String message;
  const TestEvent2(this.message);
  @override
  List<Object> get props => [message];
}

class TestEvent3 extends TestEvent {
  final bool check;
  const TestEvent3(this.check);
  @override
  List<Object> get props => [check];
}

TestState

@immutable
abstract class TestState extends Equatable {
  const TestState();
}

class TestInitializing extends TestState {
  @override
  List<Object> get props => [];
}

class TestState1 extends TestState {
  const TestState1();
  @override
  List<Object?> get props => [];
}

class TestState2 extends TestState {
  final String message;
  const TestState2({
    required this.message,
  });
  @override
  List<Object> get props => [message];
}

class TestState3 extends TestState {
  final bool check;
  const TestState3({
    required this.check,
  });
  @override
  List<Object> get props => [check];
}

testbloc barrel class

export 'test_bloc.dart';

Body:
A bloc can only have one state at a time. If you want more states than that you'll have to either maintain a custom internal state mechanism inside TestBloc or create 3 separate TestBlocs and then provide each BlocBuilder with each TestBloc like so:

class TestScreen extends StatelessWidget {
  TestScreen({Key? key}) : super(key: key) {
  }

  final TestBloc bloc1 = TestBloc();
  final TestBloc bloc2 = TestBloc();
  final TestBloc bloc3 = TestBloc();

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
        create: (context) => TestBloc()..add(const TestEvent1()),
        child: Scaffold(
          appBar: AppBar(
            title: const Text('Test'),
          ),
          body: Stack(
            children: [
              Builder(builder: (context) {
                return Padding(
                  padding: const EdgeInsets.only(top: 0),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      ElevatedButton(
                          onPressed: () =>
                              bloc1.add(const TestEvent1()),
                          child: const Text("Event1")),
                      const SizedBox(width: 10),
                      ElevatedButton(
                          onPressed: () => bloc2.add(const TestEvent2(" event 2")),
                          child: const Text("Event2")),
                      const SizedBox(width: 10),
                      ElevatedButton(
                          onPressed: () => bloc3.add(const TestEvent3(false)),
                          child: const Text("Event3")),
                    ],
                  ),
                );
              }),
              BlocBuilder<TestBloc, TestState>(
                bloc: bloc1,
                builder: (context, state) {
                  if (state is TestState1) {
                    return const Center(child: Text("I am state 1"));
                  }
                  return const SizedBox.shrink();
                },
              ),
              Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  BlocBuilder<TestBloc, TestState>(
                    bloc: bloc2,
                    builder: (context, state) {
                      if (state is TestState2) {
                        return Center(
                            child: Text("I am state 2 ${state.message}"));
                      }
                      return const SizedBox.shrink();
                    },
                  ),
                  BlocBuilder<TestBloc, TestState>(
                    bloc: bloc3,
                    builder: (context, state) {
                      if (state is TestState3) {
                        return Center(
                            child: Text("I am state 3 ${state.check}"));
                      }
                      return const SizedBox.shrink();
                    },
                  ),
                ],
              ),
            ],
          ),
        ));
  }
}

However making 3 separate blocs (TestBloc1, TestBloc2, TestBloc3) isn't necessaryly a bad way to go in regards to speration of concerns.


问:
Apache does not start at boot on OpenSUSE
I want Apache2 to start att boot. This is what I have

ls -l in

```<code>/etc/init.d/rc5.d
</code>```

lists, among a lot of other things, this:

```<code>lrwxrwxrwx 1 root root 10 Aug 18 10:35 S12apache2 -> ../apache2
</code>```

In /etc/init.d/ 'apache2' is indeed located. And ls -l on apache2 lists

```<code>-rwxr--r-- 1 root root 10635 Feb 18 22:09 apache2
</code>```

/sbin/chkconfig -a apache2 prints

```<code>apache2                   0:off  1:off  2:off  3:on   4:off  5:on   6:off
</code>```

Shouldn't this be necessary in order for Apache to start at boot?

I usually start manually using sudo /usr/sbin/rcapache2 restart

/Niklas

答: chmod 755 /etc/init.d/apache2 fixed it

Body:
I want Apache2 to start att boot. This is what I have

ls -l in

/etc/init.d/rc5.d

lists, among a lot of other things, this:

lrwxrwxrwx 1 root root 10 Aug 18 10:35 S12apache2 -> ../apache2

In /etc/init.d/ 'apache2' is indeed located. And ls -l on apache2 lists

-rwxr--r-- 1 root root 10635 Feb 18 22:09 apache2

/sbin/chkconfig -a apache2 prints

apache2                   0:off  1:off  2:off  3:on   4:off  5:on   6:off

Shouldn't this be necessary in order for Apache to start at boot?

I usually start manually using sudo /usr/sbin/rcapache2 restart

/Niklas

Body: chmod 755 /etc/init.d/apache2 fixed it


问:
Combining of logical conditions in IF statement
I just notice the if condition below:

//1
if ((i >= 0) != (j >= 0))
 return false;
```
<p>is just a short way for:</p>
<pre class="lang-js prettyprint-override"><code>//2
if((i>=0 && j < 0) || (i < 0 && j >=0))
 return false;
</code>```

Going from 1. to 2. takes some time to figure out, but how do we deduce the logic to go from 2. to 1.?

答:
If you have any two boolean statements A and B then A != B means that they are different. I.e. either A is true and B is false, or A is false and B is true. This goes also the other way if A is true and B is false, or A is false and B is true, then A does not equal B.

In other words (A != B) = ((A && !B) || (!A && B)). Therefore, statement 1 and 2 are the same

If you feel my argumentation is imprecise, you can use truth tables to proof it rigorous mathematically:

A
B
A!=B
(A && !B)
(!A && B)
(A && !B) || (!A && B))

true
true
false
false
false
false

true
false
true
true
false
true

false
true
true
false
true
true

false
false
false
false
false
false

Body:
I just notice the if condition below:

//1
if ((i >= 0) != (j >= 0))
 return false;

is just a short way for:

//2
if((i>=0 && j < 0) || (i < 0 && j >=0))
 return false;

Going from 1. to 2. takes some time to figure out, but how do we deduce the logic to go from 2. to 1.?


问:
How to verify that a website is reachable with Swift?
My app shall access a php file on a hosted website in order to get data from a backend SQL database. This works fine but I want to be prepared or all kind of possible errors. In case there is no internet connection or the host cannot be reached, an error is thrown - fine. But if the url address is modified to an address which does not exist on the host, no error is thrown. But I want to cover this condition as well. What is the best way in Swift to do this?

Here is my code:

```<code>    @available(iOS 15.0, *)
   func checkCustomerExistsInBackend(emailAddress: String) async throws -> String
   {

    let url = URL(string: "https://myHost.de/mySite/checkCustomerexists.php")!
    var request = URLRequest(url: url)
    request.httpMethod = "POST"

    let dataString = "EmailAddress=\(emailAddress)"
    var returnValue = ""
    do {
        let dataD = dataString.data(using: .utf8)
        let (data, _) = try await URLSession.shared.upload(for: request, from: dataD!, delegate: nil)
        let answer = try JSONDecoder().decode(BackendMessage.self, from: data)
        returnValue = answer.Message
    }
    catch {
        let myError: NSError = error as NSError
        switch myError.localizedDescription {
        case "The Internet connection appears to be offline.":
            throw BackendError.noInternet
        case "A server with the specified hostname could not be found.":
            throw BackendError.serverNotFound
        default:
            throw error
        }
    }
    return returnValue
}
</code>```

The url above with "https://myHost.de/mySite/checkCustomerexists.php" is not the true address of course. But when I replace "myHost.de" with the true host address, no error is thrown even though a site "mySite" does not exist.

I spent several hours searching for the answer in SO but could not find anything that works for my constellation.

Any hint would be appreciated!

答:
Larme's comment answered this question. In case it is helpful for anybody stepping over the same subject, here the modified code of my example with the solution based on Larme's advice:</p>
```<code>   @available(iOS 15.0, *)
func checkCustomerExistsInBackend(emailAddress: String) async throws -> String {

    let url = URL(string: "https://myHost.de/mySite/checkCustomerexists.php")!
    var request = URLRequest(url: url)
    request.httpMethod = "POST"

    let dataString = "EmailAddress=\(emailAddress)"
    var returnValue = ""
    do {
        let dataD = dataString.data(using: .utf8)
        let (data, response) = try await URLSession.shared.upload(for: request, from: dataD!, delegate: nil)

        let httpURLResponse = response as? HTTPURLResponse
        let statusCode = httpURLResponse?.statusCode
        if statusCode != 404 {
            let answer = try JSONDecoder().decode(BackendMessage.self, from: data)
            returnValue = answer.Message
        }
        else {
            throw BackendError.invalidURL
        }
    }
    catch {
        let myError: NSError = error as NSError
        print(myError.localizedDescription)
        switch myError.localizedDescription {
        case "The Internet connection appears to be offline.":
            throw BackendError.noInternet
        case "A server with the specified hostname could not be found.":
            throw BackendError.serverNotFound
        default:
            throw error
        }
    }
    return returnValue
}
</code>```

Body:
My app shall access a php file on a hosted website in order to get data from a backend SQL database. This works fine but I want to be prepared or all kind of possible errors. In case there is no internet connection or the host cannot be reached, an error is thrown - fine. But if the url address is modified to an address which does not exist on the host, no error is thrown. But I want to cover this condition as well. What is the best way in Swift to do this?

Here is my code:

    @available(iOS 15.0, *)
   func checkCustomerExistsInBackend(emailAddress: String) async throws -> String
   {

    let url = URL(string: "https://myHost.de/mySite/checkCustomerexists.php")!
    var request = URLRequest(url: url)
    request.httpMethod = "POST"

    let dataString = "EmailAddress=\(emailAddress)"
    var returnValue = ""
    do {
        let dataD = dataString.data(using: .utf8)
        let (data, _) = try await URLSession.shared.upload(for: request, from: dataD!, delegate: nil)
        let answer = try JSONDecoder().decode(BackendMessage.self, from: data)
        returnValue = answer.Message
    }
    catch {
        let myError: NSError = error as NSError
        switch myError.localizedDescription {
        case "The Internet connection appears to be offline.":
            throw BackendError.noInternet
        case "A server with the specified hostname could not be found.":
            throw BackendError.serverNotFound
        default:
            throw error
        }
    }
    return returnValue
}

The url above with "https://myHost.de/mySite/checkCustomerexists.php" is not the true address of course. But when I replace "myHost.de" with the true host address, no error is thrown even though a site "mySite" does not exist.

I spent several hours searching for the answer in SO but could not find anything that works for my constellation.

Any hint would be appreciated!

Body:
Larme's comment answered this question. In case it is helpful for anybody stepping over the same subject, here the modified code of my example with the solution based on Larme's advice:

   @available(iOS 15.0, *)
func checkCustomerExistsInBackend(emailAddress: String) async throws -> String {

    let url = URL(string: "https://myHost.de/mySite/checkCustomerexists.php")!
    var request = URLRequest(url: url)
    request.httpMethod = "POST"

    let dataString = "EmailAddress=\(emailAddress)"
    var returnValue = ""
    do {
        let dataD = dataString.data(using: .utf8)
        let (data, response) = try await URLSession.shared.upload(for: request, from: dataD!, delegate: nil)

        let httpURLResponse = response as? HTTPURLResponse
        let statusCode = httpURLResponse?.statusCode
        if statusCode != 404 {
            let answer = try JSONDecoder().decode(BackendMessage.self, from: data)
            returnValue = answer.Message
        }
        else {
            throw BackendError.invalidURL
        }
    }
    catch {
        let myError: NSError = error as NSError
        print(myError.localizedDescription)
        switch myError.localizedDescription {
        case "The Internet connection appears to be offline.":
            throw BackendError.noInternet
        case "A server with the specified hostname could not be found.":
            throw BackendError.serverNotFound
        default:
            throw error
        }
    }
    return returnValue
}


问:
jq: pick value if field exist
This is my script:

```<code>def pick_partOf($uids):
    (reduce $uids[] as $uid (
        {};
        . + ($uid | {(.oid1): .id})
    )) as $dict
    | map(. + { partOf: $dict[."parent-identifier-value"] } | del(..|nulls));

def pick_organization:
    {
        resourceType: "Organization",
        active: true,
        partOf: .partOf?
    };

pick_partOf($identifiers) | pick_organization
</code>```

Problem here, is that sometimes some input objects doesn't contains ."parent-identifier-value", and I'm getting:

jq: error (at rsan.json:7): Cannot index object with null

Those are my input objects:

{
  "identifier-value": "61",
  "name": "name61"
}
{
  "id": "62",
  "name": "name62",
  "parent-identifier-value": "61"
}
```
<p>Currently, I'm launching jq using empty array as <code>$identifiers</code> arg:</p>
```jq -s -f build-organization-bundle.jq --argjson identifiers '[]' rsan.json
```
<p>However, my <code>identifiers</code> is an other json files like this:</p>
<pre class="lang-json prettyprint-override"><code>{
  "id": "be8a02b6-54b9-450f-bf45-f28ab7ebf2dd",
  "oid1": "61"
}
{
  "id": "f1652f3a-bca9-433c-a2c4-c924811196f6",
  "oid1": "62"
}
</code>```

I've tried with:

```<code>def pick_partOf($uids):
    (reduce $uids[] as $uid (
        {};
        . + ($uid | {(.oid1): .id})
    )) as $dict
    | map(. + (
        if (.|has("parent-identifier-value")) then
        { partOf: $dict[."parent-identifier-value"] }
        else null end
    ))
    | del(..|nulls));
</code>```

But here I'm facing with some syntax issue I don't quite figure out how to fix it.

答:
You did not specify why you want pick_partOf to achieve.

If its output should be

{
  "identifier-value": "61",
  "name": "name61"
}
{
  "id": "62",
  "name": "name62",
  "parent-identifier-value": "61",
  "partOf": "be8a02b6-54b9-450f-bf45-f28ab7ebf2dd"
}
```
<p>then you can use</p>
```if ."parent-identifier-value" then
   .partOf = $dict[."parent-identifier-value"]
else
   .
end
```
<p>Demo on jqplay</p>
<p>Repeating <code>."parent-identifier-value"</code> was annoying me.</p>
```."parent-identifier-value" as $piv |
if $piv then .partOf = $dict[$piv] else . end
```

Demo on jqplay

Title: jq: pick value if field exist

Body:
This is my script:

def pick_partOf($uids):
    (reduce $uids[] as $uid (
        {};
        . + ($uid | {(.oid1): .id})
    )) as $dict
    | map(. + { partOf: $dict[."parent-identifier-value"] } | del(..|nulls));

def pick_organization:
    {
        resourceType: "Organization",
        active: true,
        partOf: .partOf?
    };

pick_partOf($identifiers) | pick_organization

Problem here, is that sometimes some input objects doesn't contains ."parent-identifier-value", and I'm getting:

jq: error (at rsan.json:7): Cannot index object with null

Those are my input objects:

{
  "identifier-value": "61",
  "name": "name61"
}
{
  "id": "62",
  "name": "name62",
  "parent-identifier-value": "61"
}

Currently, I'm launching jq using empty array as $identifiers arg:

jq -s -f build-organization-bundle.jq --argjson identifiers '[]' rsan.json

However, my identifiers is an other json files like this:

{
  "id": "be8a02b6-54b9-450f-bf45-f28ab7ebf2dd",
  "oid1": "61"
}
{
  "id": "f1652f3a-bca9-433c-a2c4-c924811196f6",
  "oid1": "62"
}

I've tried with:

def pick_partOf($uids):
    (reduce $uids[] as $uid (
        {};
        . + ($uid | {(.oid1): .id})
    )) as $dict
    | map(. + (
        if (.|has("parent-identifier-value")) then
        { partOf: $dict[."parent-identifier-value"] }
        else null end
    ))
    | del(..|nulls));

But here I'm facing with some syntax issue I don't quite figure out how to fix it.

Body:
You did not specify why you want pick_partOf to achieve.

If its output should be

{
  "identifier-value": "61",
  "name": "name61"
}
{
  "id": "62",
  "name": "name62",
  "parent-identifier-value": "61",
  "partOf": "be8a02b6-54b9-450f-bf45-f28ab7ebf2dd"
}

then you can use

if ."parent-identifier-value" then
   .partOf = $dict[."parent-identifier-value"]
else
   .
end

Demo on jqplay

Repeating ."parent-identifier-value" was annoying me.

."parent-identifier-value" as $piv |
if $piv then .partOf = $dict[$piv] else . end

Demo on jqplay


问:
I need a query to create a week circle
I already write this query

```<code>    Select to_date(concat(to_char(kyc.kyc_verify_date,'YY-MM'),'-01'),'YY-MM-DD') AS "Month"
    Count (columnname)
    From kyc;
</code>```

And the table result i given like this:

```<code>         Month                count

January 1, 2021, 12:00 AM     2324

February 1, 2021, 12:00 AM    23245
</code>```

As you can see, the date always start from the 1st day of the month.

Now i need a query for a week, just like that query, it will start from Monday
Can someone help me with this.

Thank you

答:
Use the date_trunc function, it does exactly what you need (and it will also do the trick for months, so you can simplify your original example):

```<code>SELECT date_trunc('week', current_timestamp);

       date_trunc
════════════════════════
 2022-02-07 00:00:00+01
(1 row)
</code>```

Title: I need a query to create a week circle

Body:
I already write this query

    Select to_date(concat(to_char(kyc.kyc_verify_date,'YY-MM'),'-01'),'YY-MM-DD') AS "Month"
    Count (columnname)
    From kyc;

And the table result i given like this:

         Month                count

January 1, 2021, 12:00 AM     2324

February 1, 2021, 12:00 AM    23245

As you can see, the date always start from the 1st day of the month.

Now i need a query for a week, just like that query, it will start from Monday
Can someone help me with this.

Thank you

Body:
Use the date_trunc function, it does exactly what you need (and it will also do the trick for months, so you can simplify your original example):

SELECT date_trunc('week', current_timestamp);

       date_trunc
════════════════════════
 2022-02-07 00:00:00+01
(1 row)


问:
Generated constants for enum values
I'd need to store some properties of the enum's entries in their constants. For example indicate whether a color is cold or warm.

```<code>enum Colors
{
  Yellow, // warm
  Blue,   // cold
  Gray,   // cold
  Red,    // warm
  // etc.
}
</code>```

In C++ I would define a macro to generate bitmasks for the constants.
Something like:

```<code>#define WARM 1
#define COLD 0

#define MAKECOLOR(index, type) ((index << 8) | type)

enum Colors
{
  Yellow = MAKECOLOR(0, WARM),
  Blue   = MAKECOLOR(1, COLD),
  Gray   = MAKECOLOR(2, COLD),
  Red    = MAKECOLOR(3, WARM),
  // etc.
}
</code>```

In C# this is not possible because there are no macros. I want to avoid writing bitmask expressions directly in the enum. Like this:

```<code>  ...
  Gray   = ((2 << 8) | 0),
  ...
</code>```

Any ideas?

P.S.

Yes, I'm a syntactic sugar freak. :D

答:
In C#, enum need to have const values defined at compile-time. In sum, C# is more const than C++.

In C#, const is used to denote a compile-time constant expression. It'd be similar to this C++ code:

```<code>enum {
  count = buffer.Length;
}
</code>```

Because buffer.Length is evaluated at runtime, it is not a constant expression, and so this would produce a compile error.

C# has a readonly keyword which is a bit more similar to C++'s const. (It's still much more limited though, and there is no such thing as const-correctness in C#).

const is meant to represent a compile-time constant... not just a read-only value.

You can't specify read-only but non-compile-time-constant local variables in C#, I'm afraid. Some local variables are inherently read-only - such as the iteration variable in a foreach loop and any variables declared in the first part of a using statement. However, you can't create your own read-only variables.

If you use const within a method, that effectively replaces any usage of that identifier with the compile-time constant value.

So, you are going to have to define your values at compile-time in your enum. They cannot be evaluated at run-time. Those are the rules.

Title: Generated constants for enum values

Body:
I'd need to store some properties of the enum's entries in their constants. For example indicate whether a color is cold or warm.

enum Colors
{
  Yellow, // warm
  Blue,   // cold
  Gray,   // cold
  Red,    // warm
  // etc.
}

In C++ I would define a macro to generate bitmasks for the constants.
Something like:

#define WARM 1
#define COLD 0

#define MAKECOLOR(index, type) ((index << 8) | type)

enum Colors
{
  Yellow = MAKECOLOR(0, WARM),
  Blue   = MAKECOLOR(1, COLD),
  Gray   = MAKECOLOR(2, COLD),
  Red    = MAKECOLOR(3, WARM),
  // etc.
}

In C# this is not possible because there are no macros. I want to avoid writing bitmask expressions directly in the enum. Like this:

  ...
  Gray   = ((2 << 8) | 0),
  ...

Any ideas?

P.S.

Yes, I'm a syntactic sugar freak. :D

Body:
In C#, enum need to have const values defined at compile-time. In sum, C# is more const than C++.

In C#, const is used to denote a compile-time constant expression. It'd be similar to this C++ code:

enum {
  count = buffer.Length;
}

Because buffer.Length is evaluated at runtime, it is not a constant expression, and so this would produce a compile error.

C# has a readonly keyword which is a bit more similar to C++'s const. (It's still much more limited though, and there is no such thing as const-correctness in C#).

const is meant to represent a compile-time constant... not just a read-only value.

You can't specify read-only but non-compile-time-constant local variables in C#, I'm afraid. Some local variables are inherently read-only - such as the iteration variable in a foreach loop and any variables declared in the first part of a using statement. However, you can't create your own read-only variables.

If you use const within a method, that effectively replaces any usage of that identifier with the compile-time constant value.

So, you are going to have to define your values at compile-time in your enum. They cannot be evaluated at run-time. Those are the rules.


问:
Extract multi value points using CDO into a single text file
I have come across the code

cdo -outputtab, date,value -remapnn,lon=X/lat=Y infile.nc > Outfile.txt

which very nicely extracts for a single point only. Is there any way I can extract time series data from netcdf file for multiple points using a single command line or by using some script and get the output in a single text file? Something like this -

lat-lon1, lat-lon2, lat-lon3

235, 256, 254

264, 246, 249

289, 278, 259

......

答:
You can solve this in Python using my package nctoolkit, which uses CDO as a backend. Code would be something like the following:

```<code>import pandas as pd
import nctoolkit as nc
# load data
ds = nc.open_data("in.nc")
# define coords you want to regrid to
coords = pd.DataFrame({"lon":[0, 10, 20], "lat":[0, 10, 20]})
# regrid using nn
ds.regrid(coords, "nn")
# convert to pandas df
df = ds.to_dataframe()
</code>```

Under the hood this will generate a single grid file based on the specified coordinates and then call CDO once to do the regridding, so should be computationally efficient.

Body:
You can solve this in Python using my package nctoolkit, which uses CDO as a backend. Code would be something like the following:

import pandas as pd
import nctoolkit as nc
# load data
ds = nc.open_data("in.nc")
# define coords you want to regrid to
coords = pd.DataFrame({"lon":[0, 10, 20], "lat":[0, 10, 20]})
# regrid using nn
ds.regrid(coords, "nn")
# convert to pandas df
df = ds.to_dataframe()

Under the hood this will generate a single grid file based on the specified coordinates and then call CDO once to do the regridding, so should be computationally efficient.


问:
The generate command requires to be run in an Angular project, but a project definition could not be found
at the time I'm going to create component using ng g component command I facing with this error what I need to do to solve this.

"The generate command requires to be run in an Angular project, but a project definition could not be found."

答: After ng new project make sure you entered project directory in terminal.</p>