问:
Can't convert object of type 'function' to 'str' for 'text
Good day everyone I'm sorry I'm new to python programming sorry if I'm asking this even this is basic or not. Someone can help me with this? The problem is I want to put the data that has been read by my Pyserial from my Arduino temperature sensor but I don't know how.

Here code for the Temperature to pyserial:

```<code>def tempe():
    import serial
    import time

    ser = serial.Serial('COM5', 9600)
    time.sleep(2)

    data =[]                       # empty list to store the data
    for i in range(50):
        b = ser.readline()         # read a byte string
        string = b.rstrip()        # remove \n and \r

        temp =  string             <= this data here I want to show to my opencv

        data.append(string)        # add to the end of data list
        time.sleep(0.1)            # wait (sleep) 0.1 seconds

    ser.close()
</code>```

And here's the whole code that I want to show in my PutText on opencv:

```<code>def offrecog():

screen2.destroy() <=dont mind this
screen.destroy()  <= dont mind this
def recog2(img, classifier, scaleFactor,miNeighbors, color, text, clf):
    image =  cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    features = classifier.detectMultiScale(image, scaleFactor, miNeighbors)

    for (x,y,w,h) in features:
        cv2.rectangle(img, (x,y),(x+w,y+h), color, 2)

        id, pred = clf.predict(image [y:y+h, x:x+w])
        confidence = int(100*(1-pred/300))

        databases = mysql.connector.connect(
        host ="localhost",
        user = "userdata",
        password = "",
        database = "facerecog"
        )

        mycursor = databases.cursor()

        mycursor.execute("SELECT names FROM record WHERE ids= " + str(id))
        datas = mycursor.fetchone()
        datas = "+".join(datas)

        cursor2 = databases.cursor()
        cursor2.execute("SELECT course_year FROM record WHERE ids= " + str(id))
        datas1 = mycursor.fetchone()
        datas1 = "+".join(datas1)

        cursor3 = databases.cursor()
        cursor3.execute("SELECT positions FROM record WHERE ids= " + str(id))
        datas2 = mycursor.fetchone()
        datas2 = "+".join(datas2)

        if confidence>70:
            cv2.putText(img, datas, (x,y+205), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2, cv2.LINE_AA)
            cv2.putText(img, datas1, (x,y+230), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2, cv2.LINE_AA)
            cv2.putText(img, datas2, (x,y+250), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2, cv2.LINE_AA)
            cv2.putText(img, tempe, (x,y+280), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2, cv2.LINE_AA)
            markattend(datas,datas1,datas2)

        else:

            cv2.putText(img, "UNKNOWN", (x,y+205), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0,0,255), 1, cv2.LINE_AA)

    return img

faceCascade = cv2.CascadeClassifier("C:\\Users\\So_Low\\Desktop\\final_recog\\haarcascade_frontalface_default.xml")

clf = cv2.face.LBPHFaceRecognizer_create()
clf.read("trained.xml")

video_capture = cv2.VideoCapture(0)

while True:
    ret, img = video_capture.read()
    img = recog2(img, faceCascade, 1.3, 4, (255,255,255), "Face", clf)
    cv2.imshow("FACE RECOGNITION", img)

    if cv2.waitKey(1) & 0xFF == ord('!'):
        break
video_capture.release()
cv2.destroyAllWindows()
screen2.destroy()
</code>```

and I got this error when I run it:

```<code>File "c:\Users\So_Low\Desktop\Offrecog\offrecog.py", line 97, in recog2
    cv2.putText(img, wew, (x,y+280), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2, cv2.LINE_AA)
cv2.error: OpenCV(4.5.3) :-1: error: (-5:Bad argument) in function 'putText'
> Overload resolution failed:
>  - Can't convert object of type 'function' to 'str' for 'text'
>  - Can't convert object of type 'function' to 'str' for 'text'

[ WARN:0] global C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-u4kjpz2z\opencv\modules\videoio\src\cap_msmf.cpp (438) `anonymous-namespace'::SourceReaderCB::~SourceReaderCB terminating async callback

[Done] exited with code=0 in 14.22 seconds

[Running] python -u "c:\Users\So_Low\Desktop\Offrecog\offrecog.py"
Exception in Tkinter callback
Traceback (most recent call last):
  File "I:\Python\lib\tkinter\__init__.py", line 1883, in __call__
    return self.func(*args)
  File "c:\Users\So_Low\Desktop\Offrecog\offrecog.py", line 136, in login_verify
    offrecog()
  File "c:\Users\So_Low\Desktop\Offrecog\offrecog.py", line 113, in offrecog
    img = recog2(img, faceCascade, 1.3, 4, (255,255,255), "Face", clf)
  File "c:\Users\So_Low\Desktop\Offrecog\offrecog.py", line 95, in recog2
    cv2.putText(img, temps, (x,y+280), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2, cv2.LINE_AA)
cv2.error: OpenCV(4.5.3) :-1: error: (-5:Bad argument) in function 'putText'
> Overload resolution failed:
>  - Can't convert object of type 'module' to 'str' for 'text'
>  - Can't convert object of type 'module' to 'str' for 'text'
</code>```

Even If I don't put the temperature code into function It run the pyserial 1st before the opencv.
Please Help I don't know what to do. Please

答:
Your function tempe doesn't seem to be returning anything.
Why don't you try adding return data at the end of the function (after ser.close()) ?

def tempe():
    import serial
    import time

    ser = serial.Serial('COM5', 9600)
    time.sleep(2)

    data =[]                       # empty list to store the data
    for i in range(50):
        b = ser.readline()         # read a byte string
        string = b.rstrip()        # remove \n and \r

        temp =  string             <= this data here I want to show to my opencv

        data.append(string)        # add to the end of data list
        time.sleep(0.1)            # wait (sleep) 0.1 seconds

    ser.close()
    return data <= try adding this
```

You might have to note that, you can't directly put this list into the addText command since cv2 does not seem to support taking data from anything other than strings. I think you can use a for loop to iterate over tempe() using for text in tempe() and do whatever you want with it. Again, depends on your specific use case.

Body:
Good day everyone I'm sorry I'm new to python programming sorry if I'm asking this even this is basic or not. Someone can help me with this? The problem is I want to put the data that has been read by my Pyserial from my Arduino temperature sensor but I don't know how.

Here code for the Temperature to pyserial:

def tempe():
    import serial
    import time

    ser = serial.Serial('COM5', 9600)
    time.sleep(2)

    data =[]                       # empty list to store the data
    for i in range(50):
        b = ser.readline()         # read a byte string
        string = b.rstrip()        # remove \n and \r

        temp =  string             <= this data here I want to show to my opencv

        data.append(string)        # add to the end of data list
        time.sleep(0.1)            # wait (sleep) 0.1 seconds

    ser.close()

And here's the whole code that I want to show in my PutText on opencv:

def offrecog():

screen2.destroy() <=dont mind this
screen.destroy()  <= dont mind this
def recog2(img, classifier, scaleFactor,miNeighbors, color, text, clf):
    image =  cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    features = classifier.detectMultiScale(image, scaleFactor, miNeighbors)

    for (x,y,w,h) in features:
        cv2.rectangle(img, (x,y),(x+w,y+h), color, 2)

        id, pred = clf.predict(image [y:y+h, x:x+w])
        confidence = int(100*(1-pred/300))

        databases = mysql.connector.connect(
        host ="localhost",
        user = "userdata",
        password = "",
        database = "facerecog"
        )

        mycursor = databases.cursor()

        mycursor.execute("SELECT names FROM record WHERE ids= " + str(id))
        datas = mycursor.fetchone()
        datas = "+".join(datas)

        cursor2 = databases.cursor()
        cursor2.execute("SELECT course_year FROM record WHERE ids= " + str(id))
        datas1 = mycursor.fetchone()
        datas1 = "+".join(datas1)

        cursor3 = databases.cursor()
        cursor3.execute("SELECT positions FROM record WHERE ids= " + str(id))
        datas2 = mycursor.fetchone()
        datas2 = "+".join(datas2)

        if confidence>70:
            cv2.putText(img, datas, (x,y+205), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2, cv2.LINE_AA)
            cv2.putText(img, datas1, (x,y+230), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2, cv2.LINE_AA)
            cv2.putText(img, datas2, (x,y+250), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2, cv2.LINE_AA)
            cv2.putText(img, tempe, (x,y+280), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2, cv2.LINE_AA)
            markattend(datas,datas1,datas2)

        else:

            cv2.putText(img, "UNKNOWN", (x,y+205), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0,0,255), 1, cv2.LINE_AA)

    return img

faceCascade = cv2.CascadeClassifier("C:\\Users\\So_Low\\Desktop\\final_recog\\haarcascade_frontalface_default.xml")

clf = cv2.face.LBPHFaceRecognizer_create()
clf.read("trained.xml")

video_capture = cv2.VideoCapture(0)

while True:
    ret, img = video_capture.read()
    img = recog2(img, faceCascade, 1.3, 4, (255,255,255), "Face", clf)
    cv2.imshow("FACE RECOGNITION", img)

    if cv2.waitKey(1) & 0xFF == ord('!'):
        break
video_capture.release()
cv2.destroyAllWindows()
screen2.destroy()

and I got this error when I run it:

File "c:\Users\So_Low\Desktop\Offrecog\offrecog.py", line 97, in recog2
    cv2.putText(img, wew, (x,y+280), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2, cv2.LINE_AA)
cv2.error: OpenCV(4.5.3) :-1: error: (-5:Bad argument) in function 'putText'
> Overload resolution failed:
>  - Can't convert object of type 'function' to 'str' for 'text'
>  - Can't convert object of type 'function' to 'str' for 'text'

