问:
How to call external API in django application with username and password
I am trying to receive data from an API endpoint in my django application. I found the solution here: Django rest framework & external api.

But when I tried this solution I got error:

SSLError at /external-api
HTTPSConnectionPool(host='example.com', port=443): Max retries exceeded with url: /example (Caused by SSLError(SSLError("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')])")))

When I open the external API directly on browser, I need to provide the username and password of the account which has access to that API. But while calling through API I am not providing it anywhere.

I am not sure how to set the username and password in the URL or in the settings file to access the external API.

Edited: Also I am not sure what could be the reason behind the error.

答:
Try this

```<code>import requests
from requests.auth import HTTPBasicAuth

response = requests.get('your-url', auth=HTTPBasicAuth('your-username', 'your-password'))

print(response)

</code>```

Body:
Try this

import requests
from requests.auth import HTTPBasicAuth

response = requests.get('your-url', auth=HTTPBasicAuth('your-username', 'your-password'))

print(response)


来源: stackexchange

问:
how to read the response from a web site?
I have a website url which gives corresponding city names by taking zip code as input parameter. Now I want to know how to read the response from the site.

This is the link I am using http://zipinfo.com/cgi-local/zipsrch.exe?zip=60680

答:
Used the WebClient Class (http://msdn.microsoft.com/en-us/library/system.net.webclient%28v=VS.100%29.aspx) to request the page and get the response as a string.

```<code>        WebClient wc = new WebClient();
        String s = wc.DownloadString(DestinationUrl);
</code>```

You can search the response for specific HTML using String.IndexOf, SubString, etc, regular expressions, or try something like the HTML Agility Pack (http://htmlagilitypack.codeplex.com/) which was created specifically to help parse HTML.

ContentLicense: CC BY-SA 3.0

Body:
Used the WebClient Class (http://msdn.microsoft.com/en-us/library/system.net.webclient%28v=VS.100%29.aspx) to request the page and get the response as a string.

        WebClient wc = new WebClient();
        String s = wc.DownloadString(DestinationUrl);

You can search the response for specific HTML using String.IndexOf, SubString, etc, regular expressions, or try something like the HTML Agility Pack (http://htmlagilitypack.codeplex.com/) which was created specifically to help parse HTML.


问:
How to resolve mutating state directly issue
I have inherited this code with mutated stated errors but I am having difficulty resolving it.

The issue is in the 'handleSomeFunctions'. THe is already useState being used and I believe I should be destructuring to shorten that and integrating the 'evt.target.value' just not sure how.

Can anyone point me in the right direction please?

```<code>import React, { Component } from "react";
import queryRequest from "../../../utils/queryRequest";
import { RoleLink } from "../routes";

import Card from "react-bootstrap/Card";
import Row from "react-bootstrap/Row";
import Col from "react-bootstrap/Col";
import Button from "react-bootstrap/Button";
import Form from "react-bootstrap/Form";

import AuthContext from "../../../context/auth-context";
import Swal from "sweetalert2";

import { translate } from "react-i18next";

class ClientTool extends Component {
  constructor(props) {
    this.state = {
      client: { _id: "", company: "", person: "", email: "", phone: "" },
    };
  }

  controller = new AbortController();
  static contextType = AuthContext;

  componentWillReceiveProps(props) {
    this.setState({
      client: { _id: "", company: "", person: "", email: "", phone: "" },
    });
    if (props.selected) {
      this.loadClientData(props.selected);
    }
  }

  async loadClientData(id) {
    const query = `query{ client(_id: "${id}"){ company person email phone }}`;
    try {
      const { client } = await queryRequest(query, this.controller.signal);
      if (client) {
        if (!client.email) client.email = "";
        if (!client.phone) client.phone = "";
        this.setState({ client: { ...client, _id: id } });
      }
    } catch (err) {
      console.log("Fetch failed: ", err.toString());
    }
  }

  handleDelete = async (evt) => {
    const { t } = this.props;
    const query = `mutation{clientHardDelete(_id:"${this.state.client._id}")}`;
    Swal.fire({
      title: t("db.client.form.delete.warning.title"),
      text: t("db.client.form.delete.warning.text"),
      icon: "warning",
      showCancelButton: true,
      confirmButtonColor: "#3085d6",
      cancelButtonColor: "#d33",
      confirmButtonText: "Yes",
      cancelButtonText: "Cancel",
    }).then(async (result) => {
      if (!result.value) return;
      try {
        const { clientHardDelete } = await queryRequest(
          query,
          this.controller.signal
        );
        if (clientHardDelete) {
          Swal.fire({
            icon: "success",
            title: t("db.client.form.delete.success.title"),
            showConfirmButton: false,
            timer: 1500,
          });
          this.setState({
            client: { _id: "", company: "", person: "", email: "", phone: "" },
          });
          this.props.doRefresh();
        } else {
          Swal.fire({
            icon: "error",
            title: t("db.client.form.delete.failed.title"),
            text: t("db.client.form.delete.failed.text"),
            showConfirmButton: false,
            timer: 1500,
          });
        }
      } catch (err) {
        console.log("Error while loading", err.toString());
      }
    });
  };

  async handleSubmit(evt) {
    evt.preventDefault();

    const { _id, company, email, person, phone } = this.state.client;
    const query = _id
      ? `mutation{clientUpdate(_id:"${_id}" company:"${company}",person:"${person}",email:"${email}",phone:"${phone}"){ company }}`
      : `mutation{clientCreate(company:"${company}",person:"${person}",email:"${email}",phone:"${phone}"){ company }}`;
    try {
      await queryRequest(query, this.controller.abort());
      this.setState({
        client: { _id: "", company: "", person: "", email: "", phone: "" },
      });
      this.props.doRefresh();
    } catch (err) {
      console.log(err);
    }
  }

  handleNameChange = (evt) => {
    const { company, client } = this.state.client;
    // this.state.client.company = evt.target.value;
    this.setState({ company: evt.target.value, client });
  };

  handlePersonChange = (evt) => {
    const { person, client } = this.state.client;
    // this.state.client.person = evt.target.value;
    this.setState({ client, person: evt.target.value });
  };

  handleEmailChange = (evt) => {
    const { email, client } = this.state.client;
    // this.state.client.email = evt.target.value;
    this.setState({ client, email: evt.target.value });
  };

  handlePhoneChange = (evt) => {
    const { phone, client } = this.state.client;
    // this.state.client.phone = evt.target.value;
    this.setState({ client, phone: evt.target.value });
  };

  render() {
    const { t } = this.props;
    return (
      <Col xl={4}>
        <Card className="m-b-20">
          <Card.Body>
            <h4>
              {this.state.client._id ? (
                <React.Fragment>
                  {t("db.client.form.title")}
                  <RoleLink
                    to="client"
                    id={this.state.client._id}
                    className="pull-right"
                  >
                    <i className="mdi mdi-arrow-expand-all m-r-5 text-primary" />
                  </RoleLink>
                </React.Fragment>
              ) : (
                t("db.client.form.title.new")
              )}
            </h4>

            <Form onSubmit={(evt) => this.handleSubmit(evt)}>
              <Form.Group>
                <Form.Label>{t("db.client.form.name")}</Form.Label>
                <Form.Control
                  type="text"
                  value={this.state.client.company}
                  onChange={(evt) => this.handleNameChange(evt)}
                  required
                />
              </Form.Group>

              <Form.Group>
                <Form.Label>{t("db.client.form.person")}</Form.Label>
                <Form.Control
                  type="text"
                  value={this.state.client.person}
                  onChange={(evt) => this.handlePersonChange(evt)}
                  required
                />
              </Form.Group>
</code>```

答:
You can replace those handle<field_name>Change functions into one.

```<code><Form.Control
  type="text"
  name="company"
  value={this.state.client.company}
  onChange={this.handleChange}
  required
/>
</code>```

handleChange = ({target: {name, value}}) => {
  this.setState(state => ({ ...state, [name]: value }));
};
```

ContentLicense: CC BY-SA 4.0

Body:
I have inherited this code with mutated stated errors but I am having difficulty resolving it.

The issue is in the 'handleSomeFunctions'. THe is already useState being used and I believe I should be destructuring to shorten that and integrating the 'evt.target.value' just not sure how.

Can anyone point me in the right direction please?

import React, { Component } from "react";
import queryRequest from "../../../utils/queryRequest";
import { RoleLink } from "../routes";

import Card from "react-bootstrap/Card";
import Row from "react-bootstrap/Row";
import Col from "react-bootstrap/Col";
import Button from "react-bootstrap/Button";
import Form from "react-bootstrap/Form";

import AuthContext from "../../../context/auth-context";
import Swal from "sweetalert2";

import { translate } from "react-i18next";

class ClientTool extends Component {
  constructor(props) {
    this.state = {
      client: { _id: "", company: "", person: "", email: "", phone: "" },
    };
  }

  controller = new AbortController();
  static contextType = AuthContext;

  componentWillReceiveProps(props) {
    this.setState({
      client: { _id: "", company: "", person: "", email: "", phone: "" },
    });
    if (props.selected) {
      this.loadClientData(props.selected);
    }
  }

  async loadClientData(id) {
    const query = `query{ client(_id: "${id}"){ company person email phone }}`;
    try {
      const { client } = await queryRequest(query, this.controller.signal);
      if (client) {
        if (!client.email) client.email = "";
        if (!client.phone) client.phone = "";
        this.setState({ client: { ...client, _id: id } });
      }
    } catch (err) {
      console.log("Fetch failed: ", err.toString());
    }
  }

  handleDelete = async (evt) => {
    const { t } = this.props;
    const query = `mutation{clientHardDelete(_id:"${this.state.client._id}")}`;
    Swal.fire({
      title: t("db.client.form.delete.warning.title"),
      text: t("db.client.form.delete.warning.text"),
      icon: "warning",
      showCancelButton: true,
      confirmButtonColor: "#3085d6",
      cancelButtonColor: "#d33",
      confirmButtonText: "Yes",
      cancelButtonText: "Cancel",
    }).then(async (result) => {
      if (!result.value) return;
      try {
        const { clientHardDelete } = await queryRequest(
          query,
          this.controller.signal
        );
        if (clientHardDelete) {
          Swal.fire({
            icon: "success",
            title: t("db.client.form.delete.success.title"),
            showConfirmButton: false,
            timer: 1500,
          });
          this.setState({
            client: { _id: "", company: "", person: "", email: "", phone: "" },
          });
          this.props.doRefresh();
        } else {
          Swal.fire({
            icon: "error",
            title: t("db.client.form.delete.failed.title"),
            text: t("db.client.form.delete.failed.text"),
            showConfirmButton: false,
            timer: 1500,
          });
        }
      } catch (err) {
        console.log("Error while loading", err.toString());
      }
    });
  };

  async handleSubmit(evt) {
    evt.preventDefault();

    const { _id, company, email, person, phone } = this.state.client;
    const query = _id
      ? `mutation{clientUpdate(_id:"${_id}" company:"${company}",person:"${person}",email:"${email}",phone:"${phone}"){ company }}`
      : `mutation{clientCreate(company:"${company}",person:"${person}",email:"${email}",phone:"${phone}"){ company }}`;
    try {
      await queryRequest(query, this.controller.abort());
      this.setState({
        client: { _id: "", company: "", person: "", email: "", phone: "" },
      });
      this.props.doRefresh();
    } catch (err) {
      console.log(err);
    }
  }

  handleNameChange = (evt) => {
    const { company, client } = this.state.client;
    // this.state.client.company = evt.target.value;
    this.setState({ company: evt.target.value, client });
  };

  handlePersonChange = (evt) => {
    const { person, client } = this.state.client;
    // this.state.client.person = evt.target.value;
    this.setState({ client, person: evt.target.value });
  };

  handleEmailChange = (evt) => {
    const { email, client } = this.state.client;
    // this.state.client.email = evt.target.value;
    this.setState({ client, email: evt.target.value });
  };

  handlePhoneChange = (evt) => {
    const { phone, client } = this.state.client;
    // this.state.client.phone = evt.target.value;
    this.setState({ client, phone: evt.target.value });
  };

  render() {
    const { t } = this.props;
    return (
      <Col xl={4}>
        <Card className="m-b-20">
          <Card.Body>

              {this.state.client._id ? (
                <React.Fragment>
                  {t("db.client.form.title")}
                  <RoleLink
                    to="client"
                    id={this.state.client._id}
                    className="pull-right"
                  >

                  </RoleLink>
                </React.Fragment>
              ) : (
                t("db.client.form.title.new")
              )}

            <Form onSubmit={(evt) => this.handleSubmit(evt)}>
              <Form.Group>
                <Form.Label>{t("db.client.form.name")}</Form.Label>
                <Form.Control
                  type="text"
                  value={this.state.client.company}
                  onChange={(evt) => this.handleNameChange(evt)}
                  required
                />
              </Form.Group>

              <Form.Group>
                <Form.Label>{t("db.client.form.person")}</Form.Label>
                <Form.Control
                  type="text"
                  value={this.state.client.person}
                  onChange={(evt) => this.handlePersonChange(evt)}
                  required
                />
              </Form.Group>

Body:
You can replace those handle<field_name>Change functions into one.

<Form.Control
  type="text"
  name="company"
  value={this.state.client.company}
  onChange={this.handleChange}
  required
/>

handleChange = ({target: {name, value}}) => {
  this.setState(state => ({ ...state, [name]: value }));
};


问:
react-country-region-selector component given error Text string must be rendered within a <Text> component
I have copy code from npm. Below code show, given error Text string must be rendered within a  component.
How we can removed this error.
I make a component and used this code. But not working i try some style css but not working.</p>

```<code>
// note that you can also export the source data via CountryRegionData. It's in a deliberately concise format to
// keep file size down
import { CountryDropdown, RegionDropdown, CountryRegionData } from 'react-country-region-selector';

class Example extends Component {
  constructor (props) {
    super(props);
    this.state = { country: '', region: '' };
  }

  selectCountry (val) {
    this.setState({ country: val });
  }

  selectRegion (val) {
    this.setState({ region: val });
  }

  render () {
    const { country, region } = this.state;
    return (
      <div>
        <CountryDropdown
          value={country}
          onChange={(val) => this.selectCountry(val)} />
        <RegionDropdown
          country={country}
          value={region}
          onChange={(val) => this.selectRegion(val)} />
      </div>
    );
  }
}```
</code>```

答:
react-country-region-selector is a library made for React (on the web), not React Native. It includes HTML markup, which is not supported by React Native.

The reason for this exact error message is because
 is recognised as a text string (not HTML tag, not a component), and since it's not rendered within a <Text> component you get this specific error.

Body:
I have copy code from npm. Below code show, given error Text string must be rendered within a  component.
How we can removed this error.
I make a component and used this code. But not working i try some style css but not working.

// note that you can also export the source data via CountryRegionData. It's in a deliberately concise format to
// keep file size down
import { CountryDropdown, RegionDropdown, CountryRegionData } from 'react-country-region-selector';

class Example extends Component {
  constructor (props) {
    super(props);
    this.state = { country: '', region: '' };
  }

  selectCountry (val) {
    this.setState({ country: val });
  }

  selectRegion (val) {
    this.setState({ region: val });
  }

  render () {
    const { country, region } = this.state;
    return (

        <CountryDropdown
          value={country}
          onChange={(val) => this.selectCountry(val)} />
        <RegionDropdown
          country={country}
          value={region}
          onChange={(val) => this.selectRegion(val)} />

    );
  }
}```

Body:
react-country-region-selector is a library made for React (on the web), not React Native. It includes HTML markup, which is not supported by React Native.

The reason for this exact error message is because <div> is recognised as a text string (not HTML tag, not a component), and since it's not rendered within a <Text> component you get this specific error.


问:
iOS safari crashing (a problem repeatedly occured)
I'm developing a website and have recently run into a problem when testing on my iPhone X - the site wont load.

Safari tries to load it, then reports the error 'this web page was reloaded because a problem occured', and after a couple of tries it gives up and reports 'a problem repeatedly occured'. Chrome on my iPhone also doesn't load the site.

At this time I can't share the website publicly, but there are no errors reported in the chrome desktop console. In fact, the website runs perfectly fine on my desktop, my laptop, my old iPhone 6 and 5s, my friends Samsung android, and 15 other random computers and phones I've tested it on. It also loads fine in xCode simulator. But it doesn't work on my iPhone X.

My research across SO and the internet in general has led me to believe this error is usually due to excessive memory usage, but desktop Chrome reports the memory usage peaks at 20mb only. Also the site loads just fine on my inferior iPhone 5s.

I have cleared the safari and chrome caches on my iPhone X, toggled block cookies on/off, reset network settings, and restarted the phone.

My worry is that if my iPhone X doesn't load the site, no doubt other users will have problems, even if the 20 miscellaneous devices I have also tested work just fine.

Does anyone have any idea what is going on here?

答:
I faced a similar issue:

on my website (only on a specific page) iOS safari shows error message "a problem repeatedly occurred on my-page-url" without any errors in the console.
On all desktop browsers this page works fine, on all Android mobile phones also, but on iOS Safari page shows error...

After many hours of investigation, I have found that the problem was with the CSS property

```<code>height: intrinsic;
</code>```

it was really strange, because this property works fine only on desktop Safari, on other browsers it was just ignored. But mobile Safari dies...

So I changed this CSS property and everything was fixed :)

Hope this will help someone to save few hours of debugging :)

Body:
I faced a similar issue:

on my website (only on a specific page) iOS safari shows error message "a problem repeatedly occurred on my-page-url" without any errors in the console.
On all desktop browsers this page works fine, on all Android mobile phones also, but on iOS Safari page shows error...

After many hours of investigation, I have found that the problem was with the CSS property

height: intrinsic;

it was really strange, because this property works fine only on desktop Safari, on other browsers it was just ignored. But mobile Safari dies...

So I changed this CSS property and everything was fixed :)

Hope this will help someone to save few hours of debugging :)


问:
What is the size of a page table entry in a multi level page table?
I understand why a multi-level page table saves memory. In the classic 32-bit example, the size of each Page Table Entry (PTE) in a single-level table is 32 bit (4 Bytes). The fact that 20 of the 32 bits are used for page number means there are 2^20 (~1M) possible entries in this table. The total size of a single-level table is therefore 4 Bytes * 1M = 4MB.A two-level page table requires less memory because it does not need all of the second-level pages at the same time.

However, in a lot of examples for the calculations of two-level page table on the internet, people still use 4 Bytes to indicate the size of each PTE. Since we are only accessing 10 of the 32 bits at the first level, shouldn't the size of these PTEs be smaller than 4 Bytes?

答:
The virtual address is broken to 10-10-12 first 10 bits are an index in the first level page table, there, you will find the address of the second level page table, which you index with the seconds 10 bits to find the start of the physical frame which you index with the remaining 12 bits.

Actually each entry contains the number of the virtual page (there are 2^20 such pages) and 12 flag bits.


问:
Use selenium to capture 'Did you mean' on google search page
If I type Johnkaranski in google search , 'Did you mean: John Kransky' appears on the top . I want the result of Did you mean to be returned by my google query function .

```<code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
chromedriver = 'chrome/chromedriver.exe'
options = webdriver.ChromeOptions()
#options.add_argument('headless')
driver = webdriver.Chrome(chromedriver,options=options)

def is_google_listing(query):
    driver.get("https://www.google.com/search?q={}".format(query))
    #try:
    wait = WebDriverWait(driver, 10)
    wait.until(EC.visibility_of((By.ID, 'fprsl')))
    didumean = driver.find_element_by_id('fprsl')
    return didumean
    #except:
      #  return False
</code>```

I have commented the try exept statements . I get errors . I found out that Did you mean is stored in id:fprsl

答:
Give this a go:</p>

```<code>didumean=wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, 'a.gL9Hy'))).text
</code>```

Body:
If I type Johnkaranski in google search , 'Did you mean: John Kransky' appears on the top . I want the result of Did you mean to be returned by my google query function .

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
chromedriver = 'chrome/chromedriver.exe'
options = webdriver.ChromeOptions()
#options.add_argument('headless')
driver = webdriver.Chrome(chromedriver,options=options)

def is_google_listing(query):
    driver.get("https://www.google.com/search?q={}".format(query))
    #try:
    wait = WebDriverWait(driver, 10)
    wait.until(EC.visibility_of((By.ID, 'fprsl')))
    didumean = driver.find_element_by_id('fprsl')
    return didumean
    #except:
      #  return False

I have commented the try exept statements . I get errors . I found out that Did you mean is stored in id:fprsl

Body:
Give this a go:

didumean=wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, 'a.gL9Hy'))).text


问:
How to make a player die while falling?
I am developing a basic game on Unity to improve myself. It's a basic endless runner platform game.

If you right click when the player is on the ground, it jumps; if it's not on the ground, it falls faster.

But I couldn't figure out how to make a player die while falling when it couldn't catch the platform. Could you please check my code? I am trying to find an "if" command to make it happen.

```<code>using JetBrains.Annotations;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class PlayerControls : MonoBehaviour
{
    public Rigidbody2D rb;
    public Transform groundCheck;
    public float groundCheckRadius;
    public LayerMask whatIsGround;
    private bool onGround;
    float CurrentFallTime;
    public float MaxFallTime = 7;
    bool PlayerIsFalling;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        rb.velocity = new Vector2(5, rb.velocity.y);
        onGround = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, whatIsGround);

        CurrentFallTime += Time.deltaTime;

        if (Input.GetMouseButtonDown(0) && onGround)
        {
            rb.velocity = new Vector2(rb.velocity.x, 12);
        }

        if (Input.GetMouseButtonDown(0) && !onGround)
        {
            rb.velocity = new Vector2(rb.velocity.x, -10);
        }

        // I want it to die and go to game over screen when it exceeds the CurrentFallTime
        if ()
        {
            if (CurrentFallTime >= MaxFallTime)
            {
                SceneManager.LoadScene("GameOver");
            }
        }
    }
}
</code>```

EDIT: It solved! I simpy added "if(onGround)" and reset the CurrentFallTime. Here is the new code:

```<code>using JetBrains.Annotations;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class PlayerControls : MonoBehaviour
{
    public Rigidbody2D rb;
    public Transform groundCheck;
    public float groundCheckRadius;
    public LayerMask whatIsGround;
    private bool onGround;
    float CurrentFallTime;
    public float MaxFallTime = 7;
    bool PlayerIsFalling;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        rb.velocity = new Vector2(5, rb.velocity.y);
        onGround = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, whatIsGround);

        CurrentFallTime += Time.deltaTime;

        if (onGround)
        {
            CurrentFallTime = 0f;
        }

        if (Input.GetMouseButtonDown(0) && onGround)
        {
            rb.velocity = new Vector2(rb.velocity.x, 12);
        }

        if (Input.GetMouseButtonDown(0) && !onGround)
        {
            rb.velocity = new Vector2(rb.velocity.x, -10);
        }

        if (CurrentFallTime >= MaxFallTime)
        {
            SceneManager.LoadScene("GameOver");
        }

    }
}
</code>```

答:
This is something that I just thought of now, so I'm not sure how well it will work, but you can create a 1-sided plane collider and position it to follow the x- and y-coordinate of the player, but stay slightly lower than the height of the ground, e.g. 1unit. Then check when the player collides with the plane, if it does then you know that the player has fallen.

So, create an empty GameObject and add the collider, no need for any mesh properties and set the collider trigger to true. Then in player controls add something like in update.

```<code>colliderGo.transform.location = new Vector3(transform.x, groundHeight - 1, transform.z)
</code>```

Also in the player controller function

```<code>function onTrigger(Collider col) {
    if (col.tag == "fallDetector") {
        Debug.Log("What a cruel world")
        playHasFallen = true;
    }
}
</code>```

Something like this should work.

Title: How to make a player die while falling?

Body:
I am developing a basic game on Unity to improve myself. It's a basic endless runner platform game.

If you right click when the player is on the ground, it jumps; if it's not on the ground, it falls faster.

But I couldn't figure out how to make a player die while falling when it couldn't catch the platform. Could you please check my code? I am trying to find an "if" command to make it happen.

using JetBrains.Annotations;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class PlayerControls : MonoBehaviour
{
    public Rigidbody2D rb;
    public Transform groundCheck;
    public float groundCheckRadius;
    public LayerMask whatIsGround;
    private bool onGround;
    float CurrentFallTime;
    public float MaxFallTime = 7;
    bool PlayerIsFalling;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        rb.velocity = new Vector2(5, rb.velocity.y);
        onGround = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, whatIsGround);

        CurrentFallTime += Time.deltaTime;

        if (Input.GetMouseButtonDown(0) && onGround)
        {
            rb.velocity = new Vector2(rb.velocity.x, 12);
        }

        if (Input.GetMouseButtonDown(0) && !onGround)
        {
            rb.velocity = new Vector2(rb.velocity.x, -10);
        }

        // I want it to die and go to game over screen when it exceeds the CurrentFallTime
        if ()
        {
            if (CurrentFallTime >= MaxFallTime)
            {
                SceneManager.LoadScene("GameOver");
            }
        }
    }
}

EDIT: It solved! I simpy added "if(onGround)" and reset the CurrentFallTime. Here is the new code:

using JetBrains.Annotations;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class PlayerControls : MonoBehaviour
{
    public Rigidbody2D rb;
    public Transform groundCheck;
    public float groundCheckRadius;
    public LayerMask whatIsGround;
    private bool onGround;
    float CurrentFallTime;
    public float MaxFallTime = 7;
    bool PlayerIsFalling;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        rb.velocity = new Vector2(5, rb.velocity.y);
        onGround = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, whatIsGround);

        CurrentFallTime += Time.deltaTime;

        if (onGround)
        {
            CurrentFallTime = 0f;
        }

        if (Input.GetMouseButtonDown(0) && onGround)
        {
            rb.velocity = new Vector2(rb.velocity.x, 12);
        }

        if (Input.GetMouseButtonDown(0) && !onGround)
        {
            rb.velocity = new Vector2(rb.velocity.x, -10);
        }

        if (CurrentFallTime >= MaxFallTime)
        {
            SceneManager.LoadScene("GameOver");
        }

    }
}

Body:
This is something that I just thought of now, so I'm not sure how well it will work, but you can create a 1-sided plane collider and position it to follow the x- and y-coordinate of the player, but stay slightly lower than the height of the ground, e.g. 1unit. Then check when the player collides with the plane, if it does then you know that the player has fallen.

So, create an empty GameObject and add the collider, no need for any mesh properties and set the collider trigger to true. Then in player controls add something like in update.

colliderGo.transform.location = new Vector3(transform.x, groundHeight - 1, transform.z)

Also in the player controller function

function onTrigger(Collider col) {
    if (col.tag == "fallDetector") {
        Debug.Log("What a cruel world")
        playHasFallen = true;
    }
}

Something like this should work.


问:
Problem when defining Int as an instance of a type class in Haskell
I am trying to define Int as an instance of my type class Add.
I wanted to define my own operator +++, which should be overloaded on integers and strings. My goal was to be able to add integers and concatenate strings with the same operator. Therefore i created the type class Add with the instances Int and [char]:

```<code>class Add a where
    (+++) :: a -> a -> a

