问:
How to update a clicked element using useState
kinda new to React and I am looking to use useState but only to be applied to the clicked element. For example:

```<code>const [backgroundColor, setBackgroundColor] = useState({background: "green"});
</code>```

in my function I have something like this:

```<code>function updateBackground(){
let updateColor = {background: "blue"};
setBackgroundColor(updateColor);
}
</code>```

then in my return JSX code I have

```<code>{subButtons.map(function(subButton, index){
   return (<div key={index} onClick={updateBackground} style={backgroundColor}>{subButton}</div>)
 })}
</code>```

but this will apply this function to all generated elements of the .map method.

How can I update my code to be applied to the clicked only element?

Thank you.

答:
```<code>const [backgroundColor, setBackgroundColor] = useState("green");

function updateBackground(){
  let updateColor = "blue"
  setBackgroundColor(updateColor);
}
</code>```

try this instead

Body:
kinda new to React and I am looking to use useState but only to be applied to the clicked element. For example:

const [backgroundColor, setBackgroundColor] = useState({background: "green"});

in my function I have something like this:

function updateBackground(){
let updateColor = {background: "blue"};
setBackgroundColor(updateColor);
}

then in my return JSX code I have

{subButtons.map(function(subButton, index){
   return (
{subButton}
)
 })}

but this will apply this function to all generated elements of the .map method.

How can I update my code to be applied to the clicked only element?

Thank you.

Body:
const [backgroundColor, setBackgroundColor] = useState("green");

function updateBackground(){
  let updateColor = "blue"
  setBackgroundColor(updateColor);
}

try this instead


来源: stackexchange

问:
Problem with creating EBS snapshot on server(Linux EC2 instance)
I am working on a task that required to run a script on a server, The script will grab instance id, create snapshot and run yum update -y command and reboot the server.

#!/bin/bash

set -eu

