问:
How to display items aligned?
this is for sure a common question but text-align and display properties are not solving it, so i must have some mistake.
What should i do to display the 3 items in the same horizontal line?

.contact__information {
  vertical-align: middle;
  margin-bottom: var(--mb-1);
  padding-right: var(--mb-.75);
  align-items: right;
  text-align: center;
  display: inline-flex;
  margin-left: auto;
  margin-right: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="contact section" id="contact">
  <h2 class="section__title">Contacte</h2>
  <span class="section__subtitle">Contacte para mais informações</span>

  <div class="contact__information">
    <i class="uil uil-phone contact__icon"></i>
    <div>
      <h3 class="contact__title">Telemóvel</h3>
      <span class="contact__subtitle">999-777-666</span>
    </div>
  </div>

  <div class="contact__information">
    <i class="uil uil-envelope contact__icon"></i>
    <div>
      <h3 class="contact__title">Email</h3>
      <span class="contact__subtitle">email.com</span>
    </div>
  </div>

  <div class="contact__information">
    <i class="uil uil-map-marker contact__icon"></i>
    <div>
      <h3 class="contact__title">Morada</h3>
      <span class="contact__subtitle">Portugal</span>
    </div>
  </div>
</section></code>```

答:
Step 1: Define width

Step 2: Locate parent to flex - #contact

Step 3: align-items: center; makes all elements inline (aligned)

Step 4: justify-content: space-evenly; spaces all elements evenly. Using up extra space.

#contact {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-evenly;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="contact section" id="contact">
  <h2 class="section__title">Contacte</h2>
  <span class="section__subtitle">Contacte para mais informações</span>

  <div class="contact__information">
    <i class="uil uil-phone contact__icon"></i>
    <div>
      <h3 class="contact__title">Telemóvel</h3>
      <span class="contact__subtitle">999-777-666</span>
    </div>
  </div>

  <div class="contact__information">
    <i class="uil uil-envelope contact__icon"></i>
    <div>
      <h3 class="contact__title">Email</h3>
      <span class="contact__subtitle">email.com</span>
    </div>
  </div>

  <div class="contact__information">
    <i class="uil uil-map-marker contact__icon"></i>
    <div>
      <h3 class="contact__title">Morada</h3>
      <span class="contact__subtitle">Portugal</span>
    </div>
  </div>
</section></code>```

Title: How to display items aligned?

Body:
this is for sure a common question but text-align and display properties are not solving it, so i must have some mistake.
What should i do to display the 3 items in the same horizontal line?

.contact__information {
  vertical-align: middle;
  margin-bottom: var(--mb-1);
  padding-right: var(--mb-.75);
  align-items: right;
  text-align: center;
  display: inline-flex;
  margin-left: auto;
  margin-right: auto;
}

Contacte

  Contacte para mais informações

Telemóvel

      999-777-666

Email

      email.com

Morada

      Portugal

Body:
Step 1: Define width

Step 2: Locate parent to flex - #contact

Step 3: align-items: center; makes all elements inline (aligned)

Step 4: justify-content: space-evenly; spaces all elements evenly. Using up extra space.

#contact {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-evenly;
}

<section class="contact section" id="contact">
  <h2 class="section__title">Contacte</h2>
  <span class="section__subtitle">Contacte para mais informações</span>

  <div class="contact__information">
    <i class="uil uil-phone contact__icon"></i>
    <div>
      <h3 class="contact__title">Telemóvel</h3>
      <span class="contact__subtitle">999-777-666</span>
    </div>
  </div>

  <div class="contact__information">
    <i class="uil uil-envelope contact__icon"></i>
    <div>
      <h3 class="contact__title">Email</h3>
      <span class="contact__subtitle">email.com</span>
    </div>
  </div>

  <div class="contact__information">
    <i class="uil uil-map-marker contact__icon"></i>
    <div>
      <h3 class="contact__title">Morada</h3>
      <span class="contact__subtitle">Portugal</span>
    </div>
  </div>
</section>


来源: stackexchange

问:
Kotlin Data Class Parsing Mutiple member properties at once
Let say I have a data class called Class A

```<code>data class ClassA {
 val x0 = ""
 val x1 = "some string"
 val x2 = "some string"
 val x3 = "some string"
 val x4 = "some string"
 val x5 = ""
 val x6 = ""
 val y = ""
 val z = ""
}
</code>```

I can retrieve the value of these class member thru its class object

```<code>val obj = ClassA()
// if the properties has prefix x and not empty then concatenate to this x variable
val x = obj.x1 + obj.x2 + etc...
...
</code>```

Let say if this data class has 50+ x(n) in it and I want to retrieve any member that does not have an "empty string or null" and match the prefix then how do I do it dynamically (can be a for-loop), instead of type out statically every single properties that I want to retrieve, is there an alternative way to do it?

答:
You could solve that with Reflection:

```<code>data class ClassA (
  val x0: String = "",
  val x1: String = "some string 1",
  val x2: String = "some string 2",
  val x3: String = "some string 3",
  val x4: String = "some string 4",
  val x5: String = "",
  val x6: String = "",
  val y: String = "",
  val z: String = ""
)

val obj = ClassA()

val result = ClassA::class.java.declaredFields   // or:
  .filter { it.name.startsWith("x") }
  .onEach { it.isAccessible = true }
  .map { it.get(obj) }
  .joinToString("; ")

println(result)
</code>```

This will print:

```<code>; some string 1; some string 2; some string 3; some string 4; ;
</code>```

If you want to omit x0, x5, and x6, which all are empty strings, and you want to concatenate without semicolon:

```<code>val result = Class::class.java.declaredFields
  .filter { it.name.startsWith("x") }
  .onEach { it.isAccessible = true }
  .map { it.get(obj) }
  .filter { it != "" }
  .joinToString("")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Let say I have a data class called Class A

data class ClassA {
 val x0 = ""
 val x1 = "some string"
 val x2 = "some string"
 val x3 = "some string"
 val x4 = "some string"
 val x5 = ""
 val x6 = ""
 val y = ""
 val z = ""
}

I can retrieve the value of these class member thru its class object

val obj = ClassA()
// if the properties has prefix x and not empty then concatenate to this x variable
val x = obj.x1 + obj.x2 + etc...
...

Let say if this data class has 50+ x(n) in it and I want to retrieve any member that does not have an "empty string or null" and match the prefix then how do I do it dynamically (can be a for-loop), instead of type out statically every single properties that I want to retrieve, is there an alternative way to do it?

Body:
You could solve that with Reflection:

data class ClassA (
  val x0: String = "",
  val x1: String = "some string 1",
  val x2: String = "some string 2",
  val x3: String = "some string 3",
  val x4: String = "some string 4",
  val x5: String = "",
  val x6: String = "",
  val y: String = "",
  val z: String = ""
)

val obj = ClassA()

val result = ClassA::class.java.declaredFields   // or:
  .filter { it.name.startsWith("x") }
  .onEach { it.isAccessible = true }
  .map { it.get(obj) }
  .joinToString("; ")

println(result)

This will print:

; some string 1; some string 2; some string 3; some string 4; ;

If you want to omit x0, x5, and x6, which all are empty strings, and you want to concatenate without semicolon:

val result = Class::class.java.declaredFields
  .filter { it.name.startsWith("x") }
  .onEach { it.isAccessible = true }
  .map { it.get(obj) }
  .filter { it != "" }
  .joinToString("")


问:
Fixing issues with geom_text and axis labels
I have a barplot in which I need to rotate the bar labels giving the Freq values:

```<code>library(dplyr)
ggplot(df,
  aes(x = partcl, y = Pct)) +
  geom_bar(stat="identity") +
  # rotate x-axis labels by 90°:
  theme(axis.text.x = element_text(angle = 90)) +
  # plot `Freq` labels:
  geom_text(aes(x = partcl, y = Pct, label = Freq, angle = 90, hjust = -0.2))
</code>```

But there are two issues: first, the Freq labels are not fitted to the plotting area; instead the maximum Frequ label (for yeah well) is cut off. Second, the x-axis labels are not perfectly aligned with the x-axis ticks. How can these issues be fixed?

Data:

```<code>df <- structure(list(partcl = c("yeah well", "well yeah", "yeah yeah well",
                                "yeah well well", "yeah well yeah", "well yeah well", "well yeah yeah",
                                "well yeah yeah yeah", "yeah yeah yeah well", "well yeah well well"
), Freq = c(1515L, 408L, 52L, 20L, 17L, 11L, 8L, 2L, 2L, 1L),
Pct = c(74.3011280039235, 20.0098087297695, 2.55026974006866,
        0.980872976949485, 0.833742030407062, 0.539480137322217,
        0.392349190779794, 0.0980872976949485, 0.0980872976949485,
        0.0490436488474743)), class = c("tbl_df", "tbl", "data.frame"
        ), row.names = c(NA, -10L))
</code>```

答:
For the ticks set vjust=.5 as by default theme_grey uses vjust=1. For the labels I don't know of any out-of-the-box option except for increasing the expansion of the y scale:

library(ggplot2)

ggplot(df, aes(x = partcl, y = Pct)) +
  geom_bar(stat="identity") +
  # rotate x-axis labels by 90°:
  theme(axis.text.x = element_text(angle = 90, vjust = .5)) +
  # plot `Freq` labels:
  geom_text(aes(x = partcl, y = Pct, label = Freq, angle = 90, hjust = -0.2)) +
  scale_y_continuous(expand = expansion(mult = c(0, .15)))
```

Body:
I have a barplot in which I need to rotate the bar labels giving the Freq values:

library(dplyr)
ggplot(df,
  aes(x = partcl, y = Pct)) +
  geom_bar(stat="identity") +
  # rotate x-axis labels by 90°:
  theme(axis.text.x = element_text(angle = 90)) +
  # plot `Freq` labels:
  geom_text(aes(x = partcl, y = Pct, label = Freq, angle = 90, hjust = -0.2))

But there are two issues: first, the Freq labels are not fitted to the plotting area; instead the maximum Frequ label (for yeah well) is cut off. Second, the x-axis labels are not perfectly aligned with the x-axis ticks. How can these issues be fixed?

Data:

df <- structure(list(partcl = c("yeah well", "well yeah", "yeah yeah well",
                                "yeah well well", "yeah well yeah", "well yeah well", "well yeah yeah",
                                "well yeah yeah yeah", "yeah yeah yeah well", "well yeah well well"
), Freq = c(1515L, 408L, 52L, 20L, 17L, 11L, 8L, 2L, 2L, 1L),
Pct = c(74.3011280039235, 20.0098087297695, 2.55026974006866,
        0.980872976949485, 0.833742030407062, 0.539480137322217,
        0.392349190779794, 0.0980872976949485, 0.0980872976949485,
        0.0490436488474743)), class = c("tbl_df", "tbl", "data.frame"
        ), row.names = c(NA, -10L))