instance Add Int where
    x +++ y = x + y

instance Add [char] where
    x +++ y = x ++ y
</code>```

Problem: When evaluating the expression 1 +++ 2, GHCi gives me the following error message:

```<code><interactive>:9:1: error:
    • Ambiguous type variable ‘a0’ arising from a use of ‘print’
      prevents the constraint ‘(Show a0)’ from being solved.
      Probable fix: use a type annotation to specify what ‘a0’ should be.
      These potential instances exist:
        instance Show Ordering -- Defined in ‘GHC.Show’
        instance Show Integer -- Defined in ‘GHC.Show’
        instance Show a => Show (Maybe a) -- Defined in ‘GHC.Show’
        ...plus 22 others
        ...plus 18 instances involving out-of-scope types
        (use -fprint-potential-instances to see them all)
    • In a stmt of an interactive GHCi command: print it
</code>```

But when defining Integer as an instance of Add

```<code>instance Add Integer where
    x +++ y = x + y
</code>```

GHCi can evaluate 1 +++ 2 to 3 and i don't get an error.

Question: Why is it not working, when using Int as an instance? What is the difference in using Int or Integer?

答:
Given that it works for Integer but not Int, I'm fairly sure this is due to "type defaulting".

In GHCi (and to a lesser extent in compiled code), if an expression has an ambiguous type, the compiler tries several "default types", which of which is Integer (but not Int). That's almost certainly where the difference is coming from.

I suspect if you add :: Int to the end of your expression, it will execute just fine. The problem isn't that there's a type error, it's that more than one type potentially fits, and the compiler isn't sure which one you intended.

I've never tried this, but I believe you can change the defaults by saying something like default (Int, Double). (Usually it's default (Integer, Double).) I think that's the right syntax; not 100% sure.

There's a bit about this in the GHCi manual: https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/ghci.html#type-defaulting-in-ghci

Also the Haskell Report: https://www.haskell.org/onlinereport/haskell2010/haskellch4.html#x10-750004.3 (Section 4.3.4)

Body:
I am trying to define Int as an instance of my type class Add.
I wanted to define my own operator +++, which should be overloaded on integers and strings. My goal was to be able to add integers and concatenate strings with the same operator. Therefore i created the type class Add with the instances Int and [char]:

class Add a where
    (+++) :: a -> a -> a

instance Add Int where
    x +++ y = x + y

instance Add [char] where
    x +++ y = x ++ y

Problem: When evaluating the expression 1 +++ 2, GHCi gives me the following error message:

<interactive>:9:1: error:
    • Ambiguous type variable ‘a0’ arising from a use of ‘print’
      prevents the constraint ‘(Show a0)’ from being solved.
      Probable fix: use a type annotation to specify what ‘a0’ should be.
      These potential instances exist:
        instance Show Ordering -- Defined in ‘GHC.Show’
        instance Show Integer -- Defined in ‘GHC.Show’
        instance Show a => Show (Maybe a) -- Defined in ‘GHC.Show’
        ...plus 22 others
        ...plus 18 instances involving out-of-scope types
        (use -fprint-potential-instances to see them all)
    • In a stmt of an interactive GHCi command: print it

But when defining Integer as an instance of Add

instance Add Integer where
    x +++ y = x + y

GHCi can evaluate 1 +++ 2 to 3 and i don't get an error.

Question: Why is it not working, when using Int as an instance? What is the difference in using Int or Integer?


问:
Delete a cell array column
Placed simple values into the cell array for testing.

```<code>model{1,1}=1;model{1,2}=2;model{1,3}=3;
model{2,1}=4;model{2,2}=5;model{2,3}=6;
i=2;//I want to remove the second column