[ WARN:0] global C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-u4kjpz2z\opencv\modules\videoio\src\cap_msmf.cpp (438) `anonymous-namespace'::SourceReaderCB::~SourceReaderCB terminating async callback

[Done] exited with code=0 in 14.22 seconds

[Running] python -u "c:\Users\So_Low\Desktop\Offrecog\offrecog.py"
Exception in Tkinter callback
Traceback (most recent call last):
  File "I:\Python\lib\tkinter\__init__.py", line 1883, in __call__
    return self.func(*args)
  File "c:\Users\So_Low\Desktop\Offrecog\offrecog.py", line 136, in login_verify
    offrecog()
  File "c:\Users\So_Low\Desktop\Offrecog\offrecog.py", line 113, in offrecog
    img = recog2(img, faceCascade, 1.3, 4, (255,255,255), "Face", clf)
  File "c:\Users\So_Low\Desktop\Offrecog\offrecog.py", line 95, in recog2
    cv2.putText(img, temps, (x,y+280), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2, cv2.LINE_AA)
cv2.error: OpenCV(4.5.3) :-1: error: (-5:Bad argument) in function 'putText'
> Overload resolution failed:
>  - Can't convert object of type 'module' to 'str' for 'text'
>  - Can't convert object of type 'module' to 'str' for 'text'

Even If I don't put the temperature code into function It run the pyserial 1st before the opencv.
Please Help I don't know what to do. Please

Body:
Your function tempe doesn't seem to be returning anything.
Why don't you try adding return data at the end of the function (after ser.close()) ?

def tempe():
    import serial
    import time

    ser = serial.Serial('COM5', 9600)
    time.sleep(2)

    data =[]                       # empty list to store the data
    for i in range(50):
        b = ser.readline()         # read a byte string
        string = b.rstrip()        # remove \n and \r

        temp =  string             <= this data here I want to show to my opencv

        data.append(string)        # add to the end of data list
        time.sleep(0.1)            # wait (sleep) 0.1 seconds

    ser.close()
    return data <= try adding this

You might have to note that, you can't directly put this list into the addText command since cv2 does not seem to support taking data from anything other than strings. I think you can use a for loop to iterate over tempe() using for text in tempe() and do whatever you want with it. Again, depends on your specific use case.


来源: stackexchange

问:
add count (.length) each items in option on v-select
I want to add count course.length from api to each item option on v-select and show data to active based filter.

For example : Items in v-select contains options all(count), passed(count) which filtered from online.passed, not complete(count)

which filtered from online.complete, etc.

vue.js template :

```<code><template>
  <v-select
    v-model="filter"
    :items="items"
  ></v-select>
  <v-card v-for="online in onlineCourse" :key="online.id">
    <v-card-title>{{online.title}</v-card-title>
    <p v-if="online.complete === 100">{{online.complete}}%</p>
    <p v-else-if="online.complete < 100 && online.complete > 0">{{online.complete}}%</p>
    <p v-else>{{online.complete}}%</p>
  </v-card>
</template>
<script>
  data () {
   return {
     onlineCourse: [],
     filter: 'All',
     items: [
      'All',
      'passed',
      'not complete',
     ],
   }
 }
 method: {
   async getDataOnline () {
    try {
      const request = await Axios.get('v1/courses')
      this.onlineCourse = request.courses
    } catch (error) {
      console.log(error.message);
    }
   }
 }
</script>
</code>```

Response JSON :

```<code> "courses": [
    {
        "id": 1,
        "title": "title1",
        "passed": false,
        "completed": 0
    },
    {
        "id": 2,
        "title": "title2",
        "passed": true,
        "completed": 100
    },
    {
        "id": 3,
        "title": "title3",
        "passed": false,
        "completed": 50
    }
],
</code>```

答:
Few Observations in current code you posted :

You are checking for online.complete === 100 but you don't have complete property in online object. Hence, corrected that to completed instead of complete.

closing braces is missing from online.title expression.

Now coming to the original problem :

To achieve the counts in the v-select options. You have to convert your items array from array of elements to array of objects.

```<code>items: ['All', 'passed', 'not complete']
</code>```

to

```<code>items: [{
        name: 'All',
        count: this.onlineCourse.length
      }, {
        name: 'passed',
        count: this.onlineCourse.filter((course) => course.passed)
      }, {
        name: 'not complete',
        count: this.onlineCourse.filter((course) => course.completed === 0)
      }]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to add count course.length from api to each item option on v-select and show data to active based filter.

For example : Items in v-select contains options all(count), passed(count) which filtered from online.passed, not complete(count)

which filtered from online.complete, etc.

vue.js template :

<template>
  <v-select
    v-model="filter"
    :items="items"
  ></v-select>
  <v-card v-for="online in onlineCourse" :key="online.id">
    <v-card-title>{{online.title}</v-card-title>

{{online.complete}}%

    <p v-else-if="online.complete < 100 && online.complete > 0">{{online.complete}}%

{{online.complete}}%

  </v-card>
</template>

Response JSON :

 "courses": [
    {
        "id": 1,
        "title": "title1",
        "passed": false,
        "completed": 0
    },
    {
        "id": 2,
        "title": "title2",
        "passed": true,
        "completed": 100
    },
    {
        "id": 3,
        "title": "title3",
        "passed": false,
        "completed": 50
    }
],

Body:
Few Observations in current code you posted :

You are checking for online.complete === 100 but you don't have complete property in online object. Hence, corrected that to completed instead of complete.

closing braces is missing from online.title expression.

Now coming to the original problem :

To achieve the counts in the v-select options. You have to convert your items array from array of elements to array of objects.

items: ['All', 'passed', 'not complete']

to

items: [{
        name: 'All',
        count: this.onlineCourse.length
      }, {
        name: 'passed',
        count: this.onlineCourse.filter((course) => course.passed)
      }, {
        name: 'not complete',
        count: this.onlineCourse.filter((course) => course.completed === 0)
      }]


问:
Import contentful in to react-native
I am extremely excited about using contentful for my project, but I can't get the JS library to work in a react-native project.

I get the following error:

I have tried the following approaches:

```<code>import contentful from 'contentful';
// or
var contentful = require('contentful');
</code>```

You can reproduce the bug by going to this repo and following the steps I have provided.

Help would be greatly appreciated.

答:
I think the best way to use Contentful APIs with React Native is to use Apollo client and graphQL packages.
I worked around the same and get it done.

Install Apollo client and GraphQL npm package

npm install @apollo/client graphql

Install react-native async storage to store cache

npm install @react-native-async-storage/async-storage

Install apollo cache persist to persist the cache

npm install apollo3-cache-persist

you can read apollographql official documents for implementation

Create ApolloClient in the app.tsx/.js file

import { ApolloClient, ApolloProvider, InMemoryCache } from '@apollo/client';

const cache = new InMemoryCache();

const client = new ApolloClient({
  uri: 'https://graphql.contentful.com/content/v1/spaces/{SPACE_ID}',
  cache,
  credentials: 'same-origin',
  headers: {
    Authorization: `Bearer {CDA-Access-Token}`,
  },
});```
</div>
</div>
</p>
<ul>
<li>Wrap all components in <code>ApolloProvider</code></li>
</ul>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const App = () => {
  const [loadingCache, setLoadingCache] = useState(true);

  useEffect(() => {
    persistCache({
      cache,
      storage: AsyncStorage,
    }).then(() => setLoadingCache(false));
  }, []);

  if (loadingCache) {
    return <Loader />;
  }

  return (
    <ApolloProvider client={client}>
      <SafeAreaView style={{flex: 1}}>
        <Posts />
      </SafeAreaView>
    </ApolloProvider>
  );
};
export default App;</code>```

Import gql and useQuery to fetch data

import { gql, useQuery } from '@apollo/client';

Now, write GraphQL query

const QUERY_COLLECTION = gql`
  {
    postsCollection {
      items {
        title
        author
        publishDate
        inshorts
        featuredImage {
          url
        }
      }
    }
  }
`;```

Fetch data using useQuery function

 const { data, loading } = useQuery(QUERY_COLLECTION);

That's all to fetch data from Contentful in React Native App.
To read this in detailed, have a look to this post

ContentLicense: CC BY-SA 3.0

Title: Import contentful in to react-native

Body:
I am extremely excited about using contentful for my project, but I can't get the JS library to work in a react-native project.

I get the following error:

I have tried the following approaches:

import contentful from 'contentful';
// or
var contentful = require('contentful');

You can reproduce the bug by going to this repo and following the steps I have provided.

Help would be greatly appreciated.

Body:
I think the best way to use Contentful APIs with React Native is to use Apollo client and graphQL packages.
I worked around the same and get it done.

Install Apollo client and GraphQL npm package

npm install @apollo/client graphql

Install react-native async storage to store cache

npm install @react-native-async-storage/async-storage

Install apollo cache persist to persist the cache

npm install apollo3-cache-persist

you can read apollographql official documents for implementation

Create ApolloClient in the app.tsx/.js file

import { ApolloClient, ApolloProvider, InMemoryCache } from '@apollo/client';

const cache = new InMemoryCache();

const client = new ApolloClient({
  uri: 'https://graphql.contentful.com/content/v1/spaces/{SPACE_ID}',
  cache,
  credentials: 'same-origin',
  headers: {
    Authorization: `Bearer {CDA-Access-Token}`,
  },
});

Wrap all components in ApolloProvider

const App = () => {
  const [loadingCache, setLoadingCache] = useState(true);

  useEffect(() => {
    persistCache({
      cache,
      storage: AsyncStorage,
    }).then(() => setLoadingCache(false));
  }, []);

  if (loadingCache) {
    return <Loader />;
  }

  return (
    <ApolloProvider client={client}>
      <SafeAreaView style={{flex: 1}}>
        <Posts />
      </SafeAreaView>
    </ApolloProvider>
  );
};
export default App;

Import gql and useQuery to fetch data

import { gql, useQuery } from '@apollo/client';

Now, write GraphQL query

const QUERY_COLLECTION = gql`
  {
    postsCollection {
      items {
        title
        author
        publishDate
        inshorts
        featuredImage {
          url
        }
      }
    }
  }
`;

Fetch data using useQuery function

 const { data, loading } = useQuery(QUERY_COLLECTION);

That's all to fetch data from Contentful in React Native App.
To read this in detailed, have a look to this post


问:
Regex to match word after keyword, including hypen after keyword
I am trying to write a regex to produce the word after a keyword in a sentence. I have this regex that matches the word after "hello ".

```<code>(?<=hello )(\w+)
</code>```

However, what I am having trouble with is that if, say, hello is hyphenated like hello-bye, then I want to save the hyphen and the word ("-bye"). Any help would be greatly appreciated.

答:
The space then has to optional.  But then it can't be used in the negative lookbehind.

If it's fine as long the space isn't part of the capture group.

```<code>(?<=hello\b)[ ]*(-?\w+)
</code>```

Body:
I am trying to write a regex to produce the word after a keyword in a sentence. I have this regex that matches the word after "hello ".

(?<=hello )(\w+)

However, what I am having trouble with is that if, say, hello is hyphenated like hello-bye, then I want to save the hyphen and the word ("-bye"). Any help would be greatly appreciated.

Body:
The space then has to optional.  But then it can't be used in the negative lookbehind.

If it's fine as long the space isn't part of the capture group.

(?<=hello\b)[ ]*(-?\w+)


问:
Error compiling for Git installion on Linux
I am trying to install Git on a Raspberry Pi 3.

I am following this: https://linuxize.com/post/how-to-install-git-on-raspberry-pi/#installing-git-from-the-source

When I run:

```<code>sudo make prefix=/usr/local all
</code>```

then it throws this:

```<code>LINK t/helper/test-tool
reftable/libreftable.a(block.o): In function `block_reader_init':
/usr/src/git-2.35.1/reftable/block.c:213: undefined reference to `uncompress2'
collect2: error: ld returned 1 exit status
Makefile:2949: recipe for target 't/helper/test-tool' failed
make: * [t/helper/test-tool] Error 1
</code>```

Does anyone know how to fix this or can point me to something that can help me?

答:
if you want to install Git on your Raspberry it recommended that install with apt install git . it's the easiest way but if you need to compile it from sourc try this:

```<code> undefined reference to `uncompress2'
</code>```

this error means that the uncompress2 package is not installed. try to install these package on your Raspberry and try again.

```<code>apt install zlib1g-dev
</code>```

or

```<code>apt install zlib-devel
</code>```

Body:
I am trying to install Git on a Raspberry Pi 3.

I am following this: https://linuxize.com/post/how-to-install-git-on-raspberry-pi/#installing-git-from-the-source

When I run:

sudo make prefix=/usr/local all

then it throws this:

LINK t/helper/test-tool
reftable/libreftable.a(block.o): In function `block_reader_init':
/usr/src/git-2.35.1/reftable/block.c:213: undefined reference to `uncompress2'
collect2: error: ld returned 1 exit status
Makefile:2949: recipe for target 't/helper/test-tool' failed
make: * [t/helper/test-tool] Error 1

Does anyone know how to fix this or can point me to something that can help me?

Body:
if you want to install Git on your Raspberry it recommended that install with apt install git . it's the easiest way but if you need to compile it from sourc try this:

 undefined reference to `uncompress2'

this error means that the uncompress2 package is not installed. try to install these package on your Raspberry and try again.

apt install zlib1g-dev

or

apt install zlib-devel


问:
Oracle APEX User Rights and Previleges
I do not have much experience and I would like to know if there is an easy way to create user rights and privileges, so that each user can access only specific records from the database tables, based on the level he belongs to.

More specifically, suppose we have a group of companies where this group has some companies and these companies have some branches and the branches have some users.

I want the user belonging to the "group of companies" level to have access to and view all the entries in the database related to that group and what is below it (its companies and the branches of these companies).

The user who belongs to the "company" level should have access and see only the files of this company and the branches that this company may have in the database.

The user belonging to the "Branch" level should only be able to access and view this barnch records in the database.

And finally the user belonging to the "End User" level to have access and see only the records created by the user in the database.

Of course level "administrator" will have access to all records in the database.

I thought of creating a user table with a field "User_Level" and in each table to enter USER_ID where based on this I can find the level of a user but how can I restrict access based on the Group of Companies or the Company or the Branch where it belongs?

答:
In APEX you can create authorization schemes to determine what components a user has access to within an application - but that is just a part of the answer to this question. Your question is about filtering the data that is showed to a user based on certain criteria.
There are a couple of possible solutions to this. Since this is a very broad question I'm just going to give you pointers/concepts to start your research. Up to you to determine what solution/combination is most suitable for your implementation.

Concept: Multi-Tenancy
If the data is used by multiple tenants then add a tenant_id to each table that has tenant specific data. In your case a tenant should be a branch. A simple design could be a groups table (to hold branch - companies - company groups), a group_members table (to define relationship between branch - companies - company groups OR between any group and a user) and a users table.

Concept: VPD This is a feature in the oracle database that allows a transparent implementation of security rules. In the application you'll define a simple select like

```<code>  SELECT * FROM emp
</code>```

But the VPD implementation will automatically add a where clause to the query to only show the records defined in the VPD policy. This makes developing the application a lot easier since there is less room for errors. Note that this database option could not be included for your licence. There is also something called "Poor Man's VPD" that does not use the VPD option. Google on how to implement this in your apex application.

Just do it all by hand: This is the least preferred option but it can be done. For every component where a select is done, manually add a where clause to restrict the returned rows. However this is very maintenance intensive and there is a ton of room for errors - obiously the data model will still have to support the striping of the data.

This blog post by Jeffrey Kemp might give you some pointers as well: https://jeffkemponoracle.com/2017/11/convert-an-apex-application-to-multi-tenant/ - go through the "further reading" section at the bottom.

Title: Oracle APEX User Rights and Previleges

Body:
In APEX you can create authorization schemes to determine what components a user has access to within an application - but that is just a part of the answer to this question. Your question is about filtering the data that is showed to a user based on certain criteria.
There are a couple of possible solutions to this. Since this is a very broad question I'm just going to give you pointers/concepts to start your research. Up to you to determine what solution/combination is most suitable for your implementation.

Concept: Multi-Tenancy
If the data is used by multiple tenants then add a tenant_id to each table that has tenant specific data. In your case a tenant should be a branch. A simple design could be a groups table (to hold branch - companies - company groups), a group_members table (to define relationship between branch - companies - company groups OR between any group and a user) and a users table.

Concept: VPD This is a feature in the oracle database that allows a transparent implementation of security rules. In the application you'll define a simple select like

  SELECT * FROM emp

But the VPD implementation will automatically add a where clause to the query to only show the records defined in the VPD policy. This makes developing the application a lot easier since there is less room for errors. Note that this database option could not be included for your licence. There is also something called "Poor Man's VPD" that does not use the VPD option. Google on how to implement this in your apex application.

Just do it all by hand: This is the least preferred option but it can be done. For every component where a select is done, manually add a where clause to restrict the returned rows. However this is very maintenance intensive and there is a ton of room for errors - obiously the data model will still have to support the striping of the data.

This blog post by Jeffrey Kemp might give you some pointers as well: https://jeffkemponoracle.com/2017/11/convert-an-apex-application-to-multi-tenant/ - go through the "further reading" section at the bottom.


问:
jQuery Tweet plugin custom template not working
I'm using the Tweet plugin by SeaofClouds (can be found at http://tweet.seaofclouds.com/)

The code is simple:

```<code>$(document).ready(function(){
    $('#twitter_feed_chad').tweet({
        avatar_size: 24,
        count: 1,
        username: "<? echo $settings['twitter'][0]?>",
        template: "{text} » {retweet_action}"
    });
    $('#twitter_feed_ian').tweet({
        avatar_size: 24,
        count: 1,
        username: "<? echo $settings['twitter'][1]?>",
        template: "{text} » {retweet_action}"
    });
});
</code>```

And the HTML is straight forward..

```<code><h4>Chad's Tweets</h4>
<div class="grid_6 alpha omega footer_twitter_feed" id="twitter_feed_chad">
</div>
<h4>Ian's Tweets</h4>
<div class="grid_6 alpha omega footer_twitter_feed" id="twitter_feed_ian">
</div>
</code>```

However I cannot get the template to change - it stays at its default where it displays the time of tweet first (about an hour ago etc.) followed by the tweet text, and no retweet link at all.

The site in question is located at http://www.moveinottawa.com/

答: Staying at it's default could be indicative that something could be wrong with the data you are grabbing from your server and something is wrong with the PHP portion of the code. Try writing out the whole tag and see if anything changes, I.E <?php echo $settings['twitter'][0];?> because it could be that your PHP settings are disabling short tags. And see if you can successfully echo those variables after $(document).ready(function(){

Body:
I'm using the Tweet plugin by SeaofClouds (can be found at http://tweet.seaofclouds.com/)

The code is simple:

$(document).ready(function(){
    $('#twitter_feed_chad').tweet({
        avatar_size: 24,
        count: 1,
        username: "<? echo $settings['twitter'][0]?>",
        template: "{text} » {retweet_action}"
    });
    $('#twitter_feed_ian').tweet({
        avatar_size: 24,
        count: 1,
        username: "<? echo $settings['twitter'][1]?>",
        template: "{text} » {retweet_action}"
    });
});

And the HTML is straight forward..

Chad's Tweets

Ian's Tweets

However I cannot get the template to change - it stays at its default where it displays the time of tweet first (about an hour ago etc.) followed by the tweet text, and no retweet link at all.

The site in question is located at http://www.moveinottawa.com/


问:
set env variable in Kubernetes clusters
I am new to Kubernetes.

I found some errors while using google-cloud-storage.

The problem is,
when I specify GCLOUD_PRIVATE_KEY directly in .yaml file,
I work nicely.

```<code> - name: GCLOUD_PRIVATE_KEY
   value: "-----BEGIN PRIVATE KEY-----\n(...)\n-----END PRIVATE KEY-----\n"
</code>```

However, when I inject the variable to cluster.

AT terminal

```<code>kubectl create secret generic gcloud-private-key --from-literal=GCLOUD_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n(...)\n-----END PRIVATE KEY-----\n"
</code>```

AT .yaml

```<code>- name: GCLOUD_PRIVATE_KEY
  valueFrom:
    secretKeyRef:
       name: gcloud-private-key
       key: GCLOUD_PRIVATE_KEY
</code>```

The error related to key occurs.
I even tried for escape notation just in case,

AT terminal

```<code>kubectl create secret generic gcloud-private-key --from-literal=GCLOUD_PRIVATE_KEY='"-----BEGIN PRIVATE KEY-----\n(...)\n-----END PRIVATE KEY-----\n"'
</code>```

However, it doesn't work as well! Can you let me know how I can fix it??

答:
kubectl create secret generic gcloud-private-key --from-literal=GCLOUD_PRIVATE_KEY='"...\n...

'\n', '"' are invalid character for TLS key when create from literal. You can load the key directly from the original file as-is:

kubectl create secret generic gcloud-private-key --from-literal GCLOUD_PRIVATE_KEY="$(cat <file>)"

Title: set env variable in Kubernetes clusters

Body:
I am new to Kubernetes.

I found some errors while using google-cloud-storage.

The problem is,
when I specify GCLOUD_PRIVATE_KEY directly in .yaml file,
I work nicely.

 - name: GCLOUD_PRIVATE_KEY
   value: "-----BEGIN PRIVATE KEY-----\n(...)\n-----END PRIVATE KEY-----\n"

However, when I inject the variable to cluster.

AT terminal

kubectl create secret generic gcloud-private-key --from-literal=GCLOUD_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n(...)\n-----END PRIVATE KEY-----\n"

AT .yaml

- name: GCLOUD_PRIVATE_KEY
  valueFrom:
    secretKeyRef:
       name: gcloud-private-key
       key: GCLOUD_PRIVATE_KEY

The error related to key occurs.
I even tried for escape notation just in case,

AT terminal

kubectl create secret generic gcloud-private-key --from-literal=GCLOUD_PRIVATE_KEY='"-----BEGIN PRIVATE KEY-----\n(...)\n-----END PRIVATE KEY-----\n"'

However, it doesn't work as well! Can you let me know how I can fix it??


问:
how many columns does TDengine database support?
I think the TDengine database only supports 6 tags, but I want to know about non-tag columns, is there an unlimited number of non-tag columns?</p>

答: I think you use the 1.6 version of TDengine which only supports a max of 6 tags, but the current version of TDengine (2.4) supports maximum of 128 tags and a total of 4096 columns.</p>


问:
Webpage for recording user data and creating visualisations from data
Is there a way to record user data using a form, and then display visualisations of the user's data against an already available database? I tried Wix but I don't think their form submissions allow data to be manipulated and shown in-site. Any suggestions would be very helpful!</p>

答: This sounds like it's definitely doable on Wix, but we'd need more detail as to what exactly you're trying to do to say for sure and point you in the right direction.</p>


问:
Snowflake - UDF compilation error if query using UDF returns no data
```<code>CREATE TABLE TEST_DATA
(
  READING    NUMBER(3)
);

CREATE TABLE TEST_VALIDATE
(
  MNEMONIC          VARCHAR2(3),
  MINIMUM_VALUE     NUMBER(3),
  MAXIMUM_VALUE     NUMBER(3)
);

CREATE OR REPLACE FUNCTION TEST_RANGE( p_mnemonic VARCHAR2, p_reading NUMBER )
RETURNS NUMBER AS
'SELECT
MAX(CASE
    WHEN p_reading BETWEEN MINIMUM_VALUE AND MAXIMUM_VALUE THEN p_reading
    WHEN p_reading < MINIMUM_VALUE THEN MINIMUM_VALUE
    WHEN p_reading > MAXIMUM_VALUE THEN MAXIMUM_VALUE
    ELSE NULL
END)
FROM TEST_VALIDATE
WHERE MNEMONIC = p_mnemonic';
</code>```

All rows in table TEST_DATA is validated against TEST_VALIDATE (via a UDF) so that the values are adjusted to a range.  Run these below to see something I don't understand:

```<code>-- If there is no data in both tables, this runs fine, returning nothing:
SELECT
    TEST_RANGE( 'XX', READING )
FROM TEST_DATA;

-- Insert a row to TEST_VALIDATE
INSERT INTO TEST_VALIDATE ( MNEMONIC, MINIMUM_VALUE, MAXIMUM_VALUE ) VALUES ( 'XX', 2, 100 );

-- Now this same query aborts with "002031 (42601): SQL compilation error: Unsupported subquery type cannot be evaluated"
SELECT
    TEST_RANGE( 'XX', READING )
FROM TEST_DATA;

-- Add a row to the data table:
INSERT INTO TEST_DATA ( READING ) VALUES ( 111 );

-- Now this query runs again returning one row:
SELECT
    TEST_RANGE( 'XX', READING )
FROM TEST_DATA;

-- This also works returning no rows:
SELECT
    TEST_RANGE( 'OO', READING )
FROM TEST_DATA;
</code>```

What could be happening?

答:
The error message is snowflake, "your corolated sub-query is too tricky for me" message. This form seems to be related to the Scalar Subquery. MAX by itself is in effect a GROUP BY, which might be why the trigger is happening..

When snowflake metadata knows what's in tables, it knows how to write the query to work. It might also start to fail if you put lots of data into the test_data table, with this message.

But when the tables are empty, it doesn't know what is in the table, so doesn't know how to write an optimized query. Which might imply skip empty tables

anyways your SQL is in effect this:

```<code>WITH test_validate(mnemonic, minimum_value, maximum_value) AS (
  SELECT 'XX', 2, 100
), test_data(reading) AS (
  SELECT * FROM values (111)
)
SELECT
   (SELECT
        MAX(
          CASE
                WHEN td.reading BETWEEN tv.minimum_value AND tv.maximum_value THEN td.reading
                WHEN td.reading < tv.minimum_value THEN tv.minimum_value
                WHEN td.reading > tv.maximum_value THEN tv.maximum_value
                ELSE NULL
            END)
    FROM test_validate AS tv
    WHERE tv.mnemonic = 'XX')
FROM test_data AS td
</code>```

this can be rewritten as:

```<code>WITH test_validate(mnemonic, minimum_value, maximum_value) AS (
  SELECT 'XX', 2, 100
), test_data(reading) AS (
  SELECT 1 limit 0
  --SELECT 111
)
SELECT
    MAX(
        CASE
              WHEN td.reading BETWEEN tv.minimum_value AND tv.maximum_value THEN td.reading
              WHEN td.reading < tv.minimum_value THEN tv.minimum_value
              WHEN td.reading > tv.maximum_value THEN tv.maximum_value
              ELSE NULL
          END
     )
FROM test_data AS td
CROSS JOIN test_validate AS tv
WHERE tv.mnemonic = 'XX'
</code>```

which gives a single value of NULL, because there are no rows in test_data and then across those rows MAX is run (as GROUPING function) and given there is no input, it returns NULL.

Body:
CREATE TABLE TEST_DATA
(
  READING    NUMBER(3)
);

CREATE TABLE TEST_VALIDATE
(
  MNEMONIC          VARCHAR2(3),
  MINIMUM_VALUE     NUMBER(3),
  MAXIMUM_VALUE     NUMBER(3)
);

CREATE OR REPLACE FUNCTION TEST_RANGE( p_mnemonic VARCHAR2, p_reading NUMBER )
RETURNS NUMBER AS
'SELECT
MAX(CASE
    WHEN p_reading BETWEEN MINIMUM_VALUE AND MAXIMUM_VALUE THEN p_reading
    WHEN p_reading < MINIMUM_VALUE THEN MINIMUM_VALUE
    WHEN p_reading > MAXIMUM_VALUE THEN MAXIMUM_VALUE
    ELSE NULL
END)
FROM TEST_VALIDATE
WHERE MNEMONIC = p_mnemonic';

All rows in table TEST_DATA is validated against TEST_VALIDATE (via a UDF) so that the values are adjusted to a range.  Run these below to see something I don't understand:

-- If there is no data in both tables, this runs fine, returning nothing:
SELECT
    TEST_RANGE( 'XX', READING )
FROM TEST_DATA;

-- Insert a row to TEST_VALIDATE
INSERT INTO TEST_VALIDATE ( MNEMONIC, MINIMUM_VALUE, MAXIMUM_VALUE ) VALUES ( 'XX', 2, 100 );

-- Now this same query aborts with "002031 (42601): SQL compilation error: Unsupported subquery type cannot be evaluated"
SELECT
    TEST_RANGE( 'XX', READING )
FROM TEST_DATA;

-- Add a row to the data table:
INSERT INTO TEST_DATA ( READING ) VALUES ( 111 );

-- Now this query runs again returning one row:
SELECT
    TEST_RANGE( 'XX', READING )
FROM TEST_DATA;

-- This also works returning no rows:
SELECT
    TEST_RANGE( 'OO', READING )
FROM TEST_DATA;

What could be happening?

Body:
The error message is snowflake, "your corolated sub-query is too tricky for me" message. This form seems to be related to the Scalar Subquery. MAX by itself is in effect a GROUP BY, which might be why the trigger is happening..

When snowflake metadata knows what's in tables, it knows how to write the query to work. It might also start to fail if you put lots of data into the test_data table, with this message.

But when the tables are empty, it doesn't know what is in the table, so doesn't know how to write an optimized query. Which might imply skip empty tables

anyways your SQL is in effect this:

WITH test_validate(mnemonic, minimum_value, maximum_value) AS (
  SELECT 'XX', 2, 100
), test_data(reading) AS (
  SELECT * FROM values (111)
)
SELECT
   (SELECT
        MAX(
          CASE
                WHEN td.reading BETWEEN tv.minimum_value AND tv.maximum_value THEN td.reading
                WHEN td.reading < tv.minimum_value THEN tv.minimum_value
                WHEN td.reading > tv.maximum_value THEN tv.maximum_value
                ELSE NULL
            END)
    FROM test_validate AS tv
    WHERE tv.mnemonic = 'XX')
FROM test_data AS td

this can be rewritten as:

WITH test_validate(mnemonic, minimum_value, maximum_value) AS (
  SELECT 'XX', 2, 100
), test_data(reading) AS (
  SELECT 1 limit 0
  --SELECT 111
)
SELECT
    MAX(
        CASE
              WHEN td.reading BETWEEN tv.minimum_value AND tv.maximum_value THEN td.reading
              WHEN td.reading < tv.minimum_value THEN tv.minimum_value
              WHEN td.reading > tv.maximum_value THEN tv.maximum_value
              ELSE NULL
          END
     )
FROM test_data AS td
CROSS JOIN test_validate AS tv
WHERE tv.mnemonic = 'XX'

which gives a single value of NULL, because there are no rows in test_data and then across those rows MAX is run (as GROUPING function) and given there is no input, it returns NULL.


问:
How can I shorten the next repeated statement?
How can I shorten the next repeated statement?
I want to show 4~7, 5~7, 6~7, 7 for case 1,2,3,4.

The code below is very messy and I was wondering if there is a way to reduce it.

```<code>function selectTeeShotCount() {
    console.log(document.teeShotInfoForm.TeeCount);
    const radioTeeShot = document.teeShotInfoForm.TeeCount;
    let prev = null;
    for (const radioTeeShotElement of radioTeeShot) {
        radioTeeShotElement.addEventListener('change', event => {
            (prev) ? console.log(prev.value): null;
            if (this !== prev) {
                prev = this;
            }

            document.querySelector('#teeShotInfoForm > div:nth-child(3)').classList.remove('d-none');
            document.querySelector('#teeShotInfoForm > div:nth-child(4)').classList.remove('d-none');
            document.querySelector('#teeShotInfoForm > div:nth-child(5)').classList.remove('d-none');
            document.querySelector('#teeShotInfoForm > div:nth-child(6)').classList.remove('d-none');
            document.querySelector('#teeShotInfoForm > div:nth-child(7)').classList.remove('d-none');

            switch (parseInt(radioTeeShot.value)) {
                case 1:
                    document.querySelector('#teeShotInfoForm > div:nth-child(4)').classList.add('d-none');
                    document.querySelector('#teeShotInfoForm > div:nth-child(5)').classList.add('d-none');
                    document.querySelector('#teeShotInfoForm > div:nth-child(6)').classList.add('d-none');
                    document.querySelector('#teeShotInfoForm > div:nth-child(7)').classList.add('d-none');
                    break;
                case 2:
                    document.querySelector('#teeShotInfoForm > div:nth-child(5)').classList.add('d-none');
                    document.querySelector('#teeShotInfoForm > div:nth-child(6)').classList.add('d-none');
                    document.querySelector('#teeShotInfoForm > div:nth-child(7)').classList.add('d-none');
                    break;
                case 3:
                    document.querySelector('#teeShotInfoForm > div:nth-child(6)').classList.add('d-none');
                    document.querySelector('#teeShotInfoForm > div:nth-child(7)').classList.add('d-none');
                    break;
                case 4:
                    document.querySelector('#teeShotInfoForm > div:nth-child(7)').classList.add('d-none');
                    break;
            }
        });
    }
}
</code>```

答:
Instead of using a separate selector for each element, you can select each block of divs by modifying the syntax to

document.querySelectorAll("#teeShotInfoForm div:nth-child(YOUR_NUMBER)~div")
```
<p>For instance, if you want to select the divs from 4 to 7, you can try</p>
<pre class="lang-css prettyprint-override"><code>document.querySelectorAll("#teeShotInfoForm div:nth-child(3)~div")
</code>```

(since the counting starts with 0) === every div starting with the 4th element.
I hope it works!

Body:
How can I shorten the next repeated statement?
I want to show 4~7, 5~7, 6~7, 7 for case 1,2,3,4.

The code below is very messy and I was wondering if there is a way to reduce it.

function selectTeeShotCount() {
    console.log(document.teeShotInfoForm.TeeCount);
    const radioTeeShot = document.teeShotInfoForm.TeeCount;
    let prev = null;
    for (const radioTeeShotElement of radioTeeShot) {
        radioTeeShotElement.addEventListener('change', event => {
            (prev) ? console.log(prev.value): null;
            if (this !== prev) {
                prev = this;
            }

            document.querySelector('#teeShotInfoForm > div:nth-child(3)').classList.remove('d-none');
            document.querySelector('#teeShotInfoForm > div:nth-child(4)').classList.remove('d-none');
            document.querySelector('#teeShotInfoForm > div:nth-child(5)').classList.remove('d-none');
            document.querySelector('#teeShotInfoForm > div:nth-child(6)').classList.remove('d-none');
            document.querySelector('#teeShotInfoForm > div:nth-child(7)').classList.remove('d-none');

            switch (parseInt(radioTeeShot.value)) {
                case 1:
                    document.querySelector('#teeShotInfoForm > div:nth-child(4)').classList.add('d-none');
                    document.querySelector('#teeShotInfoForm > div:nth-child(5)').classList.add('d-none');
                    document.querySelector('#teeShotInfoForm > div:nth-child(6)').classList.add('d-none');
                    document.querySelector('#teeShotInfoForm > div:nth-child(7)').classList.add('d-none');
                    break;
                case 2:
                    document.querySelector('#teeShotInfoForm > div:nth-child(5)').classList.add('d-none');
                    document.querySelector('#teeShotInfoForm > div:nth-child(6)').classList.add('d-none');
                    document.querySelector('#teeShotInfoForm > div:nth-child(7)').classList.add('d-none');
                    break;
                case 3:
                    document.querySelector('#teeShotInfoForm > div:nth-child(6)').classList.add('d-none');
                    document.querySelector('#teeShotInfoForm > div:nth-child(7)').classList.add('d-none');
                    break;
                case 4:
                    document.querySelector('#teeShotInfoForm > div:nth-child(7)').classList.add('d-none');
                    break;
            }
        });
    }
}

Body:
Instead of using a separate selector for each element, you can select each block of divs by modifying the syntax to

document.querySelectorAll("#teeShotInfoForm div:nth-child(YOUR_NUMBER)~div")

For instance, if you want to select the divs from 4 to 7, you can try

document.querySelectorAll("#teeShotInfoForm div:nth-child(3)~div")

(since the counting starts with 0) === every div starting with the 4th element.
I hope it works!


问:
Is my code a performance killer?
I am showing the value of the timer.php through AJAX in index.php . However I am concern about the performance of this, if it is a server killer if there are 30 people online, and things like this. Do you suggest me some edits?

Thank you.

index.php

```<code><script language='JavaScript'>
setInterval( 'SANAjax();', 1000 );

$(function() {
SANAjax = function(){

$('#dataDisplay').load('timer.php');

}
 });

</script>
<div id="dataDisplay"></div>
</code>```

timer.php

```<code>function time_difference($endtime){
    $days= (date("j",$endtime)-1);
    $hours =date("G",$endtime);
    $mins =date("i",$endtime);
    $secs =date("s",$endtime);
    $diff="'day': ".$days.",'hour': ".$hours.",'min': ".$mins.",'sec': ".$secs;
    return $diff;
}

$future_time = mktime(0, 0, 0, 9, 19, 2011);
$now_time = strtotime("+2 hours");
$end_time = $future_time - $now_time;
$difference = time_difference($end_time);
if ($future_time <= $now_time ) { echo "Date reached"; } else { echo $difference; };
?>
</code>```

答:
I use jQuery Countdown http://keith-wood.name/countdown.html to put a timer on my pages to let the user know when they are going to be logged out of the system due to inactivity.

You can bind a function to the counter expiring event.

http://code.google.com/p/jquery-countdown/  ...Simple example

http://keith-wood.name/countdown.html  ...shows off all the bells and whistles...

It can be as simple as the first one or as detailed as the second!

-=Bryan

Title: Is my code a performance killer?

Body:
I am showing the value of the timer.php through AJAX in index.php . However I am concern about the performance of this, if it is a server killer if there are 30 people online, and things like this. Do you suggest me some edits?

Thank you.

index.php

timer.php

function time_difference($endtime){
    $days= (date("j",$endtime)-1);
    $hours =date("G",$endtime);
    $mins =date("i",$endtime);
    $secs =date("s",$endtime);
    $diff="'day': ".$days.",'hour': ".$hours.",'min': ".$mins.",'sec': ".$secs;
    return $diff;
}

$future_time = mktime(0, 0, 0, 9, 19, 2011);
$now_time = strtotime("+2 hours");
$end_time = $future_time - $now_time;
$difference = time_difference($end_time);
if ($future_time <= $now_time ) { echo "Date reached"; } else { echo $difference; };
?>


问:
Jest did not exit one second after the test run has completed using express
I'm using JEST for unit testing my express routes.

While running the yarn test all my test case are getting passed, but I'm getting an error

```<code>Jest did not exit one second after the test run has completed.

This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with `--detectOpenHandles` to troubleshoot this issue.
</code>```

I used async & done, but still it throws the above error.

Below is my spec code. Please help

routes.spec.ts

```<code>const request = require('supertest');
describe('Test the root path', () => {
  const app = require('./index');

  test('GET /gql/gql-communication-portal/release-notes', async (done) => {
    const response = await request(app).get('/gql/gql-communication-portal/release-notes');
    expect(response.status).toBe(200);
    done();
  });
});
</code>```

答:
You can try this one

"test": "jest --runInBand --force-exit"

Body:
I'm using JEST for unit testing my express routes.

While running the yarn test all my test case are getting passed, but I'm getting an error

Jest did not exit one second after the test run has completed.

This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with `--detectOpenHandles` to troubleshoot this issue.

I used async & done, but still it throws the above error.

Below is my spec code. Please help

routes.spec.ts

const request = require('supertest');
describe('Test the root path', () => {
  const app = require('./index');

  test('GET /gql/gql-communication-portal/release-notes', async (done) => {
    const response = await request(app).get('/gql/gql-communication-portal/release-notes');
    expect(response.status).toBe(200);
    done();
  });
});


答:
You can wrap the repeated functionality into a method.

e.g.

```<code>const remove = (...childs) => {
    for (const child in childs) {
        document.querySelector('#teeShotInfoForm > div:nth-child(' + child + ')').classList.remove('d-none');
    }
}

const add = (...childs) => {
    for (const child in childs) {
        document.querySelector('#teeShotInfoForm > div:nth-child(' + child + ')').classList.add('d-none');
    }
}
</code>```

then use it.

e.g.

```<code>function selectTeeShotCount() {
    const radioTeeShot = document.teeShotInfoForm.TeeCount;
    let prev = null;
    for (const radioTeeShotElement of radioTeeShot) {
        radioTeeShotElement.addEventListener('change', event => {
            (prev) ? console.log(prev.value): null;
            if (this !== prev) {
                prev = this;
            }
            remove(3, 4, 5, 6, 7);
            switch (parseInt(radioTeeShot.value)) {
                case 1:
                    add(4, 5, 6, 7);
                    break;
                case 2:
                    add(5, 6, 7);
                    break;
                case 3:
                    add(6, 7);
                    break;
                case 4:
                    add(7);
                    break;
            }
        });
    }
}
</code>```

Title: How can I shorten the next repeated statement?

Body:
You can wrap the repeated functionality into a method.

e.g.

const remove = (...childs) => {
    for (const child in childs) {
        document.querySelector('#teeShotInfoForm > div:nth-child(' + child + ')').classList.remove('d-none');
    }
}

const add = (...childs) => {
    for (const child in childs) {
        document.querySelector('#teeShotInfoForm > div:nth-child(' + child + ')').classList.add('d-none');
    }
}

then use it.

e.g.

function selectTeeShotCount() {
    const radioTeeShot = document.teeShotInfoForm.TeeCount;
    let prev = null;
    for (const radioTeeShotElement of radioTeeShot) {
        radioTeeShotElement.addEventListener('change', event => {
            (prev) ? console.log(prev.value): null;
            if (this !== prev) {
                prev = this;
            }
            remove(3, 4, 5, 6, 7);
            switch (parseInt(radioTeeShot.value)) {
                case 1:
                    add(4, 5, 6, 7);
                    break;
                case 2:
                    add(5, 6, 7);
                    break;
                case 3:
                    add(6, 7);
                    break;
                case 4:
                    add(7);
                    break;
            }
        });
    }
}


问:
Docker compose fails with 'COPY failed: stat usr/src/app/dist: file does not exist' - only on github actions
I'm creating web application (angular + nest.js) and I'm trying to make multi stage build - I want to reduce size of docker image.

Angular build works good.

Nest.js one builds successfully on my pc using docker compose build, but fails on github actions with following error: Status: COPY failed: stat usr/src/app/dist: file does not exist, Code: 1

What can i do to fix it?

Dockerfile:

```<code>FROM node:16.13.1-alpine AS build
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install --only=development
RUN npm run build
COPY . .

FROM node:16.13.1-alpine
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install --only=production
COPY . .
COPY --from=build /usr/src/app/dist ./dist
EXPOSE 7000
CMD ["node", "dist/main"]
</code>```

previous single stage Dockerfile (builds successfully):

```<code>FROM node:16.13.1-alpine
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
RUN npm run build
COPY . .
EXPOSE 7000
CMD [ "npm", "start" ]
</code>```

docker-compose.yml:

```<code>version: '3.8'

services:
  backend:
    container_name: nestjs
    image: ghcr.io/<gh-nickname/repo-name>/backend
    build:
      context: backend
      dockerfile: Dockerfile
    ports:
    - 7000:7000
  frontend:
    container_name: angular
    image: ghcr.io/<gh-nickname/repo-name>/frontend
    build:
      context: frontend
      dockerfile: Dockerfile
    ports:
    - 8000:80
</code>```

github workflow file:

```<code>name: Build and publish to github packages

on:
  push:
    branches:
      - master

env:
  REGISTRY: ghcr.io
  IMAGE_NAME: ${{ github.repository }}

jobs:
  build-and-push-image:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write

    steps:
    - name: Checkout
      uses: actions/checkout@v2

    - name: Log in to the Container registry
      uses: docker/login-action@v1
      with:
        registry: ${{ env.REGISTRY }}
        username: ${{ github.actor }}
        password: ${{ secrets.GITHUB_TOKEN }}

    - name: Extract metadata (tags, labels) for Docker
      id: meta
      uses: docker/metadata-action@v3
      with:
        images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}

    - name: Build image
      run: docker compose build

    - name: Publish image
      run: docker compose push
</code>```

答:
Caching multistage builds on CI Servers is not that easy as locally. You have to tell it where to get the layers from. As schema:

```<code>docker build --target build-image --cache-from=you/repo/backend:build-stage --tag you/repo/backend:build-stage

docker build --target prod-image --cache-from=you/repo/backend:build-stage --cache-from=you/repo/backend:prod-stage --tag you/repo/backend:prod-stage

docker push
</code>```

So for GH Actions you can use the internal caching of GH and do something like:

```<code>steps:
- name: Build base image
        id: docker_build_base
        uses: docker/build-push-action@v2
        with:
          context: .
          file: Dockerfile
          push: false
          cache-from: |
            type=gha,scope=base
          cache-to: |
            type=gha,scope=base,mode=max
          target: base
          tags: you/repo/backend:build-stage

      - name: Build prod image
        id: docker_build_prod
        uses: docker/build-push-action@v2
        with:
          context: .
          file: Dockerfile
          push: true
          cache-from: |
            type=gha,scope=prod
            type=gha,scope=base
          cache-to: |
            type=gha,scope=prod,mode=max
          target: prod
          tags: you/repo/backend:prod-stage
</code>```

Remark: It's showing you the right direction and no copy&paste solution. Please adjust as you need..

Body:
I'm creating web application (angular + nest.js) and I'm trying to make multi stage build - I want to reduce size of docker image.

Angular build works good.

Nest.js one builds successfully on my pc using docker compose build, but fails on github actions with following error: Status: COPY failed: stat usr/src/app/dist: file does not exist, Code: 1

What can i do to fix it?

Dockerfile:

FROM node:16.13.1-alpine AS build
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install --only=development
RUN npm run build
COPY . .

FROM node:16.13.1-alpine
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install --only=production
COPY . .
COPY --from=build /usr/src/app/dist ./dist
EXPOSE 7000
CMD ["node", "dist/main"]

previous single stage Dockerfile (builds successfully):

FROM node:16.13.1-alpine
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
RUN npm run build
COPY . .
EXPOSE 7000
CMD [ "npm", "start" ]

docker-compose.yml:

version: '3.8'

services:
  backend:
    container_name: nestjs
    image: ghcr.io/<gh-nickname/repo-name>/backend
    build:
      context: backend
      dockerfile: Dockerfile
    ports:
    - 7000:7000
  frontend:
    container_name: angular
    image: ghcr.io/<gh-nickname/repo-name>/frontend
    build:
      context: frontend
      dockerfile: Dockerfile
    ports:
    - 8000:80

github workflow file:

name: Build and publish to github packages

on:
  push:
    branches:
      - master

env:
  REGISTRY: ghcr.io
  IMAGE_NAME: ${{ github.repository }}

jobs:
  build-and-push-image:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write

    steps:
    - name: Checkout
      uses: actions/checkout@v2

    - name: Log in to the Container registry
      uses: docker/login-action@v1
      with:
        registry: ${{ env.REGISTRY }}
        username: ${{ github.actor }}
        password: ${{ secrets.GITHUB_TOKEN }}

    - name: Extract metadata (tags, labels) for Docker
      id: meta
      uses: docker/metadata-action@v3
      with:
        images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}

    - name: Build image
      run: docker compose build

    - name: Publish image
      run: docker compose push

Body:
Caching multistage builds on CI Servers is not that easy as locally. You have to tell it where to get the layers from. As schema:

docker build --target build-image --cache-from=you/repo/backend:build-stage --tag you/repo/backend:build-stage

docker build --target prod-image --cache-from=you/repo/backend:build-stage --cache-from=you/repo/backend:prod-stage --tag you/repo/backend:prod-stage

docker push

So for GH Actions you can use the internal caching of GH and do something like:

steps:
- name: Build base image
        id: docker_build_base
        uses: docker/build-push-action@v2
        with:
          context: .
          file: Dockerfile
          push: false
          cache-from: |
            type=gha,scope=base
          cache-to: |
            type=gha,scope=base,mode=max
          target: base
          tags: you/repo/backend:build-stage

      - name: Build prod image
        id: docker_build_prod
        uses: docker/build-push-action@v2
        with:
          context: .
          file: Dockerfile
          push: true
          cache-from: |
            type=gha,scope=prod
            type=gha,scope=base
          cache-to: |
            type=gha,scope=prod,mode=max
          target: prod
          tags: you/repo/backend:prod-stage

Remark: It's showing you the right direction and no copy&paste solution. Please adjust as you need..


问:
Try to scrape withdrawal fee using Selenium. But doesn't work. (newbie)
I try to scrape this website https://www.bitkub.com/fee/cryptocurrency using Selenium.
I followed the tutorial from Youtube but It doesn't work. It can't find the element I wanted to use (coin_name, chain and withdrawal fees).
I'm newbie to coding by the way. thank you in advance.

Here my code

```<code>from selenium import webdriver
website = 'https://www.bitkub.com/fee/cryptocurrency'
path = r"C:\\Users\\USER\\Downloads\\chromedriver.exe"
driver = webdriver.Chrome(path)
driver.get(website)

#pull_data

coins = driver.find_elements_by_tag_name('tr')

#variable
coin_name = []
chain = []
fee = []
for coin in coins:
    coin_name.append(coin.find_element_by_xpath('./td[2]').text)
    chain.append(coin.find_element_by_xpath('./td[3]').text)
    fee.append(coin.find_element_by_xpath('./td[4]').text)
#driver.quit()
</code>```

答:
My new updated code. is it gonna work if I store all the data in one variable.
But I wanted to export data to CSV using Pandas. That's why I'm trying to specify the element, So I can create a list out of it.

```<code>from selenium import webdriver
website = 'https://www.bitkub.com/fee/cryptocurrency'
path = r"C:\\Users\\USER\\Downloads\\chromedriver.exe"
driver = webdriver.Chrome(path)
driver.get(website)

#pull_data

coins = driver.find_elements_by_tag_name('tr')

#for_loop
for coin in coins:
    print(coin.text)
#driver.quit()
</code>```

Body:
I try to scrape this website https://www.bitkub.com/fee/cryptocurrency using Selenium.
I followed the tutorial from Youtube but It doesn't work. It can't find the element I wanted to use (coin_name, chain and withdrawal fees).
I'm newbie to coding by the way. thank you in advance.

Here my code

from selenium import webdriver
website = 'https://www.bitkub.com/fee/cryptocurrency'
path = r"C:\\Users\\USER\\Downloads\\chromedriver.exe"
driver = webdriver.Chrome(path)
driver.get(website)

#pull_data

coins = driver.find_elements_by_tag_name('tr')

#variable
coin_name = []
chain = []
fee = []
for coin in coins:
    coin_name.append(coin.find_element_by_xpath('./td[2]').text)
    chain.append(coin.find_element_by_xpath('./td[3]').text)
    fee.append(coin.find_element_by_xpath('./td[4]').text)
#driver.quit()

Body:
My new updated code. is it gonna work if I store all the data in one variable.
But I wanted to export data to CSV using Pandas. That's why I'm trying to specify the element, So I can create a list out of it.

from selenium import webdriver
website = 'https://www.bitkub.com/fee/cryptocurrency'
path = r"C:\\Users\\USER\\Downloads\\chromedriver.exe"
driver = webdriver.Chrome(path)
driver.get(website)

#pull_data

coins = driver.find_elements_by_tag_name('tr')

#for_loop
for coin in coins:
    print(coin.text)
#driver.quit()


问:
Flutter gradle.build error: Could not get unknown property 'compileSdkVersion' for extension 'flutter' of type FlutterExtension
I Manually added a flutter project to AndroidStudioProjects directory.

I started getting this error

error:

```<code>FAILURE: Build failed with an exception.

 * Where:
Build file 'C:\Users\username\AndroidStudioProjects\projectName\android\app\build.gradle' line: 29

 * What went wrong:
A problem occurred evaluating project ':app'.
> Could not get unknown property 'compileSdkVersion' for extension 'flutter' of type FlutterExtension.
</code>```

build.gradle file:

```<code>def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion flutter.compileSdkVersion     // FAILURE: Build failed with an exception.

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = '1.8'
    }

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.example.newweather"
        minSdkVersion flutter.minSdkVersion
        targetSdkVersion flutter.targetSdkVersion
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}