问:
draw in an eclipse rcp view?
I need to draw some circles and nodes (according to their (x,y) coordinates) in an rcp view. I think Zest is not appropriate or my application (the nodes can be moved, no coordinates..) I did my best to use jung, but  always got problems... so I decided to plot them using SWT "shapes". however, when I draw a circle and then resize the view (a new editor appears so the view is smaller) I miss the circle (doesn't appear)...
 I really need you help to know which is the best way to do my application? and if you too got problems using jung?
thanks a lot</p>

答:
There are many, many ways to this...

Apart from ZEST and Jung, you also have GMF and Graphitti, though these both can be considered overkill for a small project.

Last, but not least, you have SWT - as you also note - based on a Canvas. For an example on how to use this see the SWT Snippets - specially  paint a circle in a canvas
 .

ContentLicense: CC BY-SA 3.0

Title: draw in an eclipse rcp view?


问:
Restructuring a Pandas series
I have the following series:

```<code>r = [1,2,3,4,'None']
ser = pd.Series(r, copy=False)
</code>```

The output of which is -

```<code>ser
Out[406]:
0       1
1       2
2       3
3       4
4    None
</code>```

At ser[1], I want to set the value to be 'NULL' and copy the [2,3,4] to be shifted by one index.

Therefore the desired output would be:

```<code>ser
Out[406]:
0       1
1      NULL
2       2
3       3
4       4
</code>```

I did the following which is not working:

```<code>slice_ser = ser[1:-1]
ser[2] = 'NULL'
ser[3:-1] = slice_ser
</code>```

I am getting an error 'ValueError: cannot set using a slice indexer with a different length than the value'. How do I fix the issue?

答:
You can shift values after position 1 and assign it back:</p>
```<code>ser.iloc[1:] = ser.iloc[1:].shift()

ser
0      1
1    NaN
2      2
3      3
4      4
dtype: object
</code>```

Title: Restructuring a Pandas series

Body:
I have the following series:

r = [1,2,3,4,'None']
ser = pd.Series(r, copy=False)

The output of which is -

ser
Out[406]:
0       1
1       2
2       3
3       4
4    None

At ser[1], I want to set the value to be 'NULL' and copy the [2,3,4] to be shifted by one index.

Therefore the desired output would be:

ser
Out[406]:
0       1
1      NULL
2       2
3       3
4       4

I did the following which is not working:

slice_ser = ser[1:-1]
ser[2] = 'NULL'
ser[3:-1] = slice_ser

I am getting an error 'ValueError: cannot set using a slice indexer with a different length than the value'. How do I fix the issue?

Body:
You can shift values after position 1 and assign it back:

ser.iloc[1:] = ser.iloc[1:].shift()

ser
0      1
1    NaN
2      2
3      3
4      4
dtype: object


问:
Memory Leak in React component using useEffect
Im doing a Carrousel that when it opens a "news" you can see a description in a modal, that works perfect, but when you click on a offer you redirect to another page with the info about that product.

It's working but when you do it, in the consolo shows the error of memory leak
"react-dom.development.js:67 Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function."

I'm knew using useEffect and I don't know how to avoid this.

Thanks for your time

This is the "AxiosCollection"

import axios from "axios";
const baseURL = "http://localhost:8080";

function AxiosGetData(url, setData) {
  axios
    .get(`${baseURL}${url}`, {
      headers: {
        "Content-type": "application/json",
      },
    })
    .then((response) => {
      setData(response.data);
    })
    .catch((error) => {
      return error;
    });
}

export {
  AxiosGetData
};```
</div>
</div>
</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import React, { useState, useEffect } from "react";
import { AxiosGetData } from "../AxiosCollection/AxiosCollection";
import Modal from "../Modal/Modal";
import { Link } from "react-router-dom";

// Import Swiper React components
import { Swiper, SwiperSlide } from "swiper/react";

// Import Swiper styles
import "swiper/swiper-bundle.min.css";
import "swiper/swiper.min.css";

import BenefitCard from "../";

//Css file
import "./Slider.css";

// import Swiper core and required modules
import SwiperCore, { Pagination, Navigation } from "swiper";

// install Swiper modules
SwiperCore.use([Pagination, Navigation]);

const Slider = () => {
  //state to populate with featured object from API
  const [featured, setFeatured] = useState([]);
  const [isOpen, setIsOpen] = useState(false);
  const [featuredById, setFeaturedById] = useState();
  const onCloseRequest = () => setIsOpen(false);

  // hook to fetch data with Axios,it only runs once, takes an url and a function as params

  const handleClick = (item) => {
    AxiosGetData(`/jp-coin/featured/${item.featuredId}`, setFeaturedById);
    setIsOpen(true);
  };

  useEffect(() => {
    AxiosGetData("/...", setFeatured);

  }, []);

  return (
    <Swiper
      slidesPerView={1}
      spaceBetween={30}
      slidesPerGroup={1}
      loop={true}
      loopFillGroupWithBlank={true}
      pagination={{ clickable: true }}
      navigation={true}
      breakpoints={{
        768: {
          slidesPerView: 3,
          spaceBetween: 30,
          slidesPerGroup: 3,
        },
      }}
      className="mySwiper"
    >
      {featured.map((item) => (
        <SwiperSlide key={item.featuredId} onClick={() => handleClick(item)}>
          <Link to={item.type === "offer" ? `/jp-coin/offers/${item.featuredId}` : "/"}>
            <BenefitCard benefit={item} />
          </Link>
        </SwiperSlide>
      ))}
      {featuredById && featuredById.type === "news" && (
        <>
          <Modal
            isOpen={isOpen}
            onCloseRequest={onCloseRequest}
            className="slider__modalContainer"
          >
            <img src={featuredById.image} alt={featuredById.title} />
            <h1 className="slider__modalTitle">{featuredById.title}</h1>
            <p className="slider__modalDescription">
              Lorem ipsum dolor sit, amet consectetur adipisicing elit. Hic
              blanditiis aperiam fuga ex, ratione recusandae ut harum, nam
              doloremque veniam necessitatibus, fugiat delectus placeat possimus
              totam sequi. Minus, at vitae.
            </p>
          </Modal>
        </>
      )}
      ;
    </Swiper>
  );
};

export default Slider;</code>```

答:
That happens, because you're trying to update state asynchronously, and the update could happen when the component is unmounted.

You can keep a ref that will check if the component is mounted or not like in the code below.

Because I can't see the implementation of the AxiosGetData, you can just check is that ref is true, when you will consume the promise from the axios.

```<code>  const isMountedRef = useRef();

  useEffect(() => {
    isMountedRef.current = true
    // In your async function check is the isMountedRef is true or not
    AxiosGetData("/jp-coin/featured", setFeatured);

    return () => { isMountedRef.current = false }
  }, []);
</code>```

For example, using the regular fetch, you could achieve it like this:

```<code>  const isMountedRef = useRef();

  useEffect(() => {
    isMountedRef.current = true;

    fetch('someAPIDomain').then(data => {
      isMountedRef.current && setState(data);
    });

    return () => { isMountedRef.current = false }
  }, []);
</code>```

Body:
Im doing a Carrousel that when it opens a "news" you can see a description in a modal, that works perfect, but when you click on a offer you redirect to another page with the info about that product.

It's working but when you do it, in the consolo shows the error of memory leak
"react-dom.development.js:67 Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function."

I'm knew using useEffect and I don't know how to avoid this.

Thanks for your time

This is the "AxiosCollection"

import axios from "axios";
const baseURL = "http://localhost:8080";

function AxiosGetData(url, setData) {
  axios
    .get(`${baseURL}${url}`, {
      headers: {
        "Content-type": "application/json",
      },
    })
    .then((response) => {
      setData(response.data);
    })
    .catch((error) => {
      return error;
    });
}

export {
  AxiosGetData
};

import React, { useState, useEffect } from "react";
import { AxiosGetData } from "../AxiosCollection/AxiosCollection";
import Modal from "../Modal/Modal";
import { Link } from "react-router-dom";

// Import Swiper React components
import { Swiper, SwiperSlide } from "swiper/react";

// Import Swiper styles
import "swiper/swiper-bundle.min.css";
import "swiper/swiper.min.css";

import BenefitCard from "../";

//Css file
import "./Slider.css";

// import Swiper core and required modules
import SwiperCore, { Pagination, Navigation } from "swiper";

// install Swiper modules
SwiperCore.use([Pagination, Navigation]);

const Slider = () => {
  //state to populate with featured object from API
  const [featured, setFeatured] = useState([]);
  const [isOpen, setIsOpen] = useState(false);
  const [featuredById, setFeaturedById] = useState();
  const onCloseRequest = () => setIsOpen(false);

  // hook to fetch data with Axios,it only runs once, takes an url and a function as params

  const handleClick = (item) => {
    AxiosGetData(`/jp-coin/featured/${item.featuredId}`, setFeaturedById);
    setIsOpen(true);
  };

  useEffect(() => {
    AxiosGetData("/...", setFeatured);

  }, []);

  return (
    <Swiper
      slidesPerView={1}
      spaceBetween={30}
      slidesPerGroup={1}
      loop={true}
      loopFillGroupWithBlank={true}
      pagination={{ clickable: true }}
      navigation={true}
      breakpoints={{
        768: {
          slidesPerView: 3,
          spaceBetween: 30,
          slidesPerGroup: 3,
        },
      }}
      className="mySwiper"
    >
      {featured.map((item) => (
        <SwiperSlide key={item.featuredId} onClick={() => handleClick(item)}>
          <Link to={item.type === "offer" ? `/jp-coin/offers/${item.featuredId}` : "/"}>
            <BenefitCard benefit={item} />
          </Link>
        </SwiperSlide>
      ))}
      {featuredById && featuredById.type === "news" && (
        <>
          <Modal
            isOpen={isOpen}
            onCloseRequest={onCloseRequest}
            className="slider__modalContainer"
          >

{featuredById.title}

              Lorem ipsum dolor sit, amet consectetur adipisicing elit. Hic
              blanditiis aperiam fuga ex, ratione recusandae ut harum, nam
              doloremque veniam necessitatibus, fugiat delectus placeat possimus
              totam sequi. Minus, at vitae.

          </Modal>
        </>
      )}
      ;
    </Swiper>
  );
};

export default Slider;

Body:
That happens, because you're trying to update state asynchronously, and the update could happen when the component is unmounted.

You can keep a ref that will check if the component is mounted or not like in the code below.

Because I can't see the implementation of the AxiosGetData, you can just check is that ref is true, when you will consume the promise from the axios.

  const isMountedRef = useRef();

  useEffect(() => {
    isMountedRef.current = true
    // In your async function check is the isMountedRef is true or not
    AxiosGetData("/jp-coin/featured", setFeatured);

    return () => { isMountedRef.current = false }
  }, []);

For example, using the regular fetch, you could achieve it like this:

  const isMountedRef = useRef();

  useEffect(() => {
    isMountedRef.current = true;

    fetch('someAPIDomain').then(data => {
      isMountedRef.current && setState(data);
    });

    return () => { isMountedRef.current = false }
  }, []);


答:
I'd use shift for this:

```<code>>>> ser[1:] = ser[1:].shift(1).fillna('NULL')
>>> ser
0       1
1    NULL
2       2
3       3
4       4
dtype: object
</code>```

Title: Restructuring a Pandas series

Body:
I'd use shift for this:

>>> ser[1:] = ser[1:].shift(1).fillna('NULL')
>>> ser
0       1
1    NULL
2       2
3       3
4       4
dtype: object


问:
.clipShape lose alignment when padding | SwiftUI | iOS15
I'm working on a custom Navigation Bottom Bar. I want it to be floating but I realized that when I add .padding() on it the .clipShape() inside its background loses alignment.

I have coded a simple version of the issue.

BottomNav without padding:

BottomNav with padding:

Main View:

```<code>struct ContentView: View {
var body: some View {
        VStack{
            Spacer()
            CustomBottomNav()
                .padding() // <- THIS MAKE THE SHAPE TO LOSE ALIGN
        }
}
</code>```

CustomBottomNav:

```<code>struct CustomBottomNav: View {

@State var selectedTab: Views = .HOME
@State private var xAxis: CGFloat = 0
@Namespace var animation

private let tabs: [Views] = [.SETTINGS, .RANKING, .HOME, .SALES, .SEARCHER]
private let iconSize: CGFloat = 25

private func isSelectedTab(_ tab: Views) -> Bool{
    return selectedTab == selectedTab
}

var body: some View {
    HStack(spacing: 0){
        ForEach(tabs, id: \.self){ tab in

            GeometryReader { geo in
                Button {

                    print(geo.frame(in: .global).midX)

                    withAnimation(.spring()) {
                        selectedTab = tab
                        xAxis = geo.frame(in: .global).midX
                    }
                } label: {
                    getImage(tab: tab)
                        .resizable()
                        .renderingMode(.template)
                        .aspectRatio(contentMode: .fit)
                        .frame(width: 30, height: 30)
                        .padding(isSelectedTab(tab) ? 15 : 0)
                        .background(
                            Color.orange
                                .opacity(
                                    isSelectedTab(tab) ? 1 : 0
                                ).clipShape(Circle())
                        )
                        .matchedGeometryEffect(id: tab, in: animation)
                }
                .position(x: geo.frame(in: .local).midX, y: geo.frame(in: .local).midY)
                .offset(
                    y: -60
                )
                .onAppear {
                    if isSelectedTab(tab) {
                        xAxis = geo.frame(in: .global).midX
                    }
                }
            }
            .frame(width: iconSize, height: iconSize)
            .overlay(
                Rectangle()
                    .stroke(.red)
            )

            if tab != tabs.last{
                Spacer()
            }

        }
    }
    .padding(.horizontal, 30)
    .padding(.vertical)
    .background(
        Color.yellow
            .clipShape(BottomNavShape(xAxis: xAxis))
            .cornerRadius(15)
    )
}

func getImage(tab: Views) -> Image {
    switch tab {
        case .SETTINGS:
            return Image("house")
        case .RANKING:
            return Image("house")
        case .HOME:
            return Image("house")
        case .SALES:
            return Image("house")
        case .SEARCHER:
            return Image("house")
    }
}

enum Views{
    case SETTINGS
    case RANKING
    case HOME
    case SALES
    case SEARCHER

}
}
</code>```

BottomNavShape:

```<code>struct BottomNavShape: Shape{

var xAxis: CGFloat

//Animating path
var animatableData: CGFloat{
    get{
        return xAxis
    }
    set{
        xAxis = newValue
    }
}

func path(in rect: CGRect) -> Path {
    return Path{ path in
        path.move(to: CGPoint(x: 0, y: 0))
       path.addLine(to: CGPoint(x: rect.width, y: 0))
       path.addLine(to: CGPoint(x: rect.width, y: rect.height))
       path.addLine(to: CGPoint(x: 0, y: rect.height))

       let center = CGPoint(x: xAxis, y: rect.midY)

        path.move(to: center)

        path.addArc(center: center, radius: 15, startAngle: .degrees(0), endAngle:
.degrees(1), clockwise: true)
    }
}
}
</code>```

These classes are all you need to replicate the issue.

I'm using XCode 13 and iOS 15.

答:
The problem is that your are passing a global coordinate to BottomNavShape which uses local coordinates to draw itself.

So global X = 30 coordinate passed to BottomNavShape will be 30 points after BottomNavShape's minX starts in global context.

In order to solve this I changed xAxis for xAxisMultiplier.

I made this function:

```<code>    func setAxisMultiplier(_ index: Int){
        xAxisMultiplier = CGFloat(index) / CGFloat(tabs.count - 1)
    }
</code>```

Where index is the index of tab inside tabs

I added two more params to BottomNavShape: horizontalPadding and iconSize

BottomNavShape:

```<code>struct BottomNavShape: Shape{

var xAxisMultiplier: CGFloat
var horizontalPadding: CGFloat
var iconSize: CGFloat

//Animating path
var animatableData: CGFloat{
    get{
        return xAxisMultiplier
    }
    set{
        xAxisMultiplier = newValue
    }
}

func path(in rect: CGRect) -> Path {
    return Path{ path in
        path.move(to: CGPoint(x: 0, y: 0))
        path.addLine(to: CGPoint(x: rect.width, y: 0))
        path.addLine(to: CGPoint(x: rect.width, y: rect.height))
        path.addLine(to: CGPoint(x: 0, y: rect.height))

        let xCenter = ((rect.maxX - (horizontalPadding * 2) - iconSize) * xAxisMultiplier) + horizontalPadding + (iconSize * 0.5)

        path.move(to: CGPoint(x: xCenter - 50, y: 0))

        let to1 = CGPoint(x: xCenter, y: 35)
        let control1 = CGPoint(x: xCenter - 25, y: 0)
        let control2 = CGPoint(x: xCenter - 25, y: 35)

        let to2 = CGPoint(x: xCenter + 50, y: 0)
        let control3 = CGPoint(x: xCenter + 25, y: 35)
        let control4 = CGPoint(x: xCenter + 25, y: 0)

        path.addCurve(to: to1, control1: control1, control2: control2)

        path.addCurve(to: to2, control1: control3, control2: control4)
    }
}
}
</code>```

Body:
I'm working on a custom Navigation Bottom Bar. I want it to be floating but I realized that when I add .padding() on it the .clipShape() inside its background loses alignment.

I have coded a simple version of the issue.

BottomNav without padding:

BottomNav with padding:

Main View:

struct ContentView: View {
var body: some View {
        VStack{
            Spacer()
            CustomBottomNav()
                .padding() // <- THIS MAKE THE SHAPE TO LOSE ALIGN
        }
}

CustomBottomNav:

struct CustomBottomNav: View {

@State var selectedTab: Views = .HOME
@State private var xAxis: CGFloat = 0
@Namespace var animation

private let tabs: [Views] = [.SETTINGS, .RANKING, .HOME, .SALES, .SEARCHER]
private let iconSize: CGFloat = 25

private func isSelectedTab(_ tab: Views) -> Bool{
    return selectedTab == selectedTab
}

var body: some View {
    HStack(spacing: 0){
        ForEach(tabs, id: \.self){ tab in

            GeometryReader { geo in
                Button {

                    print(geo.frame(in: .global).midX)

                    withAnimation(.spring()) {
                        selectedTab = tab
                        xAxis = geo.frame(in: .global).midX
                    }
                } label: {
                    getImage(tab: tab)
                        .resizable()
                        .renderingMode(.template)
                        .aspectRatio(contentMode: .fit)
                        .frame(width: 30, height: 30)
                        .padding(isSelectedTab(tab) ? 15 : 0)
                        .background(
                            Color.orange
                                .opacity(
                                    isSelectedTab(tab) ? 1 : 0
                                ).clipShape(Circle())
                        )
                        .matchedGeometryEffect(id: tab, in: animation)
                }
                .position(x: geo.frame(in: .local).midX, y: geo.frame(in: .local).midY)
                .offset(
                    y: -60
                )
                .onAppear {
                    if isSelectedTab(tab) {
                        xAxis = geo.frame(in: .global).midX
                    }
                }
            }
            .frame(width: iconSize, height: iconSize)
            .overlay(
                Rectangle()
                    .stroke(.red)
            )

            if tab != tabs.last{
                Spacer()
            }

        }
    }
    .padding(.horizontal, 30)
    .padding(.vertical)
    .background(
        Color.yellow
            .clipShape(BottomNavShape(xAxis: xAxis))
            .cornerRadius(15)
    )
}

func getImage(tab: Views) -> Image {
    switch tab {
        case .SETTINGS:
            return Image("house")
        case .RANKING:
            return Image("house")
        case .HOME:
            return Image("house")
        case .SALES:
            return Image("house")
        case .SEARCHER:
            return Image("house")
    }
}

enum Views{
    case SETTINGS
    case RANKING
    case HOME
    case SALES
    case SEARCHER

}
}

BottomNavShape:

struct BottomNavShape: Shape{

var xAxis: CGFloat

//Animating path
var animatableData: CGFloat{
    get{
        return xAxis
    }
    set{
        xAxis = newValue
    }
}

func path(in rect: CGRect) -> Path {
    return Path{ path in
        path.move(to: CGPoint(x: 0, y: 0))
       path.addLine(to: CGPoint(x: rect.width, y: 0))
       path.addLine(to: CGPoint(x: rect.width, y: rect.height))
       path.addLine(to: CGPoint(x: 0, y: rect.height))

       let center = CGPoint(x: xAxis, y: rect.midY)

        path.move(to: center)

        path.addArc(center: center, radius: 15, startAngle: .degrees(0), endAngle:
.degrees(1), clockwise: true)
    }
}
}

These classes are all you need to replicate the issue.

I'm using XCode 13 and iOS 15.

Body:
The problem is that your are passing a global coordinate to BottomNavShape which uses local coordinates to draw itself.

So global X = 30 coordinate passed to BottomNavShape will be 30 points after BottomNavShape's minX starts in global context.

In order to solve this I changed xAxis for xAxisMultiplier.

I made this function:

    func setAxisMultiplier(_ index: Int){
        xAxisMultiplier = CGFloat(index) / CGFloat(tabs.count - 1)
    }

Where index is the index of tab inside tabs

I added two more params to BottomNavShape: horizontalPadding and iconSize

BottomNavShape:

struct BottomNavShape: Shape{

var xAxisMultiplier: CGFloat
var horizontalPadding: CGFloat
var iconSize: CGFloat

//Animating path
var animatableData: CGFloat{
    get{
        return xAxisMultiplier
    }
    set{
        xAxisMultiplier = newValue
    }
}

func path(in rect: CGRect) -> Path {
    return Path{ path in
        path.move(to: CGPoint(x: 0, y: 0))
        path.addLine(to: CGPoint(x: rect.width, y: 0))
        path.addLine(to: CGPoint(x: rect.width, y: rect.height))
        path.addLine(to: CGPoint(x: 0, y: rect.height))

        let xCenter = ((rect.maxX - (horizontalPadding * 2) - iconSize) * xAxisMultiplier) + horizontalPadding + (iconSize * 0.5)

        path.move(to: CGPoint(x: xCenter - 50, y: 0))

        let to1 = CGPoint(x: xCenter, y: 35)
        let control1 = CGPoint(x: xCenter - 25, y: 0)
        let control2 = CGPoint(x: xCenter - 25, y: 35)

        let to2 = CGPoint(x: xCenter + 50, y: 0)
        let control3 = CGPoint(x: xCenter + 25, y: 35)
        let control4 = CGPoint(x: xCenter + 25, y: 0)

        path.addCurve(to: to1, control1: control1, control2: control2)

        path.addCurve(to: to2, control1: control3, control2: control4)
    }
}
}


问:
How to convert from string to number in nodejs mongoose
How can I convert publicationDate from string to number/int using mongoose on nodejs? I would like to then sort my data by year.
Thank you.

Here is my code :

```<code>app.get("/getAlbumData.json",(req,res)=> {
    Wasabi.find( {publicationDate: { $in: ['2009','2010','2011','2012','2013','2014','2015','2016'] } }, function (err, doc) {
            res.send(doc);
            res.end();

    }).limit(200)
})
</code>```

答:
You can convert it into a Decimal, and then use .toNumber, here is an example if you already have moongose imported:

import Decimal from "decimal.js";

const yourNumber =  new Decimal(yourString).toNumber();

the const yourNumber is now in type number, not Number.

Body:
How can I convert publicationDate from string to number/int using mongoose on nodejs? I would like to then sort my data by year.
Thank you.

Here is my code :

app.get("/getAlbumData.json",(req,res)=> {
    Wasabi.find( {publicationDate: { $in: ['2009','2010','2011','2012','2013','2014','2015','2016'] } }, function (err, doc) {
            res.send(doc);
            res.end();

    }).limit(200)
})


问:
How does setMicrophoneMute() work?
I have been trying to use Android's AudioManager.setMicrophoneMute() without much success. That is, it simply refuses to mute the microphone, no matter what I do.

I searched the web for some clues and I found several references reporting similar experience:

AudioManger.setMicrophoneMute functionality not working??

setMicrophoneMute(boolean) doesn't work on some devices

Unable to mute the microphone in Android

Which begs the question: Does AudioManager.setMicrophoneMute() work at all? Is it only a stub method, waiting to be implemented in some future version of Android? If not, how does it work? What do I need to make it work? What are the conditions that make it work as its name implies?

EDIT: I noticed that the documentation for this method says:

This method should only be used by applications that replace the
  platform-wide management of audio settings or the main telephony
  application.

What does this mean? Why would I want to replace the platform-wide management? Do I really need to do that? If so, how do I do that?

EDIT: The answer below is great but I still don't understand:

How is that flag (SET_MIC_MUTE in database) being used?

When does this flag actually disconnect the microphone signal from
the pre-amplifier circuit inside the phone?

If it doesn't do that, who does that?

If nothing does that, how is this "mute" expected to work?

Please explain. Thanks.

答:
To elaborate on an00b:s answer above and the edited version of the question we have to dig deeper into the source code. IAudioflinger is the interface to the AudioFlinger service and the call to

```<code>virtual status_t setMicMute(bool state)
{
    Parcel data, reply;
    data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
    data.writeInt32(state);
    remote()->transact(SET_MIC_MUTE, data, &reply);
    return reply.readInt32();
}
</code>```

is actually the Binder transaction to mute the microphone. The receiving side of the Binder call looks like:

```<code>status_t BnAudioFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)  {
    switch(code) {
        ...
        case SET_MIC_MUTE: {
            CHECK_INTERFACE(IAudioFlinger, data, reply);
            int state = data.readInt32();
            reply->writeInt32( setMicMute(state) );
            return NO_ERROR;
        } break;
    ...
    }
}
</code>```

and calls to the actual implementation of setMicMute in the AudioFlinger. Next step is to look at this function:

```<code>status_t AudioFlinger::setMicMute(bool state) {
    // check calling permissions
    if (!settingsAllowed()) {
        return PERMISSION_DENIED;
    }

    AutoMutex lock(mHardwareLock);
    mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
    status_t ret = mAudioHardware->setMicMute(state);
    mHardwareStatus = AUDIO_HW_IDLE;
    return ret;
}
</code>```

Here we can note two things. The first is that there is a permissions check to be able to mute the microphone. The permission being checked for in settingsAllowed is android.permission.MODIFY_AUDIO_SETTINGS so as mentioned in one of the comments above the first requirement for muting the microphone is that your application has declared that it needs this permission. The next thing to note is that we now call in to the hardware specific version of setMicMute using mAudioHardware->setMicMute(state).

For more info on the way the hardware is plugged study the file AudioHardwareInterface.cpp. Basically it ends up in a libhardware with an extern C call to createAudioHardware which plugs in the correct AudioHardWare for the platform. There are also switches for using an A2DP based hardware, a generic one for the emulator and stubbing the audio. Assumed that you are working on an actual device the implementation is then very much hardware depending. To get a feel for it we can use the available audiohardware from Crespo (Nexus S) as an example.

```<code>status_t AudioHardware::setMicMute(bool state) {
    LOGV("setMicMute(%d) mMicMute %d", state, mMicMute);
    sp<AudioStreamInALSA> spIn;
    {
        AutoMutex lock(mLock);
        if (mMicMute != state) {
            mMicMute = state;
            // in call mute is handled by RIL
            if (mMode != AudioSystem::MODE_IN_CALL) {
                spIn = getActiveInput_l();
            }
        }
    }

    if (spIn != 0) {
        spIn->standby();
    }

    return NO_ERROR;
}
</code>```

Based on this example we may wrap up with a discussion of the implementation of audio routing in smartphones. As you can see in the Crespo implementation the mic mute call will only be respected if you are not in a call. The reason for this is that audio is routed through the analog baseband which handles power regulation, amplification and other things. When in a call the voice audio is often handled by analog baseband and modem CPU together and is not routed throught the application CPU. In that case you may need to go through the modem CPU through the RIL in order to mute the microphone. But since this behavior is hardware dependent there is no general solution.

To give the short version to your 4 additional questions:

The flag is passed on through several layers of code until it ends up in the hardware specific mute microphone.

The mic is disconnected when the hardware specific code has run except when in a call at least on some devices.

When setMicrophoneMute does not mute the mic, i.e. when in a call it may be possible to do that using one of the telephony API:s, I would suggest studying the phone app.

Based on the current implementation mute seems to work when not in a call but there may be hardware specific issues on platforms we have not studied here.

EDIT:

Did some more digging and the way to send a mute command to the modem CPU is via the internal Phone interface that is part of the com.android.internal.telephony package that is not available to SDK developers. Based on the comment you saw that this function should only be used by applications that replace audio management or the original telephony application I would guess that AudioManager.setMicrophoneMute() was supposed to always mute the microphone regardless. But since other applications probably use this they added a check in the hardware implementation in order not to mess up the state of the phone application which keeps track of muted connections as well as the microphone. The function is probably not working as supposed to right now due to hardware implementation details and the fact that mute is a much more complex operation than one would initially think when considering call states as well.

Title: How does setMicrophoneMute() work?

Body:
To elaborate on an00b:s answer above and the edited version of the question we have to dig deeper into the source code. IAudioflinger is the interface to the AudioFlinger service and the call to

virtual status_t setMicMute(bool state)
{
    Parcel data, reply;
    data.writeInterfaceToken(IAudioFlinger::getInterfaceDescriptor());
    data.writeInt32(state);
    remote()->transact(SET_MIC_MUTE, data, &reply);
    return reply.readInt32();
}

is actually the Binder transaction to mute the microphone. The receiving side of the Binder call looks like:

status_t BnAudioFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)  {
    switch(code) {
        ...
        case SET_MIC_MUTE: {
            CHECK_INTERFACE(IAudioFlinger, data, reply);
            int state = data.readInt32();
            reply->writeInt32( setMicMute(state) );
            return NO_ERROR;
        } break;
    ...
    }
}

and calls to the actual implementation of setMicMute in the AudioFlinger. Next step is to look at this function:

status_t AudioFlinger::setMicMute(bool state) {
    // check calling permissions
    if (!settingsAllowed()) {
        return PERMISSION_DENIED;
    }

    AutoMutex lock(mHardwareLock);
    mHardwareStatus = AUDIO_HW_SET_MIC_MUTE;
    status_t ret = mAudioHardware->setMicMute(state);
    mHardwareStatus = AUDIO_HW_IDLE;
    return ret;
}

Here we can note two things. The first is that there is a permissions check to be able to mute the microphone. The permission being checked for in settingsAllowed is android.permission.MODIFY_AUDIO_SETTINGS so as mentioned in one of the comments above the first requirement for muting the microphone is that your application has declared that it needs this permission. The next thing to note is that we now call in to the hardware specific version of setMicMute using mAudioHardware->setMicMute(state).

For more info on the way the hardware is plugged study the file AudioHardwareInterface.cpp. Basically it ends up in a libhardware with an extern C call to createAudioHardware which plugs in the correct AudioHardWare for the platform. There are also switches for using an A2DP based hardware, a generic one for the emulator and stubbing the audio. Assumed that you are working on an actual device the implementation is then very much hardware depending. To get a feel for it we can use the available audiohardware from Crespo (Nexus S) as an example.

status_t AudioHardware::setMicMute(bool state) {
    LOGV("setMicMute(%d) mMicMute %d", state, mMicMute);
    sp<AudioStreamInALSA> spIn;
    {
        AutoMutex lock(mLock);
        if (mMicMute != state) {
            mMicMute = state;
            // in call mute is handled by RIL
            if (mMode != AudioSystem::MODE_IN_CALL) {
                spIn = getActiveInput_l();
            }
        }
    }

    if (spIn != 0) {
        spIn->standby();
    }

    return NO_ERROR;
}

Based on this example we may wrap up with a discussion of the implementation of audio routing in smartphones. As you can see in the Crespo implementation the mic mute call will only be respected if you are not in a call. The reason for this is that audio is routed through the analog baseband which handles power regulation, amplification and other things. When in a call the voice audio is often handled by analog baseband and modem CPU together and is not routed throught the application CPU. In that case you may need to go through the modem CPU through the RIL in order to mute the microphone. But since this behavior is hardware dependent there is no general solution.

To give the short version to your 4 additional questions:

The flag is passed on through several layers of code until it ends up in the hardware specific mute microphone.

The mic is disconnected when the hardware specific code has run except when in a call at least on some devices.

When setMicrophoneMute does not mute the mic, i.e. when in a call it may be possible to do that using one of the telephony API:s, I would suggest studying the phone app.

Based on the current implementation mute seems to work when not in a call but there may be hardware specific issues on platforms we have not studied here.

EDIT:

Did some more digging and the way to send a mute command to the modem CPU is via the internal Phone interface that is part of the com.android.internal.telephony package that is not available to SDK developers. Based on the comment you saw that this function should only be used by applications that replace audio management or the original telephony application I would guess that AudioManager.setMicrophoneMute() was supposed to always mute the microphone regardless. But since other applications probably use this they added a check in the hardware implementation in order not to mess up the state of the phone application which keeps track of muted connections as well as the microphone. The function is probably not working as supposed to right now due to hardware implementation details and the fact that mute is a much more complex operation than one would initially think when considering call states as well.


问:
How can this "nano" error in JavaScript be solved?

/home/admin/.pm2/logs/app-error.log last 15 lines: 3|app      |     at
Object.
(/home/admin/pcpro-backend/helper/db.helper.js:1:29) 3|app      |

at Module._compile (internal/modules/cjs/loader.js:1085:14) 3|app

|     at Object.Module._extensions..js
(internal/modules/cjs/loader.js:1114:10) 3|app      |     at
Module.load (internal/modules/cjs/loader.js:950:32) 3|app      |

at Function.Module._load (internal/modules/cjs/loader.js:790:12) 3|app
|     at Module.require (internal/modules/cjs/loader.js:974:19) 3|app
|     at Module.Hook._require.Module.require
(/usr/local/lib/node_modules/pm2/node_modules/require-in-the-middle/index.js:80:39)
3|app      |     at require (internal/modules/cjs/helpers.js:101:18)
3|app      |     at Object.
(/home/admin/pcpro-backend/routes/users.js:4:18) { 3|app      |

generatedMessage: false, 3|app      |   code: 'ERR_ASSERTION', 3|app

|   actual: 'undefined', 3|app      |   expected: 'object', 3|app

|   operator: 'strictEqual' 3|app      | }

app.js

    var fs = require("fs");
    const dotenv = require('dotenv');

    var express = require('express');
    var path = require('path');
    var logger = require('morgan');
    var cookieParser = require('cookie-parser');
    var bodyParser = require('body-parser');
    var methodOverride = require('method-override');
    var cors = require('cors');

    var index = require('./routes/index');
    var users = require('./routes/users');
    var languages = require('./routes/language');
    var formAndTemplates = require('./routes/formAndTemplates');
    var app = express();

    // view engine setup
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'ejs');

    // uncomment after placing your favicon in /public
    //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
    app.use(logger('dev'));
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({'extended':'true'}));
    app.use(bodyParser.json({type:'application/vnd.api+json'}));
    app.use(methodOverride());
    app.use(cookieParser());
    app.use(cors());
    app.use(express.static(path.join(__dirname, 'public')));
    app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

    app.use('/', index);
    app.use('/users', users);
    app.use('/languages', languages);
    app.use('/api/v1/form-template', formAndTemplates);

    // catch 404 and forward to error handler
    app.use(function(req, res, next) {
      var err = new Error('Not Found');
      err.status = 404;
      next(err);
    });

    // error handler
    app.use(function(err, req, res, next) {
      // set locals, only providing error in development
      res.locals.message = err.message;
      res.locals.error = req.app.get('env') === 'development' ? err : {};

      // render the error page
      res.status(err.status || 500);
      res.json(err.message);
    });

    module.exports = app;