temp={  model{:,1:i-1} model{:,i+1:size(model,2)}  }
</code>```

I wanted a result like this:

temp =

```<code>[1]    [3]
[4]    [6]
</code>```

But I'm getting this:

temp =

```<code>[1]    [4]    [3]    [6]
</code>```

How can I get this right?

p.s: for anyone working on Cell Arrays, there's a nice technique for appending here.

答:
You can reshape or delete the cells themselves using ()-addressing.</p>

```<code>model(:,2) = [];
</code>```

Title: Delete a cell array column

Body:
Placed simple values into the cell array for testing.

model{1,1}=1;model{1,2}=2;model{1,3}=3;
model{2,1}=4;model{2,2}=5;model{2,3}=6;
i=2;//I want to remove the second column

temp={  model{:,1:i-1} model{:,i+1:size(model,2)}  }

I wanted a result like this:

temp =

[1]    [3]
[4]    [6]

But I'm getting this:

temp =

[1]    [4]    [3]    [6]

How can I get this right?

p.s: for anyone working on Cell Arrays, there's a nice technique for appending here.

Body:
You can reshape or delete the cells themselves using ()-addressing.

model(:,2) = [];


问:
Background audio in Web page
I want to use a audio in background of a web page but after a web page changes the audio is restarted. I want it to play continuously whether web page changes or not without any interrupt. </p>

答:
I don't think you can actually do that as I think you want to do it. I assume you load and reproduce the audio in some .js file, which is run on page load by the browser; as you navigate i.e. in your website, the browser re-load all the source files (and also your audio).

I think the best thing you can do is to re-project your page/website as a web-app. Doing that, when you navigate from a page to another you're not actually "leaving" the main page, but you're hiding/showing some html content: in this case, load the audio when the main page is loaded and it will continue to reproduce.

Another, worse, thing you can do is to save the timestamp of the audio track in the current session when you leave the first page, and re-load the audio track from the saved timestamp in the next page. I think this is a worse option as your audio track will be paused till the next page content is loaded (and that could take time in case of connection issues and/or big media files)

Title: Background audio in Web page


问:
DatabaseReference 'setValue' Android Studio shows error
This is my first use firebase, I follow the steps, but I cannot run

```<code>FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("message");
myRef.setValue("Hello, World!");
</code>```

and error text

```<code>2020-06-02 14:48:51.664 28968-29015/com.example.chatapp E/RunLoop: Uncaught exception in Firebase Database runloop (3.0.0). Please report to firebase-database-client@google.com
    java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/firebase/FirebaseApp$IdTokenListener;