# Set Vars
AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
export REGION=$(curl --silent http://169.254.169.254/latest/meta-data/placement/availability-zone | sed 's/[a-z]$//')
export INSTANCE_ID=$(curl http://169.254.169.254/latest/meta-data/instance-id)
echo $AWS_ACCOUNT_ID
echo $REGION

# Fetch VolumeId
volumeid=$(aws ec2 describe-instances --region $REGION --instance-id "$INSTANCE_ID" --filters Name=instance-state-name,Values=running  --query "Reservations[*].Instances[].[BlockDeviceMappings[*].{VolumeName:Ebs.VolumeId}]" --output text)

echo $INSTANCE_ID
echo $volumeid

# Create snapshot
aws ec2 create-snapshot --region $REGION --volume-id $volumeid --description "Test-Snapshot-$INSTANCE_ID"
read -p "waiting a while to complete creation of EBS snapshot" -t 100
echo -e "\x1B[01;36m Snapshot has been created \x1B[0m"```
</div>
</div>
</p>

<p>I can get the Instance id but when I am trying to create snapshot id from Instance id, I am getting following error:</p>

<p><strong>ERROR</strong></p>

```us-east-1

An error occurred (UnauthorizedOperation) when calling the DescribeInstances operation: You are not authorized to perform this operation.
```

Thank you so much in advance for your support.

答:
Your IAM permissions do not grant access to DescribeInstances.

If you’re using an IAM role for the instance check it’s policies.

If it’s a user then make sure the credentials are being retrieved, either via aws credentials file or via environment variable

ContentLicense: CC BY-SA 4.0

Body:
I am working on a task that required to run a script on a server, The script will grab instance id, create snapshot and run yum update -y command and reboot the server.

#!/bin/bash

set -eu

# Set Vars
AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
export REGION=$(curl --silent http://169.254.169.254/latest/meta-data/placement/availability-zone | sed 's/[a-z]$//')
export INSTANCE_ID=$(curl http://169.254.169.254/latest/meta-data/instance-id)
echo $AWS_ACCOUNT_ID
echo $REGION

# Fetch VolumeId
volumeid=$(aws ec2 describe-instances --region $REGION --instance-id "$INSTANCE_ID" --filters Name=instance-state-name,Values=running  --query "Reservations[*].Instances[].[BlockDeviceMappings[*].{VolumeName:Ebs.VolumeId}]" --output text)

echo $INSTANCE_ID
echo $volumeid

# Create snapshot
aws ec2 create-snapshot --region $REGION --volume-id $volumeid --description "Test-Snapshot-$INSTANCE_ID"
read -p "waiting a while to complete creation of EBS snapshot" -t 100
echo -e "\x1B[01;36m Snapshot has been created \x1B[0m"

I can get the Instance id but when I am trying to create snapshot id from Instance id, I am getting following error:

ERROR

us-east-1

An error occurred (UnauthorizedOperation) when calling the DescribeInstances operation: You are not authorized to perform this operation.

Thank you so much in advance for your support.


问:
CircleCI takes environment variable as empty string-does not pickup value of environment variable
I am new to the CircleCI flow, and we are using cypress, CircleCI and yarn.
The person who did the CircleCI setup is not with us anymore. So I recently created a new test in cypress, which needs two additional environment variables.
I added the environment variables in cypress.json locally and the test runs fine.
Inorder for it to run in CircleCI, I added the environment variables in Environment Variables section in CircleCI (just the way the environment variables of other cypress tests have been set); and also added them to config.yml.
However, when the test is run from CircleCI, it is getting the value of those environment variables as empty string, I am not sure how to fix it.

Should the environment variables be set somewhere else too, other than config.yml and the Environment variables (in project settings in CircleCI)?
Why is it getting the value of the environment variables as empty?

Thanks!

答:
I resolved this. There was an error in the config.yml
The variable was inside ( ) brackets, where it should be enclosed in flower brackets.
I had it as password=$(PASSWORD)
whereas the right way to do it is password=${PASSWORD}</p>


问:
Images with BBcode (php, preg_replace). Security question
Bbcode question. This:

```<code>$text = preg_replace("@\[img\](.*)\[\/img\]@si",
"<img src=\"$1\" border=\"0\" />", $text);
</code>```

works fine, but at the same time it's a big security problem, for example:

```<code>[img]http://www.domain.com/delete-account/[/img]
</code>```

or

```<code>[img]http://www.domain.com/logout/[/img]
</code>```

Any ideas how to control this so that only image links which ends with .jpg are being converted into html?

```<code>[img]http://www.domain.com/image.jpg[/img]
</code>```

Thanks.

答:
One way to think about this problem is as well to check on server side that GEt and POST request are not equivalent.

A POST request can alter data in server side, a GET request musn't change anything. That's the HTTP protocol. An IMG tag is a GET request, always. And the browser can perform this GET request without any risk, so the problem is on server side, every action that can change alter data (database, session, etc) must check the request is a POST one. For example your /post or /delete-account url, should return either a 403 or a 200 code but with a form page, asking for a POST confirmation. If this is wrong in your application, then you'll have problems not only with altered IMG tags, but maybe as well with 'html page speeders' that make preload of GET referecnes, or even bots.

If you can find a copy of this excellent book you may find some advanced image links problems and filtering tricks. For example links on foreign websites can sometime be a problem. But this is a problem far more complex than starting by handling GET and POST requests in a convenient way.

ContentLicense: CC BY-SA 3.0

Body:
Bbcode question. This:

$text = preg_replace("@\[img\](.*)\[\/img\]@si",
"", $text);

works fine, but at the same time it's a big security problem, for example:

[img]http://www.domain.com/delete-account/[/img]

or

[img]http://www.domain.com/logout/[/img]

Any ideas how to control this so that only image links which ends with .jpg are being converted into html?

[img]http://www.domain.com/image.jpg[/img]

Thanks.


问:
How can I compare time in SQL Server?
I'm trying to compare time in a datetime field in a SQL query, but I don't know if it's right. I don't want to compare the date part, just the time part.

I'm doing this:

```<code>SELECT timeEvent
FROM tbEvents
WHERE convert(datetime, startHour, 8) >= convert(datetime, @startHour, 8)
</code>```

Is it correct?

I'm asking this because I need to know if 08:00:00 is less or greater than 07:30:00 and I don't want to compare the date, just the time part.

Thanks!

答:
TL;DR

Separate the time value from the date value if you want to use indexes in your search (you probably should, for performance). You can: (1) use function-based indexes or (2) create a new column for time only, index this column and use it in you SELECT clause.

Keep in mind you will lose any index performance boost if you use functions in a SQL's WHERE clause, the engine has to do a scan search. Just run your query with EXPLAIN SELECT... to confirm this. This happens because the engine has to process EVERY value in the field for EACH comparison, and the converted value is not indexed.

Most answers say to use float(), convert(), cast(), addtime(), etc.. Again, your database won't use indexes if you do this. For small tables that may be OK.

It is OK to use functions in WHERE params though (where field = func(value)), because you won't be changing EACH field's value in the table.

In case you want to keep use of indexes, you can create a function-based index for the time value. The proper way to do this (and support for it) may depend on your database engine. Another option is adding a column to store only the time value and index this column, but try the former approach first.

Edit 06-02

Do some performance tests before updating your database to have a new time column or whatever to make use of indexes. In my tests, I found out the performance boost was minimal (when I could see some improvement) and wouldn't be worth the trouble and overhead of adding a new index.

Title: How can I compare time in SQL Server?

Body:
I'm trying to compare time in a datetime field in a SQL query, but I don't know if it's right. I don't want to compare the date part, just the time part.

I'm doing this:

SELECT timeEvent
FROM tbEvents
WHERE convert(datetime, startHour, 8) >= convert(datetime, @startHour, 8)

Is it correct?

I'm asking this because I need to know if 08:00:00 is less or greater than 07:30:00 and I don't want to compare the date, just the time part.

Thanks!


问:
including specific header files with same names in different directories
Here is a sample of my directory structure:

```<code>TopDir
|-Makefile
|-Dir1
   |- A.c
   |- A.h
   |- Config.h
|-Dir2
   |- B.c
   |- B.h
   |- Config.h
</code>```

This is my straight forward code (Every sub directory follows the same pattern):

```<code>In file Config.h
# SomeConfig

in file A.h
#include "Config.h"

in file A.c
#include "A.h"
</code>```

And here is my Makefile:

```<code>CC = gcc
INC_DIR = -IDir1 \
          -IDir2
CFLAGS = -Wall -Wextra -pedantic $(INC_DIR)
AExe: A.c
    $(CC) $(CFLAGS) -o $@ $
BExe: A.c B.c
    $(CC) $(CFLAGS) -o $@ $
</code>```

When I compile, i just call:

```<code>$make AExe
</code>```

or

```<code>$make BExe
</code>```

My problem here is I am unable to include/build a Config specific to its own directory because of -I rule which just blindly picks the first Config.h it finds. AExe builds fine including its own Config. However BExe first finds the Config.h in Dir1 and ignores the Config.h in Dir2. If i reverse the INC_DIR order to include Dir2 first then B.h gets the right Config. In my case I have more directories with similar structure and they all could have dependencies on other directories header files only. Configs are meant for the specific directory. How do I instruct in Makefile to tell A.h to make using its own Config.h and B.h to use its own Config.h.

答:
This is a case where something like

```<code>#include "Dir1/Config.h"
</code>```

might make sense. But if you want to keep the source files (including headers) as they are, we must adjust the makefile.

BExe is made of A.c and B.c. We can see that A.c includes one Config.h, and presumably B.c includes the other, so we will have two #include "Config.h" statements that refer to different files, so we cannot process them with one command and hope to keep them straight. We must compile them separately and then link the object files:

```<code>A.o: A.c
    ...

B.o: B.c
    ...

AExe: A.o
    $(CC) $(CFLAGS) -o $@ $^

BExe: A.o B.o
    $(CC) $(CFLAGS) -o $@ $^
</code>```

Now for the .... You must tell Make how to find the source files A.c and B.c, but once you do, it will search for included files (such as Config.h) in the directory of the source file that includes them. So it will use Dir1/Config.h when compiling Dir/A.c, and Dir2/Config.h when compiling Dir2/B.c.

The only thing left is to tell Make where to find A.c and B.c. You can do this explicitly:

```<code>A.o: Dir1/A.c
    ...

B.o: Dir2/B.c
    ...
</code>```

or use something like the vpath directive:

```<code>vpath %.c Dir1 Dir2

A.o: A.c
    ...

B.o: B.c
    ...
</code>```

Body:
Here is a sample of my directory structure:

TopDir
|-Makefile
|-Dir1
   |- A.c
   |- A.h
   |- Config.h
|-Dir2
   |- B.c
   |- B.h
   |- Config.h

This is my straight forward code (Every sub directory follows the same pattern):

In file Config.h
# SomeConfig

in file A.h
#include "Config.h"

in file A.c
#include "A.h"

And here is my Makefile:

CC = gcc
INC_DIR = -IDir1 \
          -IDir2
CFLAGS = -Wall -Wextra -pedantic $(INC_DIR)
AExe: A.c
    $(CC) $(CFLAGS) -o $@ $
BExe: A.c B.c
    $(CC) $(CFLAGS) -o $@ $

When I compile, i just call:

$make AExe

or

$make BExe

My problem here is I am unable to include/build a Config specific to its own directory because of -I rule which just blindly picks the first Config.h it finds. AExe builds fine including its own Config. However BExe first finds the Config.h in Dir1 and ignores the Config.h in Dir2. If i reverse the INC_DIR order to include Dir2 first then B.h gets the right Config. In my case I have more directories with similar structure and they all could have dependencies on other directories header files only. Configs are meant for the specific directory. How do I instruct in Makefile to tell A.h to make using its own Config.h and B.h to use its own Config.h.

Body:
This is a case where something like

#include "Dir1/Config.h"

might make sense. But if you want to keep the source files (including headers) as they are, we must adjust the makefile.

BExe is made of A.c and B.c. We can see that A.c includes one Config.h, and presumably B.c includes the other, so we will have two #include "Config.h" statements that refer to different files, so we cannot process them with one command and hope to keep them straight. We must compile them separately and then link the object files:

A.o: A.c
    ...

B.o: B.c
    ...

AExe: A.o
    $(CC) $(CFLAGS) -o $@ $^

BExe: A.o B.o
    $(CC) $(CFLAGS) -o $@ $^

Now for the .... You must tell Make how to find the source files A.c and B.c, but once you do, it will search for included files (such as Config.h) in the directory of the source file that includes them. So it will use Dir1/Config.h when compiling Dir/A.c, and Dir2/Config.h when compiling Dir2/B.c.

The only thing left is to tell Make where to find A.c and B.c. You can do this explicitly:

A.o: Dir1/A.c
    ...

B.o: Dir2/B.c
    ...

or use something like the vpath directive:

vpath %.c Dir1 Dir2

A.o: A.c
    ...

B.o: B.c
    ...


问:
Python MySQLdb - Connection in a class
I am making a Python project where I have to seek and retreive data from a database.

I tried making a class, in which I declare the connection and do my queries, here is moreless what I have so far.

```<code>import MySQLdb
dbc =("localhost","root","1234","users")
class sql:
    db = MySQLdb.connect(dbc[0],dbc[1],dbc[2],dbc[3])
    cursor = db.cursor()

    def query(self,sql):
        sql.cursor.execute(sql)
        return sql.cursor.fetchone()

    def rows(self):
        return sql.cursor.rowcount

sqlI = sql()
print(sqlI.query("SELECT `current_points` FROM `users` WHERE `nick` = 'username';"))
</code>```

So, the main problem is that the variable db and cursor are not callable from other def's/functions from the same Class. What I'd like to get, is a polished query, where I can make queries and retreive it's content. This would summarize my code, therefore I should do.

答:
```<code>from config import Config
import MySQLdb

class Connection:
    def __init__(self):
        self.db=MySQLdb.connect(
            Config.DATABASE_CONFIG['server'],
            Config.DATABASE_CONFIG['user'],
            Config.DATABASE_CONFIG['password'],
            Config.DATABASE_CONFIG['name']
            )
        self.db.autocommit(True)
        self.db.set_character_set('utf8mb4')
        self.cur=self.db.cursor()
</code>```

EXAMPLE CONFIG CLASS(config.py):

```<code>class Config(object):

  DATABASE_CONFIG = {
          'server': 'localhost',
          'user': 'dbuser',
          'password': 'password',
          'name': 'dbname',
          }
</code>```

Title: Python MySQLdb - Connection in a class

Body:
I am making a Python project where I have to seek and retreive data from a database.

I tried making a class, in which I declare the connection and do my queries, here is moreless what I have so far.

import MySQLdb
dbc =("localhost","root","1234","users")
class sql:
    db = MySQLdb.connect(dbc[0],dbc[1],dbc[2],dbc[3])
    cursor = db.cursor()

    def query(self,sql):
        sql.cursor.execute(sql)
        return sql.cursor.fetchone()

    def rows(self):
        return sql.cursor.rowcount

sqlI = sql()
print(sqlI.query("SELECT `current_points` FROM `users` WHERE `nick` = 'username';"))

So, the main problem is that the variable db and cursor are not callable from other def's/functions from the same Class. What I'd like to get, is a polished query, where I can make queries and retreive it's content. This would summarize my code, therefore I should do.

Body:
from config import Config
import MySQLdb

class Connection:
    def __init__(self):
        self.db=MySQLdb.connect(
            Config.DATABASE_CONFIG['server'],
            Config.DATABASE_CONFIG['user'],
            Config.DATABASE_CONFIG['password'],
            Config.DATABASE_CONFIG['name']
            )
        self.db.autocommit(True)
        self.db.set_character_set('utf8mb4')
        self.cur=self.db.cursor()

EXAMPLE CONFIG CLASS(config.py):

class Config(object):

  DATABASE_CONFIG = {
          'server': 'localhost',
          'user': 'dbuser',
          'password': 'password',
          'name': 'dbname',
          }


问:
Trying to make an HP bar for a game using HTML/JavaScript
I'm trying to make a health bar for a game where I have 2 buttons linked to the bar, one adds damage and the other adds health. I have it all designed the way I want it but am having trouble with the JavaScript part. The buttons are linked but when I click to add damage or health it only adjusts the amount of HP by one in either direction but no more than that. I also can't figure out how to make the width of the bar move with the number associated with the amount of health. I think I'm close but just need a little help. I'll add the CSS code too so there is some more context.

function add() {
  let addHealth = document.getElementById('health')
  let width = 100;
  addHealth.width += 1;

  if (addHealth) {
    addHealth.style.width = width + '%';
    addHealth.innerHTML = width * 1 + 'hp';
  }
}

function remove() {
  let damage = document.getElementById('health')
  let width = 100;
  damage.width -= 1;

  if (damage) {
    damage.style.width = width + '%';
    damage.innerHTML = width - 1 + 'hp';
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hp {
  text-align: center;
  padding-bottom: 50px;
}

.gage {
  display: inline-block;
  width: 500px;
  padding-bottom: 30px;
}

.bar {
  height: 60px;
  position: relative;
  background: #555;
  -moz-border-radius: 25px;
  -webkit-border-radius: 25px;
  border-radius: 25px;
  padding: 10px;
  box-shadow: inset 0 -1px 1px rgba(255, 255, 255, 0.3);
}

.bar>span {
  display: block;
  height: 100%;
  border-top-right-radius: 8px;
  border-bottom-right-radius: 8px;
  border-top-left-radius: 20px;
  border-bottom-left-radius: 20px;
  background-color: rgb(43, 194, 83);
  background-image: linear-gradient( center bottom, rgb(43, 194, 83) 37%, rgb(84, 240, 84) 69%);
  box-shadow: inset 0 2px 9px rgba(255, 255, 255, 0.3), inset 0 -2px 6px rgba(0, 0, 0, 0.4);
  position: relative;
  overflow: hidden;
}

.lvl {
  background-color: #078a25;
  background-image: linear-gradient(to bottom, #078a25, #f36d0a);
}

#health {
  font-size: 20px;
  color: white;
  font-weight: bold;
  text-align: right;
}

.btn-3d {
  position: relative;
  display: inline-block;
  font-size: 22px;
  padding: 20px 60px;
  color: white;
  margin: 20px 10px 10px;
  border-radius: 6px;
  text-align: center;
  transition: top .01s linear;
  text-shadow: 0 1px 0 rgba(0, 0, 0, 0.15);
  cursor: pointer;
}

.btn-3d.green:hover {
  background-color: #80C49D;
}

.btn-3d:active {
  top: 9px;
}

.btn-3d.green {
  background-color: #82c8a0;
  box-shadow: 0 0 0 1px #82c8a0 inset, 0 0 0 2px rgba(255, 255, 255, 0.15) inset, 0 8px 0 0 rgba(126, 194, 155, .7), 0 8px 0 1px rgba(0, 0, 0, .4), 0 8px 8px 1px rgba(0, 0, 0, 0.5);
}

.btn-3d.green:active {
  box-shadow: 0 0 0 1px #82c8a0 inset, 0 0 0 2px rgba(255, 255, 255, 0.15) inset, 0 0 0 1px rgba(0, 0, 0, 0.4);
}

.btn-3d.red:hover {
  background-color: #e74c3c;
}

.btn-3d.red {
  background-color: #e74c3c;
  box-shadow: 0 0 0 1px #c63702 inset, 0 0 0 2px rgba(255, 255, 255, 0.15) inset, 0 8px 0 0 #C24032, 0 8px 0 1px rgba(0, 0, 0, 0.4), 0 8px 8px 1px rgba(0, 0, 0, 0.5);
}

.btn-3d.red:active {
  box-shadow: 0 0 0 1px #c63702 inset, 0 0 0 2px rgba(255, 255, 255, 0.15) inset, 0 0 0 1px rgba(0, 0, 0, 0.4);
}</code>```

      100hp

    Health
    Damage

```

Also, if anyone has any ideas to improve the design I'm all ears!

答:
In your example you merely change the output but never the actual health width itself. Here is a quick analysis

```<code>function add() {
    //REM: You fetch the element correctly;
    let addHealth = document.getElementById('health')
    //REM: You reset the heath to 100 for some reason?
    let width = 100;
    //REM: You change a width property of the element?
    //REM: Here you should reduce the value of width
    addHealth.width += 1;

    if (addHealth) {
        //REM: You set the width of the element according to the health, which seems correct
        addHealth.style.width = width + '%';
        //REM: You set the displayed value to 100, since width always gets set to 100 inside the function
        addHealth.innerHTML = width * 1  + 'hp';
    }
}
</code>```

The most simple way is to store the health in a seperate variable and build on that.

var _Health = 100; //REM: Default HP

function add() {
 let addHealth = document.getElementById('health')
 _Health += 1;

 if (addHealth) {
  addHealth.style.width = _Health + '%';
     addHealth.innerHTML = _Health + 'hp';
    }
}

function remove() {
 let damage = document.getElementById('health')
 _Health -= 1;

 if(damage) {
  damage.style.width = _Health + '%';
      damage.innerHTML = _Health + 'hp';
 }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hp {
 text-align: center;
 padding-bottom: 50px;
}

.gage {
 display: inline-block;
 width: 500px;
 padding-bottom: 30px;
}

.bar {
 height: 60px;
 position: relative;
 background: #555;
 -moz-border-radius: 25px;
 -webkit-border-radius: 25px;
 border-radius: 25px;
 padding: 10px;
 box-shadow: inset 0 -1px 1px rgba(255,255,255,0.3);
}

.bar > span {
  display: block;
  height: 100%;
  border-top-right-radius: 8px;
  border-bottom-right-radius: 8px;
  border-top-left-radius: 20px;
  border-bottom-left-radius: 20px;
  background-color: rgb(43,194,83);
  background-image: linear-gradient(
    center bottom,
    rgb(43,194,83) 37%,
    rgb(84,240,84) 69%
  );
  box-shadow:
    inset 0 2px 9px  rgba(255,255,255,0.3),
    inset 0 -2px 6px rgba(0,0,0,0.4);
  position: relative;
  overflow: hidden;
}

.lvl {
  background-color: #078a25;
  background-image: linear-gradient(to bottom, #078a25, #f36d0a);
}

#health {
 font-size: 20px;
 color: white;
 font-weight: bold;
 text-align: right;
}

.btn-3d {
 position: relative;
 display: inline-block;
 font-size: 22px;
 padding: 20px 60px;
 color: white;
 margin: 20px 10px 10px;
 border-radius: 6px;
 text-align: center;
 transition: top .01s linear;
 text-shadow: 0 1px 0 rgba(0,0,0,0.15);
 cursor: pointer;
}

.btn-3d.green:hover  {background-color: #80C49D;}

.btn-3d:active {
 top: 9px;
}

.btn-3d.green {
 background-color: #82c8a0;
 box-shadow: 0 0 0 1px #82c8a0 inset,
    0 0 0 2px rgba(255,255,255,0.15) inset,
    0 8px 0 0 rgba(126, 194, 155, .7),
    0 8px 0 1px rgba(0,0,0,.4),
    0 8px 8px 1px rgba(0,0,0,0.5);
}
.btn-3d.green:active {
 box-shadow: 0 0 0 1px #82c8a0 inset,
    0 0 0 2px rgba(255,255,255,0.15) inset,
    0 0 0 1px rgba(0,0,0,0.4);
}

.btn-3d.red:hover    {background-color: #e74c3c;}

.btn-3d.red {
 background-color: #e74c3c;
 box-shadow: 0 0 0 1px #c63702 inset,
        0 0 0 2px rgba(255,255,255,0.15) inset,
        0 8px 0 0 #C24032,
        0 8px 0 1px rgba(0,0,0,0.4),
    0 8px 8px 1px rgba(0,0,0,0.5);
}
.btn-3d.red:active {
 box-shadow: 0 0 0 1px #c63702 inset,
    0 0 0 2px rgba(255,255,255,0.15) inset,
    0 0 0 1px rgba(0,0,0,0.4);
}</code>```

    100hp

   Health
   Damage

```

Body:
I'm trying to make a health bar for a game where I have 2 buttons linked to the bar, one adds damage and the other adds health. I have it all designed the way I want it but am having trouble with the JavaScript part. The buttons are linked but when I click to add damage or health it only adjusts the amount of HP by one in either direction but no more than that. I also can't figure out how to make the width of the bar move with the number associated with the amount of health. I think I'm close but just need a little help. I'll add the CSS code too so there is some more context.

function add() {
  let addHealth = document.getElementById('health')
  let width = 100;
  addHealth.width += 1;

  if (addHealth) {
    addHealth.style.width = width + '%';
    addHealth.innerHTML = width * 1 + 'hp';
  }
}

function remove() {
  let damage = document.getElementById('health')
  let width = 100;
  damage.width -= 1;

  if (damage) {
    damage.style.width = width + '%';
    damage.innerHTML = width - 1 + 'hp';
  }
}

.hp {
  text-align: center;
  padding-bottom: 50px;
}

.gage {
  display: inline-block;
  width: 500px;
  padding-bottom: 30px;
}

.bar {
  height: 60px;
  position: relative;
  background: #555;
  -moz-border-radius: 25px;
  -webkit-border-radius: 25px;
  border-radius: 25px;
  padding: 10px;
  box-shadow: inset 0 -1px 1px rgba(255, 255, 255, 0.3);
}

.bar>span {
  display: block;
  height: 100%;
  border-top-right-radius: 8px;
  border-bottom-right-radius: 8px;
  border-top-left-radius: 20px;
  border-bottom-left-radius: 20px;
  background-color: rgb(43, 194, 83);
  background-image: linear-gradient( center bottom, rgb(43, 194, 83) 37%, rgb(84, 240, 84) 69%);
  box-shadow: inset 0 2px 9px rgba(255, 255, 255, 0.3), inset 0 -2px 6px rgba(0, 0, 0, 0.4);
  position: relative;
  overflow: hidden;
}

.lvl {
  background-color: #078a25;
  background-image: linear-gradient(to bottom, #078a25, #f36d0a);
}

#health {
  font-size: 20px;
  color: white;
  font-weight: bold;
  text-align: right;
}

.btn-3d {
  position: relative;
  display: inline-block;
  font-size: 22px;
  padding: 20px 60px;
  color: white;
  margin: 20px 10px 10px;
  border-radius: 6px;
  text-align: center;
  transition: top .01s linear;
  text-shadow: 0 1px 0 rgba(0, 0, 0, 0.15);
  cursor: pointer;
}

.btn-3d.green:hover {
  background-color: #80C49D;
}

.btn-3d:active {
  top: 9px;
}

.btn-3d.green {
  background-color: #82c8a0;
  box-shadow: 0 0 0 1px #82c8a0 inset, 0 0 0 2px rgba(255, 255, 255, 0.15) inset, 0 8px 0 0 rgba(126, 194, 155, .7), 0 8px 0 1px rgba(0, 0, 0, .4), 0 8px 8px 1px rgba(0, 0, 0, 0.5);
}

.btn-3d.green:active {
  box-shadow: 0 0 0 1px #82c8a0 inset, 0 0 0 2px rgba(255, 255, 255, 0.15) inset, 0 0 0 1px rgba(0, 0, 0, 0.4);
}

.btn-3d.red:hover {
  background-color: #e74c3c;
}

.btn-3d.red {
  background-color: #e74c3c;
  box-shadow: 0 0 0 1px #c63702 inset, 0 0 0 2px rgba(255, 255, 255, 0.15) inset, 0 8px 0 0 #C24032, 0 8px 0 1px rgba(0, 0, 0, 0.4), 0 8px 8px 1px rgba(0, 0, 0, 0.5);
}

.btn-3d.red:active {
  box-shadow: 0 0 0 1px #c63702 inset, 0 0 0 2px rgba(255, 255, 255, 0.15) inset, 0 0 0 1px rgba(0, 0, 0, 0.4);
}

      100hp

    Health
    Damage

Also, if anyone has any ideas to improve the design I'm all ears!

Body:
In your example you merely change the output but never the actual health width itself. Here is a quick analysis

function add() {
    //REM: You fetch the element correctly;
    let addHealth = document.getElementById('health')
    //REM: You reset the heath to 100 for some reason?
    let width = 100;
    //REM: You change a width property of the element?
    //REM: Here you should reduce the value of width
    addHealth.width += 1;

    if (addHealth) {
        //REM: You set the width of the element according to the health, which seems correct
        addHealth.style.width = width + '%';
        //REM: You set the displayed value to 100, since width always gets set to 100 inside the function
        addHealth.innerHTML = width * 1  + 'hp';
    }
}

The most simple way is to store the health in a seperate variable and build on that.

var _Health = 100; //REM: Default HP

function add() {
 let addHealth = document.getElementById('health')
 _Health += 1;

 if (addHealth) {
  addHealth.style.width = _Health + '%';
     addHealth.innerHTML = _Health + 'hp';
    }
}

function remove() {
 let damage = document.getElementById('health')
 _Health -= 1;

 if(damage) {
  damage.style.width = _Health + '%';
      damage.innerHTML = _Health + 'hp';
 }
}

.hp {
 text-align: center;
 padding-bottom: 50px;
}

.gage {
 display: inline-block;
 width: 500px;
 padding-bottom: 30px;
}

.bar {
 height: 60px;
 position: relative;
 background: #555;
 -moz-border-radius: 25px;
 -webkit-border-radius: 25px;
 border-radius: 25px;
 padding: 10px;
 box-shadow: inset 0 -1px 1px rgba(255,255,255,0.3);
}

.bar > span {
  display: block;
  height: 100%;
  border-top-right-radius: 8px;
  border-bottom-right-radius: 8px;
  border-top-left-radius: 20px;
  border-bottom-left-radius: 20px;
  background-color: rgb(43,194,83);
  background-image: linear-gradient(
    center bottom,
    rgb(43,194,83) 37%,
    rgb(84,240,84) 69%
  );
  box-shadow:
    inset 0 2px 9px  rgba(255,255,255,0.3),
    inset 0 -2px 6px rgba(0,0,0,0.4);
  position: relative;
  overflow: hidden;
}

.lvl {
  background-color: #078a25;
  background-image: linear-gradient(to bottom, #078a25, #f36d0a);
}

#health {
 font-size: 20px;
 color: white;
 font-weight: bold;
 text-align: right;
}

.btn-3d {
 position: relative;
 display: inline-block;
 font-size: 22px;
 padding: 20px 60px;
 color: white;
 margin: 20px 10px 10px;
 border-radius: 6px;
 text-align: center;
 transition: top .01s linear;
 text-shadow: 0 1px 0 rgba(0,0,0,0.15);
 cursor: pointer;
}

.btn-3d.green:hover  {background-color: #80C49D;}

.btn-3d:active {
 top: 9px;
}

.btn-3d.green {
 background-color: #82c8a0;
 box-shadow: 0 0 0 1px #82c8a0 inset,
    0 0 0 2px rgba(255,255,255,0.15) inset,
    0 8px 0 0 rgba(126, 194, 155, .7),
    0 8px 0 1px rgba(0,0,0,.4),
    0 8px 8px 1px rgba(0,0,0,0.5);
}
.btn-3d.green:active {
 box-shadow: 0 0 0 1px #82c8a0 inset,
    0 0 0 2px rgba(255,255,255,0.15) inset,
    0 0 0 1px rgba(0,0,0,0.4);
}

.btn-3d.red:hover    {background-color: #e74c3c;}

.btn-3d.red {
 background-color: #e74c3c;
 box-shadow: 0 0 0 1px #c63702 inset,
        0 0 0 2px rgba(255,255,255,0.15) inset,
        0 8px 0 0 #C24032,
        0 8px 0 1px rgba(0,0,0,0.4),
    0 8px 8px 1px rgba(0,0,0,0.5);
}
.btn-3d.red:active {
 box-shadow: 0 0 0 1px #c63702 inset,
    0 0 0 2px rgba(255,255,255,0.15) inset,
    0 0 0 1px rgba(0,0,0,0.4);
}

<div class="hp">
  <div class="gage">
   <div class="bar">
    <span id="health" class="lvl" style="width: 100%">100hp</span>
   </div>
  </div>
  <div class="click">
   <span class="btn-3d green" onclick="add()">Health</span>
   <span class="btn-3d red" onclick="remove()">Damage</span>
  </div>
 </div>


问:
How to filter with wms background maps in Tableau
I created a map with locations plotted in Tableau and have utilized a background map from NOAA to show which locations are being impacted by excessive rainfall. How do I filter the data so only those that fall within the excessive rainfall areas appear on the map? Alternatively how do I get aggregate measures of the locations that fall within the excessive rainfall zone? </p>

答:
A background map is delivered from the server to the client as some sort of raster (bitmap) image. The WMS server does not send the data that was used to construct the background image, it just sends the resulting image based on whatever options you selected.

If you want to use that image as a background layer behind your other data layers, that's all you need. If you want to do analysis that combines your other data with the spatial data for filtering or calculations, you'll need to get the actual underlying geospatial data and not just a raster image.

Tableau can work with spatial data, and then do spatial calculations and spatial joins. You'll need to get your rainfall data in a spatial data set, such as a shape file, GeoJSON file, KML file or at least a CSV file with coordinate locations included, and then learn to use Geometry datatypes. If your data is large or your calculations are complex, you may benefit from using a spatially aware database such as the spatial extensions to PostgreSQL (called PostGIS), Oracle or SQL Server.


问:
Using Module and path
I am running into some issues with loading a PSM1 file. The PSM1 is always in the same folder as the PS1, but that folder can change. It works if I use a literal path like this...

```<code>Using module '\\Mac\iCloud Drive\Px Tools 4.#\Dev 4.0\#Spikes\Windows7\library.psm1'
</code>```

But that's useless since the code could be installed anywhere. And the code is signed, so it can't change.

It also doesn't work to use the new (in PS3.0) $PSScriptRoot automatic variable...

```<code>Using module "$PSScriptRoot\library.psm1"
</code>```

Nor does a relative path or simple file name, as in...

```<code>Using module ".\library.psm1"
</code>```

or...

```<code>Using module "library.psm1"
</code>```

What am I missing, other than perhaps it's time to call it a day?

Also, note that the library contains classes, so other module loading options like Import-Module don't work. This has me wondering if perhaps classes are better supported in a later version, and I should really be targeting PS 6.0, rather than 5.1?

答:
Looking for more info on your problem, I came around this blog post. It says relative paths work, so have you tried using relative path with single quotes or without quotes?

Since values inside double-quotes get evaluated before passing them to the cmdlet, using them might not work.

Title: Using Module and path

Body:
I am running into some issues with loading a PSM1 file. The PSM1 is always in the same folder as the PS1, but that folder can change. It works if I use a literal path like this...

Using module '\\Mac\iCloud Drive\Px Tools 4.#\Dev 4.0\#Spikes\Windows7\library.psm1'

But that's useless since the code could be installed anywhere. And the code is signed, so it can't change.

It also doesn't work to use the new (in PS3.0) $PSScriptRoot automatic variable...

Using module "$PSScriptRoot\library.psm1"

Nor does a relative path or simple file name, as in...

Using module ".\library.psm1"

or...

Using module "library.psm1"

What am I missing, other than perhaps it's time to call it a day?

Also, note that the library contains classes, so other module loading options like Import-Module don't work. This has me wondering if perhaps classes are better supported in a later version, and I should really be targeting PS 6.0, rather than 5.1?


问:
How to monitor the process of SciPy.odeint?
SciPy can solve ode equations by scipy.integrate.odeint or other packages, but it gives result after the function has been solved completely. However, if the ode function is very complex, the program will take a lot of time(one or two days) to give the whole result. So how can I mointor the step it solve the equations(print out result when the equation hasn't been solved completely)?</p>

答:
When I was googling for an answer, I couldn't find a satisfactory one. So I made a simple gist with a proof-of-concept solution using the tqdm project. Hope that helps you.

Edit: Moderators asked me to give an explanation of what is going on in the link above.

First of all, I am using scipy's OOP version of odeint (solve_ivp) but you could adapt it back to odeint. Say you want to integrate from time T0 to T1 and you want to show progress for every 0.1% of progress. You can modify your ode function to take two extra parameters, a pbar (progress bar) and a state (current state of integration). Like so:

def fun(t, y, omega, pbar, state):
    # state is a list containing last updated time t:
    # state = [last_t, dt]
    # I used a list because its values can be carried between function
    # calls throughout the ODE integration
    last_t, dt = state

    # let's subdivide t_span into 1000 parts
    # call update(n) here where n = (t - last_t) / dt
    time.sleep(0.1)
    n = int((t - last_t)/dt)
    pbar.update(n)

    # we need this to take into account that n is a rounded number.
    state[0] = last_t + dt * n

    # YOUR CODE HERE
    dydt = 1j * y * omega
    return dydt
```
<p>This is necessary because the function itself must know where it is located, but scipy's <code>odeint</code> doesn't really give this context to the function. Then, you can integrate <code>fun</code> with the following code:</p>
<pre class="lang-py prettyprint-override"><code>T0 = 0
T1 = 1
t_span = (T0, T1)
omega = 20
y0 = np.array([1], dtype=np.complex)
t_eval = np.arange(*t_span, 0.25/omega)

with tqdm(total=1000, unit="‰") as pbar:
    sol = solve_ivp(
        fun,
        t_span,
        y0,
        t_eval=t_eval,
        args=[omega, pbar, [T0, (T1-T0)/1000]],
    )
</code>```

Note that anything mutable (like a list) in the args is instantiated once and can be changed from within the function. I recommend doing this rather than using a global variable.

This will show a progress bar that looks like this:

```<code>100%|█████████▉| 999/1000 [00:13<00:00, 71.69‰/s]
</code>```

Body:
When I was googling for an answer, I couldn't find a satisfactory one. So I made a simple gist with a proof-of-concept solution using the tqdm project. Hope that helps you.

Edit: Moderators asked me to give an explanation of what is going on in the link above.

First of all, I am using scipy's OOP version of odeint (solve_ivp) but you could adapt it back to odeint. Say you want to integrate from time T0 to T1 and you want to show progress for every 0.1% of progress. You can modify your ode function to take two extra parameters, a pbar (progress bar) and a state (current state of integration). Like so:

def fun(t, y, omega, pbar, state):
    # state is a list containing last updated time t:
    # state = [last_t, dt]
    # I used a list because its values can be carried between function
    # calls throughout the ODE integration
    last_t, dt = state

    # let's subdivide t_span into 1000 parts
    # call update(n) here where n = (t - last_t) / dt
    time.sleep(0.1)
    n = int((t - last_t)/dt)
    pbar.update(n)

    # we need this to take into account that n is a rounded number.
    state[0] = last_t + dt * n

    # YOUR CODE HERE
    dydt = 1j * y * omega
    return dydt

This is necessary because the function itself must know where it is located, but scipy's odeint doesn't really give this context to the function. Then, you can integrate fun with the following code:

T0 = 0
T1 = 1
t_span = (T0, T1)
omega = 20
y0 = np.array([1], dtype=np.complex)
t_eval = np.arange(*t_span, 0.25/omega)

with tqdm(total=1000, unit="‰") as pbar:
    sol = solve_ivp(
        fun,
        t_span,
        y0,
        t_eval=t_eval,
        args=[omega, pbar, [T0, (T1-T0)/1000]],
    )

Note that anything mutable (like a list) in the args is instantiated once and can be changed from within the function. I recommend doing this rather than using a global variable.

This will show a progress bar that looks like this:

100%|█████████▉| 999/1000 [00:13<00:00, 71.69‰/s]


问:
CSS resources blocking by Spring Security for non authorized requests
I'm using spring boot, my CSS resources are located in .../src/main/resources/static and i have WebSecurityConfig class:

```<code>@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserService userService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                    .antMatchers("/", "/registration", "/static/**").permitAll()
                    .anyRequest().authenticated()
                .and()
                    .formLogin()
                    .loginPage("/login")
                    .permitAll()
                .and()
                    .logout()
                    .permitAll();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService)
                .passwordEncoder(NoOpPasswordEncoder.getInstance());
    }
}
</code>```

and MvcConfig class:

```<code>@Configuration
public class MvcConfig implements WebMvcConfigurer {

    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/login").setViewName("login");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/");
    }
}