```
<p>.env</p>
<pre class="lang-bash prettyprint-override"><code>    COUCHDB_URL=http://admin:somepassword@localhost:5984/
    PORT=3002
    NODE_ENV=local
</code>```

db.helper

    const nano = require('nano')(process.env.COUCHDB_URL);

    const getDBInstance = (name) => {
        return nano.db.use(name)
    };

    module.exports = {
        getDBInstance
    };

```

How can I solve this error?

答:
nano.db.use, much like all nano methods, is asynchronous.  Modern implementations use the async/await pattern, though some people continue to use Promises.

Try something like this as a sanity check:

const nano = require("nano")("http://user:pass@localhost:5984/");

const getDBInstance = async (name) => nano.db.use(name);

(async () => {
    let db = await getDBInstance("stack");
    let result = await db.info();
    console.log(JSON.stringify(result, 0, 2));
})();
```

Body:
/home/admin/.pm2/logs/app-error.log last 15 lines: 3|app      |     at
Object.
(/home/admin/pcpro-backend/helper/db.helper.js:1:29) 3|app      |

at Module._compile (internal/modules/cjs/loader.js:1085:14) 3|app

|     at Object.Module._extensions..js
(internal/modules/cjs/loader.js:1114:10) 3|app      |     at
Module.load (internal/modules/cjs/loader.js:950:32) 3|app      |

