问:
Write an htaccess file with specific rules
So basically I'm trying to write the below rules:

Assuming I have this website: www.example.com

HTTP -> redirect to -> HTTPS

www -> redirect to -> non-www

https://example.com/xyz -> rewrite to -> https//example.com/post.php?id=xyz

All these rules should be working at the same time. I tried the below sample:

```<code>RewriteRule ^(.*)$RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !\.(?:css|js|jpe?g|gif|png)$ [NC]
RewriteRule ^(.*)$ post.php?id=$1 [L]
</code>```

Thank you so much for your help.

答:
```<code>RewriteRule ^(.*)$RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !\.(?:css|js|jpe?g|gif|png)$ [NC]
RewriteRule ^(.*)$ post.php?id=$1 [L]
</code>```

Your first line looks like a typo(?) as it doesn't make sense.

Your second rule (a rewrite) is pretty much correct in order to rewrite the request to post.php?id=<url>. However, strictly speaking, the two conditions are in the wrong order considering the second condition is really only required for efficiency. Filesystem checks are relatively expensive, so you should be excluding requests for your static resources (using a regex string comparison) before resorting to a filesystem check.

So, before this rewrite you just need to add a HTTP to HTTPS and www to non-www redirect, which could be implemented as one or two rules.

Try the following instead:

```<code>RewriteEngine On

# HTTP to HTTPS and www to non-www generic redirect
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+?)\.?$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]

# Rewrite requests to "post.php"
RewriteCond %{REQUEST_URI} !\.(?:css|js|jpe?g|gif|png)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (.*) post.php?id=$1 [L]
</code>```

NB: Test first with a 302 (temporary) redirect to avoid potential caching issues.

%1 in the first rule is a backreference to the last matched CondPattern. ie. This holds the domain name, less the www. subdomain (if any).

With regards to the HTTP to HTTPS redirect, this does assume the SSL cert is installed directly on your application server and you aren't using a front-end proxy that is managing your SSL cert.

If you are not expecting URLs to contain .php extensions then you should also consider adding this to the list of stated extensions in the RewriteCond directive.

Body:
So basically I'm trying to write the below rules:

Assuming I have this website: www.example.com

HTTP -> redirect to -> HTTPS

www -> redirect to -> non-www

https://example.com/xyz -> rewrite to -> https//example.com/post.php?id=xyz

All these rules should be working at the same time. I tried the below sample:

RewriteRule ^(.*)$RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !\.(?:css|js|jpe?g|gif|png)$ [NC]
RewriteRule ^(.*)$ post.php?id=$1 [L]

Thank you so much for your help.

Body:
RewriteRule ^(.*)$RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !\.(?:css|js|jpe?g|gif|png)$ [NC]
RewriteRule ^(.*)$ post.php?id=$1 [L]

Your first line looks like a typo(?) as it doesn't make sense.

Your second rule (a rewrite) is pretty much correct in order to rewrite the request to post.php?id=<url>. However, strictly speaking, the two conditions are in the wrong order considering the second condition is really only required for efficiency. Filesystem checks are relatively expensive, so you should be excluding requests for your static resources (using a regex string comparison) before resorting to a filesystem check.

So, before this rewrite you just need to add a HTTP to HTTPS and www to non-www redirect, which could be implemented as one or two rules.

Try the following instead:

RewriteEngine On

# HTTP to HTTPS and www to non-www generic redirect
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+?)\.?$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]

# Rewrite requests to "post.php"
RewriteCond %{REQUEST_URI} !\.(?:css|js|jpe?g|gif|png)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (.*) post.php?id=$1 [L]

NB: Test first with a 302 (temporary) redirect to avoid potential caching issues.

%1 in the first rule is a backreference to the last matched CondPattern. ie. This holds the domain name, less the www. subdomain (if any).

With regards to the HTTP to HTTPS redirect, this does assume the SSL cert is installed directly on your application server and you aren't using a front-end proxy that is managing your SSL cert.

If you are not expecting URLs to contain .php extensions then you should also consider adding this to the list of stated extensions in the RewriteCond directive.


来源: stackexchange

问:
How to set different images alternately in listView's row?
I have a listview, in which I am fetching data from Twitter, I also show it in listView,
but I want to show different images in different rows of listView.

I used convert-view.setBackGroundResource(R.drawable.strip1);, it repeats this image in all rows, but I want to set it alternatively. How is it possible?

答:
You want to change your image from what criteria ?

For example you can do something like :

```<code>public View getView(int position, View convertView, ViewGroup parent) {
    MyCell resultView = (MyCell) convertView;
    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) MyActivity.this.getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.mycell, null);
    }
    if (position % 2 == 0) {
        convert-view.setBackGroundResource(R.drawable.strip1);
    } else {
        convert-view.setBackGroundResource(R.drawable.strip2);
    }
    return resultView;
}
</code>```

To have different background based on the cell's position parity.

ContentLicense: CC BY-SA 3.0

Body:
You want to change your image from what criteria ?

For example you can do something like :

public View getView(int position, View convertView, ViewGroup parent) {
    MyCell resultView = (MyCell) convertView;
    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) MyActivity.this.getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.mycell, null);
    }
    if (position % 2 == 0) {
        convert-view.setBackGroundResource(R.drawable.strip1);
    } else {
        convert-view.setBackGroundResource(R.drawable.strip2);
    }
    return resultView;
}

To have different background based on the cell's position parity.


问:
Error in /etc/nanorc in GIT for Windows, no /usr/share/nano
I got this error while using nano in Windows Terminal, with GIT-bash.</p>
```<code>$ nano .bashrc
Error in /etc/nanorc on line 237: Error expanding /usr/share/nano/*.nanorc: No such file or directory
</code>```

答:
run this command from git bash (as admin)