</code>```

When i logged in css resources are activated.
I have access to my templates when i'm not logged in.

Why CSS resources blocking for non authorized request?

Sorry for my English. I'll very grateful for your help!

答:
```<code>    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests().antMatchers("/control").hasRole("ADMIN")
                .antMatchers("/register", "/login_auth", "/login").permitAll()
                .antMatchers("/img/*.jpg", "/*.js", "/*.css").permitAll()...
</code>```

i did this to access the files in the root static folder.
if you got em under folders do this instead:

```<code>.antMatchers("/img/**", "/js/**", "/css/**").permitAll()
</code>```

Body:
I'm using spring boot, my CSS resources are located in .../src/main/resources/static and i have WebSecurityConfig class:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserService userService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                    .antMatchers("/", "/registration", "/static/**").permitAll()
                    .anyRequest().authenticated()
                .and()
                    .formLogin()
                    .loginPage("/login")
                    .permitAll()
                .and()
                    .logout()
                    .permitAll();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService)
                .passwordEncoder(NoOpPasswordEncoder.getInstance());
    }
}

and MvcConfig class:

@Configuration
public class MvcConfig implements WebMvcConfigurer {

    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/login").setViewName("login");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/");
    }
}

When i logged in css resources are activated.
I have access to my templates when i'm not logged in.

Why CSS resources blocking for non authorized request?

Sorry for my English. I'll very grateful for your help!

Body:
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests().antMatchers("/control").hasRole("ADMIN")
                .antMatchers("/register", "/login_auth", "/login").permitAll()
                .antMatchers("/img/*.jpg", "/*.js", "/*.css").permitAll()...

i did this to access the files in the root static folder.
if you got em under folders do this instead:

.antMatchers("/img/**", "/js/**", "/css/**").permitAll()


问:
Angular - Display message on specific item in a Loop
I have a list of rows using For Loop. Clicking on any row, pops up a modal window. The modal window contains a Cancel and Ok button. When clicked on OK button, a message should appear on the ROW which was clicked.
Currently I can get the index number of the row and the message is showing on ALL rows when clicked OK. How can I display the message only on that specific ROW.

```<code><div class="row" *ngFor="let item of items; let i = index">
</code>```

```<code><div class="row">
    <div class="col-2">
        <span (click)="showModalWindow">
            <img class="actionIcon" src="images/action.png" />
        </span>
    </div>
    <div class="col-4">
        <div class="ietm-img" *ngIf="item.image">
            <img [src]="item.image" alt="item" />
        </div>
    </div>
    <div class="col-6">
        <div class="text">
            <h6>{{item.name}}</h6>
            <p>MESSAGE NEEDS TO APPEAR ONLY ON THE SELECTED ROW</p>
            <span>{{item.measurement}} {{item.length}}</span>
        </div>
    </div>