at Function.Module._load (internal/modules/cjs/loader.js:790:12) 3|app
|     at Module.require (internal/modules/cjs/loader.js:974:19) 3|app
|     at Module.Hook._require.Module.require
(/usr/local/lib/node_modules/pm2/node_modules/require-in-the-middle/index.js:80:39)
3|app      |     at require (internal/modules/cjs/helpers.js:101:18)
3|app      |     at Object.
(/home/admin/pcpro-backend/routes/users.js:4:18) { 3|app      |

generatedMessage: false, 3|app      |   code: 'ERR_ASSERTION', 3|app

|   actual: 'undefined', 3|app      |   expected: 'object', 3|app

|   operator: 'strictEqual' 3|app      | }

app.js

    var fs = require("fs");
    const dotenv = require('dotenv');

    var express = require('express');
    var path = require('path');
    var logger = require('morgan');
    var cookieParser = require('cookie-parser');
    var bodyParser = require('body-parser');
    var methodOverride = require('method-override');
    var cors = require('cors');

    var index = require('./routes/index');
    var users = require('./routes/users');
    var languages = require('./routes/language');
    var formAndTemplates = require('./routes/formAndTemplates');
    var app = express();

    // view engine setup
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'ejs');

    // uncomment after placing your favicon in /public
    //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
    app.use(logger('dev'));
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({'extended':'true'}));
    app.use(bodyParser.json({type:'application/vnd.api+json'}));
    app.use(methodOverride());
    app.use(cookieParser());
    app.use(cors());
    app.use(express.static(path.join(__dirname, 'public')));
    app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

    app.use('/', index);
    app.use('/users', users);
    app.use('/languages', languages);
    app.use('/api/v1/form-template', formAndTemplates);

    // catch 404 and forward to error handler
    app.use(function(req, res, next) {
      var err = new Error('Not Found');
      err.status = 404;
      next(err);
    });

    // error handler
    app.use(function(err, req, res, next) {
      // set locals, only providing error in development
      res.locals.message = err.message;
      res.locals.error = req.app.get('env') === 'development' ? err : {};

      // render the error page
      res.status(err.status || 500);
      res.json(err.message);
    });

    module.exports = app;