</code>```

The error appears on the second line and early time appears in the third line.

The firebase rule has been changed to true.

What should I do?

Thanks

答: if your "message" node includes sub-nodes or sub-values, you can't use setValue directly for this node. You should clear contents of this node.</p>

Body:
This is my first use firebase, I follow the steps, but I cannot run

FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("message");
myRef.setValue("Hello, World!");

and error text

2020-06-02 14:48:51.664 28968-29015/com.example.chatapp E/RunLoop: Uncaught exception in Firebase Database runloop (3.0.0). Please report to firebase-database-client@google.com
    java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/firebase/FirebaseApp$IdTokenListener;

The error appears on the second line and early time appears in the third line.

The firebase rule has been changed to true.

What should I do?

Thanks


问:
How to install PHP_CodeSniffer in macOSx?
I tried to install phpcs in the macOS Catalina but I was getting multiple errors. So in my answer, I shared the steps to install phpcs easily.</p>

答:
I tried the following steps and it's worked out. My macOS version is 10.15.4 (Catalina) and PHP version is 7.2.

```<code>$ sudo cp /etc/php.ini.default /etc/php.ini;
</code>```

Then install go-pear

```<code>$ curl -O https://pear.php.net/go-pear.phar
$ php -d detect_unicode=0 go-pear.phar
</code>```

Here you'll have some question to install the pear.

So type 1, and then press Enter.

Enter /usr/local/pear

Press Enter.

Then, you will need to change the Binaries directory.

Type 4, and then press Enter.

Enter /usr/local/bin

Press Enter.

After installing pear, I got the following warning.

```<code>******************************************************************************
WARNING: Cannot write to /etc/php.ini, but php.ini was successfully created
at </usr/local/bin/php.ini-gopear>. Please replace the file </etc/php.ini> with
</usr/local/bin/php.ini-gopear> or modify your php.ini by adding:

include_path=".:/usr/local/bin/share/pear"
</code>```

So edited the /etc/php.ini file and added the above (include_path=".:/usr/local/bin/share/pear") line.

After that install PHP_CodeSniffer -

```<code>$ sudo pear upgrade-all;\n
$ sudo pear install PHP_CodeSniffer;\n
$ phpcs --version
</code>```

Finally got it -

```<code>PHP_CodeSniffer version 3.5.5 (stable) by Squiz (http://www.squiz.net)
</code>```

Body:
I tried the following steps and it's worked out. My macOS version is 10.15.4 (Catalina) and PHP version is 7.2.

$ sudo cp /etc/php.ini.default /etc/php.ini;

Then install go-pear

$ curl -O https://pear.php.net/go-pear.phar
$ php -d detect_unicode=0 go-pear.phar

Here you'll have some question to install the pear.

So type 1, and then press Enter.

Enter /usr/local/pear

Press Enter.

Then, you will need to change the Binaries directory.

Type 4, and then press Enter.

Enter /usr/local/bin

Press Enter.

After installing pear, I got the following warning.

******************************************************************************
WARNING: Cannot write to /etc/php.ini, but php.ini was successfully created
at </usr/local/bin/php.ini-gopear>. Please replace the file </etc/php.ini> with
</usr/local/bin/php.ini-gopear> or modify your php.ini by adding:

include_path=".:/usr/local/bin/share/pear"

So edited the /etc/php.ini file and added the above (include_path=".:/usr/local/bin/share/pear") line.

After that install PHP_CodeSniffer -

$ sudo pear upgrade-all;\n
$ sudo pear install PHP_CodeSniffer;\n
$ phpcs --version

Finally got it -

PHP_CodeSniffer version 3.5.5 (stable) by Squiz (http://www.squiz.net)


问:
AXIOS Post stay on PENDING in my REACT application

Below is the Redux Action code that will be dispatched whenever onSubmit of Create
  / Updating a profile:

I am using AXIOS lib for making the below POST calls to the backend - MongoDB.

```<code>const res = await axios.post(
      '/api/profile',
      formData,                 // Body
      config                    // Headers
    );
</code>```

On my React application, the above lines of code works fine for Create but for the Update, it isn't returning anything and in the Networks Tab on Chrome Dev Tools, the status is Pending. Can someone help me understand where I would have made a mistake?

Both the Create/Update calls worked fine when I did the POST request using
  Postman with the same Headers and Payload data.

Below is the Full code:

```<code>// Create/Update Profile
export const createProfile = (formData, history, edit = false) => async (
  dispatch
) => {
  try {
    const config = {
      headers: {
        'Content-Type': 'application/json',
      },
    };
    debugger;
    const res = await axios.post(
      '/api/profile',
      formData,
      config
    );
    dispatch({
      type: GET_PROFILE,
      payload: res.data,
    });

    dispatch(setAlert(edit ? 'Profile Updated' : 'Profile Created'), 'success');

    if (!edit) {
      history.push('/dashboard');
    }
  } catch (error) {
    const errors = error.response.data.errors;
    if (errors) {
      errors.forEach((error) => dispatch(setAlert(error.msg, 'danger')));
    }

    dispatch({
      type: PROFILE_ERROR,
      payload: {
        msg: error.response.statusText,
        status: error.response.status,
      },
    });
  }
};
</code>```

答:
Oh, My Bad!

I had some issue on the API endpoint,
I was checking if(formData.Skills) and by mistake, I closed the curly braces at the wrong place after catch block and so the status was in Pending as there isn't any data returned.

Sorry, Guys!

Thank you all for your solutions, It helped me too. Have a lovely day!

Body:
Below is the Redux Action code that will be dispatched whenever onSubmit of Create
  / Updating a profile:

I am using AXIOS lib for making the below POST calls to the backend - MongoDB.

const res = await axios.post(
      '/api/profile',
      formData,                 // Body
      config                    // Headers
    );

On my React application, the above lines of code works fine for Create but for the Update, it isn't returning anything and in the Networks Tab on Chrome Dev Tools, the status is Pending. Can someone help me understand where I would have made a mistake?

Both the Create/Update calls worked fine when I did the POST request using
  Postman with the same Headers and Payload data.

Below is the Full code:

// Create/Update Profile
export const createProfile = (formData, history, edit = false) => async (
  dispatch
) => {
  try {
    const config = {
      headers: {
        'Content-Type': 'application/json',
      },
    };
    debugger;
    const res = await axios.post(
      '/api/profile',
      formData,
      config
    );
    dispatch({
      type: GET_PROFILE,
      payload: res.data,
    });

    dispatch(setAlert(edit ? 'Profile Updated' : 'Profile Created'), 'success');

    if (!edit) {
      history.push('/dashboard');
    }
  } catch (error) {
    const errors = error.response.data.errors;
    if (errors) {
      errors.forEach((error) => dispatch(setAlert(error.msg, 'danger')));
    }

    dispatch({
      type: PROFILE_ERROR,
      payload: {
        msg: error.response.statusText,
        status: error.response.status,
      },
    });
  }
};


问:
I got this error => TypeError: Cannot read property 'image' of undefined
I am very new in this area and I searched in many places and could not find the solution. I get the error "TypeError: Cannot read property 'image' of undefined". I don't know where is the problem.The image of the error is here.

The class with the error is here.

```<code>import React, {useEffect} from 'react';
import { Link } from 'react-router-dom';
import { useSelector, useDispatch } from 'react-redux';
import { detailsProduct } from '../actions/productActions';
function ProductScreen(props){

const productDetails = useSelector(state => state.productDetails);
const {product,loading,error} = productDetails;
const dispatch = useDispatch();

useEffect(() => {
    dispatch(detailsProduct(props.match.params.id));
    return () => {
        //
    }
}, [])

return <div>
    <div className="back-to-result">
        <Link to="/">Back to result</Link>
    </div>
    {loading?<div>Loading...</div>:
    error? <div>{error}</div>:
    (
    <div className="details">
        <div className="details-image">
            <img src={product.image} alt="product"></img>
        </div>
        <div className="details-info">
            <ul>
                <li>
                    <h4>{product.name}</h4>
                </li>
                <li>
                    {product.rating} Stars ({product.numReviews} Reviews)
                </li>
                <li>
                    Price: <b>${product.price}</b>
                </li>
                <li>
                    Description:
                    <div>
                        {product.description}
                    </div>
                </li>
            </ul>
        </div>
        <div className="details-action">
            <ul>
                <li>
                    Price: {product.price}
                </li>
                <li>
                    Status: {product.status}
                </li>
                <li>
                    Qty: <select>
                        <option>1</option>
                        <option>2</option>
                        <option>3</option>
                        <option>4</option>
                    </select>
                </li>
                <li>
                    <button className="button">Add to Cart</button>
                </li>
            </ul>
        </div>
    </div>
    )
    }

</div>
}
export default ProductScreen;
</code>```

console.log(productDetails) is here

答:
It's because it doesn't think, or know, that 'image' exists on 'product'. You can fix it with this minor change:

```<code>{product.image && <img src={product.image} alt="product" />}
</code>```

You might still run into the same issue with all the other objects on product though. A better solution might be to destructure product to ensure the pieces exis:

```<code>const { image, name, rating, numReviews, price, description, status } = product;
</code>```

Body:
I am very new in this area and I searched in many places and could not find the solution. I get the error "TypeError: Cannot read property 'image' of undefined". I don't know where is the problem.The image of the error is here.

The class with the error is here.

import React, {useEffect} from 'react';
import { Link } from 'react-router-dom';
import { useSelector, useDispatch } from 'react-redux';
import { detailsProduct } from '../actions/productActions';
function ProductScreen(props){

const productDetails = useSelector(state => state.productDetails);
const {product,loading,error} = productDetails;
const dispatch = useDispatch();

useEffect(() => {
    dispatch(detailsProduct(props.match.params.id));
    return () => {
        //
    }
}, [])

return

        <Link to="/">Back to result</Link>

    {loading?
Loading...
:
    error?
{error}
:
    (

{product.name}

                    {product.rating} Stars ({product.numReviews} Reviews)

                    Price: ${product.price}

                    Description:

                        {product.description}

                    Price: {product.price}

                    Status: {product.status}

                    Qty: <select>
                        <option>1</option>
                        <option>2</option>
                        <option>3</option>
                        <option>4</option>
                    </select>

                    <button className="button">Add to Cart</button>

    )
    }

}
export default ProductScreen;

console.log(productDetails) is here

Body:
It's because it doesn't think, or know, that 'image' exists on 'product'. You can fix it with this minor change:

{product.image && <img src={product.image} alt="product" />}

You might still run into the same issue with all the other objects on product though. A better solution might be to destructure product to ensure the pieces exis:

const { image, name, rating, numReviews, price, description, status } = product;


问:
The free Delphi 2006 compiler
On Wikipedia I read:

Borland Delphi 2006 [...] Each version is available in two editions:
  Explorer—a free downloadable
  version—and Professional

Is this edition still available? Or are people who grabbed it in 2006 lucky and the others not that much?

答: Lazarus Free Pascal is free and OpenSource, it is very similar to Delphi.</p>

Title: The free Delphi 2006 compiler


问:
Can't sort a linked list
I'm trying to sort a list in ascending order.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct city {
    char ISO[3];
    char name[20];
    unsigned long inhabitants;
};
typedef struct city City;

struct listnode {
    City thecity;
    struct listnode *nextPtr;
};
typedef struct listnode ListNode;

ListNode *sortForInhabitants(ListNode *, size_t );

int main(){
    /* stuff to initialize list */

    ListNode sortedlist = *sortForInhabitants(&startPtr,num_elem);

    /* printf the output */
}

ListNode *sortForInhabitants(ListNode *sPtr, size_t num_nodes){
    ListNode *newsortedlist = NULL;
    ListNode *prevsortedPtr;
    ListNode *prevUNsortedPtr = sPtr;
    ListNode *exchangePtr;
    ListNode *currUNsortedPtr = sPtr;
    ListNode *tempPtr;
    for (size_t i=1; i<=num_nodes; ++i){
        exchangePtr = prevUNsortedPtr;
        for (size_t i=1; i<=num_nodes; ++i){
            if (exchangePtr->thecity.inhabitants > currUNsortedPtr->thecity.inhabitants){
                tempPtr = exchangePtr;
                exchangePtr = currUNsortedPtr;
                currUNsortedPtr = tempPtr;
            }
        }
        prevUNsortedPtr = prevUNsortedPtr->nextPtr;

        if (newsortedlist==NULL){
            ListNode *newsortlinkPtr = calloc(1,sizeof(ListNode));
            if (newsortlinkPtr){
                newsortlinkPtr->thecity.inhabitants = exchangePtr->thecity.inhabitants;
                newsortlinkPtr->nextPtr = NULL;
                newsortedlist = newsortlinkPtr;
                prevsortedPtr = newsortlinkPtr;
            } else {
                printf("\nNo memory.\n");
            }
        } else {
            ListNode *newsortlinkPtr = calloc(1,sizeof(ListNode));
            if (newsortlinkPtr){
                newsortlinkPtr->thecity.inhabitants = exchangePtr->thecity.inhabitants;
                newsortlinkPtr->nextPtr = NULL;
                prevsortedPtr->nextPtr = newsortlinkPtr;
                prevsortedPtr = newsortlinkPtr;
            } else {
                printf("\nNo memory.\n");
            }
        }
    }

    return newsortedlist;
}
</code>```

Output:

```<code>Unsorted list:
PA Palermo 673735
ME Messina 236962
CT Catania 313396
TP Trapani 68528
AG Agrigento 59605
RG Ragusa 73500

Sorted list:
  673735
  236962
  313396
  68528
  59605
  73500
</code>```

Why? It took me a long time but I don't see the effects of the effort.

Also, I'd like to know if it is adviceable to create a new ListNode (like I'm doing in this sorting function) or to just "adjusts" the previous ListNode just using pointers... What would be better?