</code>```

I tried these, they didnt work:

https://stackoverflow.com/a/60565001/17740672

changing compileSdkVersion to a constant number

jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj

jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj

答:
Try the commands

flutter clean

and

flutter upgrade

Worked for me.

Body:
I Manually added a flutter project to AndroidStudioProjects directory.

I started getting this error

error:

FAILURE: Build failed with an exception.

 * Where:
Build file 'C:\Users\username\AndroidStudioProjects\projectName\android\app\build.gradle' line: 29

 * What went wrong:
A problem occurred evaluating project ':app'.
> Could not get unknown property 'compileSdkVersion' for extension 'flutter' of type FlutterExtension.

build.gradle file:

def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion flutter.compileSdkVersion     // FAILURE: Build failed with an exception.

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = '1.8'
    }

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.example.newweather"
        minSdkVersion flutter.minSdkVersion
        targetSdkVersion flutter.targetSdkVersion
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}

I tried these, they didnt work:

https://stackoverflow.com/a/60565001/17740672

changing compileSdkVersion to a constant number

jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj

jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj


问:
Clamp RotateAround object Unity
I am making a script to rotate my camera around a sphere but I need to clamp the y axis so the camera does not co over the polls of the sphere I am using rotate around to move my camera.

Thanks!

My current code

```<code>public float sensitivity = 1;
public float moveSpeed = 10;
public float maxUp = 45f;
public float maxDown = -45f;