.env

    COUCHDB_URL=http://admin:somepassword@localhost:5984/
    PORT=3002
    NODE_ENV=local

db.helper

    const nano = require('nano')(process.env.COUCHDB_URL);

    const getDBInstance = (name) => {
        return nano.db.use(name)
    };

    module.exports = {
        getDBInstance
    };

How can I solve this error?


问:
Issue understanding modification of variable in jupyter notebook
I'm quite new to jupyter and just can't figure out how this work :

With these 3 blocks of code, a multiple execution of the 3rd one make n incremental, i.e. [1,2], then [1,3], [1,4], etc

```<code>n = [1,2]
</code>```

--

```<code>def fonction(x):
  y=x
  y[1]=x[1]+1
  return y
</code>```

--

```<code>res = fonction(n)
print(res)
</code>```

This is the minimal example i can provide. I don't understand why the variable n is modified though it's only the argument in the 3rd block (and the 2nd block isn't modifying the argument of the function !)

Thanks a lot for your patience explaining 101 jupyter to this old engineer, sincerely

答:
Since you are writing y = x inside of fonction that is not giving y the value contained in x, but rather making y point to the value of x. In this case y is pointing to x and x is pointing to n (via input of fonction) therefore y[1] =  will assign a value to the variable which is stored in the location that y is pointing to... Since y is pointing to the same location as n it changes that list. This means that when you reference n again it is still pointing to the same list, but the list has been modified via y[1] = x[1] + 1.

You can fix this issue by using y = x[:] which will create an entirely new list for y so that it does not point to the list stored in n.

This can be applied to your code like so:

```<code>def fonction(x):
  y=x[:] #notice the change here
  y[1]=x[1]+1
  return y
</code>```

Body:
I'm quite new to jupyter and just can't figure out how this work :

With these 3 blocks of code, a multiple execution of the 3rd one make n incremental, i.e. [1,2], then [1,3], [1,4], etc

n = [1,2]

--

def fonction(x):
  y=x
  y[1]=x[1]+1
  return y

--

res = fonction(n)
print(res)

This is the minimal example i can provide. I don't understand why the variable n is modified though it's only the argument in the 3rd block (and the 2nd block isn't modifying the argument of the function !)

Thanks a lot for your patience explaining 101 jupyter to this old engineer, sincerely

Body:
Since you are writing y = x inside of fonction that is not giving y the value contained in x, but rather making y point to the value of x. In this case y is pointing to x and x is pointing to n (via input of fonction) therefore y[1] =  will assign a value to the variable which is stored in the location that y is pointing to... Since y is pointing to the same location as n it changes that list. This means that when you reference n again it is still pointing to the same list, but the list has been modified via y[1] = x[1] + 1.

You can fix this issue by using y = x[:] which will create an entirely new list for y so that it does not point to the list stored in n.

This can be applied to your code like so:

def fonction(x):
  y=x[:] #notice the change here
  y[1]=x[1]+1
  return y


问:
Check for BST using Level Order Traversal
So I have been trying out questions from Hackerrank and there has been a question on checking whether a tree is BST or not. I have been using the level order traversal for this check. if node.left.value> node.value and node.right.value<node.value the Tree must not be a BST.

Apart from the condition where I haven't checked for a single root node, all the other test cases fail. Where have I been going wrong?

```<code>def checkBST(root):

    # if root.left and root.right is None:
    #     return True
    if not root:
            return
    flag=0
    q=[root]
    while len(q)>0:
        temp=q.pop(0)
        if temp.left is not None:
            if temp.left.data> temp.data:
                flag=1
                break
            else:
                q.append(temp.left)
        if temp.right is not None:
            if temp.right.data<temp.data:
                flag=1
                break
            else:
                q.append(temp.right)

    if flag==1:
        return False
    else:
        return True
</code>```

答:
It is not enough to test that a direct child is in the correct relation to its parent. There are invalid BSTs for which all those comparison-tests pass. You need to ensure that in the whole left subtree of a node there is no node with a greater value than that node's value.

So a level order traversal is not really the right tool to do this. It will work better with an in-order traversal, since a BST will have an non-decreasing in-order traversal.

Body:
So I have been trying out questions from Hackerrank and there has been a question on checking whether a tree is BST or not. I have been using the level order traversal for this check. if node.left.value> node.value and node.right.value<node.value the Tree must not be a BST.

Apart from the condition where I haven't checked for a single root node, all the other test cases fail. Where have I been going wrong?

def checkBST(root):

    # if root.left and root.right is None:
    #     return True
    if not root:
            return
    flag=0
    q=[root]
    while len(q)>0:
        temp=q.pop(0)
        if temp.left is not None:
            if temp.left.data> temp.data:
                flag=1
                break
            else:
                q.append(temp.left)
        if temp.right is not None:
            if temp.right.data<temp.data:
                flag=1
                break
            else:
                q.append(temp.right)

    if flag==1:
        return False
    else:
        return True


问:
I am trying to retrieved data from firestore in recyclerview in android studio but getting blank page and no error i have tried many way but not work
sorry in adavaced bcz i am first time askking question on stack flow so and if need any other please let me know
okk my firestore Collestion is like these collection("user").document(currentUserId).collection("AddBlog").document
and i need AddBlog document and last my field name of firestore is same to model.java variable

code of activity name Trial.java

```<code>package com.example.talkvirtual;

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QuerySnapshot;

import java.util.ArrayList;
import java.util.List;

public class TrialActivity extends AppCompatActivity {
    RecyclerView recyclerView;
    ArrayList<Model> dataList;

    FirebaseFirestore db;
    FirebaseAuth mAuth;

    MyAdapter myAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_trial);

        recyclerView = findViewById(R.id.recyclerViewTrial);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        dataList = new ArrayList<>();
        recyclerView.setAdapter(myAdapter);

        myAdapter = new MyAdapter(dataList,this);
        db = FirebaseFirestore.getInstance();
        mAuth= FirebaseAuth.getInstance();
        String currentUserId = mAuth.getCurrentUser().getUid();
        db.collection("user").document(currentUserId).collection("AddBlog").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
            @Override
            public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments();
                for (DocumentSnapshot d : list) {
                    Model model = d.toObject(Model.class);
                    dataList.add(model);
                }
                myAdapter.notifyDataSetChanged();
            }
        });
    }
}
</code>```

code of adpater class name MyAdapter.java

```<code>package com.example.talkvirtual;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {

    public MyAdapter(ArrayList<Model> listblogProfile, Context context) {
        this.ListblogProfile = listblogProfile;
        this.context = context;
    }

    private ArrayList<Model> ListblogProfile;
  private Context context;

  //  private ShowActivity activity;

    @NonNull
    @Override
    public MyAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.container_blog, parent, false);
        return new MyViewHolder(view);

    }

    @Override
    public void onBindViewHolder(@NonNull MyAdapter.MyViewHolder holder, int position) {
        Model model = ListblogProfile.get(position);

        holder.blogTitleTv.setText(model.getBlogTitle());
        holder.blogContentTv.setText(model.getBlogContent());
    }

    @Override
    public int getItemCount() {
        return ListblogProfile.size();

    }

    public static class MyViewHolder extends RecyclerView.ViewHolder {
        private TextView blogTitleTv, blogContentTv;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            blogContentTv = itemView.findViewById(R.id.blogContentContainer);
            blogTitleTv = itemView.findViewById(R.id.getTitleContainer);

        }
    }
}
</code>```

code of my cardView xml file

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/layoutNote"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:foreground="?attr/selectableItemBackgroundBorderless"
    app:cardElevation="8dp"
    android:layout_margin="10dp"
    android:background="@color/light_dark">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/getTitleContainer"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Title"
            android:textColor="@color/textColor"
            android:textSize="24dp"
            android:textStyle="bold"
            android:padding="10dp"
            />

        <TextView
            android:id="@+id/blogContentContainer"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:maxHeight="100dp"
            android:textColor="@color/textColor"
            android:hint="Blog Content"
            android:textColorHint="@color/gray"
            android:textSize="20dp"
            android:padding="10dp"/>
    </LinearLayout>

</androidx.cardview.widget.CardView>
</code>```

code of model class

```<code>  package com.example.talkvirtual;

public class Model {
    String blogTitle;
    String blogContent;
    String id;
    public Model(){}//empty constructor is neccessary firebase

    public Model(String blogTitle, String blogContent, String id) {
        this.blogTitle = blogTitle;
        this.blogContent = blogContent;
        this.id = id;
    }
    public String getBlogTitle() {
        return blogTitle;
    }

    public void setBlogTitle(String blogTitle) {
        this.blogTitle = blogTitle;
    }

    public String getBlogContent() {
        return blogContent;
    }

    public void setBlogContent(String blogContent) {
        this.blogContent = blogContent;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

}
</code>```

答:
I think There are two mistake

1.Your adapter does not have the valid value
when you set it for the recyclerview

2.Your data is null because you don't add any member to it as well as the adapter.

```<code> db.collection("user").document(currentUserId).collection("AddBlog").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
        @Override
        public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
            List<DocumentSnapshot> list =     queryDocumentSnapshots.getDocuments();
            for (DocumentSnapshot d : list) {
                Model model = d.toObject(Model.class);
                dataList.add(model);
            }
            myAdapter.notifyDataSetChanged();
        }
    });
  myAdapter = new MyAdapter(dataList,this);
  recyclerView.setAdapter(myAdapter);