答:
I am assuming you were implementing the selection sort algorithm. Your secondary loop had a very obvious bug which you missed. </p>

```<code>ListNode *sortForInhabitants(ListNode *sPtr, size_t num_nodes){

  // initial code

  // this loop is for finding the i_th smallest element
  for (size_t i=1; i<=num_nodes; ++i){
    exchangePtr = prevUNsortedPtr;

    // your second loop is wrong. Correct access of the loop is given below.
    // as you have already found (i-1) smallest elements, you are now going
    // to search through the rest of the linked list.
    for (size_t j=i+1; j<=num_nodes; ++j){
      if (exchangePtr->thecity.inhabitants > currUNsortedPtr->thecity.inhabitants){
        tempPtr = exchangePtr;
        exchangePtr = currUNsortedPtr;
        currUNsortedPtr = tempPtr;
    }
  // rest of your code
}
</code>```

Title: Can't sort a linked list

Body:
I'm trying to sort a list in ascending order.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct city {
    char ISO[3];
    char name[20];
    unsigned long inhabitants;
};
typedef struct city City;

struct listnode {
    City thecity;
    struct listnode *nextPtr;
};
typedef struct listnode ListNode;

ListNode *sortForInhabitants(ListNode *, size_t );

int main(){
    /* stuff to initialize list */

    ListNode sortedlist = *sortForInhabitants(&startPtr,num_elem);

    /* printf the output */
}

ListNode *sortForInhabitants(ListNode *sPtr, size_t num_nodes){
    ListNode *newsortedlist = NULL;
    ListNode *prevsortedPtr;
    ListNode *prevUNsortedPtr = sPtr;
    ListNode *exchangePtr;
    ListNode *currUNsortedPtr = sPtr;
    ListNode *tempPtr;
    for (size_t i=1; i<=num_nodes; ++i){
        exchangePtr = prevUNsortedPtr;
        for (size_t i=1; i<=num_nodes; ++i){
            if (exchangePtr->thecity.inhabitants > currUNsortedPtr->thecity.inhabitants){
                tempPtr = exchangePtr;
                exchangePtr = currUNsortedPtr;
                currUNsortedPtr = tempPtr;
            }
        }
        prevUNsortedPtr = prevUNsortedPtr->nextPtr;

        if (newsortedlist==NULL){
            ListNode *newsortlinkPtr = calloc(1,sizeof(ListNode));
            if (newsortlinkPtr){
                newsortlinkPtr->thecity.inhabitants = exchangePtr->thecity.inhabitants;
                newsortlinkPtr->nextPtr = NULL;
                newsortedlist = newsortlinkPtr;
                prevsortedPtr = newsortlinkPtr;
            } else {
                printf("\nNo memory.\n");
            }
        } else {
            ListNode *newsortlinkPtr = calloc(1,sizeof(ListNode));
            if (newsortlinkPtr){
                newsortlinkPtr->thecity.inhabitants = exchangePtr->thecity.inhabitants;
                newsortlinkPtr->nextPtr = NULL;
                prevsortedPtr->nextPtr = newsortlinkPtr;
                prevsortedPtr = newsortlinkPtr;
            } else {
                printf("\nNo memory.\n");
            }
        }
    }

    return newsortedlist;
}

Output:

Unsorted list:
PA Palermo 673735
ME Messina 236962
CT Catania 313396
TP Trapani 68528
AG Agrigento 59605
RG Ragusa 73500

Sorted list:
  673735
  236962
  313396
  68528
  59605
  73500

Why? It took me a long time but I don't see the effects of the effort.

Also, I'd like to know if it is adviceable to create a new ListNode (like I'm doing in this sorting function) or to just "adjusts" the previous ListNode just using pointers... What would be better?

Body:
I am assuming you were implementing the selection sort algorithm. Your secondary loop had a very obvious bug which you missed.