public Transform target;

void Update()
{
    transform.LookAt(target);

    float HorizontalAxis = Input.GetAxis("Horizontal") * moveSpeed;
    float VerticalAxis = Input.GetAxis("Vertical") * moveSpeed;

    if (HorizontalAxis >= 1 || VerticalAxis >= 1 || HorizontalAxis <= -1 || VerticalAxis <= -1)
    {
        Quaternion targetPos = transform.rotation;
        targetPos.x += HorizontalAxis * sensitivity;
        targetPos.y += VerticalAxis * sensitivity;

        transform.RotateAround(target.position, Vector3.left, targetPos.y);
        transform.RotateAround(target.position, Vector3.up, targetPos.x);
    }
}
</code>```

答:
Your code makes no sense to begin with.

You do

```<code>Quaternion targetPos = transform.rotation;
    targetPos.x += HorizontalAxis * sensitivity;
    targetPos.y += VerticalAxis * sensitivity;
</code>```

Just to then use these as parameters in

```<code> transform.RotateAround(target.position, Vector3.left, targetPos.y);
 transform.RotateAround(target.position, Vector3.up, targetPos.x);
</code>```

A Quaternion has not three but four components x, y, z and w and they move in ranges between -1 and 1. You never touch the individual component of a Quaternion except you really know exactly what you are doing!

You rather simply want to use the HorizontalAxis and VerticalAxis directly as the parameters to RotateAround.

You could rather simply remember and clamp how much you already rotated like e.g.

```<code>private float rotatedY;