</code>```

I guess this should be work.

Body:
sorry in adavaced bcz i am first time askking question on stack flow so and if need any other please let me know
okk my firestore Collestion is like these collection("user").document(currentUserId).collection("AddBlog").document
and i need AddBlog document and last my field name of firestore is same to model.java variable

code of activity name Trial.java

package com.example.talkvirtual;

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QuerySnapshot;

import java.util.ArrayList;
import java.util.List;

public class TrialActivity extends AppCompatActivity {
    RecyclerView recyclerView;
    ArrayList<Model> dataList;

    FirebaseFirestore db;
    FirebaseAuth mAuth;

    MyAdapter myAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_trial);

        recyclerView = findViewById(R.id.recyclerViewTrial);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        dataList = new ArrayList<>();
        recyclerView.setAdapter(myAdapter);

        myAdapter = new MyAdapter(dataList,this);
        db = FirebaseFirestore.getInstance();
        mAuth= FirebaseAuth.getInstance();
        String currentUserId = mAuth.getCurrentUser().getUid();
        db.collection("user").document(currentUserId).collection("AddBlog").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
            @Override
            public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments();
                for (DocumentSnapshot d : list) {
                    Model model = d.toObject(Model.class);
                    dataList.add(model);
                }
                myAdapter.notifyDataSetChanged();
            }
        });
    }
}

code of adpater class name MyAdapter.java

package com.example.talkvirtual;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {

    public MyAdapter(ArrayList<Model> listblogProfile, Context context) {
        this.ListblogProfile = listblogProfile;
        this.context = context;
    }

    private ArrayList<Model> ListblogProfile;
  private Context context;

  //  private ShowActivity activity;

    @NonNull
    @Override
    public MyAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.container_blog, parent, false);
        return new MyViewHolder(view);

    }

    @Override
    public void onBindViewHolder(@NonNull MyAdapter.MyViewHolder holder, int position) {
        Model model = ListblogProfile.get(position);

        holder.blogTitleTv.setText(model.getBlogTitle());
        holder.blogContentTv.setText(model.getBlogContent());
    }

    @Override
    public int getItemCount() {
        return ListblogProfile.size();

    }

    public static class MyViewHolder extends RecyclerView.ViewHolder {
        private TextView blogTitleTv, blogContentTv;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            blogContentTv = itemView.findViewById(R.id.blogContentContainer);
            blogTitleTv = itemView.findViewById(R.id.getTitleContainer);

        }
    }
}

code of my cardView xml file

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/layoutNote"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:foreground="?attr/selectableItemBackgroundBorderless"
    app:cardElevation="8dp"
    android:layout_margin="10dp"
    android:background="@color/light_dark">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/getTitleContainer"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Title"
            android:textColor="@color/textColor"
            android:textSize="24dp"
            android:textStyle="bold"
            android:padding="10dp"
            />

        <TextView
            android:id="@+id/blogContentContainer"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:maxHeight="100dp"
            android:textColor="@color/textColor"
            android:hint="Blog Content"
            android:textColorHint="@color/gray"
            android:textSize="20dp"
            android:padding="10dp"/>
    </LinearLayout>

</androidx.cardview.widget.CardView>

code of model class

  package com.example.talkvirtual;

public class Model {
    String blogTitle;
    String blogContent;
    String id;
    public Model(){}//empty constructor is neccessary firebase

    public Model(String blogTitle, String blogContent, String id) {
        this.blogTitle = blogTitle;
        this.blogContent = blogContent;
        this.id = id;
    }
    public String getBlogTitle() {
        return blogTitle;
    }

    public void setBlogTitle(String blogTitle) {
        this.blogTitle = blogTitle;
    }

    public String getBlogContent() {
        return blogContent;
    }

    public void setBlogContent(String blogContent) {
        this.blogContent = blogContent;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

}

Body:
I think There are two mistake

1.Your adapter does not have the valid value
when you set it for the recyclerview

2.Your data is null because you don't add any member to it as well as the adapter.

 db.collection("user").document(currentUserId).collection("AddBlog").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
        @Override
        public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
            List<DocumentSnapshot> list =     queryDocumentSnapshots.getDocuments();
            for (DocumentSnapshot d : list) {
                Model model = d.toObject(Model.class);
                dataList.add(model);
            }
            myAdapter.notifyDataSetChanged();
        }
    });
  myAdapter = new MyAdapter(dataList,this);
  recyclerView.setAdapter(myAdapter);

I guess this should be work.


问:
Can't perform a React state update on an unmounted component with EventListener
I have the following piece of code on which I am getting warning two warnings:

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

unmountComponentAtNode(): The node you're attempting to unmount was rendered by another copy of React.

```<code>    import React, { useState, useEffect } from "react";
    import GravatarList from "./GravatarList";
    import Header from "./Header";
    import { calculateNumberOfImages } from "./utils";

    const App = () => {
      const handle = () => {
        setState({ images: calculateNumberOfImages() });
      }

      useEffect(() => {
          return () => {

            window.removeEventListener('resize', () => handle())
            window.removeEventListener('scroll', () => handle())
          }
       }, [])

      const [state, setState] = useState(() => {

        window.addEventListener("scroll", () => handle());
        window.addEventListener("resize", () => handle());

        return { images: calculateNumberOfImages() };
      });

      return (
        <div>

          <Header />
          <GravatarList state={state} />
        </div>
      );
    };

    export default App;