</div>
</code>```

答:
Since your data appears to be coming from an API you may not have the ability to add an additional property to track the selected state of the row.

Consider capturing the selected row when the row is clicked, like so,

```<code><span (click)="showModalWindow(); selectedRow=i" style="border:1px solid red">
</code>```

Then you can set the hidden state when the row is clicked,

```<code><p [hidden]="selectedRow !== i">MESSAGE NEEDS TO APPEAR ONLY ON THE SELECTED ROW</p>
</code>```

In your component you'll need a variable to capture the state

```<code>selectedRow: Number;`
</code>```

The completed template would look something like this:

```<code><div class="row" *ngFor="let item of items; let i = index">
  <div class="row">
    <div class="col-2">
          <span (click)="showModalWindow(); selectedRow=i" style="border:1px solid red">
              <img class="actionIcon" src="images/action.png" />
          </span>
    </div>
    <div class="col-4">
      <div class="ietm-img" *ngIf="item.image">
        <img [src]="item.image" alt="item" />
      </div>
    </div>
    <div class="col-6">
      <div class="text">
        <h6>{{item.name}}</h6>
        <p [hidden]="selectedRow !== i">MESSAGE NEEDS TO APPEAR ONLY ON THE SELECTED ROW</p>
        <span>{{item.measurement}} {{item.length}}</span>
      </div>
    </div>
  </div>
</div>
</code>```