private void Update()
{
    transform.LookAt(target);

    // why two different multipliers anyway though?
    var HorizontalAxis = Input.GetAxis("Horizontal") * moveSpeed * sensitivity;
    var VerticalAxis = Input.GetAxis("Vertical") * moveSpeed * sensitivity;

    // would a positive rotation exceed the maxUp?
    if(rotatedY + VerticalAxis > maxUp)
    {
        // then rotate only so much that you terminate exactly on maxUp
        VerticalAxis = maxUp - rotatedY;
    }
    // would a negative rotation exceed the maxDown?
    else if(rotatedY + VerticalAxis < maxDown)
    {
        // then you rotate only that much that you terminate exactly on maxDown
        VerticalAxis = maxDown - rotatedY;
    }

    transform.RotateAround(target.position, Vector3.left, VerticalAxis);
    transform.RotateAround(target.position, Vector3.up, HorizontalAxis);

    // sum up how much you already rotated vertically
    rotatedY += VerticalAxis;
}
</code>```

Title: Clamp RotateAround object Unity

Body:
I am making a script to rotate my camera around a sphere but I need to clamp the y axis so the camera does not co over the polls of the sphere I am using rotate around to move my camera.

Thanks!

My current code

public float sensitivity = 1;
public float moveSpeed = 10;
public float maxUp = 45f;
public float maxDown = -45f;

public Transform target;

void Update()
{
    transform.LookAt(target);

    float HorizontalAxis = Input.GetAxis("Horizontal") * moveSpeed;
    float VerticalAxis = Input.GetAxis("Vertical") * moveSpeed;

    if (HorizontalAxis >= 1 || VerticalAxis >= 1 || HorizontalAxis <= -1 || VerticalAxis <= -1)
    {
        Quaternion targetPos = transform.rotation;
        targetPos.x += HorizontalAxis * sensitivity;
        targetPos.y += VerticalAxis * sensitivity;

        transform.RotateAround(target.position, Vector3.left, targetPos.y);
        transform.RotateAround(target.position, Vector3.up, targetPos.x);
    }
}

Body:
Your code makes no sense to begin with.

You do

Quaternion targetPos = transform.rotation;
    targetPos.x += HorizontalAxis * sensitivity;
    targetPos.y += VerticalAxis * sensitivity;

Just to then use these as parameters in

 transform.RotateAround(target.position, Vector3.left, targetPos.y);
 transform.RotateAround(target.position, Vector3.up, targetPos.x);

A Quaternion has not three but four components x, y, z and w and they move in ranges between -1 and 1. You never touch the individual component of a Quaternion except you really know exactly what you are doing!

You rather simply want to use the HorizontalAxis and VerticalAxis directly as the parameters to RotateAround.

You could rather simply remember and clamp how much you already rotated like e.g.

private float rotatedY;

private void Update()
{
    transform.LookAt(target);

    // why two different multipliers anyway though?
    var HorizontalAxis = Input.GetAxis("Horizontal") * moveSpeed * sensitivity;
    var VerticalAxis = Input.GetAxis("Vertical") * moveSpeed * sensitivity;

    // would a positive rotation exceed the maxUp?
    if(rotatedY + VerticalAxis > maxUp)
    {
        // then rotate only so much that you terminate exactly on maxUp
        VerticalAxis = maxUp - rotatedY;
    }
    // would a negative rotation exceed the maxDown?
    else if(rotatedY + VerticalAxis < maxDown)
    {
        // then you rotate only that much that you terminate exactly on maxDown
        VerticalAxis = maxDown - rotatedY;
    }

    transform.RotateAround(target.position, Vector3.left, VerticalAxis);
    transform.RotateAround(target.position, Vector3.up, HorizontalAxis);

    // sum up how much you already rotated vertically
    rotatedY += VerticalAxis;
}


问:
docker image multistage build: How to create a docker image copying only python packages
I am trying to create a python based image with some packages installed. But i want the image layer not to show anything about the packages I installed.

I am trying to use the multistage build

eg:

```<code>FROM python:3.9-slim-buster as builder
RUN pip install django # (I dont want this command to be seen when checking the docker image layers, So thats why using multistage build)