</code>```

I can't seem to figure out what I am doing wrong as I have already cleared the listeners in useEffect.

答:
The issue here is that the event callbacks you are trying to remove aren't the same callbacks you added to begin with. The issue is because you are using anonymous functions to call the function updating state.

You should also not use the state initializer function to do side effects like adding event listeners.

Move the handle callback and adding of event listeners into the mounting useEffect hook. Pass the handle callback reference to the add/remove functions,

```<code>const App = () => {
  const [state, setState] = useState(() => ({
    images: calculateNumberOfImages()
  }));

  useEffect(() => {
    const handle = () => {
      setState({ images: calculateNumberOfImages() });
    };

    window.addEventListener("scroll", handle);
    window.addEventListener("resize", handle);

    return () => {
      window.removeEventListener('resize', handle);
      window.removeEventListener('scroll', handle);
    }
   }, []);

  return (
    <div>
      <Header />
      <GravatarList state={state} />
    </div>
  );
};
</code>```

Body:
I have the following piece of code on which I am getting warning two warnings:

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

unmountComponentAtNode(): The node you're attempting to unmount was rendered by another copy of React.

    import React, { useState, useEffect } from "react";
    import GravatarList from "./GravatarList";
    import Header from "./Header";
    import { calculateNumberOfImages } from "./utils";

    const App = () => {
      const handle = () => {
        setState({ images: calculateNumberOfImages() });
      }

      useEffect(() => {
          return () => {

            window.removeEventListener('resize', () => handle())
            window.removeEventListener('scroll', () => handle())
          }
       }, [])

      const [state, setState] = useState(() => {

        window.addEventListener("scroll", () => handle());
        window.addEventListener("resize", () => handle());

        return { images: calculateNumberOfImages() };
      });

      return (

          <GravatarList state={state} />

      );
    };

    export default App;

I can't seem to figure out what I am doing wrong as I have already cleared the listeners in useEffect.

Body:
The issue here is that the event callbacks you are trying to remove aren't the same callbacks you added to begin with. The issue is because you are using anonymous functions to call the function updating state.

You should also not use the state initializer function to do side effects like adding event listeners.

Move the handle callback and adding of event listeners into the mounting useEffect hook. Pass the handle callback reference to the add/remove functions,

const App = () => {
  const [state, setState] = useState(() => ({
    images: calculateNumberOfImages()
  }));

  useEffect(() => {
    const handle = () => {
      setState({ images: calculateNumberOfImages() });
    };

    window.addEventListener("scroll", handle);
    window.addEventListener("resize", handle);

    return () => {
      window.removeEventListener('resize', handle);
      window.removeEventListener('scroll', handle);
    }
   }, []);

  return (
    <div>
      <Header />
      <GravatarList state={state} />
    </div>
  );
};


问:
How to convert result from win32file.ReadFile to something readable?
I made a named pipe and its working fine: the client is writing to it and the server is receiving it.

How do I convert a PyOVERLAPPEDReadBuffer object to the actual data that I want? Im passing a double with size of 8 (i think).

The docs im using: http://timgolden.me.uk/pywin32-docs/win32file__ReadFile_meth.html

```<code>hr, thing = win32file.ReadFile(pipe, 8)
print("hr: " + str(hr))
print("thing: " + str(thing))
</code>```

output

```<code>hr: 0
thing: b'\xbc\x91y\xe4\x0f\x06\xeb?'
</code>```

答:
In case thing is Bytes and you expect a double, you could use struct.unpack to convert:

```<code>>>> thing = b'\xbc\x91y\xe4\x0f\x06\xeb?'
>>> import struct
>>> d, = struct.unpack('d', thing)
>>> d
0.84449
</code>```

Body:
I made a named pipe and its working fine: the client is writing to it and the server is receiving it.

How do I convert a PyOVERLAPPEDReadBuffer object to the actual data that I want? Im passing a double with size of 8 (i think).

The docs im using: http://timgolden.me.uk/pywin32-docs/win32file__ReadFile_meth.html

hr, thing = win32file.ReadFile(pipe, 8)
print("hr: " + str(hr))
print("thing: " + str(thing))

output

hr: 0
thing: b'\xbc\x91y\xe4\x0f\x06\xeb?'

Body:
In case thing is Bytes and you expect a double, you could use struct.unpack to convert:

>>> thing = b'\xbc\x91y\xe4\x0f\x06\xeb?'
>>> import struct
>>> d, = struct.unpack('d', thing)
>>> d
0.84449


问:
How to import from a module in the root directory?
I have the following project structure:

```<code>root
 |--pkg1
 |   |--__init__.py
 |   |--other_stuff.py
 |--stuff.py
</code>```

In the real project, I also have a tests package in the root directory.

If I run unit tests with python -m unittest at root, it works seamlessly.

I want to make the other_stuff.py module also executable as a script.
However, if I run it from either root or pkg1 directories, the Python interpreter returns me this error:

```<code>Traceback (most recent call last):
  File "pkg1/other_stuff.py", line 1, in <module>
    from stuff import Dummy
ModuleNotFoundError: No module named 'stuff'
</code>```

Here is the code:

```<code># file pkg1/__init__.py
# (empty)

# file pkg1/other_stuff.py
from stuff import Dummy

if __name__ == '__main__':
    # do other stuff
    pass

# file stuff.py
class Dummy:
    pass
</code>```

I also tried the package relative imports from .stuff and from ..stuff, but it gives the error:

```<code>Traceback (most recent call last):
  File "pkg1/other_stuff.py", line 1, in <module>
    from ..stuff import Dummy
ImportError: attempted relative import with no known parent package
</code>```

I'm not used to the Python3 import system.

What is the right way to import stuff.py in other_stuff.py to make it work both in the tests and as a script?

答:
I have found a solution that might not be the best, but it worked.
To run other_stuff.py as a script, I just need to open the terminal in the root directory and run python3 -m pkg1.other_stuff.

Body:
I have the following project structure:

root
 |--pkg1
 |   |--__init__.py
 |   |--other_stuff.py
 |--stuff.py

In the real project, I also have a tests package in the root directory.

If I run unit tests with python -m unittest at root, it works seamlessly.

I want to make the other_stuff.py module also executable as a script.
However, if I run it from either root or pkg1 directories, the Python interpreter returns me this error:

Traceback (most recent call last):
  File "pkg1/other_stuff.py", line 1, in <module>
    from stuff import Dummy
ModuleNotFoundError: No module named 'stuff'

Here is the code:

# file pkg1/__init__.py
# (empty)

# file pkg1/other_stuff.py
from stuff import Dummy

if __name__ == '__main__':
    # do other stuff
    pass

# file stuff.py
class Dummy:
    pass

I also tried the package relative imports from .stuff and from ..stuff, but it gives the error:

Traceback (most recent call last):
  File "pkg1/other_stuff.py", line 1, in <module>
    from ..stuff import Dummy
ImportError: attempted relative import with no known parent package

I'm not used to the Python3 import system.

What is the right way to import stuff.py in other_stuff.py to make it work both in the tests and as a script?


问:
iOS App with Cocoapods error - .xcworkspace in Xcode does not show Podfile and Pods folder is empty
I have an iOS application which in which I have installed cocoapods. It has all been working fine for years.  However after a couple of recent branches and merges, I ended up with lots of errors relating to the files in Pods. I tried to fix everything but had an error that I was unable to fix, so I decided that the best solution would be to reinstall cocoapods.

I did this with

pod deintegrate

pod install.

However, I now have a problem where, when I open the .xcworkspace from my project folder, the Pods folder is in red and empty, and the podfile is not shown in the directory at all.  However, when I look at the folder on my computer, the podfile is there and the Pods folder is populated.

So my project folder on my computer contains the .xcworkspace, the podfile and the Pods folder but when I open the .xcworkspace in Xcode, it appears that the podfile and Pods folder are not linked to it.

The error in Xcode currently is "Module 'Firebase' not found"

I have tried all of the following again and again to the point where it is driving me crazy, but the problem still persists.

reinstalling again and again with pod deintegrate followed by pod install

deleted the derived data

rebuilding in Xcode between pod deintegrate and pod install

restarting Xcode

pod clean

pod install --repo-update

rm -rf ~/.cocoapods

deleting the podfile then running pod setup and/or pod init
again before pod install.

I am making sure each time that my podfile includes the pods that I
want to be installed (editing in Xcode).

I am opening the .xcworkspace file NOT the .xcodeproj file.

I am able to successfully rebuild the pod file and reinstall pods on all occasions, but whatever I have tried, when I open the .xcworkspace in Xcode I can't see the podfile and the Pods folder is empty even though these items are in the project folder.

I've searched for solutions and tried everything I can find to no avail. Please can someone point me in the right direction!

答: Does the project work if you go back to an older commit/branch?</p>


答:
There are two questions in one here to answer:

How to adjust the position of the x axis labels?  Use vjust= and hjust= arguments inside element_text() to position the text relative to the anchor point.  When rotated, you'll need to fix this (because it's different for how you would position horizontal text).  Use vjust=0.5 to set the middle of the text to align with the tick mark.  Use hjust=1 to set the text aligned to the "right" and move it to be next to the tick mark.  Note that your text is rotated 90 degrees, so "horizontal" and "vertical" should be understood relative to the direction of the text.

How to show the text above the bar?  For this, you will want to expand the y axis.  You can do this via scale_y_continuous(expand = expansion(mult=c(0.05, 0.15))).  The vector assigned to mult= has two values.  The first value is applied to the lower part of the axis (default is around 0.05, so no change), and the second value is applied to the upper part.  Here we expand by about 15% based on the data (rather than about 5%, which is default).

Here's the code and final look:

```<code>ggplot(df,
       aes(x = partcl, y = Pct)) +
  geom_bar(stat="identity") +
  # rotate x-axis labels by 90°:
  theme(axis.text.x = element_text(angle = 90, vjust=0.5, hjust=1)) +
  # plot `Freq` labels:
  geom_text(aes(x = partcl, y = Pct, label = Freq, angle = 90, hjust = -0.2)) +
  scale_y_continuous(expand = expansion(mult=c(0.05, 0.15)))