Body:
I have a list of rows using For Loop. Clicking on any row, pops up a modal window. The modal window contains a Cancel and Ok button. When clicked on OK button, a message should appear on the ROW which was clicked.
Currently I can get the index number of the row and the message is showing on ALL rows when clicked OK. How can I display the message only on that specific ROW.

{{item.name}}

MESSAGE NEEDS TO APPEAR ONLY ON THE SELECTED ROW

            {{item.measurement}} {{item.length}}

Body:
Since your data appears to be coming from an API you may not have the ability to add an additional property to track the selected state of the row.

Consider capturing the selected row when the row is clicked, like so,

<span (click)="showModalWindow(); selectedRow=i" style="border:1px solid red">

Then you can set the hidden state when the row is clicked,

<p [hidden]="selectedRow !== i">MESSAGE NEEDS TO APPEAR ONLY ON THE SELECTED ROW</p>

In your component you'll need a variable to capture the state

selectedRow: Number;`

The completed template would look something like this:

<div class="row" *ngFor="let item of items; let i = index">
  <div class="row">
    <div class="col-2">
          <span (click)="showModalWindow(); selectedRow=i" style="border:1px solid red">
              <img class="actionIcon" src="images/action.png" />
          </span>
    </div>
    <div class="col-4">
      <div class="ietm-img" *ngIf="item.image">
        <img [src]="item.image" alt="item" />
      </div>
    </div>
    <div class="col-6">
      <div class="text">
        <h6>{{item.name}}</h6>
        <p [hidden]="selectedRow !== i">MESSAGE NEEDS TO APPEAR ONLY ON THE SELECTED ROW</p>
        <span>{{item.measurement}} {{item.length}}</span>
      </div>
    </div>
  </div>
</div>


问:
how can i put different colors in ListView
i want to get the different colors in each row of the list view

but current only one color is shown

so how can i do this

```<code>ArrayAdapter<String> adapter=new ArrayAdapter<String(this,R.layout.latesthappenings,R.id.LH_Titles,titles);
            setListAdapter(adapter);
</code>```

i want to different color in each row

please tell how can i do

thanks

答:
Set all the different colors (that you want in your list) codes in an array and fetch color code from that array for each row position and use setBackgroundColor() method to set that background color to the list row.

Try this.

Body:
i want to get the different colors in each row of the list view

but current only one color is shown

so how can i do this

ArrayAdapter<String> adapter=new ArrayAdapter<String(this,R.layout.latesthappenings,R.id.LH_Titles,titles);
            setListAdapter(adapter);

i want to different color in each row

please tell how can i do

thanks


问:
How can I destroy an object after X seconds?
The problem is in that way it will create more and more objects if automatic or if using the mouse.

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ScifiEffects : MonoBehaviour
{
    public GameObject spawnEffect;
    public bool automaticFire = false;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if (automaticFire == false)
        {
            if (Input.GetMouseButtonDown(0))
            {
                GameObject effect = Instantiate(spawnEffect, transform.position, Quaternion.FromToRotation(Vector3.up, spawnEffect.transform.forward)) as GameObject;
            }
        }
        else
        {
            GameObject effect = Instantiate(spawnEffect, transform.position, Quaternion.FromToRotation(Vector3.up, spawnEffect.transform.forward)) as GameObject;
        }
    }
}
</code>```

If I add :

```<code>Destroy(effect);
</code>```

Either in the mouse or if automatic the gameobject will be destroy at once and the effect will not happen. I could use a coroutine but then I will have to call the StartCoroutine inside the Update either if automatic or not and it will start many coroutines.

答:
There are no downsides to starting a bunch of coroutines other than regular coding issues like infinite loops.

Also coroutines has exactly what you need with a method called WaitForSeconds() that only works in coroutines. As far as I know

```<code>void Update()
{
    if(true) // Change if statement so you don't create an infinite loop and crash your program
    {
        StartCoroutine("SpecialEffects");
    }
}

IEnumerator SpecialEffects()
{
    // Special Effects
    yield return new WaitForSeconds(seconds);
    // Code that destroys something
}
</code>```

Body:
The problem is in that way it will create more and more objects if automatic or if using the mouse.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ScifiEffects : MonoBehaviour
{
    public GameObject spawnEffect;
    public bool automaticFire = false;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if (automaticFire == false)
        {
            if (Input.GetMouseButtonDown(0))
            {
                GameObject effect = Instantiate(spawnEffect, transform.position, Quaternion.FromToRotation(Vector3.up, spawnEffect.transform.forward)) as GameObject;
            }
        }
        else
        {
            GameObject effect = Instantiate(spawnEffect, transform.position, Quaternion.FromToRotation(Vector3.up, spawnEffect.transform.forward)) as GameObject;
        }
    }
}