FROM python:3.9-slim-buster
# Here i want to copy all the site packages
COPY --from=builder /usr/local/lib/python3.9/site-packages /usr/local/lib/python3.9/site-packages
</code>```

Now build image

```<code>docker build -t python_3.9-slim-buster_custom:latest .
</code>```

and later check the image layers

```<code>dive python_3.9-slim-buster_custom:latest
</code>```

this will not show the RUN pip install django line

Will this be a good way to achieve what i want (hide all the pip install commands)

答:
Currently whats working for me is.</p>
```<code>FROM python:3.9-slim-buster as builder
# DO ALL YOUR STUFF HERE

FROM python:3.9-slim-buster
COPY --from=builder / /
</code>```

Body:
I am trying to create a python based image with some packages installed. But i want the image layer not to show anything about the packages I installed.

I am trying to use the multistage build

eg:

FROM python:3.9-slim-buster as builder
RUN pip install django # (I dont want this command to be seen when checking the docker image layers, So thats why using multistage build)

FROM python:3.9-slim-buster
# Here i want to copy all the site packages
COPY --from=builder /usr/local/lib/python3.9/site-packages /usr/local/lib/python3.9/site-packages

Now build image

docker build -t python_3.9-slim-buster_custom:latest .

and later check the image layers

dive python_3.9-slim-buster_custom:latest

this will not show the RUN pip install django line

Will this be a good way to achieve what i want (hide all the pip install commands)

Body:
Currently whats working for me is.

FROM python:3.9-slim-buster as builder
# DO ALL YOUR STUFF HERE

FROM python:3.9-slim-buster
COPY --from=builder / /


问:
Bootstrap Navbar Dropdown "Flashes" White When Clicking Off
When you click on the dropdown button on the navbar(button labeled Dropdown), and then click off(anywhere in the page), you can see the dropdown button flash white briefly.

I've seen this quite similar bug: Bootstrap navbar "flashing" when clicking outside of menu to close it. But it, unfortunately, doesn't work(actually copy and pasted the exact same code in css).

Here's a minimal reproducible version of the bug on plunk: https://embed.plnkr.co/plunk/nBIvKcLMkYbey8Oa

Code:

<!doctype html>

    <link rel="stylesheet" href="lib/style.css">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

                Dropdown

asdf

```
<pre class="lang-css prettyprint-override"><code>nav {
    background-color: #26445a !important;
    border-color: #26445a !important;
    margin: 0px !important;
}