</code>```

Title: Fixing issues with geom_text and axis labels

Body:
I have a barplot in which I need to rotate the bar labels giving the Freq values:

library(dplyr)
ggplot(df,
  aes(x = partcl, y = Pct)) +
  geom_bar(stat="identity") +
  # rotate x-axis labels by 90°:
  theme(axis.text.x = element_text(angle = 90)) +
  # plot `Freq` labels:
  geom_text(aes(x = partcl, y = Pct, label = Freq, angle = 90, hjust = -0.2))

But there are two issues: first, the Freq labels are not fitted to the plotting area; instead the maximum Frequ label (for yeah well) is cut off. Second, the x-axis labels are not perfectly aligned with the x-axis ticks. How can these issues be fixed?

Data:

df <- structure(list(partcl = c("yeah well", "well yeah", "yeah yeah well",
                                "yeah well well", "yeah well yeah", "well yeah well", "well yeah yeah",
                                "well yeah yeah yeah", "yeah yeah yeah well", "well yeah well well"
), Freq = c(1515L, 408L, 52L, 20L, 17L, 11L, 8L, 2L, 2L, 1L),
Pct = c(74.3011280039235, 20.0098087297695, 2.55026974006866,
        0.980872976949485, 0.833742030407062, 0.539480137322217,
        0.392349190779794, 0.0980872976949485, 0.0980872976949485,
        0.0490436488474743)), class = c("tbl_df", "tbl", "data.frame"
        ), row.names = c(NA, -10L))

Body:
There are two questions in one here to answer:

How to adjust the position of the x axis labels?  Use vjust= and hjust= arguments inside element_text() to position the text relative to the anchor point.  When rotated, you'll need to fix this (because it's different for how you would position horizontal text).  Use vjust=0.5 to set the middle of the text to align with the tick mark.  Use hjust=1 to set the text aligned to the "right" and move it to be next to the tick mark.  Note that your text is rotated 90 degrees, so "horizontal" and "vertical" should be understood relative to the direction of the text.

How to show the text above the bar?  For this, you will want to expand the y axis.  You can do this via scale_y_continuous(expand = expansion(mult=c(0.05, 0.15))).  The vector assigned to mult= has two values.  The first value is applied to the lower part of the axis (default is around 0.05, so no change), and the second value is applied to the upper part.  Here we expand by about 15% based on the data (rather than about 5%, which is default).

Here's the code and final look:

ggplot(df,
       aes(x = partcl, y = Pct)) +
  geom_bar(stat="identity") +
  # rotate x-axis labels by 90°:
  theme(axis.text.x = element_text(angle = 90, vjust=0.5, hjust=1)) +
  # plot `Freq` labels:
  geom_text(aes(x = partcl, y = Pct, label = Freq, angle = 90, hjust = -0.2)) +
  scale_y_continuous(expand = expansion(mult=c(0.05, 0.15)))


问:
BestPractice - Transform first character of a string into lower case
I'd like to have a method that transforms the first character of a string into lower case.

My approaches:

1.

```<code>public static string ReplaceFirstCharacterToLowerVariant(string name)
{
    return String.Format("{0}{1}", name.First().ToString().ToLowerInvariant(), name.Substring(1));
}
</code>```

2.

```<code>public static IEnumerable<char> FirstLetterToLowerCase(string value)
{
    var firstChar = (byte)value.First();
    return string.Format("{0}{1}", (char)(firstChar + 32), value.Substring(1));
}
</code>```

What would be your approach?

答:
With range operator C# 8.0 or above you can do this:</p>
```<code>Char.ToLowerInvariant(name[0]) + name[1..];
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'd like to have a method that transforms the first character of a string into lower case.

My approaches:

1.

public static string ReplaceFirstCharacterToLowerVariant(string name)
{
    return String.Format("{0}{1}", name.First().ToString().ToLowerInvariant(), name.Substring(1));
}

2.

public static IEnumerable<char> FirstLetterToLowerCase(string value)
{
    var firstChar = (byte)value.First();
    return string.Format("{0}{1}", (char)(firstChar + 32), value.Substring(1));
}

What would be your approach?

Body:
With range operator C# 8.0 or above you can do this:

Char.ToLowerInvariant(name[0]) + name[1..];


问:
OpenJDK 1.8.0 installs jre but not jdk?
I found this older post: sudo yum install installs only JRE not JDK - Centos

But when I ran sudo yum install java-1.8.0-openjdk-devel I don't see the jdk installed?
I checked;

$ sudo alternatives --config java

There is 1 program that provides 'java'.

Selection    Command

*+ 1           java-1.8.0-openjdk.x86_64 (/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.322.b06-2.el8_5.x86_64/jre/bin/java)

I do devops, not a developer but the devs asked for me to finish the install and get jdk on there, any advice?

Thanks!

答:
The JDK should be installed after installing this package, you can check with:

```<code>sudo alternatives --config javac
</code>```

The JRE is just installed inside the /jre subdirectory.

Title: OpenJDK 1.8.0 installs jre but not jdk?

Body:
The JDK should be installed after installing this package, you can check with:

sudo alternatives --config javac

The JRE is just installed inside the /jre subdirectory.


问:
How to implement gimp like highlights and white point adjustment functionality using opencv?
Gimp is a famous open source image editor. Is there any way to implement this gimp like highlights and white point adjustment functionality using OpenCV. I'm currently working on an image manipulation project. And, want to implement this functionality in my projects. I researched everything that is available on the internet but nothing actually works for me.

Specifically, I want to add a slider functionality that will adjust image highlights and white point adjustment.

As per the documentation in gimp:-

https://docs.gimp.org/2.10/en/gimp-filter-shadows-highlights.html

High Lights Adjustment  This slider controls the effect on highlights; negative values will darken highlights while positive values will lighten them up.

White Point Adjustment By default the algorithm of this modules leaves black point and white point untouched. In some cases an image might contain tonal variations beyond the white point, i.e. above a luminance value of 100. A negative shift in the white point adjustment slider allows to bring these values down into the proper range so that further details in the highlights get visible.

I want this same effect that gimp uses in this slider.
Please help me to find

答:
There is a not-so-equal but nice implementation of this functionality here. I could use it successfully to code the same gimp functionality, in spite there are some color field transformation that may be replaced with opencv cvtColor() functions.

Have a nice day!


问:
"No appropriate default constructor available" error in Visual C++
I don't get it. I've been staring at the code the code for three hours and I can't see the problem.

The class I'm creating, called TwoDayPackage is derived from a class called Package.

This is how I defined the constructor:

```<code>    TwoDayPackage(string, string, string, string, int, string, string, string, string, int, float, float, float);
</code>```

This is how I implement the constructor:

```<code>TwoDayPackage::TwoDayPackage(string sName, string sAddress, string sState, string sCountry, int sZIP, string rName, string rAddress, string rState, string rCountry, int rZIP, float weight, float cost, float flat)
{
Package::Package(sName, sAddress, sState, sCountry, sZIP, rName, rAddress, rState, rCountry, rZIP, weight, cost);
flatRate = flat;
}
</code>```

This is how i use it in my main function.

```<code>TwoDayPackage pack2(senderName, senderAddress, senderState, senderCountry, senderZIP, receipientName, receipientAddress, receipientState, receipientCountry, receipientZIP, weight, cost, flat);
</code>```

I know my argument list is pretty long, there's a reason for that.
Thanks.

答:
The answer is that of dirkgently. The explanation is the initialization sequence in C++.

When constructing a class, all base classes are constructed first. If you provide a call to the constructor in the initialization list, then it will call the appropriate constructor. If the base class does not appear in the initialization list, then it will be default constructed. All this happens before entering the constructor block (curly braces).

OwnerDisplayName: chustar

Body:
I don't get it. I've been staring at the code the code for three hours and I can't see the problem.

The class I'm creating, called TwoDayPackage is derived from a class called Package.

This is how I defined the constructor:

    TwoDayPackage(string, string, string, string, int, string, string, string, string, int, float, float, float);

This is how I implement the constructor:

TwoDayPackage::TwoDayPackage(string sName, string sAddress, string sState, string sCountry, int sZIP, string rName, string rAddress, string rState, string rCountry, int rZIP, float weight, float cost, float flat)
{
Package::Package(sName, sAddress, sState, sCountry, sZIP, rName, rAddress, rState, rCountry, rZIP, weight, cost);
flatRate = flat;
}

This is how i use it in my main function.

TwoDayPackage pack2(senderName, senderAddress, senderState, senderCountry, senderZIP, receipientName, receipientAddress, receipientState, receipientCountry, receipientZIP, weight, cost, flat);

I know my argument list is pretty long, there's a reason for that.
Thanks.

OwnerDisplayName: dribeas