```<code>dos2unix /usr/share/nano/git.nanorc
</code>```

It fixes line breaks, which are different in Linux and Windows.

from :
https://www.scivision.dev/git-for-windows-nano-error-fix/

ContentLicense: CC BY-SA 4.0

Body:
I got this error while using nano in Windows Terminal, with GIT-bash.

$ nano .bashrc
Error in /etc/nanorc on line 237: Error expanding /usr/share/nano/*.nanorc: No such file or directory

Body:
run this command from git bash (as admin)

dos2unix /usr/share/nano/git.nanorc

It fixes line breaks, which are different in Linux and Windows.

from :
https://www.scivision.dev/git-for-windows-nano-error-fix/


问:
How can I intregate ESLint in a Vite+React project?
When I create a React application using Create React App, ESLint is included by default. That's why we don't want to integrate ESLint manually. But when I create a React application using Vite there doesn't exist any kind of linting like ESLint or JSLint .

How can I install ESLint in a Vite+React project?

答:
create-react-app has put their eslint rules into a dedicated package:

https://www.npmjs.com/package/eslint-config-react-app

Follow their instructions to set it up:

```<code>npm install --save-dev eslint-config-react-app eslint@^8.0.0
</code>```

or

```<code>yarn add -D eslint-config-react-app eslint@^8.0.0
</code>```

and then create an .eslintrc.json with this content:

{
  "extends": "react-app"
}
```
<p>This is already sufficient for VSCode to start linting in the editor. (provided you have an eslint plugin installed)</p>
<p>To manually trigger the linting process, you can add this to the <code>scripts</code> part of your <code>package.json</code>:</p>
<pre class="lang-json prettyprint-override"><code>{
  "scripts": {
    "lint": "eslint --max-warnings=0 src"
  }
}
</code>```

and run it via npm run lint or yarn lint.

You could also use vite-plugin-eslint to have vite give you feedback in the console.

Body:
create-react-app has put their eslint rules into a dedicated package:

https://www.npmjs.com/package/eslint-config-react-app

Follow their instructions to set it up:

npm install --save-dev eslint-config-react-app eslint@^8.0.0

or

yarn add -D eslint-config-react-app eslint@^8.0.0

and then create an .eslintrc.json with this content:

{
  "extends": "react-app"
}

This is already sufficient for VSCode to start linting in the editor. (provided you have an eslint plugin installed)

To manually trigger the linting process, you can add this to the scripts part of your package.json:

{
  "scripts": {
    "lint": "eslint --max-warnings=0 src"
  }
}

and run it via npm run lint or yarn lint.

You could also use vite-plugin-eslint to have vite give you feedback in the console.


问:
How to find long and lat from map url and then making it more dynamic by passing the long and lat as param
I am new to vue js and am stuck with embed google map url. I have google and searched a lot but not getting what I want.
I have this url for example:
"https://www.google.com/maps/embed?pb=!1m14!1m12!1m3!1d20041.58914746939!2d17.008093249999998!3d51.10479505!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!5e0!3m2!1spl!2spl!4v1644570663221!5m2!1spl!2spl";
and from this url I am  trying to get the lat and long, so I can make them more dynamic and not just hardcode it. Any help will be much appreciated!

So far I tried this below, i want to pass long and lat as param or as variable (  + lat + long...) :

```<code> computed: {
    src() {
      const url = "https://www.google.com/maps/embed?pb=";
      const params = new URLSearchParams({
        center: `${20041.58914746939},${17.008093249999998}`,
        zoom: 15,
        size: "300x300",
        maptype: "terrain",
      });
      return `${url}?${params}`;
    },
  },

</code>```
```<code>// also tried with this example ( nothing seems to work):

 computed: {
    src() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition((position) => {
          console.log(position.coords.latitude, position.coords.longitude);
          const url = "https://www.google.com/maps/embed?pb=";
          const myLatlng = `${position.coords.latitude} , ${position.coords.longitude}`;
          const params = new URLSearchParams({
            center: myLatlng,
            zoom: 15,
            size: "600x300",
            maptype: "terrain",
          });
          console.log("params", params);
          console.log("mylatlong", myLatlng);
          return `${url}?${params}`;
        });
      }
    },
  },

</code>```

and then using as props in Iframe:

```<code><template>
  <iframe :src="src" class="map" />
</template>

</code>```

答:
If the URL format is always the same, maybe you can just use RegExp like this:

const url = 'https://www.google.com/maps/embed?pb=!1m14!1m12!1m3!1d20041.58914746939!2d17.008093249999998!3d51.10479505!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!5e0!3m2!1spl!2spl!4v1644570663221!5m2!1spl!2spl';

const matchLat = url.match(/!2d.*!3d/g)[0].match(/d.*!/g)[0];
const matchLon = url.match(/!3d.*!2m/g)[0].match(/d.*!/g)[0];
const lat = matchLat.substr(1, matchLat.length - 2);
const lon = matchLon.substr(1, matchLon.length - 2);

console.log('Lat: ', lat);
console.log('Lon: ', lon);```

Body:
I am new to vue js and am stuck with embed google map url. I have google and searched a lot but not getting what I want.
I have this url for example:
"https://www.google.com/maps/embed?pb=!1m14!1m12!1m3!1d20041.58914746939!2d17.008093249999998!3d51.10479505!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!5e0!3m2!1spl!2spl!4v1644570663221!5m2!1spl!2spl";
and from this url I am  trying to get the lat and long, so I can make them more dynamic and not just hardcode it. Any help will be much appreciated!

So far I tried this below, i want to pass long and lat as param or as variable (  + lat + long...) :

 computed: {
    src() {
      const url = "https://www.google.com/maps/embed?pb=";
      const params = new URLSearchParams({
        center: `${20041.58914746939},${17.008093249999998}`,
        zoom: 15,
        size: "300x300",
        maptype: "terrain",
      });
      return `${url}?${params}`;
    },
  },

// also tried with this example ( nothing seems to work):

 computed: {
    src() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition((position) => {
          console.log(position.coords.latitude, position.coords.longitude);
          const url = "https://www.google.com/maps/embed?pb=";
          const myLatlng = `${position.coords.latitude} , ${position.coords.longitude}`;
          const params = new URLSearchParams({
            center: myLatlng,
            zoom: 15,
            size: "600x300",
            maptype: "terrain",
          });
          console.log("params", params);
          console.log("mylatlong", myLatlng);
          return `${url}?${params}`;
        });
      }
    },
  },

and then using as props in Iframe:

<template>

</template>


问:
Is it possible to access VS Codes theme properties programatically? Like, can a person use the VS Code API to change a theme color?

Programmatically Accessing VSCode Theme Properties

Is it possible to programmatically & dynamically get & set the colors of V.S. Code's theme property's using the V.S. Code API?

The snippet bellow demonstrates using The VSCode API, and its method, getConfiguration(), to change settings. I was hopping that something like this snippet would work from programmatically changing theme colors, but to no avail.

```<code>
    const workbenchConfig = vscode.workspace.getConfiguration('workspace');
    const themeColor = workbenchConfig.get(`colorTheme.${themeProperty}`);

    console.log(themeColor)

    // The argument colorTheme.${someColor} would is obviously replaced with the
    // theme's property that I want to access.

</code>```

I wanted to access the same object that the workbench.ColorCustomizations setting accesses, using the snippet above. My thinking was that I could set the theme colors in the same scope, that is used by workbench.colorCustomizations setting, but my attempt was without success.

答:
This has been a topic for a while. It depends where and how you want to use it. In webviews you can access theme colors as css variables as listed in the Theme Color reference and use them in your webview.

In the API you can get some workbench colors, like:

```<code>const wb_color = new vscode.ThemeColor ( 'activityBar.background' )
</code>```

This is probably of limited use though. You can also get the theme kind (e.g. light, dark, high contrast) of the window with

```<code>const theme = window.activeColorTheme.kind
</code>```

I am not aware of a proper way to set colors programmatically. Perhaps there are a few hackish solutions under the issue, dealing with this question here:
https://github.com/Microsoft/vscode/issues/32813

Body:
Programmatically Accessing VSCode Theme Properties

Is it possible to programmatically & dynamically get & set the colors of V.S. Code's theme property's using the V.S. Code API?

The snippet bellow demonstrates using The VSCode API, and its method, getConfiguration(), to change settings. I was hopping that something like this snippet would work from programmatically changing theme colors, but to no avail.

    const workbenchConfig = vscode.workspace.getConfiguration('workspace');
    const themeColor = workbenchConfig.get(`colorTheme.${themeProperty}`);

    console.log(themeColor)

    // The argument colorTheme.${someColor} would is obviously replaced with the
    // theme's property that I want to access.

I wanted to access the same object that the workbench.ColorCustomizations setting accesses, using the snippet above. My thinking was that I could set the theme colors in the same scope, that is used by workbench.colorCustomizations setting, but my attempt was without success.

Body:
This has been a topic for a while. It depends where and how you want to use it. In webviews you can access theme colors as css variables as listed in the Theme Color reference and use them in your webview.

In the API you can get some workbench colors, like:

const wb_color = new vscode.ThemeColor ( 'activityBar.background' )

This is probably of limited use though. You can also get the theme kind (e.g. light, dark, high contrast) of the window with

const theme = window.activeColorTheme.kind

I am not aware of a proper way to set colors programmatically. Perhaps there are a few hackish solutions under the issue, dealing with this question here:
https://github.com/Microsoft/vscode/issues/32813


答:
current_timestamp() returns a TimestampType column, the value of which is evaluated at query time as described in the docs. So that is 'computed'  each time your call show.

Returns the current timestamp at the start of query evaluation as a
TimestampType column. All calls of current_timestamp within the same
query return the same value.

Passing this column to a lit call doesn't change anything, if you check the source code you can see lit simply returns the column you called it with.

return col if isinstance(col, Column) else _invoke_function("lit",
col)

If you cal lit with something else than a column, e.g. a datetime object then a new column is created with this literal value. The literal being the datetime object returned from datetime.now(). This is a static value representing the time the datetime.now function was called.

Title: PySpark - Timestamp behavior

Body:
I'm trying to understand behaviour differences between pyspark.sql.currenttimestamp() and datetime.now()

If I create a Spark dataframe in DataBricks using these 2 mechanisms to create a timestamp column, everything works nicely as expected....

curDate2 = spark.range(10)\
  .withColumn("current_date_lit",F.lit(date.today()))\
  .withColumn("current_timestamp_lit",F.lit(F.current_timestamp()))\
  .withColumn("current_timestamp",F.current_timestamp())\
  .withColumn("now",F.lit(datetime.now()))

+---+----------------+---------------------+--------------------+--------------------+
| id|current_date_lit|current_timestamp_lit|   current_timestamp|                 now|
+---+----------------+---------------------+--------------------+--------------------+
|  0|      2022-02-12| 2022-02-12 16:40:...|2022-02-12 16:40:...|2022-02-12 16:40:...|
|  1|      2022-02-12| 2022-02-12 16:40:...|2022-02-12 16:40:...|2022-02-12 16:40:...|
|  2|      2022-02-12| 2022-02-12 16:40:...|2022-02-12 16:40:...|2022-02-12 16:40:...|
+---+----------------+---------------------+--------------------+--------------------+

However, when I then call show() on the dataframe a couple of minutes later the columns based on currenttimestamp() show me the time NOW (16:44) whilst the datetime.now() column shows me the timestamp from the first creation of the dataframe (16:40)

Clearly one column holds a literal value & the other enumerates the function at runtime but I'm at a loss to understand why they behave differently

show() a few mins later...

+---+----------------+---------------------+--------------------+--------------------+
| id|current_date_lit|current_timestamp_lit|   current_timestamp|                 now|
+---+----------------+---------------------+--------------------+--------------------+
|  0|      2022-02-12| 2022-02-12 16:44:...|2022-02-12 16:44:...|2022-02-12 16:40:...|
|  1|      2022-02-12| 2022-02-12 16:44:...|2022-02-12 16:44:...|2022-02-12 16:40:...|
|  2|      2022-02-12| 2022-02-12 16:44:...|2022-02-12 16:44:...|2022-02-12 16:40:...|
+---+----------------+---------------------+--------------------+--------------------+

Thanks - I hope this makes sense!


问:
How do I create a new column in a dataframe using values from another dataframe?
I have two dataframes, df_1 and df_2, where df_1 has several columns of "codes" and df_2 has the definitions for all of those codes:

```<code>df_1 = pd.DataFrame({
    'Age': [42, 35, 64, 53],
    'Code 1': [1234, 3452, 9583, 8753],
    'Code 2': [3857, np.nan, np.nan, 1234]})

df_2 = pd.DataFrame({
    'Code': [3452, 8753, 3857, 1234, 9583],
    'Code Def':['a', 'b', 'c', 'd', 'e']})
</code>```

How do I create a new column in df_1 that contains the definitions of all the codes from df_2 to look something like this?

```<code>Age  Code 1  Code 2  Code def
42    1234    3857    d, c
35    3452    NaN      a
64    9583    NaN      e
53    8753    1234    b, d
</code>```

I've tried using merge() to combine the two dataframes, but that doesn't work since I want to join on multiple columns in df_1 and just one column in df_2. I also tried creating empty columns in df_1 and filling them using if statements, but that got quite complicated.

Thanks!

答:
Here anther approach

```<code>x= dict(zip(df_2["Code"], df_2['Code Def']))
tmp = df_1[["Code 1","Code 2"]].replace({"Code 1":x,'Code 2':x}).fillna('')
df_1["Code Def"] = tmp["Code 1"]+ " " + tmp["Code 2"]
</code>```

output

```<code>   Age  Code 1  Code 2 Code Def
    0   42    1234  3857.0      d c
    1   35    3452     NaN       a
    2   64    9583     NaN       e
    3   53    8753  1234.0      b d
</code>```

Body:
I have two dataframes, df_1 and df_2, where df_1 has several columns of "codes" and df_2 has the definitions for all of those codes:

df_1 = pd.DataFrame({
    'Age': [42, 35, 64, 53],
    'Code 1': [1234, 3452, 9583, 8753],
    'Code 2': [3857, np.nan, np.nan, 1234]})

df_2 = pd.DataFrame({
    'Code': [3452, 8753, 3857, 1234, 9583],
    'Code Def':['a', 'b', 'c', 'd', 'e']})

How do I create a new column in df_1 that contains the definitions of all the codes from df_2 to look something like this?

Age  Code 1  Code 2  Code def
42    1234    3857    d, c
35    3452    NaN      a
64    9583    NaN      e
53    8753    1234    b, d

I've tried using merge() to combine the two dataframes, but that doesn't work since I want to join on multiple columns in df_1 and just one column in df_2. I also tried creating empty columns in df_1 and filling them using if statements, but that got quite complicated.

Thanks!

Body:
Here anther approach

x= dict(zip(df_2["Code"], df_2['Code Def']))
tmp = df_1[["Code 1","Code 2"]].replace({"Code 1":x,'Code 2':x}).fillna('')
df_1["Code Def"] = tmp["Code 1"]+ " " + tmp["Code 2"]

output

   Age  Code 1  Code 2 Code Def
    0   42    1234  3857.0      d c
    1   35    3452     NaN       a
    2   64    9583     NaN       e
    3   53    8753  1234.0      b d


问:
Discord.py program using 100% of a core
I have a Discord bot running in python on a Raspberry Pi 3B+. The purpose of this program is to send the lab status to our server by the push of a physical button. I've noticed that the program itself does not always want to cooperate and has been using 100% of a core at all times. I believe the hardware is still healthy and the only other thing that's running is the OS itself. htop reads that the individual program is using 98-101% of a core every time I check.</p>
```<code>from os import system
from datetime import date
from time import sleep

from gpiozero import LED, Button
import discord
from discord.ext import commands

import asyncio

# Pull in server token and channel ID
with open('/home/pi/EVC-Discord-Bot/token.txt', 'r') as f:
    TOKEN = f.read()
with open('/home/pi/EVC-Discord-Bot/channel.txt', 'r') as f:
    CHANNEL = f.read()

# Define bot properties
description = '''EVC Lab Bot'''
bot = commands.Bot(command_prefix='!', description=description)

# Define client
client = discord.Client()

# Button and LED GPIO pins
openbutton=Button(17)
pendingbutton=Button(27)
closedbutton=Button(22)
###
openlight=LED(4)
pendinglight=LED(23)
closedlight=LED(24)

# Saved Messages
openmessage=':green_circle: :radio_button: :radio_button: OPEN :green_circle: :radio_button: :radio_button:'
pendingmessage=':radio_button: :yellow_circle: :radio_button: PENDING :radio_button: :yellow_circle: :radio_button:'
closedmessage=':radio_button: :radio_button: :red_circle: CLOSED :radio_button: :radio_button: :red_circle:'

print('Program Initialized')

@bot.event
async def msg(status):
    # Define desired channel
    channel = bot.get_channel(int(CHANNEL))
    # Terminal print channel and status
    print('Bot channel: ' + str(channel))
    print('Channel int: ' + str(CHANNEL))
    print('Sending message...')
    # Print respective status
    if status == 'open':
        await channel.send(openmessage)
    elif status == 'pending':
        await channel.send(pendingmessage)
    elif status == 'closed':
        await channel.send(closedmessage)
    # Terminal print "completed"
    print('Finished.')

@bot.event
async def on_ready():
    # Tell me on_ready() def has started
    print('On ready!')
    # Endless while loop
    while True:
        # Open status
        if openbutton.is_pressed:
            # Show status in terminal
            print('Green Button Pressed')
            # Call server message function
            await msg('open')
            # Toggle open light
            openlight.on()
            # Toggle pending light
            pendinglight.off()
            # Toggle closed light
            closedlight.off()
            # Wait for active button to be released
            openbutton.wait_for_release()
            # Sleep for spam-safety
            sleep(10)
        # Pending status
        elif pendingbutton.is_pressed:
            # Show status in terminal
            print('Yellow Button Pressed')
            # Call server message function
            await msg('pending')
            # Toggle open light
            openlight.off()
            # Toggle pending light
            pendinglight.on()
            # Toggle closed light
            closedlight.off()
            # Wait for active button to be released
            pendingbutton.wait_for_release()
            # Sleep for spam-safety
            sleep(10)
        # Closed status
        elif closedbutton.is_pressed:
            # Show status in terminal
            print('Red Button Pressed')
            # Call server message function
            await msg('closed')
            # Toggle open light
            openlight.off()
            # Toggle pending light
            pendinglight.off()
            # Toggle closed light
            closedlight.on()
            # Wait for active button to be released
            closedbutton.wait_for_release()
            # Sleep for spam-safety
            sleep(10)

# Start bot
bot.run(TOKEN)
# Tell me the bot booted
print('Bot is booted')
</code>```

答:
If no button is pressed, your on_ready is basically

async def on_ready():
    print('On ready!')
    while True:
        pass
```

which of course hogs 100% CPU!

Title: Discord.py program using 100% of a core

Body:
I have a Discord bot running in python on a Raspberry Pi 3B+. The purpose of this program is to send the lab status to our server by the push of a physical button. I've noticed that the program itself does not always want to cooperate and has been using 100% of a core at all times. I believe the hardware is still healthy and the only other thing that's running is the OS itself. htop reads that the individual program is using 98-101% of a core every time I check.

from os import system
from datetime import date
from time import sleep

from gpiozero import LED, Button
import discord
from discord.ext import commands

import asyncio

# Pull in server token and channel ID
with open('/home/pi/EVC-Discord-Bot/token.txt', 'r') as f:
    TOKEN = f.read()
with open('/home/pi/EVC-Discord-Bot/channel.txt', 'r') as f:
    CHANNEL = f.read()

# Define bot properties
description = '''EVC Lab Bot'''
bot = commands.Bot(command_prefix='!', description=description)

# Define client
client = discord.Client()

# Button and LED GPIO pins
openbutton=Button(17)
pendingbutton=Button(27)
closedbutton=Button(22)
###
openlight=LED(4)
pendinglight=LED(23)
closedlight=LED(24)

# Saved Messages
openmessage=':green_circle: :radio_button: :radio_button: OPEN :green_circle: :radio_button: :radio_button:'
pendingmessage=':radio_button: :yellow_circle: :radio_button: PENDING :radio_button: :yellow_circle: :radio_button:'
closedmessage=':radio_button: :radio_button: :red_circle: CLOSED :radio_button: :radio_button: :red_circle:'

print('Program Initialized')

@bot.event
async def msg(status):
    # Define desired channel
    channel = bot.get_channel(int(CHANNEL))
    # Terminal print channel and status
    print('Bot channel: ' + str(channel))
    print('Channel int: ' + str(CHANNEL))
    print('Sending message...')
    # Print respective status
    if status == 'open':
        await channel.send(openmessage)
    elif status == 'pending':
        await channel.send(pendingmessage)
    elif status == 'closed':
        await channel.send(closedmessage)
    # Terminal print "completed"
    print('Finished.')

@bot.event
async def on_ready():
    # Tell me on_ready() def has started
    print('On ready!')
    # Endless while loop
    while True:
        # Open status
        if openbutton.is_pressed:
            # Show status in terminal
            print('Green Button Pressed')
            # Call server message function
            await msg('open')
            # Toggle open light
            openlight.on()
            # Toggle pending light
            pendinglight.off()
            # Toggle closed light
            closedlight.off()
            # Wait for active button to be released
            openbutton.wait_for_release()
            # Sleep for spam-safety
            sleep(10)
        # Pending status
        elif pendingbutton.is_pressed:
            # Show status in terminal
            print('Yellow Button Pressed')
            # Call server message function
            await msg('pending')
            # Toggle open light
            openlight.off()
            # Toggle pending light
            pendinglight.on()
            # Toggle closed light
            closedlight.off()
            # Wait for active button to be released
            pendingbutton.wait_for_release()
            # Sleep for spam-safety
            sleep(10)
        # Closed status
        elif closedbutton.is_pressed:
            # Show status in terminal
            print('Red Button Pressed')
            # Call server message function
            await msg('closed')
            # Toggle open light
            openlight.off()
            # Toggle pending light
            pendinglight.off()
            # Toggle closed light
            closedlight.on()
            # Wait for active button to be released
            closedbutton.wait_for_release()
            # Sleep for spam-safety
            sleep(10)

# Start bot
bot.run(TOKEN)
# Tell me the bot booted
print('Bot is booted')

Body:
If no button is pressed, your on_ready is basically

async def on_ready():
    print('On ready!')
    while True:
        pass

which of course hogs 100% CPU!


问:
mysql fetching data from server
When get new data from the database, does this mean a new connection? mysql database

Eg:

```<code> SELECT * FROM employees WHERE ID=1
</code>```

Does this mean a new connection on the database server?

答:
Does this mean a new connection on the database server?

If you are already connected then no

If you are not connected then yes

If your connection hit a timeout on no activity, or similar then yes

You can see your connections (as a normal user) using:

show processlist
```

https://dev.mysql.com/doc/refman/8.0/en/show-processlist.html

You can see the connection ID and if you are looking to see if your connection is changing then that will help.

Title: mysql fetching data from server

Body:
When get new data from the database, does this mean a new connection? mysql database

Eg:

 SELECT * FROM employees WHERE ID=1

Does this mean a new connection on the database server?

Body:
Does this mean a new connection on the database server?

If you are already connected then no

If you are not connected then yes

If your connection hit a timeout on no activity, or similar then yes

You can see your connections (as a normal user) using:

show processlist

https://dev.mysql.com/doc/refman/8.0/en/show-processlist.html

You can see the connection ID and if you are looking to see if your connection is changing then that will help.


问:
React router error " Objects are not valid as a React child..."
Im starting with react router and exporting and importing routes.
I have {casaRoutes} imported from a file

```<code>const routes=[
  <Route path="/casas/create" element={Create} exact key="create" />,
  <Route path="/casas/edit/:id" element={Update} exact key="update" />,
  <Route path="/casas/show/:id" element={Show} exact key="show" />,
  <Route path="/casas/" element={List} exact strict key="list" />,
  <Route path="/casas/:page" element={List} exact strict key="page" />,
];

export default  routes;
</code>```

But i still get this error Objects are not valid as a React child...

How can i render the imported routers ..

Im using "react-router-dom": "^6.2.1",

Thanks in advance

答:
What you could do is a React Component that exports your routes, or even doing so in your index.jsx

```<code>import { render } from "react-dom";
import {
  BrowserRouter,
  Routes,
  Route
} from "react-router-dom";
// import your route components too

    render(
      <BrowserRouter>
        <Routes>
          <Route path="/casas/create" element={Create} exact key="create" />,
          <Route path="/casas/edit/:id" element={Update} exact key="update" />,
          <Route path="/casas/show/:id" element={Show} exact key="show" />,
          <Route path="/casas/" element={List} exact strict key="list" />,
          <Route path="/casas/:page" element={List} exact strict key="page" />,
        </Routes>
      </BrowserRouter>,
      document.getElementById("root")
    );
</code>```

Find references in the docs:
https://reactrouter.com/docs/en/v6/getting-started/overview

Body:
Im starting with react router and exporting and importing routes.
I have {casaRoutes} imported from a file

const routes=[
  <Route path="/casas/create" element={Create} exact key="create" />,
  <Route path="/casas/edit/:id" element={Update} exact key="update" />,
  <Route path="/casas/show/:id" element={Show} exact key="show" />,
  <Route path="/casas/" element={List} exact strict key="list" />,
  <Route path="/casas/:page" element={List} exact strict key="page" />,
];

export default  routes;

But i still get this error Objects are not valid as a React child...

How can i render the imported routers ..

Im using "react-router-dom": "^6.2.1",

Thanks in advance

Body:
What you could do is a React Component that exports your routes, or even doing so in your index.jsx

import { render } from "react-dom";
import {
  BrowserRouter,
  Routes,
  Route
} from "react-router-dom";
// import your route components too

    render(
      <BrowserRouter>
        <Routes>
          <Route path="/casas/create" element={Create} exact key="create" />,
          <Route path="/casas/edit/:id" element={Update} exact key="update" />,
          <Route path="/casas/show/:id" element={Show} exact key="show" />,
          <Route path="/casas/" element={List} exact strict key="list" />,
          <Route path="/casas/:page" element={List} exact strict key="page" />,
        </Routes>
      </BrowserRouter>,
      document.getElementById("root")
    );

Find references in the docs:
https://reactrouter.com/docs/en/v6/getting-started/overview


问:
How is correct to write connection string in c# web API on .NET Core?
I write my connection string like that:

{
  "ConnectionStrings": {
    "AppCon": "Data Source=192.168.1.24:3306; Initial Catalog=dbName; User Id=UName; Password=Pass"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
```
<p>When I want to navigate in the url address I receive error:</p>
<blockquote>
<p>SocketException: No such host is known.</p>
</blockquote>
<p>and the debugger stuck at this method:</p>
<pre class="lang-cs prettyprint-override"><code>[HttpGet]
public JsonResult Get()
{
    string query = @"SELECT Station, Ime FROM auto_q_stations;";

    DataTable table = new DataTable();

    string sqlDataSource = _configuration.GetConnectionString("AppCon");

    MySqlDataReader myReader;

    using(MySqlConnection mycon = new MySqlConnection(sqlDataSource))
    {
        mycon.Open();
        using(MySqlCommand myCommand = new MySqlCommand(query, mycon))
        {
            myReader = myCommand.ExecuteReader();
            table.Load(myReader);

            myReader.Close();
            mycon.Close();
        }
    }
    return new JsonResult(table);
}
</code>```

at this line:

mycon.Open();
```

What do I need to do to properly load my database?

答:
Remove the :3306 from the connection string; 3306 is the default so you don't need to specify it. If you do want to specify a non standard port, put eg Data Source=192.168.1.24;Port=12345;Initial Catalog=..

You can see the full list of keywords you can use in a connection string at: https://dev.mysql.com/doc/dev/connector-net/6.10/html/P_MySql_Data_MySqlClient_MySqlConnection_ConnectionString.htm

Body:
I write my connection string like that:

{
  "ConnectionStrings": {
    "AppCon": "Data Source=192.168.1.24:3306; Initial Catalog=dbName; User Id=UName; Password=Pass"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"

When I want to navigate in the url address I receive error:

SocketException: No such host is known.

and the debugger stuck at this method:

[HttpGet]
public JsonResult Get()
{
    string query = @"SELECT Station, Ime FROM auto_q_stations;";

    DataTable table = new DataTable();

    string sqlDataSource = _configuration.GetConnectionString("AppCon");

    MySqlDataReader myReader;

    using(MySqlConnection mycon = new MySqlConnection(sqlDataSource))
    {
        mycon.Open();
        using(MySqlCommand myCommand = new MySqlCommand(query, mycon))
        {
            myReader = myCommand.ExecuteReader();
            table.Load(myReader);

            myReader.Close();
            mycon.Close();
        }
    }
    return new JsonResult(table);
}

at this line:

mycon.Open();

What do I need to do to properly load my database?


问:
IIS Express Does Not Recognize Running VS2022 as Admin
I had a computer with VS2019 Community installed. I got a new computer, copied my documents over, and installed VS2022 Community. I am launching VS as admin. In the upper-right corner of VS it says "Admin". Also, when launching VS I get the User Account Control prompt associated with launching as an admin. Yet when I build my solution and launch IIS Express, I get a message "...You do not have permission to access the IIS configuration file. Opening and creating web sites on IIS requires running Visual Studio under an Administrator account". Does anyone know what else to do or have a suggestion of what else to look at? Any help would be appreciated.</p>

答: Seems the message is a red herring. I incorrectly assumed that IIS Express was installed with VS. The solution was to install IIS Express.</p>


问:
How to concatenate values of multiple parameters for a list of objects?
I have JSON object like that

```<code>{
   "users":[
      {
         "FName":"Islam",
         "LName":"Mohamed",
         "Id": 1
      },
      {
         "FName":"Ali",
         "LName":"Amr",
         "Id": 2
      }
   ]
}
</code>```

I want to concatenate all FName and LName for each object to get String like that

```<code>val result: String = "Islam,Mohamed,Ali,Amr"
</code>```

What is the best way to do that using collection functions in Kotlin ?

答:
There is joinToString function

val result = users.joinToString(",") { "${it.fName},${it.lName}" }

Body:
I have JSON object like that

{
   "users":[
      {
         "FName":"Islam",
         "LName":"Mohamed",
         "Id": 1
      },
      {
         "FName":"Ali",
         "LName":"Amr",
         "Id": 2
      }
   ]
}

I want to concatenate all FName and LName for each object to get String like that

val result: String = "Islam,Mohamed,Ali,Amr"

What is the best way to do that using collection functions in Kotlin ?


问:
How to regain control over an Ubuntu Remote Desktop running on a Google Cloud VM after being locked out?
Following these instructions I set up a remote desktop computer running on a Google Cloud Virtual Machine. I had a perfectly functional Ubuntu 20.04 LTS machine controllable from my browser. I left it alone for a few minutes, and now the screen is locked:

I have not specified any password before. A simple enter does not let me in.

How can I regain control over this machine?

答: You can connect to your VM using SSH and then you log in as root using sudo su. Then you can change the password of any user using passwd USER_NAME


问:
How do I list all servers in a discord.js v12 bot
I'm trying to make a command so when you go ;listservers it brings a list of current servers the bot is in but my code is sending servers one at a time making it really slow is there anyway I could fix this? this is my current code</p>
```<code>    message.channel.send(`Found ${client.guilds.cache.size} servers\nServer List:`)
    client.guilds.cache.forEach(guild => {
        message.channel.send(`${guild.name} | ${guild.id}`)
    })
</code>```

答:
To list all servers in one message you can just use one line of code:</p>
```<code>message.channel.send(client.guilds.cache.map(m => `${m.name} | ${m.id}`).join("\n"))
</code>```

Body:
I'm trying to make a command so when you go ;listservers it brings a list of current servers the bot is in but my code is sending servers one at a time making it really slow is there anyway I could fix this? this is my current code

    message.channel.send(`Found ${client.guilds.cache.size} servers\nServer List:`)
    client.guilds.cache.forEach(guild => {
        message.channel.send(`${guild.name} | ${guild.id}`)
    })

Body:
To list all servers in one message you can just use one line of code:

message.channel.send(client.guilds.cache.map(m => `${m.name} | ${m.id}`).join("\n"))


问:
Why title, description goes off the screen and date not showing properly in constrainlayout
I am developing news app  and I have implemented constraint layout with  card view but title description not showing and title and description goes of the screen in real device  but in layout inspector in android studio it is showing fine

below my view

```<code><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

        <variable
            name="article"
            type="com.example.newsworldwide.model.Article" />
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    <androidx.cardview.widget.CardView
        android:id="@+id/cardView2"
        android:layout_width="0dp"
        android:layout_height="150dp"
        android:layout_marginHorizontal="16dp"
        android:layout_marginVertical="8dp"
        app:cardCornerRadius="12dp"
        app:cardElevation="10dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <de.hdodenhof.circleimageview.CircleImageView
            android:id="@+id/articleImage"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:layout_marginStart="4dp"
            android:elevation="16dp"
            android:src="@drawable/img"
            app:civ_border_width="2dp"
            app:imageUrl="@{article.urlToImage}"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"/>

        <TextView
            android:id="@+id/articleTitle"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginHorizontal="10dp"
            android:layout_marginTop="24dp"
            android:ellipsize="end"
            android:maxLines="2"
            android:text="Mini olive pies by Vaggelio"
            android:textColor="#000"
            android:textSize="18sp"
            android:textStyle="bold"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.65"
            app:layout_constraintStart_toEndOf="@+id/articleImage"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/articleDescription"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:layout_marginTop="16dp"
            android:ellipsize="end"
            android:maxLines="6"
            android:text="This is the most information savory snack that I have ever seen!!!"
            android:textColor="#000"
            android:textSize="12sp"
            android:textStyle="italic"
            app:layout_constraintStart_toStartOf="@+id/articleTitle"
            app:layout_constraintTop_toBottomOf="@+id/articleTitle" />

        <TextView
            android:id="@+id/articleDate"
            android:layout_width="wrap_content"
            android:layout_height="16dp"
            android:layout_marginEnd="48dp"
            android:layout_marginBottom="8dp"
            android:text="01.02.2022"
            android:textColor="#FF9935"
            android:textSize="12sp"
            android:textStyle="bold"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>
    </androidx.cardview.widget.CardView>
    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>
</code>```

below my  recyclerview layout

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="491dp"
        android:layout_height="826dp"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.506"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0"
        tools:listitem="@layout/news_item" />

    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="0dp"
        android:layout_height="48dp"
        android:layout_marginBottom="260dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

following screenshot from layout inspector in android studio

following screenshot of the app  from real device

I want to know where exactly I am making mistake what I have to do in order to show title description and date so that it can fit screen perfectly

答:
I've made some tweaks to your xml files

RecyclerView layout should look like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.506"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0"
        tools:listitem="@layout/news_item" />

    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="0dp"
        android:layout_height="48dp"
        android:layout_marginBottom="260dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Your mistake was right here:

```<code>android:layout_width="491dp"
android:layout_height="826dp"
</code>```

putting exact values for layout_width and layout_height is almost never a good idea when trying to build a responsive UI. Instead try using match_parent (matches the screen width) or wrap_content (takes as much space as it needs) in your layout_width/height.

Also I found one more thing wrong with news_item.xml

articleDescription TextView should have this parameter:

```<code>app:layout_constraintEnd_toEndOf="@+id/articleTitle"
</code>```

this parameter will make sure, that your textView end where the parent view ends, means not going out of screen.

Body:
I am developing news app  and I have implemented constraint layout with  card view but title description not showing and title and description goes of the screen in real device  but in layout inspector in android studio it is showing fine

below my view

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

        <variable
            name="article"
            type="com.example.newsworldwide.model.Article" />
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    <androidx.cardview.widget.CardView
        android:id="@+id/cardView2"
        android:layout_width="0dp"
        android:layout_height="150dp"
        android:layout_marginHorizontal="16dp"
        android:layout_marginVertical="8dp"
        app:cardCornerRadius="12dp"
        app:cardElevation="10dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <de.hdodenhof.circleimageview.CircleImageView
            android:id="@+id/articleImage"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:layout_marginStart="4dp"
            android:elevation="16dp"
            android:src="@drawable/img"
            app:civ_border_width="2dp"
            app:imageUrl="@{article.urlToImage}"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"/>

        <TextView
            android:id="@+id/articleTitle"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginHorizontal="10dp"
            android:layout_marginTop="24dp"
            android:ellipsize="end"
            android:maxLines="2"
            android:text="Mini olive pies by Vaggelio"
            android:textColor="#000"
            android:textSize="18sp"
            android:textStyle="bold"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.65"
            app:layout_constraintStart_toEndOf="@+id/articleImage"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/articleDescription"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:layout_marginTop="16dp"
            android:ellipsize="end"
            android:maxLines="6"
            android:text="This is the most information savory snack that I have ever seen!!!"
            android:textColor="#000"
            android:textSize="12sp"
            android:textStyle="italic"
            app:layout_constraintStart_toStartOf="@+id/articleTitle"
            app:layout_constraintTop_toBottomOf="@+id/articleTitle" />

        <TextView
            android:id="@+id/articleDate"
            android:layout_width="wrap_content"
            android:layout_height="16dp"
            android:layout_marginEnd="48dp"
            android:layout_marginBottom="8dp"
            android:text="01.02.2022"
            android:textColor="#FF9935"
            android:textSize="12sp"
            android:textStyle="bold"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>
    </androidx.cardview.widget.CardView>
    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

below my  recyclerview layout

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="491dp"
        android:layout_height="826dp"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.506"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0"
        tools:listitem="@layout/news_item" />

    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="0dp"
        android:layout_height="48dp"
        android:layout_marginBottom="260dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

following screenshot from layout inspector in android studio

following screenshot of the app  from real device

I want to know where exactly I am making mistake what I have to do in order to show title description and date so that it can fit screen perfectly

Body:
I've made some tweaks to your xml files

RecyclerView layout should look like this:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.506"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0"
        tools:listitem="@layout/news_item" />

    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="0dp"
        android:layout_height="48dp"
        android:layout_marginBottom="260dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Your mistake was right here:

android:layout_width="491dp"
android:layout_height="826dp"

putting exact values for layout_width and layout_height is almost never a good idea when trying to build a responsive UI. Instead try using match_parent (matches the screen width) or wrap_content (takes as much space as it needs) in your layout_width/height.

Also I found one more thing wrong with news_item.xml

articleDescription TextView should have this parameter:

app:layout_constraintEnd_toEndOf="@+id/articleTitle"

this parameter will make sure, that your textView end where the parent view ends, means not going out of screen.


问:
deploy static code to apache httpd server automatically
I have a static website that I would like to deploy to my Apache httpd server using Jenkins or any other methods.

my code base available in GitHub.
My files in server has to be updated in path: /var/www/html

答:
you could set Jenkins to Poll your Repository in Github. You will need to set up the integrations between Github and Jenkins so Jenkins can poll your Repo for changes. Then you can use a Copy tool of your choice, like Rsync or SCP, and run them in the Jenkins Script to copy the file to your server.

Jenkins Polling and SCM Management - https://www.softwaretestinghelp.com/jenkins-job-tutorial/