.navbar a{
    color: #EEFBFB !important;
}
.navbar-header a{
    font-size: 1.45em !important;
}

.nav >li > a:hover, .nav > li > a:focus{
    background-color: #335369 !important;
}

.nav-item{
    background-color: #26445a !important;
    font-size: 1.23em !important;
}

#games-dropdown > .dropdown-menu a{
    background-color: #ffffff !important;
    color: #000000 !important;
    font-size: 1.2em !important;
}
#games-dropdown > .dropdown-menu a:hover{
    background-color: #d1d1d1 !important;
    color: #000000 !important;
}
</code>```

Thanks a lot!

答:
I think that adding lots of new CSS classes might be confusing Bootstrap. In the CSS detailed at your sandbox link there are many different background commands all pointing in one way or another to your navbar and the links in your navbar. These could easily be getting in the way of each other. You don't especially have to add new CSS. You only need to edit the classes that already exist within Bootstrap nav. It's the focus specifically that is causing trouble.

```<code>.nav
.navbar-brand
.navbar-dropdown
.navbar-toggler-icon
.menu-item
.dropdown-item

</code>```

Try removing all your background instructions to begin then add new backgrounds to the above.

Body:
When you click on the dropdown button on the navbar(button labeled Dropdown), and then click off(anywhere in the page), you can see the dropdown button flash white briefly.

I've seen this quite similar bug: Bootstrap navbar "flashing" when clicking outside of menu to close it. But it, unfortunately, doesn't work(actually copy and pasted the exact same code in css).

Here's a minimal reproducible version of the bug on plunk: https://embed.plnkr.co/plunk/nBIvKcLMkYbey8Oa

Code:

<!doctype html>

    <link rel="stylesheet" href="lib/style.css">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

                Dropdown

asdf

nav {
    background-color: #26445a !important;
    border-color: #26445a !important;
    margin: 0px !important;
}

.navbar a{
    color: #EEFBFB !important;
}
.navbar-header a{
    font-size: 1.45em !important;
}

.nav >li > a:hover, .nav > li > a:focus{
    background-color: #335369 !important;
}

.nav-item{
    background-color: #26445a !important;
    font-size: 1.23em !important;
}

#games-dropdown > .dropdown-menu a{
    background-color: #ffffff !important;
    color: #000000 !important;
    font-size: 1.2em !important;
}
#games-dropdown > .dropdown-menu a:hover{
    background-color: #d1d1d1 !important;
    color: #000000 !important;
}

Thanks a lot!

Body:
I think that adding lots of new CSS classes might be confusing Bootstrap. In the CSS detailed at your sandbox link there are many different background commands all pointing in one way or another to your navbar and the links in your navbar. These could easily be getting in the way of each other. You don't especially have to add new CSS. You only need to edit the classes that already exist within Bootstrap nav. It's the focus specifically that is causing trouble.

.nav
.navbar-brand
.navbar-dropdown
.navbar-toggler-icon
.menu-item
.dropdown-item

Try removing all your background instructions to begin then add new backgrounds to the above.


问:
Mongodb Is it possible to exclude the root document if only a nested document matches the result?
I have a set of documents which includes a nested set of revisions of that same document. I need to execute a search query that returns only the matched set, including the parent where matched. Below is a reduced example of the data.

```<code>{
"title_number": "46345734",
"status": "applied",
"updated": "02/04/2022",
"rev_num": 1,
"revs": [
  {
    "title_number": "46345734",
    "status": "unapplied",
    "updated": "02/06/2022",
    "rev_num": 2
  }]
},
{
"title_number": "46345802",
"status": "unapplied",
"updated": "02/05/2022",
"rev_num": 1,
"revs": [
  {
    "title_number": "46345802",
    "status": "applied",
    "updated": "02/05/2022",
    "rev_num": 2
  },
  {
    "title_number": "46345802",
    "status": "applied",
    "updated": "02/06/2022",
    "rev_num": 3
  }]
}
</code>```

In one query, I want to look for all documents with a status of "unapplied", only returning the nested documents that match the status and keeping or removing the parent if it also matched.

Below is an example of how I expected the query to look initially, and the expected result when run against the provided example data.

```<code>titles.find({
  "$and": [{
    "$or": [
      {"status": "applied"},
      {"revs.status": "applied"}
    ]
  }]
})
</code>```

Expected(Wanted) result

```<code>{
"title_number": "46345734",
"status": "applied",
"updated": "02/04/2022",
"rev_num": 1,
"revs": [],
},
{
  "title_number": "46345802",
  "status": "applied",
  "updated": "02/05/2022",
  "rev_num": 2
},
{
  "title_number": "46345802",
  "status": "applied",
  "updated": "02/06/2022",
  "rev_num": 3
}
</code>```

In the first result, the parent status matched, but not the child, so only the parent was returned. In the second result, the parent didn't match, however, two of the nested documents did, so only they were returned.

After reading a ton of posts regarding aggregates, element matching, etc, I have been able to get bits and pieces, but it seems my case is either insanely obvious or rather unique.

Thanks in advance for any assistance.

答:
use aggregate and first $filter revs with applied status and then $push applied docs to separate array and also the revs to another array and finally mix two array to one.

you can test it here mongodb playground

```<code>titles.aggregate([
  {
    "$addFields": {
      "revs": {
        $filter: {
          input: "$revs",
          as: "rev",
          cond: {
            $eq: [
              "$$rev.status",
              "applied"
            ]
          }
        }
      }
    }
  },
  {
    $group: {
      _id: null,
      applied_doc: {
        $push: {
          $cond: [
            {
              $eq: [
                "$status",
                "applied"
              ]
            },
            {
              _id: "_id",
              title_number: "$title_number",
              status: "$status",
              updated: "$updated",
              rev_num: "$rev_num",
              revs: "$revs"
            },
            "$$REMOVE"
          ]
        }
      },
      applied_sub_doc: {
        $push: "$revs"
      }
    },

  },
  // flatten array in $applied_sub_doc prop
  {
    $set: {
      applied_sub_doc: {
        $reduce: {
          input: "$applied_sub_doc",
          initialValue: [],
          in: {
            $concatArrays: [
              "$$value",
              "$$this"
            ],

          },

        },

      },

    },

  },
  {
    $project: {
      mixedDocs: {
        $concatArrays: [
          "$applied_doc",
          "$applied_sub_doc"
        ],

      },

    },

  },
  {
    $unwind: "$mixedDocs",

  },
  {
    $replaceWith: "$mixedDocs",

  },

])
</code>```

Body:
I have a set of documents which includes a nested set of revisions of that same document. I need to execute a search query that returns only the matched set, including the parent where matched. Below is a reduced example of the data.

{
"title_number": "46345734",
"status": "applied",
"updated": "02/04/2022",
"rev_num": 1,
"revs": [
  {
    "title_number": "46345734",
    "status": "unapplied",
    "updated": "02/06/2022",
    "rev_num": 2
  }]
},
{
"title_number": "46345802",
"status": "unapplied",
"updated": "02/05/2022",
"rev_num": 1,
"revs": [
  {
    "title_number": "46345802",
    "status": "applied",
    "updated": "02/05/2022",
    "rev_num": 2
  },
  {
    "title_number": "46345802",
    "status": "applied",
    "updated": "02/06/2022",
    "rev_num": 3
  }]
}

In one query, I want to look for all documents with a status of "unapplied", only returning the nested documents that match the status and keeping or removing the parent if it also matched.

Below is an example of how I expected the query to look initially, and the expected result when run against the provided example data.

titles.find({
  "$and": [{
    "$or": [
      {"status": "applied"},
      {"revs.status": "applied"}
    ]
  }]
})

Expected(Wanted) result

{
"title_number": "46345734",
"status": "applied",
"updated": "02/04/2022",
"rev_num": 1,
"revs": [],
},
{
  "title_number": "46345802",
  "status": "applied",
  "updated": "02/05/2022",
  "rev_num": 2
},
{
  "title_number": "46345802",
  "status": "applied",
  "updated": "02/06/2022",
  "rev_num": 3
}

In the first result, the parent status matched, but not the child, so only the parent was returned. In the second result, the parent didn't match, however, two of the nested documents did, so only they were returned.

After reading a ton of posts regarding aggregates, element matching, etc, I have been able to get bits and pieces, but it seems my case is either insanely obvious or rather unique.

Thanks in advance for any assistance.

Body:
use aggregate and first $filter revs with applied status and then $push applied docs to separate array and also the revs to another array and finally mix two array to one.

you can test it here mongodb playground

titles.aggregate([
  {
    "$addFields": {
      "revs": {
        $filter: {
          input: "$revs",
          as: "rev",
          cond: {
            $eq: [
              "$$rev.status",
              "applied"
            ]
          }
        }
      }
    }
  },
  {
    $group: {
      _id: null,
      applied_doc: {
        $push: {
          $cond: [
            {
              $eq: [
                "$status",
                "applied"
              ]
            },
            {
              _id: "_id",
              title_number: "$title_number",
              status: "$status",
              updated: "$updated",
              rev_num: "$rev_num",
              revs: "$revs"
            },
            "$$REMOVE"
          ]
        }
      },
      applied_sub_doc: {
        $push: "$revs"
      }
    },

  },
  // flatten array in $applied_sub_doc prop
  {
    $set: {
      applied_sub_doc: {
        $reduce: {
          input: "$applied_sub_doc",
          initialValue: [],
          in: {
            $concatArrays: [
              "$$value",
              "$$this"
            ],

          },

        },

      },

    },

  },
  {
    $project: {
      mixedDocs: {
        $concatArrays: [
          "$applied_doc",
          "$applied_sub_doc"
        ],

      },

    },

  },
  {
    $unwind: "$mixedDocs",

  },
  {
    $replaceWith: "$mixedDocs",

  },

])


问:
How to pass MFA enabled Azure account credentials into PowerShell ScriptBlock?

connect-azuread | out-null

$global:token = [Microsoft.Open.Azure.AD.CommonLibrary.AzureSession]::AccessTokens

$ceo = "<ceo_username>"

Import-Csv "C:\Users\abhilash\Music\users.txt" | ForEach-Object  {

$scriptblock = {

param($userprincipalname)

Connect-Azuread -AadAccessToken $global:token.AccessToken.AccessToken -accountid <my_username>

New-Object PSObject -property @{

Manager1 = $l = (Get-AzureADUserManager -ObjectId $userprincipalname).userprincipalname

Manager2 = $m = if ($l -ne $null -and $l -ne $CEO) { (Get-AzureADUserManager -ObjectId $l).userprincipalname } else { $null }

Manager3 = $n = if ($m -ne $null -and $m -ne $CEO) { (Get-AzureADUserManager -ObjectId $m).userprincipalname } else { $null }

Manager4 = $o = if ($n -ne $null -and $n -ne $CEO) { (Get-AzureADUserManager -ObjectId $n).userprincipalname } else { $null }

}  | Select @{N='User';E={$userprincipalname}},Manager1,Manager2,manager3,manager4

}

Start-Job $ScriptBlock -ArgumentList $_

}

While (Get-Job -State "Running") {  Start-Sleep 10 }

Get-job| receive-job

"You must call the Connect-AzureAD cmdlet before calling any other cmdlets" ...... I get this error even after having active session, tried connecting with accesstoken, now I get error as "Cannot validate argument on parameter 'AadAccessToken'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again."

答:
We have tried with your given code and its asking for users to add their credential for authentication.

AFAIK, we can not pass the MFA enabled azure account credential in PowerShell script.

So we have  to use the cmdlets to connect our services without using parameter Credential. This will show us the Sign in to our account popup (log-in window)of the services which has the support for MFA as below. We have provide the user account name in ceo and my username.

For more information please refer this BLOG & SO THREAD


问:
How to print lists in a scific order in kotlin?
im working on a project and i have a list in kotlin like:

```<code>val list = listOf("banana", "1","apple","3","banana","2")
</code>```

and i want to print it like

```<code>Output:
banana = 1
banana = 2
apple = 3
</code>```

so like every work with the number should be like one val, and i need to print in scific order (the order is toooo random for any sort command), so im panning on just coppying the whole xinhua dictionary here (since all chinese words have a scific unicode), and make the code it replace like:

```<code>val list = listOf("banana丨", "1","apple丩","3","banana丨","2")
</code>```

but how to print them in the order?

ps. even me as a chinese dont know most of the words in xinhua dictionary lol so there is more then enofe

答:
Assuming that you have the following input list, as shown in your question, where the order of occurrence is always one word followed by the scific order:

val list = listOf("banana", "1","apple","3","banana","2")
```
<p>You could do the following:</p>
<p><strong>1. Create a <code>data class</code> that defines one entry in your raw input list</strong></p>
<pre class="lang-kotlin prettyprint-override"><code>data class WordEntry(val word: String, val order: Int)
</code>```

2. Map over your raw input list by using the windowed and map methods

val dictionary = list.windowed(2, 2).map { WordEntry(it.first(), it.last().toInt()) }
```
<p>Here, the <code>windowed(2, 2)</code> method creates a window of size 2 and step 2, meaning that we iterate over the raw input list and always work with two entries at every second step. Assuming that the order in the raw input list is always the word followed by the scific order, this should work. Otherwise, this would not work, so the order is very important here!</p>
<p><strong>3. Sort the transformed <code>dictionary</code> by the <code>order</code> property</strong></p>
<pre class="lang-kotlin prettyprint-override"><code>val sortedDictionary = dictionary.sortedBy { it.order }
</code>```

Edit: You can also sort by any other property. Just pass another property to the lambda expression of sortedBy (e.g. sortedBy { it.word } if you want to sort it by the word property)

4. Finally, you can print out your sorted dictionary

val outputStr = sortedDictionary.joinToString("\n") { "${it.word} = ${it.order}" }

print(outputStr)
```
<p>Output:</p>
```banana = 1
banana = 2
apple = 3
```