If I add :

Destroy(effect);

Either in the mouse or if automatic the gameobject will be destroy at once and the effect will not happen. I could use a coroutine but then I will have to call the StartCoroutine inside the Update either if automatic or not and it will start many coroutines.

Body:
There are no downsides to starting a bunch of coroutines other than regular coding issues like infinite loops.

Also coroutines has exactly what you need with a method called WaitForSeconds() that only works in coroutines. As far as I know

void Update()
{
    if(true) // Change if statement so you don't create an infinite loop and crash your program
    {
        StartCoroutine("SpecialEffects");
    }
}

IEnumerator SpecialEffects()
{
    // Special Effects
    yield return new WaitForSeconds(seconds);
    // Code that destroys something
}


答:
Your instance, and with that your script is missing the ec2:DescribeInstances permission to run the aws ec2 describe-instances command.

You should attach that permission to the instance role that is assigned to the instance (or create a new role with the permissions attached if there is none assigned yet).

Title: Problem with creating EBS snapshot on server(Linux EC2 instance)

Body:
I am working on a task that required to run a script on a server, The script will grab instance id, create snapshot and run yum update -y command and reboot the server.

#!/bin/bash

set -eu

# Set Vars
AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
export REGION=$(curl --silent http://169.254.169.254/latest/meta-data/placement/availability-zone | sed 's/[a-z]$//')
export INSTANCE_ID=$(curl http://169.254.169.254/latest/meta-data/instance-id)
echo $AWS_ACCOUNT_ID
echo $REGION

# Fetch VolumeId
volumeid=$(aws ec2 describe-instances --region $REGION --instance-id "$INSTANCE_ID" --filters Name=instance-state-name,Values=running  --query "Reservations[*].Instances[].[BlockDeviceMappings[*].{VolumeName:Ebs.VolumeId}]" --output text)

echo $INSTANCE_ID
echo $volumeid

# Create snapshot
aws ec2 create-snapshot --region $REGION --volume-id $volumeid --description "Test-Snapshot-$INSTANCE_ID"
read -p "waiting a while to complete creation of EBS snapshot" -t 100
echo -e "\x1B[01;36m Snapshot has been created \x1B[0m"

I can get the Instance id but when I am trying to create snapshot id from Instance id, I am getting following error:

ERROR

us-east-1

An error occurred (UnauthorizedOperation) when calling the DescribeInstances operation: You are not authorized to perform this operation.

Thank you so much in advance for your support.


问:
Flutter - Error: Unable to create dart snapshot for flutter tool
When I run flutter change channel or flutter doctor, the CMD show me this:

```<code>C:\Users\MyUser>flutter doctor -v
Checking Dart SDK version...

Building flutter tool...

Running pub upgrade...

/C:/src/flutter/packages/flutter_tools/lib/src/aot.dart:144:5: Warning: Must explicitly return a value from a non-void function.
    return;
    ^
</code>```

When I run:

```<code>git clean -xfd

git pull

flutter doctor
</code>```

The CDM show me this:

```<code>fatal: not a git repository (or any of the parent directories): .git
</code>```

How can I solve it? Thank you

答:
1.Go the Flutter install directory and please run (in cmd)

git clean -xfd

git stash save --keep-index

git stash drop

git pull

2.and restart your computer
  then run

flutter doctor

3.then go to your project path run

flutter packages get

flutter run

Body:
When I run flutter change channel or flutter doctor, the CMD show me this:

C:\Users\MyUser>flutter doctor -v
Checking Dart SDK version...

Building flutter tool...

Running pub upgrade...

/C:/src/flutter/packages/flutter_tools/lib/src/aot.dart:144:5: Warning: Must explicitly return a value from a non-void function.
    return;
    ^

When I run:

git clean -xfd

git pull

flutter doctor

The CDM show me this:

fatal: not a git repository (or any of the parent directories): .git

How can I solve it? Thank you


问:
Setting up mod_proxy to pass http authentication to server
I have a problem configuring Apache as a proxy server. At the moment I access a MS Sharepoint installation using domain.net over Port 80. Before being able to use it I have to enter username and password. So far so good.

Now I want to be able to access a website over a subdomain web.domain.net. The Server hosting this site runs on another machine in the internal network. The solution I came up with is to redirect port 80 to the machine running apache to serve the new website and proxy any requests for the sharepoint to the sharepoint server.

So far I enabled all the proxy modules in my httpd.conf and added a virtual host.
EDIT: Updated config after first responses.

```<code><VirtualHost *:80>
    ServerName domain.net

    ProxyRequests Off
    <Proxy *>
        Order deny,allow
        Allow from all
    </Proxy>

    ProxyErrorOverride On
    ProxyPass   /   http://sharepoint/
    ProxyPassReverse   /   http://sharepoint/

    <Location />
        AuthType basic
        AuthBasicAuthoritative Off
        SetEnv proxy-chain-auth On
        Order allow,deny
        Allow from all
    </Location>
</VirtualHost>
</code>```

This works. Entering domain.net forwards me to the sharepoint server. Now comes the actually problem. The sharepoint asks me for my credentials. But when I enter them the login form keeps popping up as I entered no or incorrect username and password.

It seems like the credentials aren't forwarded to the sharepoint through the proxy.

Can you give me any advise how to solve this? Is it possible to do this using mod_proxy?

答: See http://httpd.apache.org/docs/2.2/mod/mod_proxy_http.html: there is a proxy-chain-auth environmental variable that should forward the credentials on to the proxied server.

Body:
I have a problem configuring Apache as a proxy server. At the moment I access a MS Sharepoint installation using domain.net over Port 80. Before being able to use it I have to enter username and password. So far so good.

Now I want to be able to access a website over a subdomain web.domain.net. The Server hosting this site runs on another machine in the internal network. The solution I came up with is to redirect port 80 to the machine running apache to serve the new website and proxy any requests for the sharepoint to the sharepoint server.

So far I enabled all the proxy modules in my httpd.conf and added a virtual host.
EDIT: Updated config after first responses.

<VirtualHost *:80>
    ServerName domain.net

    ProxyRequests Off
    <Proxy *>
        Order deny,allow
        Allow from all
    </Proxy>

    ProxyErrorOverride On
    ProxyPass   /   http://sharepoint/
    ProxyPassReverse   /   http://sharepoint/

    <Location />
        AuthType basic
        AuthBasicAuthoritative Off
        SetEnv proxy-chain-auth On
        Order allow,deny
        Allow from all
    </Location>
</VirtualHost>

This works. Entering domain.net forwards me to the sharepoint server. Now comes the actually problem. The sharepoint asks me for my credentials. But when I enter them the login form keeps popping up as I entered no or incorrect username and password.

It seems like the credentials aren't forwarded to the sharepoint through the proxy.

Can you give me any advise how to solve this? Is it possible to do this using mod_proxy?


问:
Error rendering dynamic content from Jupyter Notebook Dashboard
I'm trying to run a dashboard which is actually a Jupyter notebook. I've created the dashboard using the panel library. My dashboard contains some dynamic content. All this worked well on my local machine. Now, I'm trying to do the same on an AWS server. The static content loads fine. But I get this error somehow for the dynamic content:-

bokeh.min.js?v=57d29d5936e494351385d736f792154c:550 [bokeh] Failed to load Bokeh session HxjcYn9BmVgnOJsBicuXlx8fEuUQkxViUb7ROVIVGNel:
  Error: Could not open websocket

Can someone help me with this?
Thanks

答: I resolved this issue by passing the --allow-websocket-origin=myserver_ip:app_port argument while starting it.</p>


问:
Gatsby + React Booking Calendar: "WebpackError: ReferenceError: self is not defined "on 'gatsby build' but 'gatsby develop' works fine
I'm using Gatsby to build a website. I've added React Booking Calendar to display some calendar data.

Running 'gatsby develop' works fine but running 'gatsby build' yields the following error:

```<code>WebpackError: ReferenceError: self is not defined

  - index.js:13
    node_modules/react-booking-calendar/lib/index.js:13:10310

  - index.js:13
    node_modules/react-booking-calendar/lib/index.js:13:10234

  - index.js:13 e.exports
    node_modules/react-booking-calendar/lib/index.js:13:10505

  - index.js:13 Object.<anonymous>
    node_modules/react-booking-calendar/lib/index.js:13:11026

  - index.js:1 t
    node_modules/react-booking-calendar/lib/index.js:1:328

  - index.js:12 Object.<anonymous>
    node_modules/react-booking-calendar/lib/index.js:12:5444

  - index.js:1 t
    node_modules/react-booking-calendar/lib/index.js:1:328

  - index.js:1 Object.<anonymous>
    node_modules/react-booking-calendar/lib/index.js:1:519

  - index.js:1 t
    node_modules/react-booking-calendar/lib/index.js:1:328

  - index.js:1
    node_modules/react-booking-calendar/lib/index.js:1:401

  - index.js:1
    node_modules/react-booking-calendar/lib/index.js:1:437

  - index.js:1
    node_modules/react-booking-calendar/lib/index.js:1:65

  - index.js:1 Object../node_modules/react-booking-calendar/lib/index.js
    node_modules/react-booking-calendar/lib/index.js:1:211
</code>```

It prints the whole minified version of react-booking-calendar index.js before the error. Searching in that blob, I can see 'self' appears once:

```<code>f=h(function(){return/msie [6-9]\b/.test(self.navigator.userAgent.toLowerCase())})
</code>```

I would appreciate any advice on this issue. Thanks.

Gatsby version: Gatsby CLI version: 2.12.8
Node version: v13.13.0
React booking calendar: ^1.0.3

答:
When running in develop you're running a React SPA in the browser mostly.

When running build you're running mostly in node, which doesn't know anything about the browser - and you're trying to access navigator which is the browser.

Since node has no concept of certain things, such as the DOM, document, window, etc. you need to use react hooks and state management to access them, and even then it's good practice to check that they exist first.

Body:
I'm using Gatsby to build a website. I've added React Booking Calendar to display some calendar data.

Running 'gatsby develop' works fine but running 'gatsby build' yields the following error:

WebpackError: ReferenceError: self is not defined

  - index.js:13
    node_modules/react-booking-calendar/lib/index.js:13:10310

  - index.js:13
    node_modules/react-booking-calendar/lib/index.js:13:10234

  - index.js:13 e.exports
    node_modules/react-booking-calendar/lib/index.js:13:10505

  - index.js:13 Object.<anonymous>
    node_modules/react-booking-calendar/lib/index.js:13:11026

  - index.js:1 t
    node_modules/react-booking-calendar/lib/index.js:1:328

  - index.js:12 Object.<anonymous>
    node_modules/react-booking-calendar/lib/index.js:12:5444

  - index.js:1 t
    node_modules/react-booking-calendar/lib/index.js:1:328

  - index.js:1 Object.<anonymous>
    node_modules/react-booking-calendar/lib/index.js:1:519

  - index.js:1 t
    node_modules/react-booking-calendar/lib/index.js:1:328

  - index.js:1
    node_modules/react-booking-calendar/lib/index.js:1:401

  - index.js:1
    node_modules/react-booking-calendar/lib/index.js:1:437

  - index.js:1
    node_modules/react-booking-calendar/lib/index.js:1:65

  - index.js:1 Object../node_modules/react-booking-calendar/lib/index.js
    node_modules/react-booking-calendar/lib/index.js:1:211

It prints the whole minified version of react-booking-calendar index.js before the error. Searching in that blob, I can see 'self' appears once:

f=h(function(){return/msie [6-9]\b/.test(self.navigator.userAgent.toLowerCase())})

I would appreciate any advice on this issue. Thanks.

Gatsby version: Gatsby CLI version: 2.12.8
Node version: v13.13.0
React booking calendar: ^1.0.3


问:
Evaluation order in ternary operator with increments
```<code>#define MAX(a,b) ((a)>(b) ? (a) : (b))
   int main(void) {
   int a=2;
   int b=3;

   int c = MAX(a++,b++); // c=((a++)>(b++) ? (a++) : (b++));
   printf("\na= %d", a);// a=3
   printf("\nb= %d", b);//b=5
   printf("\nc= %d", c);//c=4

   a=3;
   b=2;
   cc = MAX(a++,b++); // c=((a++)>(b++) ? (a++) : (b++));

   printf("\na= %d", a); // a=5
   printf("\nb= %d", b); //b=3
   printf("\nc= %d", c); //c=4

return 0;
}
</code>```

I would like to know why c is not evaluating to 5.

It appears to me the evaluation order should be:

First both a and be get incremented in  (a++)>(b++)

If for example the first one is greater, the ternary operator in
c=((a++)>(b++) ? (a++) : (b++)), goes to  (a++), so a
increments again.

The result of the ternary expression, which is a twice-increment,
should be assigned to c, then c should have the greater value
twice-incremented, that is 5. However, I am getting 4. I suspect the
greater value's second increment is happening at the end, but I can't
explain why, since the parentheses seem to indicate that the
assignment comes at the end.

Any idea?

答:
For a++ it's equivalent as saying

```<code>int temp = a;
a = a + 1;
return temp;
</code>```

so in the case of a=2, b=3, we can go to the condition (a++)>(b++) and we can have a rewritten as

```<code>int temp1 = a;
a = a + 1;
return temp1;
</code>```

and b rewritten as

```<code>int temp2 = b;
b = b + 1;
return temp2;
</code>```

now since it's only a conditional statement, we're really just evaluating the old values of a and b before the increment which is temp1 = 2 and temp2 = 3 while at the same time a and b values have changed a = 3, b = 4. Since temp1 < temp2 from the old value, we go to the false clause of the ternary operator (b++) and do the same thing as we did before

```<code>int temp3 = b;
b = b + 1;
return temp3;
</code>```

so now b is 5 while the returned temp3 is the previous value of b which is 4. Hope this helps!

Body:
#define MAX(a,b) ((a)>(b) ? (a) : (b))
   int main(void) {
   int a=2;
   int b=3;

   int c = MAX(a++,b++); // c=((a++)>(b++) ? (a++) : (b++));
   printf("\na= %d", a);// a=3
   printf("\nb= %d", b);//b=5
   printf("\nc= %d", c);//c=4

   a=3;
   b=2;
   cc = MAX(a++,b++); // c=((a++)>(b++) ? (a++) : (b++));

   printf("\na= %d", a); // a=5
   printf("\nb= %d", b); //b=3
   printf("\nc= %d", c); //c=4

return 0;
}

I would like to know why c is not evaluating to 5.

It appears to me the evaluation order should be:

First both a and be get incremented in  (a++)>(b++)

If for example the first one is greater, the ternary operator in
c=((a++)>(b++) ? (a++) : (b++)), goes to  (a++), so a
increments again.

The result of the ternary expression, which is a twice-increment,
should be assigned to c, then c should have the greater value
twice-incremented, that is 5. However, I am getting 4. I suspect the
greater value's second increment is happening at the end, but I can't
explain why, since the parentheses seem to indicate that the
assignment comes at the end.

Any idea?

Body:
For a++ it's equivalent as saying

int temp = a;
a = a + 1;
return temp;

so in the case of a=2, b=3, we can go to the condition (a++)>(b++) and we can have a rewritten as

int temp1 = a;
a = a + 1;
return temp1;

and b rewritten as

int temp2 = b;
b = b + 1;
return temp2;

now since it's only a conditional statement, we're really just evaluating the old values of a and b before the increment which is temp1 = 2 and temp2 = 3 while at the same time a and b values have changed a = 3, b = 4. Since temp1 < temp2 from the old value, we go to the false clause of the ternary operator (b++) and do the same thing as we did before

int temp3 = b;
b = b + 1;
return temp3;

so now b is 5 while the returned temp3 is the previous value of b which is 4. Hope this helps!


问:
Is there a way to specify the base address of a shared library using dlopen()?
It seems that when we dlopen() some libraries, they will be loaded into some preferred (but not fixed) addresses. I've checked the source code of dlopen(), and a core function says

```<code>static __always_inline const char *
_dl_map_segments (struct link_map *l, int fd,
                  const ElfW(Ehdr) *header, int type,
                  const struct loadcmd loadcmds[], size_t nloadcmds,
                  const size_t maplength, bool has_holes,
                  struct link_map *loader)
{
  const struct loadcmd *c = loadcmds;
  if (__glibc_likely (type == ET_DYN))
    {
      /* This is a position-independent shared object.  We can let the
         kernel map it anywhere it likes, but we must have space for all
         the segments in their specified positions relative to the first.
         So we map the first segment without MAP_FIXED, but with its
         extent increased to cover all the segments.  Then we remove
         access from excess portion, and there is known sufficient space
         there to remap from the later segments.
         As a refinement, sometimes we have an address that we would
         prefer to map such objects at; but this is only a preference,
         the OS can do whatever it likes. */
      ElfW(Addr) mappref
        = (ELF_PREFERRED_ADDRESS (loader, maplength,
                                  c->mapstart & GLRO(dl_use_load_bias))
           - MAP_BASE_ADDR (l));
      /* Remember which part of the address space this object uses.  */
      l->l_map_start = (ElfW(Addr)) __mmap ((void *) mappref, maplength,
                                            c->prot,
                                            MAP_COPY|MAP_FILE,
                                            fd, c->mapoff);
      if (__glibc_unlikely ((void *) l->l_map_start == MAP_FAILED))
        return DL_MAP_SEGMENTS_ERROR_MAP_SEGMENT;
...
}
</code>```

The comment says you can specify a preferred address, but OS will determine whether to use it.

Question

Is there any way we can specify the base address for each dlopened module?

ELF_PREFERRED_ADDRESSS is set to 0 by default, but this macro seems to infer that the preferred addresses can be changed, say by an environment variable? But even there is one, I doubt that it can be changed for each dlopened library.

If I want to implement this feature myself, it seems that I need to wrap a new dlopen function and pass the preferred address to the above core function (and use MAP_FIXED maybe). Is it correct?

Thanks!

答:
Is there any way we can specify the base address for each dlopened module?

No.

ELF_PREFERRED_ADDRESSS is set to 0 by default, but this macro seems to infer that the preferred addresses can be changed, say by an environment variable? But even there is one, I doubt that it can be changed for each dlopened library.

This code is compiled into the dynamic loader ld-linux.so and can not be changed after the compilation.

If I want to implement this feature myself, it seems that I need to wrap a new dlopen function and pass the preferred address to the above core function (and use MAP_FIXED maybe). Is it correct?

The function is private to ld-linux. You will not be able to wrap it, or call it from outside of ld-linux.

P.S. What you are likely looking for is the prelink command.

Body:
It seems that when we dlopen() some libraries, they will be loaded into some preferred (but not fixed) addresses. I've checked the source code of dlopen(), and a core function says

static __always_inline const char *
_dl_map_segments (struct link_map *l, int fd,
                  const ElfW(Ehdr) *header, int type,
                  const struct loadcmd loadcmds[], size_t nloadcmds,
                  const size_t maplength, bool has_holes,
                  struct link_map *loader)
{
  const struct loadcmd *c = loadcmds;
  if (__glibc_likely (type == ET_DYN))
    {
      /* This is a position-independent shared object.  We can let the
         kernel map it anywhere it likes, but we must have space for all
         the segments in their specified positions relative to the first.
         So we map the first segment without MAP_FIXED, but with its
         extent increased to cover all the segments.  Then we remove
         access from excess portion, and there is known sufficient space
         there to remap from the later segments.
         As a refinement, sometimes we have an address that we would
         prefer to map such objects at; but this is only a preference,
         the OS can do whatever it likes. */
      ElfW(Addr) mappref
        = (ELF_PREFERRED_ADDRESS (loader, maplength,
                                  c->mapstart & GLRO(dl_use_load_bias))
           - MAP_BASE_ADDR (l));
      /* Remember which part of the address space this object uses.  */
      l->l_map_start = (ElfW(Addr)) __mmap ((void *) mappref, maplength,
                                            c->prot,
                                            MAP_COPY|MAP_FILE,
                                            fd, c->mapoff);
      if (__glibc_unlikely ((void *) l->l_map_start == MAP_FAILED))
        return DL_MAP_SEGMENTS_ERROR_MAP_SEGMENT;
...
}

The comment says you can specify a preferred address, but OS will determine whether to use it.

Question

Is there any way we can specify the base address for each dlopened module?

ELF_PREFERRED_ADDRESSS is set to 0 by default, but this macro seems to infer that the preferred addresses can be changed, say by an environment variable? But even there is one, I doubt that it can be changed for each dlopened library.

If I want to implement this feature myself, it seems that I need to wrap a new dlopen function and pass the preferred address to the above core function (and use MAP_FIXED maybe). Is it correct?

Thanks!


问:
Changing the colour of the grey "border" on input[type=text]
Is it possible to change the colour of the grey "border" around a text input without changing the border thickness using CSS?

I initially thought that using border-color would allow me to change the colour, however, as seen in the image / code example below, changing the colour also appears to make the border thicker. I would like to keep the default width (2px) but change the colour of the border.

The image is a zoomed in screenshot of the code snippet below to highlight the apparent change in border thickness when the colour is changed.

* {
  box-sizing: border-box;
}

.container {
  display: flex;
  flex-direction: column;
}

input[type=text] {
  flex: 1 1 0;
  margin-bottom: 2px;
}

.different_color {
  border-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <input type="text">
  <input type="text" class="different_color">
</div></code>```

Edit

To clarify, the default border, which according to the developer console has a border-width of 2px appears to be rendered as only part of the 2px whilst still essentially padding the content in by a fixed 2px. However, when I set a colour on the border, it no longer renders only this small part, but the whole 2px. The image below shows this with the left side of the image being the default border and the right side of the image being the border with the border-color set to red.

答:
Changing the border-color will not change the border-width per se.

But you might have noticed that form elements by default looks different on MacOS than on Windows 10. That is because unstyled form elements are rendered using platform native styling. If you inspect an unstyled <input> in Chrome or Firefox and view the browser applied rulesets, you will see the input has -webkit-appearance: textfield or -moz-appearance: textfield respectively. This makes the browser apply these platform specific styles which will override even the browser defaults.

(In Firefox you can play around with the appearance property and make a
 render as a native styled input element and make a  look like a button by adding the appearance property like the following snippet demonstrates)

div {
  display: block;
  width: 100px;
  height: 20px;
  -webkit-appearance: textfield;
  -moz-appearance: textfield;
  appearance: textfield;
}
span {
  display: block;
  width: 100px;
  height: 20px;
  -webkit-appearance: button;
  -moz-appearance: button;
  appearance: button;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div></div>
<span></span></code>```

What happens once you start styling a form element is that the appearance ruleset will be removed and the browser will apply the browser defaults instead. As for the input element, it has border-style: inset and border-width: 2px by default in Chrome. That is what you are seeing. That is why the width and style changes once you change the color. And that is why you can't just change the border color.

You will have to manually "style your way back" to simulate the platform native form element.

Body:
Is it possible to change the colour of the grey "border" around a text input without changing the border thickness using CSS?

I initially thought that using border-color would allow me to change the colour, however, as seen in the image / code example below, changing the colour also appears to make the border thicker. I would like to keep the default width (2px) but change the colour of the border.

The image is a zoomed in screenshot of the code snippet below to highlight the apparent change in border thickness when the colour is changed.

* {
  box-sizing: border-box;
}

.container {
  display: flex;
  flex-direction: column;
}

input[type=text] {
  flex: 1 1 0;
  margin-bottom: 2px;
}

.different_color {
  border-color: red;
}

  <input type="text">
  <input type="text" class="different_color">

Edit

To clarify, the default border, which according to the developer console has a border-width of 2px appears to be rendered as only part of the 2px whilst still essentially padding the content in by a fixed 2px. However, when I set a colour on the border, it no longer renders only this small part, but the whole 2px. The image below shows this with the left side of the image being the default border and the right side of the image being the border with the border-color set to red.

Body:
Changing the border-color will not change the border-width per se.

But you might have noticed that form elements by default looks different on MacOS than on Windows 10. That is because unstyled form elements are rendered using platform native styling. If you inspect an unstyled <input> in Chrome or Firefox and view the browser applied rulesets, you will see the input has -webkit-appearance: textfield or -moz-appearance: textfield respectively. This makes the browser apply these platform specific styles which will override even the browser defaults.

(In Firefox you can play around with the appearance property and make a <div> render as a native styled input element and make a <span> look like a button by adding the appearance property like the following snippet demonstrates)

div {
  display: block;
  width: 100px;
  height: 20px;
  -webkit-appearance: textfield;
  -moz-appearance: textfield;
  appearance: textfield;
}
span {
  display: block;
  width: 100px;
  height: 20px;
  -webkit-appearance: button;
  -moz-appearance: button;
  appearance: button;
}

<div></div>
<span></span>

What happens once you start styling a form element is that the appearance ruleset will be removed and the browser will apply the browser defaults instead. As for the input element, it has border-style: inset and border-width: 2px by default in Chrome. That is what you are seeing. That is why the width and style changes once you change the color. And that is why you can't just change the border color.

You will have to manually "style your way back" to simulate the platform native form element.


问:
CSS width of a  tag
I use  tags in my module titles,
e.g.

Categories.

I specify the span's background color/image, width and height in css.

But the span's width depends on its content/text.

So, if I do , with just a background image/color in css, nothing appears.

Of course, I want something to appear.

How can I resolve this?

答:
You could explicitly set the display property to "block" so it behaves like a block level element, but in that case you should probably just use a div instead.</p>

```<code><span style="display:block; background-color:red; width:100px;"></span>
</code>```

ContentLicense: CC BY-SA 2.5

Title: CSS width of a <span> tag

Body:
You could explicitly set the display property to "block" so it behaves like a block level element, but in that case you should probably just use a div instead.

<span style="display:block; background-color:red; width:100px;"></span>

OwnerDisplayName: cxfx


问:
working of tcpclient sockets in vb.net
I have an application in vb.net which will connect with an hardware device and test its functionality. The hardware device basically spits out data continuosly through ethernet. That is it recieves some data via com ports and spits out the processed data via ethernet.

So my application does both. Thats pretty much the entire app.

My problem is i am using tcpclient sockets. Now when i connect a tcpclient to the device using

```<code>tcpclient.open(ip,port);
</code>```

Immediately the device sends some data which comes and get stored in the clientsocket. Then i send a command to it ,only then i read the data from the clientsocket using

```<code>tcpclient.getstream().read()
</code>```

at this time the entire data that is the one which flowed immediately when connected to the device and the one that i actually need after passing command is both acquired. This is undesirable. I need the data which i read only after sending the command.

So i was wondering if there is any way to clear the tcpclient socket before we do a read. The manual doesnt show any such method.

Any help on this would be useful to me.

答: You need to read the stream before sending the command to read out the stuff you're not interested in.</p>

Title: working of tcpclient sockets in vb.net

Body:
I have an application in vb.net which will connect with an hardware device and test its functionality. The hardware device basically spits out data continuosly through ethernet. That is it recieves some data via com ports and spits out the processed data via ethernet.

So my application does both. Thats pretty much the entire app.

My problem is i am using tcpclient sockets. Now when i connect a tcpclient to the device using

tcpclient.open(ip,port);

Immediately the device sends some data which comes and get stored in the clientsocket. Then i send a command to it ,only then i read the data from the clientsocket using

tcpclient.getstream().read()

at this time the entire data that is the one which flowed immediately when connected to the device and the one that i actually need after passing command is both acquired. This is undesirable. I need the data which i read only after sending the command.

So i was wondering if there is any way to clear the tcpclient socket before we do a read. The manual doesnt show any such method.

Any help on this would be useful to me.


问:
.html files showing up as "listing directory" when opening live server
I am opening up a new file in a new folder in vscode. When I open up the new .html file in live server, it opens it up as a "listing directory." When I create a new file in an old folder it works perfectly fine. I tried creating different folders and they all open up as "listing directory." I even opened up the instructors file of the lesson in vscode and it gives me the same "listing directory" tab. Please help! Thank you!</p>

答: In order to get the .html files to work. I had to add the main folder to the workspace. For example, my folders look like this: documents > udemy > htmlcss > (multiple folders). When I tried to just add a new folder inside of htmlcss and drag it over to the workspace it would give me "listing directory." When I added the htmlcss folder to the workspace, the .html files worked like normal!</p>


问:
Error SocketTimeoutException connecting to google in android
i'm having a problem with the connection for my app (Android). I'm using the following code to check if i have internet connection.

```<code>    ConnectivityManager cm = (ConnectivityManager)context
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (activeNetwork != null && activeNetwork.isConnected()) {
        try {
            URL url = new URL("http://www.google.com/");
            HttpURLConnection urlc = (HttpURLConnection)url.openConnection();
            urlc.setRequestProperty("User-Agent", "test");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(5000); // mTimeout is in seconds
            urlc.connect();
            if (urlc.getResponseCode() == 200) {
                return true;
            } else {
            return false;
        }
    } catch (IOException e) {
            Log.i("warning", "Error checking internet connection", e);
            return false;
        }
    }
</code>```

After trying several times, i encounter that the problem is that im doing ping to "www.google.com.".
I dont understand why is this happening. This code was woking fine for the last 2 years in my project.

答:
If you are testing this on a latest version of android, then you need to verify that you have whitelisted domains. You should read below:
https://developer.android.com/training/articles/security-config

As a quick fix you can add below property to application tag:

android:usesCleartextTraffic="true"```

Body:
i'm having a problem with the connection for my app (Android). I'm using the following code to check if i have internet connection.

    ConnectivityManager cm = (ConnectivityManager)context
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (activeNetwork != null && activeNetwork.isConnected()) {
        try {
            URL url = new URL("http://www.google.com/");
            HttpURLConnection urlc = (HttpURLConnection)url.openConnection();
            urlc.setRequestProperty("User-Agent", "test");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(5000); // mTimeout is in seconds
            urlc.connect();
            if (urlc.getResponseCode() == 200) {
                return true;
            } else {
            return false;
        }
    } catch (IOException e) {
            Log.i("warning", "Error checking internet connection", e);
            return false;
        }
    }

After trying several times, i encounter that the problem is that im doing ping to "www.google.com.".
I dont understand why is this happening. This code was woking fine for the last 2 years in my project.