ListNode *sortForInhabitants(ListNode *sPtr, size_t num_nodes){

  // initial code

  // this loop is for finding the i_th smallest element
  for (size_t i=1; i<=num_nodes; ++i){
    exchangePtr = prevUNsortedPtr;

    // your second loop is wrong. Correct access of the loop is given below.
    // as you have already found (i-1) smallest elements, you are now going
    // to search through the rest of the linked list.
    for (size_t j=i+1; j<=num_nodes; ++j){
      if (exchangePtr->thecity.inhabitants > currUNsortedPtr->thecity.inhabitants){
        tempPtr = exchangePtr;
        exchangePtr = currUNsortedPtr;
        currUNsortedPtr = tempPtr;
    }
  // rest of your code
}


问:
Comparing sql with c# list in query?
I have a problem with comparing a value in my sql database with a list of object in my code.

The object does not exist in DB

Example of an object in the list:

```<code>{
    public long CompareId
    public bool HasAccess
}
</code>```

I'm using SQLBuilder in c#
And then I want to make a query that says something like this:

In made up code

```<code>SELECT * FROM EntityPermission
WHERE EntityPermission.HasAccess = listOfObjects.Where(obj => obj.CompareId == EntityPermission.CompareId).HasAccess
</code>```

In more made up code but with sql builder

```<code>query.WHERE("(EntityPermission.HasAccess = {0})", listOfObjects.Where(obj => obj.CompareId == EntityPermission.CompareId).HasAccess)
</code>```

I'm fully aware of that I'm mixing c# and sql here, but it was the best way I could explain what I want to accomplish.

In words

I want to find the EntityPermission where the HasAccess column is equal to the HasAccess property of the object where they have the same Id.

Really thankful for all help!

答:
I want to find the EntityPermission where the HasAccess column is equal to the HasAccess property of the object where they have the same Id.

So you have a table EntityPermissions. Every EntityPermission in this table has at least a Boolean property HasAccess, and a primary key in long property Id

Furthermore you have a list of objects, where every object has at least an CompareId and a HasAccess.

If I read your requirement correctly, you want all EntityPermissions with Id that is also a CompareId in your list, and that have equal HasAccess value.

So if your list has values:

```<code>{10, false}, {11, true}, {12, false},
</code>```

And you have EntityPermissiont:

```<code>Id  HasAccess
09  true         don't want this one, Id is not in the list
10  true         don't want this one, Id is in the list, but HasAccess incorrect
11  true         I want this one: Id is in the list, HasAccess is correct
12  false        I want this one: Id is in the list, HasAccess is correct
</code>```

Normally you would use Where(x => y.Contains(x)) for this. The problem is that with this you can only select on one property.

```<code>var checkValues = new
{
    new {CompareId = 10, HasAccess = false},
    new {CompareId = 11, HasAccess = true},
    new {CompareId = 12, HasAccess = false},
}

var result = dbContext.EntityPermissions.Select(entityPermission => new
{
    ValueToCompare = new
    {
         CompareId = entityPermission.Id,
         HasAccess = entityPermission.HasAccess,
    },

    Original = entityPermission,
})

// keep only those selected items that have a ValueToCompare in CheckValues
.Where(selectedItem => checkValues.Contains(selectedItem.ValueToCompare)

// from the remaining items, extract the original EntityPermission
.Select(selectedItem => selectedItem.Original);
</code>```

Title: Comparing sql with c# list in query?

Body:
I have a problem with comparing a value in my sql database with a list of object in my code.

The object does not exist in DB

Example of an object in the list:

{
    public long CompareId
    public bool HasAccess
}

I'm using SQLBuilder in c#
And then I want to make a query that says something like this:

In made up code

SELECT * FROM EntityPermission
WHERE EntityPermission.HasAccess = listOfObjects.Where(obj => obj.CompareId == EntityPermission.CompareId).HasAccess

In more made up code but with sql builder

query.WHERE("(EntityPermission.HasAccess = {0})", listOfObjects.Where(obj => obj.CompareId == EntityPermission.CompareId).HasAccess)

I'm fully aware of that I'm mixing c# and sql here, but it was the best way I could explain what I want to accomplish.

In words

I want to find the EntityPermission where the HasAccess column is equal to the HasAccess property of the object where they have the same Id.

Really thankful for all help!

Body:
I want to find the EntityPermission where the HasAccess column is equal to the HasAccess property of the object where they have the same Id.

So you have a table EntityPermissions. Every EntityPermission in this table has at least a Boolean property HasAccess, and a primary key in long property Id

Furthermore you have a list of objects, where every object has at least an CompareId and a HasAccess.

If I read your requirement correctly, you want all EntityPermissions with Id that is also a CompareId in your list, and that have equal HasAccess value.

So if your list has values:

{10, false}, {11, true}, {12, false},

And you have EntityPermissiont:

Id  HasAccess
09  true         don't want this one, Id is not in the list
10  true         don't want this one, Id is in the list, but HasAccess incorrect
11  true         I want this one: Id is in the list, HasAccess is correct
12  false        I want this one: Id is in the list, HasAccess is correct

Normally you would use Where(x => y.Contains(x)) for this. The problem is that with this you can only select on one property.

var checkValues = new
{
    new {CompareId = 10, HasAccess = false},
    new {CompareId = 11, HasAccess = true},
    new {CompareId = 12, HasAccess = false},
}

var result = dbContext.EntityPermissions.Select(entityPermission => new
{
    ValueToCompare = new
    {
         CompareId = entityPermission.Id,
         HasAccess = entityPermission.HasAccess,
    },

    Original = entityPermission,
})

// keep only those selected items that have a ValueToCompare in CheckValues
.Where(selectedItem => checkValues.Contains(selectedItem.ValueToCompare)

// from the remaining items, extract the original EntityPermission
.Select(selectedItem => selectedItem.Original);


问:
Firestore recursive collections backup
Is it possible to backup a hierarchy of collections?

we store the data as:

```<code> * users
     * user1
         * userInfo (on the user1 document)
         * accounts
             * account1
             * account2
         * jobs
             * job1
             * job2
             * job3
     * user2...

 * chats
     * chat1
         * chat metadata (on the chat document)
         * messages
             * message1
             * message2
         * chatUsersInfo
             * userInfo1
             * userInfo2
             * userInfo3
</code>```

(There're also deeper sub-collections)

I'm using this example for the backup job https://firebase.google.com/docs/firestore/solutions/schedule-export

Is there a way to backup the data as is and not only its first level documents?

Is it possible to restore only part of the hierarchy (i.e - restore user1 data)?

Is there a way to exclude some collections from the backup (i.e - jobs)?

答:
Is it possible to backup a hierarchy of collections?

You can only filter specific collections by using the collectionsIds field. Here is an example using the gcloud firestore export command.

In general if you need to backup just specific data you'll need to create an application that make the relevant query to read the relevant collection or document you are interested in and saving it in whatever format you consider more convenient anywhere you'd like (e.g. Cloud Storage).

Is there a way to backup the data as is and not only its first level documents?

As I already advised on the previous question if you are only interested in making a backup of specific data within your whole Firestore instance, you'll need to make an application in order to query the specific data that you want to export (please refer to the documentation for the specific query that you'll need: either list subcollections in a document or get multiple documents from a collection group, etc.)

Is it possible to restore only part of the hierarchy (i.e - restore user1 data)?

You won't be able to restore a specific part of a hierarchy, but you'd be able to import only a specific set of collections using the collectionsIds field in a similar fashion to:

gcloud firestore import gs://[BUCKET_NAME]/[EXPORT_PREFIX]/ --collection-ids=[COLLECTION_ID_1],[COLLECTION_ID_2]

Is there a way to exclude some collections from the backup (i.e - jobs)?

Notice that as explained on your example shared you can use the collectionsIds field to create a list with only the collections you want to export (and therefore by not adding the collections that you don't want to export you can exclude them from the export operation).

```<code>  return client.exportDocuments({
    name: databaseName,
    outputUriPrefix: bucket,
    // Leave collectionIds empty to export all collections
    // or set to a list of collection IDs to export,
    // collectionIds: ['users', 'posts']
    collectionIds: []
    })
</code>```

Title: Firestore recursive collections backup

Body:
Is it possible to backup a hierarchy of collections?

we store the data as:

 * users
     * user1
         * userInfo (on the user1 document)
         * accounts
             * account1
             * account2
         * jobs
             * job1
             * job2
             * job3
     * user2...

 * chats
     * chat1
         * chat metadata (on the chat document)
         * messages
             * message1
             * message2
         * chatUsersInfo
             * userInfo1
             * userInfo2
             * userInfo3

(There're also deeper sub-collections)

I'm using this example for the backup job https://firebase.google.com/docs/firestore/solutions/schedule-export

Is there a way to backup the data as is and not only its first level documents?

Is it possible to restore only part of the hierarchy (i.e - restore user1 data)?

Is there a way to exclude some collections from the backup (i.e - jobs)?

Body:
Is it possible to backup a hierarchy of collections?

You can only filter specific collections by using the collectionsIds field. Here is an example using the gcloud firestore export command.

In general if you need to backup just specific data you'll need to create an application that make the relevant query to read the relevant collection or document you are interested in and saving it in whatever format you consider more convenient anywhere you'd like (e.g. Cloud Storage).

Is there a way to backup the data as is and not only its first level documents?

As I already advised on the previous question if you are only interested in making a backup of specific data within your whole Firestore instance, you'll need to make an application in order to query the specific data that you want to export (please refer to the documentation for the specific query that you'll need: either list subcollections in a document or get multiple documents from a collection group, etc.)

Is it possible to restore only part of the hierarchy (i.e - restore user1 data)?

You won't be able to restore a specific part of a hierarchy, but you'd be able to import only a specific set of collections using the collectionsIds field in a similar fashion to:

gcloud firestore import gs://[BUCKET_NAME]/[EXPORT_PREFIX]/ --collection-ids=[COLLECTION_ID_1],[COLLECTION_ID_2]

Is there a way to exclude some collections from the backup (i.e - jobs)?

Notice that as explained on your example shared you can use the collectionsIds field to create a list with only the collections you want to export (and therefore by not adding the collections that you don't want to export you can exclude them from the export operation).

  return client.exportDocuments({
    name: databaseName,
    outputUriPrefix: bucket,
    // Leave collectionIds empty to export all collections
    // or set to a list of collection IDs to export,
    // collectionIds: ['users', 'posts']
    collectionIds: []
    })


问:
JavaFX, JLink/JPackage Module issue - adding Libraries "Error occurred during initialization of boot layer java.lang.module.FindException"
IDE: IntelliJ.
Trying to use JavaFX for the first time with some additional libraries, and with an installable package - (c/o JLink/JPackage)
Have followed directions from OpenJFX for a Modular Project from IDE and can get this to work no problem.
https://openjfx.io/openjfx-docs/

Adding libraries though I am just getting this error:
"Error occurred during initialization of boot layer
java.lang.module.FindException: Module eu.hansolo.medusa not found, required by ModuleName"

Have read a number of similar threads on this error but no joy here specifically.

Have tried adding adding to VM on run configuration ie:

--module-path
${PATH_TO_FX}:mods/production
--add-modules
javafx.controls,javafx.fxml,eu.hansolo.medusa -
still getting "Error occurred during initialization of boot layer
java.lang.module.FindException: Module eu.hansolo.medusa not found"

However.. If I delete the "module-info.java" file.. I can run the application in IntelliJ no problem.. however.. I then can't use JLink to make the custom runtime image.

Any advice or pointers to reading I can do would be greatly appreciated and many thanks in advance.

答:
So the issue appears to be that you haven't added Medusa to your module path. The way I accomplished this is by using maven.

I added the dependencies to my pom file and created a module-info.java and everything seemed to work.

pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>
    <groupId>org.example</groupId>
    <artifactId>MavenFxied</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-controls</artifactId>
            <version>14.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-graphics</artifactId>
            <version>14.0.1</version>
        </dependency>
        <dependency>
            <groupId>eu.hansolo</groupId>
            <artifactId>Medusa</artifactId>
            <version>11.5</version>
        </dependency>
    </dependencies>

</project>
</code>```

module-info.java

```<code>module mavenfxied {
    requires javafx.controls;
    requires eu.hansolo.medusa;
    exports example;
}
</code>```

I made an example class to test it out.

Main.java

```<code>package example;

import eu.hansolo.medusa.Gauge;
import eu.hansolo.medusa.GaugeBuilder;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class Main extends Application {

    public void start(Stage stage) throws Exception {
        StackPane pane = new StackPane();
        Gauge g = GaugeBuilder.create()
                .skinType(Gauge.SkinType.SPACE_X)
                .animated(true)
                .decimals(0)
                .title("SpaceX")
                .unit("km/h")
                .maxValue(30000)
                .threshold(25000)
                .build();
        pane.getChildren().add(g);
        Scene scene = new Scene(pane);
        stage.setScene(scene);
        stage.show();
    }
}
</code>```

If you aren't using maven, then the solution proposed in the comments of adding the jar file to a location on the module-path might be the only way.

Body:
So the issue appears to be that you haven't added Medusa to your module path. The way I accomplished this is by using maven.

I added the dependencies to my pom file and created a module-info.java and everything seemed to work.

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>
    <groupId>org.example</groupId>
    <artifactId>MavenFxied</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-controls</artifactId>
            <version>14.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-graphics</artifactId>
            <version>14.0.1</version>
        </dependency>
        <dependency>
            <groupId>eu.hansolo</groupId>
            <artifactId>Medusa</artifactId>
            <version>11.5</version>
        </dependency>
    </dependencies>

</project>

module-info.java

module mavenfxied {
    requires javafx.controls;
    requires eu.hansolo.medusa;
    exports example;
}

I made an example class to test it out.

Main.java

package example;

import eu.hansolo.medusa.Gauge;
import eu.hansolo.medusa.GaugeBuilder;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class Main extends Application {

    public void start(Stage stage) throws Exception {
        StackPane pane = new StackPane();
        Gauge g = GaugeBuilder.create()
                .skinType(Gauge.SkinType.SPACE_X)
                .animated(true)
                .decimals(0)
                .title("SpaceX")
                .unit("km/h")
                .maxValue(30000)
                .threshold(25000)
                .build();
        pane.getChildren().add(g);
        Scene scene = new Scene(pane);
        stage.setScene(scene);
        stage.show();
    }
}

If you aren't using maven, then the solution proposed in the comments of adding the jar file to a location on the module-path might be the only way.


答:
Your variable product isn't initialized. As it looks You are loading it in background it might not be initialiazed on first load, but can be initialized later, therefore I would show loading till it's initialized. Do check like this before you use product variable in Your code:

```<code>if (!product) {
 return <div>Loading...</div>;
}
</code>```

Title: I got this error => TypeError: Cannot read property 'image' of undefined

Body:
Your variable product isn't initialized. As it looks You are loading it in background it might not be initialiazed on first load, but can be initialized later, therefore I would show loading till it's initialized. Do check like this before you use product variable in Your code:

if (!product) {
 return <div>Loading...</div>;
}


问:
Searching users in Keycloak from Java code
I am using Spring Boot, Keycloak 10, java 8 and keycloak-admin-client jar. I am able to get user, his groups and roles.

When it comes to search I see different search method options for example I could :

```<code> List<UserRepresentation> search = getKeycloakInstance().realm("my-realm").users()
                .search("username");
</code>```

https://www.keycloak.org/docs-api/10.0/javadocs/org/keycloak/admin/client/resource/UsersResource.html

But what i need to do i to write couple of methods:

search by roles (so search users who has some roles)

search by groups and group attributes

search by text (firstname, lastname, email) in 'contains' manner: mytext

search by roles and text

search by list of ids (uuids of users)

I dont' see such possibilities in keycloak-admin-client, or it is possible of what else should I use instead of keycloak-admin-client ?

答:
Unfortunately, keycloak-admin-client doesn't provide lots of search options.

How to find users by role:

```<code>RoleResource roleResource = getKeycloakInstance().realm("realm_name")
                          .roles().get("role_name");
roleResource.getRoleUserMembers();
</code>```

How to find all users in the group:

```<code>getKeycloakInstance().realm("realm_name").groups().group("your_group").members();
</code>```

How to find users by username, firstName, lastName, email:

```<code>getKeycloakInstance().realm("my-realm").users()
            .search("username", "lastName", "email");
</code>```

If it's okay for you, try to use Keycloak Admin REST API to get more search opportunities.

Body:
I am using Spring Boot, Keycloak 10, java 8 and keycloak-admin-client jar. I am able to get user, his groups and roles.

When it comes to search I see different search method options for example I could :

 List<UserRepresentation> search = getKeycloakInstance().realm("my-realm").users()
                .search("username");

https://www.keycloak.org/docs-api/10.0/javadocs/org/keycloak/admin/client/resource/UsersResource.html

But what i need to do i to write couple of methods:

search by roles (so search users who has some roles)

search by groups and group attributes

search by text (firstname, lastname, email) in 'contains' manner: mytext

search by roles and text

search by list of ids (uuids of users)

I dont' see such possibilities in keycloak-admin-client, or it is possible of what else should I use instead of keycloak-admin-client ?

Body:
Unfortunately, keycloak-admin-client doesn't provide lots of search options.

How to find users by role:

RoleResource roleResource = getKeycloakInstance().realm("realm_name")
                          .roles().get("role_name");
roleResource.getRoleUserMembers();

How to find all users in the group:

getKeycloakInstance().realm("realm_name").groups().group("your_group").members();

How to find users by username, firstName, lastName, email:

getKeycloakInstance().realm("my-realm").users()
            .search("username", "lastName", "email");

If it's okay for you, try to use Keycloak Admin REST API to get more search opportunities.


问:
Azure powershell script - create multiple resource groups with different owners
I'm trying to create a loop script that will create multiple RG's with different owners. I have problem with adding different owner into resource groups.

```<code>$RGNamesUSE = "RG-01", "RG-02", "RG-03"
$Owner = "user1@mail.com","User2@mail.com", "User3@mail.com"

foreach($rg in $RGNamesUSE)
{
New-AzResourceGroup -Name $rg -Location westeurope
}
</code>```

I need to add for each RG the owner. It should be like RG-01 will have owner user1, RG-02 will have owner user2 etc... How can i do this?

答:
You can try the script below, that will create a resource group and assign the user as "Owner" of the resource group:</p>

```<code>$RGNamesUSE = "RG-01", "RG-02", "RG-03"
$Owner = "user1@mail.com","User2@mail.com","User3@mail.com"

For ($i=0; $i -le ($RGNamesUSE.length - 1); $i++) {
    $rg = $RGNamesUSE[$i];
    $userName = $Owner[$i];

    New-AzResourceGroup -Name $rg -Location westeurope
    New-AzRoleAssignment -SignInName $userName -RoleDefinitionName "Owner" -ResourceGroupName $rg
}
</code>```

Body:
I'm trying to create a loop script that will create multiple RG's with different owners. I have problem with adding different owner into resource groups.

$RGNamesUSE = "RG-01", "RG-02", "RG-03"
$Owner = "user1@mail.com","User2@mail.com", "User3@mail.com"

foreach($rg in $RGNamesUSE)
{
New-AzResourceGroup -Name $rg -Location westeurope
}

I need to add for each RG the owner. It should be like RG-01 will have owner user1, RG-02 will have owner user2 etc... How can i do this?

Body:
You can try the script below, that will create a resource group and assign the user as "Owner" of the resource group:

$RGNamesUSE = "RG-01", "RG-02", "RG-03"
$Owner = "user1@mail.com","User2@mail.com","User3@mail.com"

For ($i=0; $i -le ($RGNamesUSE.length - 1); $i++) {
    $rg = $RGNamesUSE[$i];
    $userName = $Owner[$i];

    New-AzResourceGroup -Name $rg -Location westeurope
    New-AzRoleAssignment -SignInName $userName -RoleDefinitionName "Owner" -ResourceGroupName $rg
}


问:
Find a XML node with a specific child using minidom
I am looking for a way to filter this XML string and print the "identifiant" value where the "source" field is HAL.

    <sudoc service="idref2source">
        <query>
            <ppn>115565329</ppn>
            <result>
                <source>HAL</source>
                <identifiant>chl</identifiant>
            </result>
        </query>
        <query>
            <ppn>115565329</ppn>
            <result>
                <source>VIAF</source>
                <identifiant>http://viaf.org/viaf/202196105</identifiant>
            </result>
        </query>
    </sudoc>
```

<p>I only parsed the string using minidom</p>

<pre class="lang-py prettyprint-override"><code>dom = parseString(r.content)
</code>```

Many thanks !

答:
Python's xml module is sufficient for this, in combination with xpath - find the element source, where the text is "HAL", ping back to the parent element and pick out the identifiant element within that parent element. Note that here I use find, not findall, since your question is specifically for the shared xml - if it is a larger file, you can run an iteration using findall :

```<code>import xml.etree.ElementTree as ET

xml = """[your data above here]"""

root = ET.fromstring(xml)

root.find(".//source[.='HAL']/..//identifiant").text

'chl'
</code>```

Body:
I am looking for a way to filter this XML string and print the "identifiant" value where the "source" field is HAL.

    <sudoc service="idref2source">
        <query>
            <ppn>115565329</ppn>
            <result>
                <source>HAL</source>
                <identifiant>chl</identifiant>
            </result>
        </query>
        <query>
            <ppn>115565329</ppn>
            <result>
                <source>VIAF</source>
                <identifiant>http://viaf.org/viaf/202196105</identifiant>
            </result>
        </query>
    </sudoc>

I only parsed the string using minidom

dom = parseString(r.content)

Many thanks !

Body:
Python's xml module is sufficient for this, in combination with xpath - find the element source, where the text is "HAL", ping back to the parent element and pick out the identifiant element within that parent element. Note that here I use find, not findall, since your question is specifically for the shared xml - if it is a larger file, you can run an iteration using findall :

import xml.etree.ElementTree as ET

xml = """[your data above here]"""

root = ET.fromstring(xml)

root.find(".//source[.='HAL']/..//identifiant").text

'chl'


问:
Exceljs : iterate each cell of each row and column
I want to put thick border in all my cells. this is an angular project, I am using typescript.

I can do this for 1 cell,

```<code>worksheet.getCell('A1').border = {
  top: { style: 'thick' },
  left: { style: 'thick' },
  bottom: { style: 'thick' },
  right: { style: 'thick' }
};
</code>```

But I want to do something like 2 nested for loops . For each row , make each cell thick

Here is I tried : app.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
import * as jspdf from 'jspdf';
import html2canvas from 'html2canvas';
// import * as XLSX from 'xlsx';

import * as ExcelJS from 'exceljs';
import * as FileSaver from 'file-saver';

import { ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'app-items-report',
  templateUrl: './items-report.component.html',
  styleUrls: ['./items-report.component.css']
})
export class ItemsReportComponent implements OnInit {
  purchases: any;
  constructor(private dataService: DataService) {
    this.GetPurchases();
  }

  ngOnInit(): void {
  }

  async GetPurchases() {
    const response = await this.dataService.GetPurchases();
    const dataService = await response.json();
    this.purchases = dataService;
  }

  downloadPDF() {
    const data = document.getElementById('purchaseTable');  // Id of the table
    html2canvas(data).then(canvas => {
      // Few necessary setting options
      const imgWidth = 208;
      const pageHeight = 295;
      const imgHeight = canvas.height * imgWidth / canvas.width;
      const heightLeft = imgHeight;

      const contentDataURL = canvas.toDataURL('image/png');
      // Your 1st parameter (landscape [l] or portrait [p]) determines what becomes the width and the height.
      const pdf = new jspdf('p', 'mm', 'a4'); // A4 size page of PDF
      const position = 0;
      /* addImage explained below:
      param 1 -> image in code format
      param 2 -> type of the image. SVG not supported. needs to be either PNG or JPEG.
      all params are specified in integer
      param 3 -> X axis margin from left
      param 4 -> Y axis margin from top
      param 5 -> width of the image
      param 6 -> height of the image
      */
      // pdf.addImage(contentDataURL, 'PNG', 0, position, imgWidth, imgHeight);
      // pdf.addImage(contentDataURL, 'PNG', 18, 30, imgWidth - 17, imgHeight);
      pdf.addImage(contentDataURL, 'PNG', 18, 30, imgWidth - 21, imgHeight);

      pdf.save('MYPdf.pdf'); // Generated PDF
    });
  }
  downloadExcel() {

    const date = new Date().toISOString().slice(0, 10).split('-').reverse().join('/');
    console.log(date);

    const workbook = new ExcelJS.Workbook();
    const worksheet = workbook.addWorksheet('My Sheet');

    worksheet.columns = [
      { header: 'Id', key: 'id', width: 10},
      { header: 'Name', key: 'name', width: 32 },
      { header: 'Quantity', key: 'quantity', width: 15 },
      { header: 'Rate', key: 'rate', width: 15 },
      { header: 'Date', key: 'date', width: 15 },
      { header: 'Total', key: 'total', width: 15 }
    ];

    for (const purchase of this.purchases) {
      worksheet.addRow({
        id: purchase.item_id ,
        date: purchase.item_purchase_date.toString().slice(0, 10).split('-').reverse().join('/'),
        name: purchase.item_name,
        quantity: purchase.item_quantity,
        rate: purchase.item_rate,
        total: purchase.item_rate * purchase.item_quantity
       })
      .alignment = { horizontal: 'left' };
    }

    worksheet.getRow(1).font = { bold: true };

// Iterate over all rows (including empty rows) in a worksheet
worksheet.eachRow({ includeEmpty: true }, (row, rowNumber) => {
  console.log('Row ' + rowNumber + ' = ' + JSON.stringify(row.values));
  row.eachCell({ includeEmpty: true }, (cell, rowNumber) => {
    // ...please make my cell thick here
    // i cant no longer write a1 or b1
    // i need to access all cells - including empty cells

  });
});

   book.xlsx.readFile('export.xlsx');

}
</code>```

I need to make each of my cells thick, inside for loop. So please help me how to access each cell in a loop without writing a1 or b1

答:
Worksheet gives you a columns property on which you can iterate and use it like :- </p>

```<code>worksheet.columns.forEach(column => {
      column.border = {
        top: { style: "thick" },
        left: { style: "thick" },
        bottom: { style: "thick" },
        right: { style: "thick" }
      };
    });
</code>```

Body:
I want to put thick border in all my cells. this is an angular project, I am using typescript.

I can do this for 1 cell,

worksheet.getCell('A1').border = {
  top: { style: 'thick' },
  left: { style: 'thick' },
  bottom: { style: 'thick' },
  right: { style: 'thick' }
};

But I want to do something like 2 nested for loops . For each row , make each cell thick

Here is I tried : app.component.ts

import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
import * as jspdf from 'jspdf';
import html2canvas from 'html2canvas';
// import * as XLSX from 'xlsx';

import * as ExcelJS from 'exceljs';
import * as FileSaver from 'file-saver';

import { ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'app-items-report',
  templateUrl: './items-report.component.html',
  styleUrls: ['./items-report.component.css']
})
export class ItemsReportComponent implements OnInit {
  purchases: any;
  constructor(private dataService: DataService) {
    this.GetPurchases();
  }

  ngOnInit(): void {
  }

  async GetPurchases() {
    const response = await this.dataService.GetPurchases();
    const dataService = await response.json();
    this.purchases = dataService;
  }

  downloadPDF() {
    const data = document.getElementById('purchaseTable');  // Id of the table
    html2canvas(data).then(canvas => {
      // Few necessary setting options
      const imgWidth = 208;
      const pageHeight = 295;
      const imgHeight = canvas.height * imgWidth / canvas.width;
      const heightLeft = imgHeight;

      const contentDataURL = canvas.toDataURL('image/png');
      // Your 1st parameter (landscape [l] or portrait [p]) determines what becomes the width and the height.
      const pdf = new jspdf('p', 'mm', 'a4'); // A4 size page of PDF
      const position = 0;
      /* addImage explained below:
      param 1 -> image in code format
      param 2 -> type of the image. SVG not supported. needs to be either PNG or JPEG.
      all params are specified in integer
      param 3 -> X axis margin from left
      param 4 -> Y axis margin from top
      param 5 -> width of the image
      param 6 -> height of the image
      */
      // pdf.addImage(contentDataURL, 'PNG', 0, position, imgWidth, imgHeight);
      // pdf.addImage(contentDataURL, 'PNG', 18, 30, imgWidth - 17, imgHeight);
      pdf.addImage(contentDataURL, 'PNG', 18, 30, imgWidth - 21, imgHeight);

      pdf.save('MYPdf.pdf'); // Generated PDF
    });
  }
  downloadExcel() {

    const date = new Date().toISOString().slice(0, 10).split('-').reverse().join('/');
    console.log(date);

    const workbook = new ExcelJS.Workbook();
    const worksheet = workbook.addWorksheet('My Sheet');

    worksheet.columns = [
      { header: 'Id', key: 'id', width: 10},
      { header: 'Name', key: 'name', width: 32 },
      { header: 'Quantity', key: 'quantity', width: 15 },
      { header: 'Rate', key: 'rate', width: 15 },
      { header: 'Date', key: 'date', width: 15 },
      { header: 'Total', key: 'total', width: 15 }
    ];

    for (const purchase of this.purchases) {
      worksheet.addRow({
        id: purchase.item_id ,
        date: purchase.item_purchase_date.toString().slice(0, 10).split('-').reverse().join('/'),
        name: purchase.item_name,
        quantity: purchase.item_quantity,
        rate: purchase.item_rate,
        total: purchase.item_rate * purchase.item_quantity
       })
      .alignment = { horizontal: 'left' };
    }

    worksheet.getRow(1).font = { bold: true };

// Iterate over all rows (including empty rows) in a worksheet
worksheet.eachRow({ includeEmpty: true }, (row, rowNumber) => {
  console.log('Row ' + rowNumber + ' = ' + JSON.stringify(row.values));
  row.eachCell({ includeEmpty: true }, (cell, rowNumber) => {
    // ...please make my cell thick here
    // i cant no longer write a1 or b1
    // i need to access all cells - including empty cells

  });
});

   book.xlsx.readFile('export.xlsx');

}

I need to make each of my cells thick, inside for loop. So please help me how to access each cell in a loop without writing a1 or b1

Body:
Worksheet gives you a columns property on which you can iterate and use it like :-

worksheet.columns.forEach(column => {
      column.border = {
        top: { style: "thick" },
        left: { style: "thick" },
        bottom: { style: "thick" },
        right: { style: "thick" }
      };
    });


问:
How to produce Kafka messages with JSON format in Python
How to delete quotes and send data like on original format
The original JSON-format is:

```<code>{
  "@timestamp": "2020-06-02T09:38:03.183186Z"
}
</code>```

This data in another topic

```<code>"{\"@timestamp\": \"2020-05-25T17:40:47.582778Z\"}"
</code>```

This is a code of sending data between servers

```<code>def parse(d):
    if str(type(d)) == "<class 'dict'>":
        return (r)
    return -1

producer = KafkaProducer(bootstrap_servers=param["BOOTSTRAP_SERVERS"],
                                 value_serializer=lambda x: dumps(x).encode('utf-8'))  # utf-8
consumer = KafkaConsumer(bootstrap_servers=param["BOOTSTRAP_SERVERS"]+'1',
                                 auto_offset_reset=param["AUTO_OFFSET_RESET"],
                                 consumer_timeout_ms=param["CONSUMER_TIMEOUT_MS"],
                                 enable_auto_commit=False,
                                 auto_commit_interval_ms=60000,
                                 group_id=param["GROUP_ID"],
                                 client_id=param["CLIENT_ID"]
                                 )
consumer.subscribe([param["TOPIC_IN"]])
 while True:
      num_rows = 0
      for msg in consumer:
          num_rows = num_rows + 1
          m = json.loads(msg.value)
          j = parse(m)
          if j != -1:
             data = json.dumps(j)
             producer.send(param["TOPIC_OUT"], value=data)
</code>```

答:
You are currently serializing your values as strings. If you want JSON instead of string, then you will need to properly serialise your values.

The following should do the trick:

```<code>import json

producer = KafkaProducer(
    bootstrap_servers='mykafka-broker',
    value_serializer=lambda v: json.dumps(v).encode('utf-8')
)
</code>```

Body:
How to delete quotes and send data like on original format
The original JSON-format is:

{
  "@timestamp": "2020-06-02T09:38:03.183186Z"
}

This data in another topic

"{\"@timestamp\": \"2020-05-25T17:40:47.582778Z\"}"

This is a code of sending data between servers

def parse(d):
    if str(type(d)) == "<class 'dict'>":
        return (r)
    return -1

producer = KafkaProducer(bootstrap_servers=param["BOOTSTRAP_SERVERS"],
                                 value_serializer=lambda x: dumps(x).encode('utf-8'))  # utf-8
consumer = KafkaConsumer(bootstrap_servers=param["BOOTSTRAP_SERVERS"]+'1',
                                 auto_offset_reset=param["AUTO_OFFSET_RESET"],
                                 consumer_timeout_ms=param["CONSUMER_TIMEOUT_MS"],
                                 enable_auto_commit=False,
                                 auto_commit_interval_ms=60000,
                                 group_id=param["GROUP_ID"],
                                 client_id=param["CLIENT_ID"]
                                 )
consumer.subscribe([param["TOPIC_IN"]])
 while True:
      num_rows = 0
      for msg in consumer:
          num_rows = num_rows + 1
          m = json.loads(msg.value)
          j = parse(m)
          if j != -1:
             data = json.dumps(j)
             producer.send(param["TOPIC_OUT"], value=data)

Body:
You are currently serializing your values as strings. If you want JSON instead of string, then you will need to properly serialise your values.

The following should do the trick:

import json

producer = KafkaProducer(
    bootstrap_servers='mykafka-broker',
    value_serializer=lambda v: json.dumps(v).encode('utf-8')
)