Body:
im working on a project and i have a list in kotlin like:

val list = listOf("banana", "1","apple","3","banana","2")

and i want to print it like

Output:
banana = 1
banana = 2
apple = 3

so like every work with the number should be like one val, and i need to print in scific order (the order is toooo random for any sort command), so im panning on just coppying the whole xinhua dictionary here (since all chinese words have a scific unicode), and make the code it replace like:

val list = listOf("banana丨", "1","apple丩","3","banana丨","2")

but how to print them in the order?

ps. even me as a chinese dont know most of the words in xinhua dictionary lol so there is more then enofe

Body:
Assuming that you have the following input list, as shown in your question, where the order of occurrence is always one word followed by the scific order:

val list = listOf("banana", "1","apple","3","banana","2")

You could do the following:

1. Create a data class that defines one entry in your raw input list

data class WordEntry(val word: String, val order: Int)

2. Map over your raw input list by using the windowed and map methods

val dictionary = list.windowed(2, 2).map { WordEntry(it.first(), it.last().toInt()) }

Here, the windowed(2, 2) method creates a window of size 2 and step 2, meaning that we iterate over the raw input list and always work with two entries at every second step. Assuming that the order in the raw input list is always the word followed by the scific order, this should work. Otherwise, this would not work, so the order is very important here!

3. Sort the transformed dictionary by the order property

val sortedDictionary = dictionary.sortedBy { it.order }

Edit: You can also sort by any other property. Just pass another property to the lambda expression of sortedBy (e.g. sortedBy { it.word } if you want to sort it by the word property)

4. Finally, you can print out your sorted dictionary

val outputStr = sortedDictionary.joinToString("\n") { "${it.word} = ${it.order}" }

print(outputStr)

Output:

banana = 1
banana = 2
apple = 3


问:
Flutter Build Error: Process 'command 'E:\Flutter Apps\flutter\bin\flutter.bat'' finished with non-zero exit value 1
I got this error when I try to generate a signed apk in the android studio of my flutter app - Process 'command 'E:\Flutter Apps\flutter\bin\flutter.bat'' finished with non-zero exit value 1

I am able to run the app in both emulator and on my device but this error shows up only when I try to build a signed apk.

```<code>flutter doctor
[√] Flutter (Channel dev, v1.2.0, on Microsoft Windows [Version 10.0.17763.253], locale en-US)
[√] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
[√] Android Studio (version 3.3)
[√] VS Code (version 1.30.2)
[√] Connected device (1 available)

• No issues found!

</code>```

Any way to fix this?

Tried flutter clean

android studio Build > clean project and rebuild project(same error)

I am doing Build > Generated signed apk > apk > release > V1(Jar signature) > Finish to build the app

答:
I encounter the same message and go to Android Studio's setting :

Language & Framework -> Flutter -> Tick "Enable Verbose logging" , and run the build again the check the actual root cause .

In my case the root cause is recursive path in android/build folder, I delete the build folder and problem solved.

Body:
I got this error when I try to generate a signed apk in the android studio of my flutter app - Process 'command 'E:\Flutter Apps\flutter\bin\flutter.bat'' finished with non-zero exit value 1

I am able to run the app in both emulator and on my device but this error shows up only when I try to build a signed apk.

flutter doctor
[√] Flutter (Channel dev, v1.2.0, on Microsoft Windows [Version 10.0.17763.253], locale en-US)
[√] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
[√] Android Studio (version 3.3)
[√] VS Code (version 1.30.2)
[√] Connected device (1 available)

• No issues found!

Any way to fix this?

Tried flutter clean

android studio Build > clean project and rebuild project(same error)

I am doing Build > Generated signed apk > apk > release > V1(Jar signature) > Finish to build the app