问:
ARM VFPv3 assembler instructions
I am attempting to debug a very low level data fault in a TI AM 3358 MCU.  It is coming from floating point math.

The system uses TI RTOS, the GNU 7.3.1 Compiler, and VFPv3 (is VFP a compiler settings?  a FP math library?  I'm not clear on the floating point code generation).  So although I have disassembly listing fragments, the fix needs to be at the C code level.

This is a two part question:

First do I understand the mnemonics correctly? And why are some not listed?

I noticed the disassembly has opcodes that there are no mnemonics for.  Here is a list fragment, no need to get into details here yet.  Just notice mnemonics are missing, and I don't think they are immediate data (comments added by me as I reverse engineered the compiled code):

```<code>8003ced0:   EEF1FA10            vmrs       apsr_nzcv, fpscr     ; Pull STAT reg to ARM MCU
8003ced4:   DA000041            ble        #0x8003cfe0          ;  branch less-equal to x0x...3cfe0
8003ced8:   EEFD7BE0           .word       0xeefd7be0          ; ???  What is this
8003cedc:   EDC47A0A            vstr       s15, [r4, #0x28]     ; Store S15 <-  r4+28 = st->f2.z
8003cee0:   E584702C            str        r7, [r4, #0x2c]      ; Store r7 <-  r4+2c = st->f2.a
8003cee4:   E3A03000            mov        r3, #0
8003cee8:   E5843030            str        r3, [r4, #0x30]
8003ceec:   EE07CA90            vmov       s15, r12             ; ( I decode this below)
8003cef0:   EEF80BE7           .word       0xeef80be7           ; ???
8003cef4:   EE702BA2           .word       0xee702ba2           ; ???
8003cef8:   EEFD7BE2           .word       0xeefd7be2           ; ???
8003cefc:   EDC47A0D            vstr       s15, [r4, #0x34]
8003cf00:   E5845018            str        r5, [r4, #0x18]
8003cf04:   EE701BA1           .word       0xee701ba1
8003cf08:   EEFD7BE1           .word       0xeefd7be1
</code>```

To be sure I could understand VFPv3 mnemonics, I decoded address 8002ceec as the following:

```<code>8003ceec:   EE07CA90            vmov       s15, r12
VMOV   (between ARM core register and single-precision register)
            1110    unconditional
            1110
            0000    opt = 0: so this is TO the VFP
            0111    Vn = 7   (but still need one more bit from nibble 1)
            1100    Rt = 12
            1010
            1001    N = 1  (so n = 01111  =S15)
            0000
</code>```

It came from https://developer.arm.com/documentation/ddi0406/c/Application-Level-Architecture/Instruction-Details/Alphabetical-list-of-instructions/VMOV--between-ARM-core-register-and-single-precision-register-?lang=en, (I'm pretty sure I got this correct, if not, any correction welcome)

So, what are op codes 0xeef80be7, 0xee702ba2, etc.?  I am unable to decipher them in the ARM books or sites.  Following the VFP/NEON pattern, this is some kind of 'unconditional move' but beyond that, I can't match the bit pattern to anything  (and the web site is extremely unfriendly do this kind of search, I resorted to downloading a PDF and doing a bit search).

As for the second question, if there is an easy obvious answer, I'd appreciate being steered in the right direction.

This is a compiled C function which passes in a pointer to a structure.  Then pulls members out of it and does some floating point math. I determined the structure address is stored in R4.

And example prototype would be

```<code>int Function(int x, int y, struct *a);
</code>```

And is called as (fictional example)

```<code>Function (5,5,&st[0]);
</code>```

later on

```<code>Function (5,7,&st[1]);
</code>```

There is a Data Abort crash which only occurs when accessing the second structure.  Never when accessing the first. And only when the VFP/Neon is accessing it, not the regular ARM registers.

Getting into the mud of the code, R4 is the address of the structure passed in:

```<code>8003cfe0:   EEFD7BE0           .word       0xeefd7be0          ;  branch lands here
8003cfe4:   EDC47A06            vstr       s15, [r4, #0x18]    ;  CRASH  Store S15 <-  r4+24 = st->f1.x
8003cfe8:   E584C01C            str        r12, [r4, #0x1c]    ;  r12 = st->f1.y
8003cfec:   E3A03000            mov        r3, #0
8003cff0:   E5843020            str        r3, [r4, #0x20]
</code>```

I verified all the offsets of the members from the pointers, and everything is correct.

Repeating, the crash occurs at address 8003cfe4, but only when the R4 pointer is pointing to the st[1], never when pointing to st[0].

I know a "Data Abort" comes from attempting to access memory that the MMU is not configured permissions for.  And yet, everything else can access all the members of st[1].  This is only when the VFP code tries to access is.

In fact, at addresses 8003cedc, 8003cee0, and 8003cee8, which all execute before address 8003cfe4, can happily accessed members of that structure.  Which makes me believe this is not a MMU access issue?

Could it be the result of a cache miss?  Or is there some other VFP issue trying to move between the VFP system and memory?  Or is there an issue where the coprocessor isn't ready yet?

I was able to get around this crash by removing all the floating point math.  But that really harms the functionality of the application.  I'd much prefer that the floating point math for correctly.

Any ideas would be welcomed.

-Scotty

答:
While I don't have an answer to the unknown op codes, in an answer to the second part, the VFP coprocessor must have data transferred into and out of it on proper boundaries, in this case 4 bytes.

While the offsets into the structure were correctly aligned, the base of the structure itself was not. It started (due to packing) at address0x...2931.  So the offset at 40 bytes in (+0x28) was on an odd number address.

Simply adding

```<code>}  __attribute__ ((aligned (4)))
</code>```

at the end of the structure declaration solved the problem.

*** Update ***

I attempted many ways to replicate this issue in a code fragment. In all cases, the compiler generated code that moved the 32bit value from memory to a register before moving it into the neon processor.

I was able to forcibly cause the data fault with an inline assembler statement attempting to move unaligned data directly from an odd numbered address to the neon processor.

```<code>asm("vstr  s15, [r0, #0x4] ");
</code>```

(R0 contained the base address ending in x1)

Therefore this is likely an optimization bug in the GNU compiler.

I post this in the event someone else gets bitten by this issue.

Title: ARM VFPv3 assembler instructions

Body:
I am attempting to debug a very low level data fault in a TI AM 3358 MCU.  It is coming from floating point math.

The system uses TI RTOS, the GNU 7.3.1 Compiler, and VFPv3 (is VFP a compiler settings?  a FP math library?  I'm not clear on the floating point code generation).  So although I have disassembly listing fragments, the fix needs to be at the C code level.

This is a two part question:

First do I understand the mnemonics correctly? And why are some not listed?

I noticed the disassembly has opcodes that there are no mnemonics for.  Here is a list fragment, no need to get into details here yet.  Just notice mnemonics are missing, and I don't think they are immediate data (comments added by me as I reverse engineered the compiled code):

8003ced0:   EEF1FA10            vmrs       apsr_nzcv, fpscr     ; Pull STAT reg to ARM MCU
8003ced4:   DA000041            ble        #0x8003cfe0          ;  branch less-equal to x0x...3cfe0
8003ced8:   EEFD7BE0           .word       0xeefd7be0          ; ???  What is this
8003cedc:   EDC47A0A            vstr       s15, [r4, #0x28]     ; Store S15 <-  r4+28 = st->f2.z
8003cee0:   E584702C            str        r7, [r4, #0x2c]      ; Store r7 <-  r4+2c = st->f2.a
8003cee4:   E3A03000            mov        r3, #0
8003cee8:   E5843030            str        r3, [r4, #0x30]
8003ceec:   EE07CA90            vmov       s15, r12             ; ( I decode this below)
8003cef0:   EEF80BE7           .word       0xeef80be7           ; ???
8003cef4:   EE702BA2           .word       0xee702ba2           ; ???
8003cef8:   EEFD7BE2           .word       0xeefd7be2           ; ???
8003cefc:   EDC47A0D            vstr       s15, [r4, #0x34]
8003cf00:   E5845018            str        r5, [r4, #0x18]
8003cf04:   EE701BA1           .word       0xee701ba1
8003cf08:   EEFD7BE1           .word       0xeefd7be1

To be sure I could understand VFPv3 mnemonics, I decoded address 8002ceec as the following:

8003ceec:   EE07CA90            vmov       s15, r12
VMOV   (between ARM core register and single-precision register)
            1110    unconditional
            1110
            0000    opt = 0: so this is TO the VFP
            0111    Vn = 7   (but still need one more bit from nibble 1)
            1100    Rt = 12
            1010
            1001    N = 1  (so n = 01111  =S15)
            0000

It came from https://developer.arm.com/documentation/ddi0406/c/Application-Level-Architecture/Instruction-Details/Alphabetical-list-of-instructions/VMOV--between-ARM-core-register-and-single-precision-register-?lang=en, (I'm pretty sure I got this correct, if not, any correction welcome)

So, what are op codes 0xeef80be7, 0xee702ba2, etc.?  I am unable to decipher them in the ARM books or sites.  Following the VFP/NEON pattern, this is some kind of 'unconditional move' but beyond that, I can't match the bit pattern to anything  (and the web site is extremely unfriendly do this kind of search, I resorted to downloading a PDF and doing a bit search).

As for the second question, if there is an easy obvious answer, I'd appreciate being steered in the right direction.

This is a compiled C function which passes in a pointer to a structure.  Then pulls members out of it and does some floating point math. I determined the structure address is stored in R4.

And example prototype would be

int Function(int x, int y, struct *a);

And is called as (fictional example)

Function (5,5,&st[0]);

later on

Function (5,7,&st[1]);

There is a Data Abort crash which only occurs when accessing the second structure.  Never when accessing the first. And only when the VFP/Neon is accessing it, not the regular ARM registers.

Getting into the mud of the code, R4 is the address of the structure passed in:

8003cfe0:   EEFD7BE0           .word       0xeefd7be0          ;  branch lands here
8003cfe4:   EDC47A06            vstr       s15, [r4, #0x18]    ;  CRASH  Store S15 <-  r4+24 = st->f1.x
8003cfe8:   E584C01C            str        r12, [r4, #0x1c]    ;  r12 = st->f1.y
8003cfec:   E3A03000            mov        r3, #0
8003cff0:   E5843020            str        r3, [r4, #0x20]

I verified all the offsets of the members from the pointers, and everything is correct.

Repeating, the crash occurs at address 8003cfe4, but only when the R4 pointer is pointing to the st[1], never when pointing to st[0].

I know a "Data Abort" comes from attempting to access memory that the MMU is not configured permissions for.  And yet, everything else can access all the members of st[1].  This is only when the VFP code tries to access is.

In fact, at addresses 8003cedc, 8003cee0, and 8003cee8, which all execute before address 8003cfe4, can happily accessed members of that structure.  Which makes me believe this is not a MMU access issue?

Could it be the result of a cache miss?  Or is there some other VFP issue trying to move between the VFP system and memory?  Or is there an issue where the coprocessor isn't ready yet?

I was able to get around this crash by removing all the floating point math.  But that really harms the functionality of the application.  I'd much prefer that the floating point math for correctly.

Any ideas would be welcomed.

-Scotty

Body:
While I don't have an answer to the unknown op codes, in an answer to the second part, the VFP coprocessor must have data transferred into and out of it on proper boundaries, in this case 4 bytes.

While the offsets into the structure were correctly aligned, the base of the structure itself was not. It started (due to packing) at address0x...2931.  So the offset at 40 bytes in (+0x28) was on an odd number address.

Simply adding

}  __attribute__ ((aligned (4)))

at the end of the structure declaration solved the problem.

*** Update ***

I attempted many ways to replicate this issue in a code fragment. In all cases, the compiler generated code that moved the 32bit value from memory to a register before moving it into the neon processor.

I was able to forcibly cause the data fault with an inline assembler statement attempting to move unaligned data directly from an odd numbered address to the neon processor.

asm("vstr  s15, [r0, #0x4] ");

(R0 contained the base address ending in x1)

Therefore this is likely an optimization bug in the GNU compiler.

I post this in the event someone else gets bitten by this issue.


来源: stackexchange

问:
Postgres set working schema from inside of function
I am facing a problem I have a function which used to create schema and tables inside that schema after table creation I am calling a function which supposed to populate this schema however feels like the second function doesn't set the working schema and throws the error that object doesn't exits (

```<code>ERROR:  relation "table" does not exist
LINE 1: INSERT INTO table
</code>```

here is what the function looks like.

```<code>    CREATE OR REPLACE FUNCTION create_schema(
        t_shema character varying,
        t_country TEXT
        )
        RETURNS character varying
        LANGUAGE 'plpgsql'
        COST 100
        VOLATILE PARALLEL UNSAFE
    AS $BODY$
    DECLARE

        tname text := t_shema;
        tschem_name text := tname||'_work';
        tsql_dyn text ;
        tschema_check numeric := 0 ;

     BEGIN

        SELECT 1
          INTO TSCHEMA_CHECK
          FROM PG_NAMESPACE
         WHERE NSPNAME = TSCHEM_NAME;

     IF TSCHEMA_CHECK  = 1 THEN

        RETURN 'Schema '||tschem_name ||' Already exists';

     ELSE
        tsql_dyn := 'CREATE SCHEMA '||tschem_name||';';
        raise notice 'EXECUTE %', tsql_dyn;
            EXECUTE tsql_dyn;

        tsql_dyn := 'SET search_path TO  '||tschem_name ||';';
        raise notice 'EXECUTE %', tsql_dyn;
            EXECUTE tsql_dyn;

    --other DDLs
---execute of function which populates freshly created schema

    SELECT public.populate_empty_schema(tname, t_country);

    RETURN tname ||' created';

    END IF;

     END;
    $BODY$;
</code>```

The second function also has a statement as first which sets the working schema.
Both functions work fine if get called separately, trows error only if second get called from the first

答: feels like Postgres cannot set working schema from the second function, my solution. was just deleting the set search path from the second function and it is working. feels like it couldn't set it as shcema is not committed at the point when the 2-nd function gets called.</p>

ContentLicense: CC BY-SA 4.0

Body:
I am facing a problem I have a function which used to create schema and tables inside that schema after table creation I am calling a function which supposed to populate this schema however feels like the second function doesn't set the working schema and throws the error that object doesn't exits (

ERROR:  relation "table" does not exist
LINE 1: INSERT INTO table

here is what the function looks like.

    CREATE OR REPLACE FUNCTION create_schema(
        t_shema character varying,
        t_country TEXT
        )
        RETURNS character varying
        LANGUAGE 'plpgsql'
        COST 100
        VOLATILE PARALLEL UNSAFE
    AS $BODY$
    DECLARE

        tname text := t_shema;
        tschem_name text := tname||'_work';
        tsql_dyn text ;
        tschema_check numeric := 0 ;

     BEGIN

        SELECT 1
          INTO TSCHEMA_CHECK
          FROM PG_NAMESPACE
         WHERE NSPNAME = TSCHEM_NAME;

     IF TSCHEMA_CHECK  = 1 THEN

        RETURN 'Schema '||tschem_name ||' Already exists';

     ELSE
        tsql_dyn := 'CREATE SCHEMA '||tschem_name||';';
        raise notice 'EXECUTE %', tsql_dyn;
            EXECUTE tsql_dyn;

        tsql_dyn := 'SET search_path TO  '||tschem_name ||';';
        raise notice 'EXECUTE %', tsql_dyn;
            EXECUTE tsql_dyn;

    --other DDLs
---execute of function which populates freshly created schema

    SELECT public.populate_empty_schema(tname, t_country);

    RETURN tname ||' created';

    END IF;

     END;
    $BODY$;

The second function also has a statement as first which sets the working schema.
Both functions work fine if get called separately, trows error only if second get called from the first


问:
Can't run a join function because of a on_message event
i'm making a discord bot with python. I have some issues about running using @client.command and @client.event at the same time.
Here is the code:
when I comment the @client.event before the on message function, the join command run. This function cause a particular issue, do you know guys where it can come from? Thank you guys</p>
```<code>import discord
import random
from discord.utils import get
from discord.ext import commands
@client.command(pass_context=True)
async def join(ctx):
  channel = ctx.author.voice.channel
  await channel.connect()
@client.command(pass_context=True)
async def leave(ctx):
    await ctx.voice_client.disconnect()
@client.event
async def on_ready():
  print("We have logged as {0.user}".format(client))
@client.event
async def on_message(message):
  user = message.author.id
  if message.content.lower() == "!poisson":
    await message.delete()
    with open('myimage.png', 'rb') as f:
      picture = discord.File(f)
      await message.channel.send(file=picture)
</code>```

答:
Put await client.process_commands(message) at the end of on_message()
If you're using on_message, then normal commands will be overridden unless you use process_commands.

Body:
i'm making a discord bot with python. I have some issues about running using @client.command and @client.event at the same time.
Here is the code:
when I comment the @client.event before the on message function, the join command run. This function cause a particular issue, do you know guys where it can come from? Thank you guys

import discord
import random
from discord.utils import get
from discord.ext import commands
@client.command(pass_context=True)
async def join(ctx):
  channel = ctx.author.voice.channel
  await channel.connect()
@client.command(pass_context=True)
async def leave(ctx):
    await ctx.voice_client.disconnect()
@client.event
async def on_ready():
  print("We have logged as {0.user}".format(client))
@client.event
async def on_message(message):
  user = message.author.id
  if message.content.lower() == "!poisson":
    await message.delete()
    with open('myimage.png', 'rb') as f:
      picture = discord.File(f)
      await message.channel.send(file=picture)


问:
rxjs trigger one observable before the other one conditionaly
I am seeking for help or a clue for an issue with rxjs that I am not able to solve.

Basically, I want to trigger an observable and complete before the original one trigger.

Case: I am working on a project in which I have two profiles, say profileA, profileB.
Sometimes profileA has some properties that I need to pass to the profileB in order to get the profileB. And at the end, I combine the both profiles and return the orignal observable.

Usually, I cache the profileA in localStorage and I can get the profileB.

```<code>getProfileB() {
  const url = `${..}/xyz/${this.profileB.username}/userData`
  return this.http.get(anUrl); // and returns the observale to the next destination
}
</code>```

But sometimes could be that the profileA is not available in the localstorage, so in that case, first I have to find fetch the profileA and then continue with the profileB fetching.

I would like to use the following approch. Since I don't about

```<code>getProfileA() {
  return this.http.get(anUrlForProfileA);
}

getProfileB() {
  const url = `${..}/xyz/${this.profileB.username}/userData`
  return this.http.get(anUrl).pipe(
    aPipeOperator() => {
    // the null could be the mean that continue with the current Observable, whereas concatenateFirst means, first completes the getProfileA observable and then continue with the original one.
      return this.profileA?.username?.length > 0? concatenateFirst(this.getProfileA()) : null;

    }
  );
}
</code>```

I am little struggling with the rxjs, and it is also difficult for me to explain, so please help me. This issue could solve me other problems too.

Thanks

答:
I think switchMap is what you are looking for.  You pass it a function that will take the result of your observable and return an observable to replace it.

const getProfileA = () => of({ name: 'A' })

const getProfileB = (profileA: any) => {
  const requestProfileB = of({ name: 'B', message: `This is profile B, using data from profile with name '${profileA.name}'`})
  return requestProfileB.pipe(map(profileB => ({ profileA, profileB })))
}

getProfileA().pipe(switchMap(getProfileB)).subscribe(x => console.log(x))
```
<p>Here <code>getProfileA</code> mimics an http call to return profile 'A'.  That result is piped into <code>switchMap</code> which you pass <code>getProfileB</code>.   That function takes profileA and creates <code>requestProfileB</code>  using data from profileA.  That is piped to map() which combines the result from the request for profileB with the passed value for profileA into one object that will be emitted when the result is subscribed to.  Result:</p>
<pre class="lang-json prettyprint-override"><code>{
    "profileA": {
        "name": "A"
    },
    "profileB": {
        "name": "B",
        "message": "This is profile B, using data from profile with name 'A'"
    }
}
</code>```

CodePen Link

Body:
I am seeking for help or a clue for an issue with rxjs that I am not able to solve.

Basically, I want to trigger an observable and complete before the original one trigger.

Case: I am working on a project in which I have two profiles, say profileA, profileB.
Sometimes profileA has some properties that I need to pass to the profileB in order to get the profileB. And at the end, I combine the both profiles and return the orignal observable.

Usually, I cache the profileA in localStorage and I can get the profileB.

getProfileB() {
  const url = `${..}/xyz/${this.profileB.username}/userData`
  return this.http.get(anUrl); // and returns the observale to the next destination
}

But sometimes could be that the profileA is not available in the localstorage, so in that case, first I have to find fetch the profileA and then continue with the profileB fetching.

I would like to use the following approch. Since I don't about

getProfileA() {
  return this.http.get(anUrlForProfileA);
}

getProfileB() {
  const url = `${..}/xyz/${this.profileB.username}/userData`
  return this.http.get(anUrl).pipe(
    aPipeOperator() => {
    // the null could be the mean that continue with the current Observable, whereas concatenateFirst means, first completes the getProfileA observable and then continue with the original one.
      return this.profileA?.username?.length > 0? concatenateFirst(this.getProfileA()) : null;

    }
  );
}

I am little struggling with the rxjs, and it is also difficult for me to explain, so please help me. This issue could solve me other problems too.

Thanks

Body:
I think switchMap is what you are looking for.  You pass it a function that will take the result of your observable and return an observable to replace it.

const getProfileA = () => of({ name: 'A' })

const getProfileB = (profileA: any) => {
  const requestProfileB = of({ name: 'B', message: `This is profile B, using data from profile with name '${profileA.name}'`})
  return requestProfileB.pipe(map(profileB => ({ profileA, profileB })))
}

getProfileA().pipe(switchMap(getProfileB)).subscribe(x => console.log(x))

Here getProfileA mimics an http call to return profile 'A'.  That result is piped into switchMap which you pass getProfileB.   That function takes profileA and creates requestProfileB  using data from profileA.  That is piped to map() which combines the result from the request for profileB with the passed value for profileA into one object that will be emitted when the result is subscribed to.  Result:

{
    "profileA": {
        "name": "A"
    },
    "profileB": {
        "name": "B",
        "message": "This is profile B, using data from profile with name 'A'"
    }
}

CodePen Link


问:
How do I get a specific token balance from a user's wallet? Then set state based on that balance to create conditional renders?
I'm looking to get a specific token balance from a user's address after they log in with metamask then use that balance to create a state. Then I can use that state to have conditionally render the navbar and subsequent page.

How do I do that? And where do I put it? I'm new very new to web dev so looking for any help or guidance, thanks!

https://github.com/zedinstead/NFT-frontend

答:
Could you be more specific about the code? I'm reading your github repo, and I could manage to find a certain getBalance function. Would that be the function that gets the users's token balance? And where would you like to display it?

From what I gather, you could perhaps create something like this in the component you want to display the balance:

```<code>const [balance, setBalance] = useState()

useEffect(() => {
        GetBalance().then((bal) => setBalance(bal))
    }, [])

</code>```

With this you may then use the balance state constant wherever you like.

Body:
Could you be more specific about the code? I'm reading your github repo, and I could manage to find a certain getBalance function. Would that be the function that gets the users's token balance? And where would you like to display it?

From what I gather, you could perhaps create something like this in the component you want to display the balance:

const [balance, setBalance] = useState()

useEffect(() => {
        GetBalance().then((bal) => setBalance(bal))
    }, [])

With this you may then use the balance state constant wherever you like.


问:
Selenium is unable to locate the element for the search bar in Pinterest
I'm new to Python and I'm trying to create a webscraper that downloads images from Pinterest's search results.

I'm in the process of making the script click on the search bar. However, the program does not recognize the search bar element.

Here's the code:

from selenium import webdriver
from selenium.webdriver.firefox.service import Service
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By

browser = webdriver.Firefox(service=Service(r'C:\Users\HP\Desktop\Python Projects\Nova pasta\geckodriver.exe'))

browser.get("https://pinterest.com/") # Opens Firefox and enters Pinterest

login = browser.find_element(By.CSS_SELECTOR, "div.erh") # Looks for the login button
login.click() # Clicks on it

email = browser.find_element(By.CSS_SELECTOR, "#email") # Looks for the email box
email.send_keys("lol no") # Types in the email

password = browser.find_element(By.CSS_SELECTOR, "#password")
password.send_keys("lol neither")

login2 = browser.find_element(By.CSS_SELECTOR, ".red > div:nth-child(1)")
login2.click()

search = browser.find_element(By.XPATH, "/html/body/div[1]/div[1]/div[1]/div[2]/div/div/div[2]/div/div/div/div[4]/div/div/div[2]/input")
search.click()
search.send_keys("South Korea")
search.send_keys(Keys.ENTER)
```

I've already tried using By.CSS_SELECTOR but that doesn't work either.

答:
You are using a wrong locator for the search input element.

You should also use Expected Conditions explicit waits.

This should work better:

from selenium import webdriver
from selenium.webdriver.firefox.service import Service
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

browser = webdriver.Firefox(service=Service(r'C:\Users\HP\Desktop\Python Projects\Nova pasta\geckodriver.exe'))
wait = WebDriverWait(browser, 20)

browser.get("https://pinterest.com/") # Opens Firefox and enters Pinterest

login = browser.find_element(By.CSS_SELECTOR, "div.erh") # Looks for the login button
login.click() # Clicks on it

email = browser.find_element(By.CSS_SELECTOR, "#email") # Looks for the email box
email.send_keys("lol no") # Types in the email

password = browser.find_element(By.CSS_SELECTOR, "#password")
password.send_keys("lol neither")

login2 = browser.find_element(By.CSS_SELECTOR, ".red > div:nth-child(1)")
login2.click()

search = wait.until(EC.visibility_of_element_located((By.XPATH, "//input[@name='searchBoxInput']")))
search.click()
search.send_keys("South Korea")
search.send_keys(Keys.ENTER)
```

You should use the wait object on the previous steps as well...

Body:
I'm new to Python and I'm trying to create a webscraper that downloads images from Pinterest's search results.

I'm in the process of making the script click on the search bar. However, the program does not recognize the search bar element.

Here's the code:

from selenium import webdriver
from selenium.webdriver.firefox.service import Service
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By

browser = webdriver.Firefox(service=Service(r'C:\Users\HP\Desktop\Python Projects\Nova pasta\geckodriver.exe'))

browser.get("https://pinterest.com/") # Opens Firefox and enters Pinterest

login = browser.find_element(By.CSS_SELECTOR, "div.erh") # Looks for the login button
login.click() # Clicks on it

email = browser.find_element(By.CSS_SELECTOR, "#email") # Looks for the email box
email.send_keys("lol no") # Types in the email

password = browser.find_element(By.CSS_SELECTOR, "#password")
password.send_keys("lol neither")

login2 = browser.find_element(By.CSS_SELECTOR, ".red > div:nth-child(1)")
login2.click()

search = browser.find_element(By.XPATH, "/html/body/div[1]/div[1]/div[1]/div[2]/div/div/div[2]/div/div/div/div[4]/div/div/div[2]/input")
search.click()
search.send_keys("South Korea")
search.send_keys(Keys.ENTER)

I've already tried using By.CSS_SELECTOR but that doesn't work either.

Body:
You are using a wrong locator for the search input element.

You should also use Expected Conditions explicit waits.

This should work better:

from selenium import webdriver
from selenium.webdriver.firefox.service import Service
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

browser = webdriver.Firefox(service=Service(r'C:\Users\HP\Desktop\Python Projects\Nova pasta\geckodriver.exe'))
wait = WebDriverWait(browser, 20)

browser.get("https://pinterest.com/") # Opens Firefox and enters Pinterest

login = browser.find_element(By.CSS_SELECTOR, "div.erh") # Looks for the login button
login.click() # Clicks on it

email = browser.find_element(By.CSS_SELECTOR, "#email") # Looks for the email box
email.send_keys("lol no") # Types in the email

password = browser.find_element(By.CSS_SELECTOR, "#password")
password.send_keys("lol neither")

login2 = browser.find_element(By.CSS_SELECTOR, ".red > div:nth-child(1)")
login2.click()

search = wait.until(EC.visibility_of_element_located((By.XPATH, "//input[@name='searchBoxInput']")))
search.click()
search.send_keys("South Korea")
search.send_keys(Keys.ENTER)

You should use the wait object on the previous steps as well...


问:
PHP include different php pages depending on results
NEW PLEASE LOOK--- so great news i got it working but its only looking at my first if statement I just need help so if its not TX then it should look at the other ELSEIF statements! Please and thxs!

OLD---I'm passing via HTML form btn to this code and I'm wanting to grab it look into my database and find the state assigned to it via that billing telephone number so if the state comes back as TX I want it to display in east.php if it comes back at KS I want it to be displayed in kc.php
and of course if its CA I want it to display ca.php I've been racking at it for awhile so unless I have then put in what state the customer is from which I don't want to do cause not everyone will know what state the person is from! i've looked at a couple different things and cant find anything closest I've seen is this using php and mysql to display a specific URL in iFrame V2

```<code>
include 'db_connect.php';
$mysqli = new mysqli($host, $user, $password, $database_in_use);
$btnfromform = $_GET['btn'];
$sql = "SELECT btn, state FROM legacy_escalation Where btn LIKE '".$btnfromform."'";
$result = $mysqli->query($sql);

?>

<?php
        if ($result->num_rows > 0)
        while($row=mysqli_fetch_assoc($result))
        {
            $state=$row['state'];
        ?>
<?php
if($state='tx')
include 'east.php';
elseif ($state='KS')
include 'kc.php';
elseif ($state='CA')
include 'ca.php';

?>

<?php
               }
               else {
                echo "<span style='color:red; font-size:20px;'>No results found.</span>";
            }
          ?>   ```
```

答:
Quick answer, if($state='tx') should likely be if ($state === 'tx')

Longer answer. You're breaking all the rules.

mixing HTML and PHP,

badly named variables,

indentation issues,

SQL injection,

opening and closing PHP tags for no apparent reason,

mixed case values ex. tx vs. KS

Start paying attention to the style as well as the logic and you'll catch these issues easily.

Body:
NEW PLEASE LOOK--- so great news i got it working but its only looking at my first if statement I just need help so if its not TX then it should look at the other ELSEIF statements! Please and thxs!

OLD---I'm passing via HTML form btn to this code and I'm wanting to grab it look into my database and find the state assigned to it via that billing telephone number so if the state comes back as TX I want it to display in east.php if it comes back at KS I want it to be displayed in kc.php
and of course if its CA I want it to display ca.php I've been racking at it for awhile so unless I have then put in what state the customer is from which I don't want to do cause not everyone will know what state the person is from! i've looked at a couple different things and cant find anything closest I've seen is this using php and mysql to display a specific URL in iFrame V2

include 'db_connect.php';
$mysqli = new mysqli($host, $user, $password, $database_in_use);
$btnfromform = $_GET['btn'];
$sql = "SELECT btn, state FROM legacy_escalation Where btn LIKE '".$btnfromform."'";
$result = $mysqli->query($sql);

?>

<?php
        if ($result->num_rows > 0)
        while($row=mysqli_fetch_assoc($result))
        {
            $state=$row['state'];
        ?>
<?php
if($state='tx')
include 'east.php';
elseif ($state='KS')
include 'kc.php';
elseif ($state='CA')
include 'ca.php';

?>

<?php
               }
               else {
                echo "No results found.";
            }
          ?>   ```


问:
How to find whether a table has a given date range
I want to find out whether a table has rows within the range of dates passed to the query. The following is the data in MYTABLE. I am using SQL Server

```<code>DISPLAY_START_DATE      DISPLAY_END_DATE
2022-02-02 00:00:00.000     2022-02-28 00:00:00.000
2022-02-02 00:00:00.000     2022-02-06 10:34:01.653
2022-02-01 00:00:00.000     2022-02-17 00:00:00.000
2022-02-07 00:00:00.000     2022-02-25 00:00:00.000
</code>```

The following is my query

```<code>DECLARE @startdate AS datetime ='2022-02-01'
DECLARE @enddate AS datetime ='2022-02-10'
SELECT * from MYTABLE mt
WHERE
(mt.DISPLAY_START_DATE = @startdate and  mt.DISPLAY_END_DATE = @enddate)    OR
(mt.DISPLAY_START_DATE < @startdate and  mt.DISPLAY_END_DATE > @enddate)    OR
(mt.DISPLAY_START_DATE < @startdate and  mt.DISPLAY_END_DATE < @enddate)    OR
(mt.DISPLAY_START_DATE < @startdate and  mt.DISPLAY_END_DATE < @enddate and
    mt.DISPLAY_END_DATE > @startdate)   OR
(mt.DISPLAY_START_DATE > @startdate and  mt.DISPLAY_END_DATE < @enddate) OR
(mt.DISPLAY_START_DATE > @startdate and mt.DISPLAY_START_DATE < @enddate and
    mt.DISPLAY_END_DATE < @enddate)
</code>```

This pulls only the second row corresponding to the following data

```<code>DISPLAY_START_DATE      DISPLAY_END_DATE
2022-02-02 00:00:00.000     2022-02-06 10:34:01.653
</code>```

答:
Two intervals intersection condition is each interval must start before the other ends:</p>
```<code>..
WHERE mt.DISPLAY_START_DATE <= @enddate AND @startdate <= mt.DISPLAY_END_DATE
</code>```

Body:
I want to find out whether a table has rows within the range of dates passed to the query. The following is the data in MYTABLE. I am using SQL Server

DISPLAY_START_DATE      DISPLAY_END_DATE
2022-02-02 00:00:00.000     2022-02-28 00:00:00.000
2022-02-02 00:00:00.000     2022-02-06 10:34:01.653
2022-02-01 00:00:00.000     2022-02-17 00:00:00.000
2022-02-07 00:00:00.000     2022-02-25 00:00:00.000

The following is my query

DECLARE @startdate AS datetime ='2022-02-01'
DECLARE @enddate AS datetime ='2022-02-10'
SELECT * from MYTABLE mt
WHERE
(mt.DISPLAY_START_DATE = @startdate and  mt.DISPLAY_END_DATE = @enddate)    OR
(mt.DISPLAY_START_DATE < @startdate and  mt.DISPLAY_END_DATE > @enddate)    OR
(mt.DISPLAY_START_DATE < @startdate and  mt.DISPLAY_END_DATE < @enddate)    OR
(mt.DISPLAY_START_DATE < @startdate and  mt.DISPLAY_END_DATE < @enddate and
    mt.DISPLAY_END_DATE > @startdate)   OR
(mt.DISPLAY_START_DATE > @startdate and  mt.DISPLAY_END_DATE < @enddate) OR
(mt.DISPLAY_START_DATE > @startdate and mt.DISPLAY_START_DATE < @enddate and
    mt.DISPLAY_END_DATE < @enddate)

This pulls only the second row corresponding to the following data

DISPLAY_START_DATE      DISPLAY_END_DATE
2022-02-02 00:00:00.000     2022-02-06 10:34:01.653

Body:
Two intervals intersection condition is each interval must start before the other ends:

..
WHERE mt.DISPLAY_START_DATE <= @enddate AND @startdate <= mt.DISPLAY_END_DATE


问:
Filemaker: webviewer timer
I’m trying to make in FileMaker a web viewer to show some “countdown” for my medical office.

I’m trying to adapt this code I have found on internet:

```<code>     "data:text/html,<html>
<head>
<script type='text/javascript'>

/*Setting JavaScript Variables to value of FileMaker fields*/
var targetTimeTxt = '" & Timer::Timestamp_End & "';
var status = '" & Timer::Status & "';
var labelTxt = '" & Timer::Label & "';
/*End FileMaker Fields*/

var currentTime = new Date();
var targetTime = new Date(targetTimeTxt);
var remaining = Math.floor((targetTime - currentTime)/1000);

function setClock()
{
    var currentTime = new Date();
    var clock = document.getElementById('clock');
    var labelobj = document.getElementById('label1');
    var secondsRemaining=0;
    if(labelTxt=='')
    {
        labelobj.innerHTML='Timer';
    }
    else
    {
        labelobj.innerHTML=labelTxt;
    }

    if (targetTime>currentTime)
    {
        secondsRemaining=Math.floor((targetTime - currentTime)/1000);
    }

    var hours = Math.floor( secondsRemaining / 3600 );
    var minutes = Math.floor((secondsRemaining%3600) / 60 );
    if(minutes<10)minutes='0' + minutes;
    var seconds = secondsRemaining%60;
    if(seconds<10)seconds='0'+seconds;

    clock.innerHTML=hours + ':' + minutes + ':' + seconds;

    if(targetTimeTxt=='' || status=='Acknowledged' || ( secondsRemaining==0 && Math.floor(currentTime/1000)%2==0 ) )
    {
        document.body.style.backgroundColor='#FFFFFF';
        if ( targetTimeTxt=='' || status=='Acknowledged' )
        {
            clock.innerHTML='--:--:--';
        }
    }
    else if(secondsRemaining==0)
    {
        document.body.style.backgroundColor='#FFFF00';
        document.getElementById('sound1').Play();
    }

    setTimeout('setClock();',1000);
}

</script>
</head>
<body style='margin:4px;padding:0;font-size:14px;font-weight:bold;font-family: Arial, Helvetica, sans-serif;text-align:center;background-color:#FFFFFF;' onload='setClock();'>
<div id='label1' style='font-size:10px;font-weight:bold;'>
</div>
<div id='clock'>
</div>
<embed src='file:///System/Library/Sounds/Glass.aiff' autostart='false'  id='sound1'
enablejavascript='true' width='0' height='0'>
</body></html>"
</code>```

The FileMaker Var are correct, and the time stamp end car get  dd/mm/yyyy hh:mm:ss results.

The web viewer works, but the timer starts always with a 2640:mm:ss….. indeed of the duration time.
I suspect there is an error in the calculation of the code, but I have no idea where to look.

Can someone help me?
I hanno no idea of Java programming.
Thanks.

答:
Here is something very simple you could use as your starting point:

```<code>Let ([
seconds = Timer::Timestamp_End - Get(CurrentTimestamp) ;
html = "data:text/html, <html>
<head>
<script type='text/javascript' language='javascript'>
function count_down(seconds) {
i = seconds;
h = Math.floor(i/3600);
m = Math.floor(i%3600/60);
s = i%60;
if (m < 10) { m = '0' + m };
if (s < 10) { s = '0' + s };
if (i > 0) {
document.getElementById('hr').innerHTML = h;
document.getElementById('min').innerHTML = m;
document.getElementById('sec').innerHTML = s;
i--;
setTimeout('count_down(i)', 1000);
}
else {
document.getElementById('timer').innerHTML = 'Expired';
}
}
</script>
</head>
<body onload='count_down(«seconds»)'>
<div id='timer'><span id='hr'></span>:<span id='min'></span>:<span id='sec'></span></div>
</body>
</html>"
] ;
Substitute ( html ; "«seconds»" ; GetAsNumber ( seconds ) )
)
</code>```

This assumes the Timestamp_End field is a Timestamp field.

Title: Filemaker: webviewer timer

Body:
I’m trying to make in FileMaker a web viewer to show some “countdown” for my medical office.

I’m trying to adapt this code I have found on internet:

     "data:text/html,

<embed src='file:///System/Library/Sounds/Glass.aiff' autostart='false'  id='sound1'
enablejavascript='true' width='0' height='0'>
"

The FileMaker Var are correct, and the time stamp end car get  dd/mm/yyyy hh:mm:ss results.

The web viewer works, but the timer starts always with a 2640:mm:ss….. indeed of the duration time.
I suspect there is an error in the calculation of the code, but I have no idea where to look.

Can someone help me?
I hanno no idea of Java programming.
Thanks.

Body:
Here is something very simple you could use as your starting point:

Let ([
seconds = Timer::Timestamp_End - Get(CurrentTimestamp) ;
html = "data:text/html, <html>
<head>
<script type='text/javascript' language='javascript'>
function count_down(seconds) {
i = seconds;
h = Math.floor(i/3600);
m = Math.floor(i%3600/60);
s = i%60;
if (m < 10) { m = '0' + m };
if (s < 10) { s = '0' + s };
if (i > 0) {
document.getElementById('hr').innerHTML = h;
document.getElementById('min').innerHTML = m;
document.getElementById('sec').innerHTML = s;
i--;
setTimeout('count_down(i)', 1000);
}
else {
document.getElementById('timer').innerHTML = 'Expired';
}
}
</script>
</head>
<body onload='count_down(«seconds»)'>
<div id='timer'><span id='hr'></span>:<span id='min'></span>:<span id='sec'></span></div>
</body>
</html>"
] ;
Substitute ( html ; "«seconds»" ; GetAsNumber ( seconds ) )
)

This assumes the Timestamp_End field is a Timestamp field.


问:
The Hostname Regex
I'm looking for the regex to validate hostnames. It must completely conform to the standard. Right now, I have

^[0-9a-z]([0-9a-z\-]{0,61}[0-9a-z])?(\.[0-9a-z](0-9a-z\-]{0,61}[0-9a-z])?)*$

but it allows successive hypens and hostnames longer than 255 characters. If the perfect regex is impossible, say so.

Edit/Clarification: a Google search didn't reveal that this is a solved (or proven unsolvable) problem. I want to to create the definitive regex so that nobody has to write his own ever. If dialects matter, I want a a version for each one in which this can be done.

答:
According to the relevant internet RFCs and assuming you have lookahead and lookbehind positive and negative assertions:

If you want to validate a local/leaf hostname for use in an internet hostname (e.g. - FQDN), then:

```<code>^(?!-)[-a-zA-Z0-9]{1,63}(?<!-)$
</code>```

That ^^^ is also the general check that a label component inside an internet hostname is valid.

If you want to validate an internet hostname (e.g. - FQDN), then:

```<code>^(?=.{1,253}\.?$)(?:(?!-)[-a-zA-Z0-9]{1,63}(?<!-)\.)*(?!-)[-a-zA-Z0-9]{1,63}(?<!-)\.?$
</code>```

ContentLicense: CC BY-SA 2.5

Title: The Hostname Regex

Body:
According to the relevant internet RFCs and assuming you have lookahead and lookbehind positive and negative assertions:

If you want to validate a local/leaf hostname for use in an internet hostname (e.g. - FQDN), then:

^(?!-)[-a-zA-Z0-9]{1,63}(?<!-)$

That ^^^ is also the general check that a label component inside an internet hostname is valid.

If you want to validate an internet hostname (e.g. - FQDN), then:

^(?=.{1,253}\.?$)(?:(?!-)[-a-zA-Z0-9]{1,63}(?<!-)\.)*(?!-)[-a-zA-Z0-9]{1,63}(?<!-)\.?$


问:
content overflowing from css grid
Problem: I am having a problem with sizing images inside css grid column/rows. I essentially object-fit: contain the imagesinside their individual cells.

The image in "SPOT 4" is not filling the given space

If you uncomment the image in "SPOT 1", it will cover the entire grid and is not confined to its own css grid cell.

I have tried setting max-width, object-fit and others on the video level and .channel-container level with no success.

Background:  The .parent-trap css class is just an example height/width. This will vary, it may be the entire browser window, or it may be small so I cannot depend on any specific min/max dimensions. There are also other .display4 in the full version that sometimes shows a single video that fills the whole grid, side by side that only shows 2 at a time etc, so any specific dimensions also tend to break individual .display*

html,
body {
  border: 0;
  margin: 0;
  height: 100%;
}

.parent-trap {
  height: 540px;
  width: 960px;
}

/* container for player */
.video-player {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  max-height: 100%;
  max-width: 100%;
  min-height: 100%;
  min-width: 100%;
}

/* container for plaback control bar */
.container-controls {
  height: 50px;
  background-color: red;
}

/* contains all the .channel-container s */
.channel-layout-container {
  display: grid;
  background: #000;
  background-color: blue;
  flex: 1;
}

/****
**** FIX HERE
****/

.channel-container {}

img {}

/** THERE ARE OTHER DYNAMIC LAYOUTS, ISSUE IS SAME ON ALL */

/** display4 **/
.channel-layout-container.display4 {
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr;
}

.channel-layout-container.display4 .channel-container:nth-child(n+5) {
  flex: none;
  display: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- try restricting various sizes -->
<div class="parent-trap">

  <!-- the classcommes that need to be transferred back over-->
  <div class="video-player">
    <div class="channel-layout-container display4">
      <div class="channel-container" style="background-color: khaki;">
        <!-- <img src="https://w.wallhaven.cc/full/3z/wallhaven-3zgz2y.png" />-->

      </div>
      <div class="channel-container" style="background-color: lavender;">
        SPOT 2
      </div>
      <div class="channel-container" style="background-color: lightcoral;">
        SPOT 3
      </div>
      <div class="channel-container" style="background-color: lightseagreen;">
        <img src="https://www.google.com/favicon.ico" />
      </div>
    </div>
    <div class="container-controls">
      common controls and other info goes here
    </div>
  </div>
</div></code>```

答:
I ended up needing 3 things, I'm not entirely sure what the min-width/height: 0 are doing to fix my issue but it works

```<code>
        .channel-layout-container {
            min-height: 0;  /* NEW */
            min-width: 0;   /* NEW; needed for Firefox */
        }

        .channel-container {
            min-height: 0;  /* NEW */
            min-width: 0;   /* NEW; needed for Firefox */
        }

        img {
            display:block;
            width :100%;
            height:100%;
            object-fit:cover;

        }
</code>```

html,
body {
    border: 0;
    margin: 0;
    height: 100%;
}

.parent-trap {
    height: 540px;
    width: 960px;
}

/* container for player */
.video-player {
    display: flex;
    flex-direction: column;
    height: 100%;
    width: 100%;
    max-height: 100%;
    max-width: 100%;
    min-height: 100%;
    min-width: 100%;
}

/* container for plaback control bar */
.container-controls {
    height: 50px;
    min-height: 50px;
    max-height: 50px;
    background-color: red;
}

/* contains all the .channel-container s */
.channel-layout-container {
    display: grid;
    background: #000;
    background-color: blue;
    flex: 1;
    min-height: 0;  /* NEW */
    min-width: 0;   /* NEW; needed for Firefox */
}

/****
**** FIX HERE
****/

.channel-container {
    min-height: 0;  /* NEW */
    min-width: 0;   /* NEW; needed for Firefox */
}

img {
    display:block;
    width :100%;
    height:100%;
    object-fit:cover;

}

/** THERE ARE OTHER DYNAMIC LAYOUTS, ISSUE IS SAME ON ALL */

/** display4 **/
.channel-layout-container.display4 {
    grid-template-columns: 1fr 1fr;
    grid-template-rows: 1fr 1fr;
}

.channel-layout-container.display4 .channel-container:nth-child(n+5) {
    flex: none;
    display: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent-trap">

    <!-- the classcommes that need to be transferred back over-->
    <div class="video-player">
        <div class="channel-layout-container display4">
            <div class="channel-container" style="background-color: khaki;">
                <img src="https://w.wallhaven.cc/full/3z/wallhaven-3zgz2y.png" />

            </div>
            <div class="channel-container" style="background-color: lavender;">
                SPOT 2
            </div>
            <div class="channel-container" style="background-color: lightcoral;">
                SPOT 3
            </div>
            <div class="channel-container" style="background-color: lightseagreen;">
                <img src="https://www.google.com/favicon.ico" />
            </div>
        </div>
        <div class="container-controls">
            common controls and other info goes here
        </div>
    </div>
</div></code>```

You can see now that changing .parent-trap dimensions keep the proper proportions , control bar is always available and just the displays adjust as necessary.

Title: content overflowing from css grid

Body:
Problem: I am having a problem with sizing images inside css grid column/rows. I essentially object-fit: contain the imagesinside their individual cells.

The image in "SPOT 4" is not filling the given space

If you uncomment the image in "SPOT 1", it will cover the entire grid and is not confined to its own css grid cell.

I have tried setting max-width, object-fit and others on the video level and .channel-container level with no success.

Background:  The .parent-trap css class is just an example height/width. This will vary, it may be the entire browser window, or it may be small so I cannot depend on any specific min/max dimensions. There are also other .display4 in the full version that sometimes shows a single video that fills the whole grid, side by side that only shows 2 at a time etc, so any specific dimensions also tend to break individual .display*

html,
body {
  border: 0;
  margin: 0;
  height: 100%;
}

.parent-trap {
  height: 540px;
  width: 960px;
}

/* container for player */
.video-player {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  max-height: 100%;
  max-width: 100%;
  min-height: 100%;
  min-width: 100%;
}

/* container for plaback control bar */
.container-controls {
  height: 50px;
  background-color: red;
}

/* contains all the .channel-container s */
.channel-layout-container {
  display: grid;
  background: #000;
  background-color: blue;
  flex: 1;
}

/****
**** FIX HERE
****/

.channel-container {}

img {}

/** THERE ARE OTHER DYNAMIC LAYOUTS, ISSUE IS SAME ON ALL */

/** display4 **/
.channel-layout-container.display4 {
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr;
}

.channel-layout-container.display4 .channel-container:nth-child(n+5) {
  flex: none;
  display: none;
}

        SPOT 2

        SPOT 3

      common controls and other info goes here

Body:
I ended up needing 3 things, I'm not entirely sure what the min-width/height: 0 are doing to fix my issue but it works

        .channel-layout-container {
            min-height: 0;  /* NEW */
            min-width: 0;   /* NEW; needed for Firefox */
        }

        .channel-container {
            min-height: 0;  /* NEW */
            min-width: 0;   /* NEW; needed for Firefox */
        }

        img {
            display:block;
            width :100%;
            height:100%;
            object-fit:cover;

        }

html,
body {
    border: 0;
    margin: 0;
    height: 100%;
}

.parent-trap {
    height: 540px;
    width: 960px;
}

/* container for player */
.video-player {
    display: flex;
    flex-direction: column;
    height: 100%;
    width: 100%;
    max-height: 100%;
    max-width: 100%;
    min-height: 100%;
    min-width: 100%;
}

/* container for plaback control bar */
.container-controls {
    height: 50px;
    min-height: 50px;
    max-height: 50px;
    background-color: red;
}

/* contains all the .channel-container s */
.channel-layout-container {
    display: grid;
    background: #000;
    background-color: blue;
    flex: 1;
    min-height: 0;  /* NEW */
    min-width: 0;   /* NEW; needed for Firefox */
}

/****
**** FIX HERE
****/

.channel-container {
    min-height: 0;  /* NEW */
    min-width: 0;   /* NEW; needed for Firefox */
}

img {
    display:block;
    width :100%;
    height:100%;
    object-fit:cover;

}

/** THERE ARE OTHER DYNAMIC LAYOUTS, ISSUE IS SAME ON ALL */

/** display4 **/
.channel-layout-container.display4 {
    grid-template-columns: 1fr 1fr;
    grid-template-rows: 1fr 1fr;
}

.channel-layout-container.display4 .channel-container:nth-child(n+5) {
    flex: none;
    display: none;
}

<div class="parent-trap">

    <!-- the classcommes that need to be transferred back over-->
    <div class="video-player">
        <div class="channel-layout-container display4">
            <div class="channel-container" style="background-color: khaki;">
                <img src="https://w.wallhaven.cc/full/3z/wallhaven-3zgz2y.png" />

            </div>
            <div class="channel-container" style="background-color: lavender;">
                SPOT 2
            </div>
            <div class="channel-container" style="background-color: lightcoral;">
                SPOT 3
            </div>
            <div class="channel-container" style="background-color: lightseagreen;">
                <img src="https://www.google.com/favicon.ico" />
            </div>
        </div>
        <div class="container-controls">
            common controls and other info goes here
        </div>
    </div>
</div>

You can see now that changing .parent-trap dimensions keep the proper proportions , control bar is always available and just the displays adjust as necessary.


问:
functional programming with coroutines python
I have async call, for example

```<code>from httpx import AsyncClient, Response

client = AsyncClient()
my_call = client.get(f"{HOST}/api/my_method")  # async call
</code>```

And I want to pass it to some retry logic like

```<code>async def retry_http(http_call):
    count = 5
    status, response = None, None
    while count > 0:
        response: Response = await http_call
        if response.status_code == 200:
            break
        count -= 1
        if response.status_code in (502, 504):
            await asyncio.sleep(2)
        else:
            break

    if response.status_code != 200:
        return {
            "success": False,
            "result": {
                "error": f"Response Error",
                "response_code": response.status_code,
                "response": response.text,
            }
        }

    return response.json()

await retry_http(my_call)
</code>```

but I got

```<code>RuntimeError
cannot reuse already awaited coroutine
</code>```

Are there any method to make my_call an reusable coroutine ?

答:
It is not possible in Python -  a co-routine, once created, have an internal state that can't be easily duplicated - so once it runs, the internal state changes, including the internal line of code that is in execution, and there is no way to "rewind" that.

The most simple approach is to do like in @RyabchenkoAlexander's answer and accept the co-routine function and its parameters separately, and create the co-routine inside your retry function.

An alternative that is a nice Python idiom is to decorate the co-routine function - you make your retry_http a decorator instead, which wraps the underlying co-routine function in the retrying code.

Then, if the functions where you want this behavior are in your code, you can use the decorator syntax (@name prefixing the function definion) so that all calls will have the retry behavior, or you can apply it as a plain expression to get a new, retriable, co-routine function. Your final call could be:

```<code>    result = await (retry_http(client.get) (f"{HOST}/api/my_method"))
</code>```

(note the extra pair of parentheses around client.get, decorating it)

The decorator itself could be:

```<code>def retry_http(coro_func):
    async def wrapper(*args, **kw):
        # your original code - just replacing the await expression
        ...
        while count > 5:
            ...
            result = await coro_func(*args, **kw)
            ...
        ...
        return result
    return wrapper

</code>```

As for your original intent: it would actually be possible to introspect a coroutine object, its internal variables and passed parameter, to recreate a co-routine object that has not yet started - however, that would involve using introspection to locate the original callable, and making the call again - it would be cumbersome, could be slow, and for little gain. I will outline the requirements, nonetheless:

A co-routine object has the cr_code and cr_frame attributes - you'd need to retrieve the function associated with the code object in cr_code- probably using the garbage colector API, or recreate a new function re-using the same code object, by calling types.FunctionType with the same parameters - and the local and global variables can be retrieved from the frame object in cr_frame.

Body:
I have async call, for example

from httpx import AsyncClient, Response

client = AsyncClient()
my_call = client.get(f"{HOST}/api/my_method")  # async call

And I want to pass it to some retry logic like

async def retry_http(http_call):
    count = 5
    status, response = None, None
    while count > 0:
        response: Response = await http_call
        if response.status_code == 200:
            break
        count -= 1
        if response.status_code in (502, 504):
            await asyncio.sleep(2)
        else:
            break

    if response.status_code != 200:
        return {
            "success": False,
            "result": {
                "error": f"Response Error",
                "response_code": response.status_code,
                "response": response.text,
            }
        }

    return response.json()

await retry_http(my_call)

but I got

RuntimeError
cannot reuse already awaited coroutine

Are there any method to make my_call an reusable coroutine ?

Body:
It is not possible in Python -  a co-routine, once created, have an internal state that can't be easily duplicated - so once it runs, the internal state changes, including the internal line of code that is in execution, and there is no way to "rewind" that.

The most simple approach is to do like in @RyabchenkoAlexander's answer and accept the co-routine function and its parameters separately, and create the co-routine inside your retry function.

An alternative that is a nice Python idiom is to decorate the co-routine function - you make your retry_http a decorator instead, which wraps the underlying co-routine function in the retrying code.

Then, if the functions where you want this behavior are in your code, you can use the decorator syntax (@name prefixing the function definion) so that all calls will have the retry behavior, or you can apply it as a plain expression to get a new, retriable, co-routine function. Your final call could be:

    result = await (retry_http(client.get) (f"{HOST}/api/my_method"))

(note the extra pair of parentheses around client.get, decorating it)

The decorator itself could be:

def retry_http(coro_func):
    async def wrapper(*args, **kw):
        # your original code - just replacing the await expression
        ...
        while count > 5:
            ...
            result = await coro_func(*args, **kw)
            ...
        ...
        return result
    return wrapper

As for your original intent: it would actually be possible to introspect a coroutine object, its internal variables and passed parameter, to recreate a co-routine object that has not yet started - however, that would involve using introspection to locate the original callable, and making the call again - it would be cumbersome, could be slow, and for little gain. I will outline the requirements, nonetheless:

A co-routine object has the cr_code and cr_frame attributes - you'd need to retrieve the function associated with the code object in cr_code- probably using the garbage colector API, or recreate a new function re-using the same code object, by calling types.FunctionType with the same parameters - and the local and global variables can be retrieved from the frame object in cr_frame.


问:
Pydantic - Use schema field as field type in another schema
Is this concept somehow possible in Pydantic:

```<code>## one file
class StatusOut(BaseModel):
    id: int
    name: str

## another file
class UserOut(BaseModel):
    name: str
    status_name: StatusOut.name  ## IS THIS ACHIEVABLE???
</code>```

I get an error "AttributeError: type object 'StatusOut' has no attribute 'name'"

答:
So the first and only thing I got in mind is to override validation with @validator(...) decorator.

```<code>from pydantic import BaseModel, validator

class StatusOut(BaseModel):
    id: int
    name: str

class UserOut(BaseModel):
    name: str
    status_name: StatusOut

    @validator("status_name")
    def redefine_status_name(cls, v):
        return v.name

status = StatusOut(id=1, name="status")

user = UserOut(name="test", status_name=status)

print(user.json())  # {"name": "test", "status_name": "status"}
</code>```

I guess there is no need to explain what I did, I just returned StatusOut().name instead of StatusOut itself

Although I do not suggest doing that, as it makes status_name's real type not the one that is declared and might confuse you in future

Body:
Is this concept somehow possible in Pydantic:

## one file
class StatusOut(BaseModel):
    id: int
    name: str

## another file
class UserOut(BaseModel):
    name: str
    status_name: StatusOut.name  ## IS THIS ACHIEVABLE???

I get an error "AttributeError: type object 'StatusOut' has no attribute 'name'"

Body:
So the first and only thing I got in mind is to override validation with @validator(...) decorator.

from pydantic import BaseModel, validator

class StatusOut(BaseModel):
    id: int
    name: str

class UserOut(BaseModel):
    name: str
    status_name: StatusOut

    @validator("status_name")
    def redefine_status_name(cls, v):
        return v.name

status = StatusOut(id=1, name="status")

user = UserOut(name="test", status_name=status)

print(user.json())  # {"name": "test", "status_name": "status"}

I guess there is no need to explain what I did, I just returned StatusOut().name instead of StatusOut itself

Although I do not suggest doing that, as it makes status_name's real type not the one that is declared and might confuse you in future


问:
Tailwind - how to get version in js or php
My context
Laravel v8.81.0 (PHP v8.1.2), Vue v3.2.30 and Tailwind

I want to get Tailwind version in js such as getting Vue version by :

```<code>//app.js
require('./bootstrap');
import { createApp } from 'vue'
import { version } from 'vue'

let app = createApp({
    data() {
        return {
            vueVersion : version
        }
    },
}).mount('#app')
</code>```

and using version variable in vue and pass it to laravel view

There is also in Laravel

```<code>//uploadfiles.blade.php
...
<div class="mb-12 mt-12">
    <h1 class="text-lg">My app</h1>
    <h4 class="text-sm mt-4">powered by Laravel v{{ Illuminate\Foundation\Application::VERSION }} (PHP v{{ PHP_VERSION }}), Vue v${ vueVersion } and Tailwind</h4>
</div>
...
</code>```

Or get Tailwind version similar to php way to render php version and laravel version.

App build/compiled? in Laravel Mix/webpack?(npm run dev ) and laravel cli (./vendor/bin/sail up)

```<code>mix.js('resources/js/app.js', 'public/js')
.postCss('resources/css/app.css', 'public/css', [
    require('tailwindcss')
]).vue();
</code>```

//package.json
{
    "private": true,
    "scripts": {
        "dev": "npm run development",
        "development": "mix",
        "watch": "mix watch",
        "watch-poll": "mix watch -- --watch-options-poll=1000",
        "hot": "mix watch --hot",
        "prod": "npm run production",
        "production": "mix --production"
    },
    "devDependencies": {
        "axios": "^0.21",
        "laravel-mix": "^6.0.6",
        "lodash": "^4.17.19",
        "postcss": "^8.1.14",
        "tailwindcss": "^3.0.18",
        "vue-loader": "^16.8.3"
    },
    "dependencies": {
        "vue": "^3.2.30"
    }
}
```

答:
You can use php file_ge_content to read package.json</p>
```<code><?php

$packageJSON = json_decode( file_get_contents(ABSPATH . 'package.json') );

var_dump($packageJSON->devDependencies->tailwindcss);
</code>```

Body:
My context
Laravel v8.81.0 (PHP v8.1.2), Vue v3.2.30 and Tailwind

I want to get Tailwind version in js such as getting Vue version by :

//app.js
require('./bootstrap');
import { createApp } from 'vue'
import { version } from 'vue'

let app = createApp({
    data() {
        return {
            vueVersion : version
        }
    },
}).mount('#app')

and using version variable in vue and pass it to laravel view

There is also in Laravel

//uploadfiles.blade.php
...

My app

powered by Laravel v{{ Illuminate\Foundation\Application::VERSION }} (PHP v{{ PHP_VERSION }}), Vue v${ vueVersion } and Tailwind

...

Or get Tailwind version similar to php way to render php version and laravel version.

App build/compiled? in Laravel Mix/webpack?(npm run dev ) and laravel cli (./vendor/bin/sail up)

mix.js('resources/js/app.js', 'public/js')
.postCss('resources/css/app.css', 'public/css', [
    require('tailwindcss')
]).vue();

//package.json
{
    "private": true,
    "scripts": {
        "dev": "npm run development",
        "development": "mix",
        "watch": "mix watch",
        "watch-poll": "mix watch -- --watch-options-poll=1000",
        "hot": "mix watch --hot",
        "prod": "npm run production",
        "production": "mix --production"
    },
    "devDependencies": {
        "axios": "^0.21",
        "laravel-mix": "^6.0.6",
        "lodash": "^4.17.19",
        "postcss": "^8.1.14",
        "tailwindcss": "^3.0.18",
        "vue-loader": "^16.8.3"
    },
    "dependencies": {
        "vue": "^3.2.30"
    }
}

Body:
You can use php file_ge_content to read package.json

<?php

$packageJSON = json_decode( file_get_contents(ABSPATH . 'package.json') );

var_dump($packageJSON->devDependencies->tailwindcss);


问:
How to apply getPerspectiveTransform twice in 1 go/ How do I multiply the coordinates of a rectangle in a rectangle in a 2D space?
I am trying to extract a rectangle that is on a boardgame(called sub in the attached illustration) from a picture (called main in the attached illustration). I know the position of the rectange relative to the board, and I know the position of the board relative to the picture. My goal is to extract the rectangle from the picture with getPerspectiveTransform.

In the following image the rectangle has been replace by a single coordinate of one of the corners to make the illustration simpler.

For the coordinate on the picture i expect a coordinate of something in the range of (290,190).

I tried using getPerspectiveTransform twice: once to get the board(sub) and then extract the rectangle from the resulting board(sub) image. But that leads to quality loss and is a hit on performance.

I also tried multiplying 2 matrixes with each other with the goal of getting the coordinates for the inner rectangle, but that didn't work. This calculation does not work in a 2d space. My knowledge of matrixes is almost none. My attempt:

```<code>main_width = 4000
mainheight = 2250

subwidth = 800
subheight = 533
# [top-left, top-right, bottom-right, bottom-left]
main  = np.float32([[386/main_width, 90/mainheight],[3441/main_width, 72/mainheight],[301/main_width, 2174/mainheight],[3540/main_width, 2163/mainheight]])
sub  = np.float32([[132/subwidth,56/subheight],[145/subwidth,79/subheight],[137/subwidth,83/subheight],[126/subwidth,59/subheight]])

innerRectangle = cv2.multiply(main,sub)
print(innerRectangle)
</code>```

How do I extract the coordinates of the inner rectangle?

答:
Well, I couldn't get it to work with the libraries, so I tried programming it myself. I came up with the following:

```<code>import numpy as np

main_width = 4000
mainheight = 2250

subwidth = 990
subheight = 660

#                   0            1               2               3
#                   [top-left,   top-right,      bottom-right,   bottom-left]
main = np.float32([ [386, 90],   [3437, 72],     [3538, 2165],   [300, 2175]])
sub = np.float32([  [166, 68],   [180, 98],      [169, 103],     [156, 73]])

subTopLeftX = sub[0][0]
boardRatioWidth = subTopLeftX/subwidth#132/800
print("boardRatioWidth: \t" + str(boardRatioWidth))#.165

subTopLeftY = sub[0][1]
boardRatioHeight = subTopLeftY/subheight#58/533
print("boardRatioHeight: \t" + str(boardRatioHeight))#0.108

#              386 +          ((291-386) * 0.108)
leftsideX = main[0][0] + ((main[3][0] - main[0][0]) * boardRatioHeight)
#3444 + ((3555-3444) * 0.108)
rightsideX = main[1][0] + ((main[2][0] - main[1][0]) * (boardRatioHeight))

x = leftsideX + ((rightsideX - leftsideX) * boardRatioWidth)

#88 + ((70 - 88 ) * .165)
topsideY = main[0][1] + ((main[1][1] - main[0][1]) * boardRatioWidth)
print("topsideY: \t" + str(topsideY))
bottomsideY = main[3][1] + ((main[2][1] - main[3][1]) * (boardRatioWidth))
print("bottomsideY: \t" + str(bottomsideY))

#87 + ((2172 - 87) * .108)
y = topsideY + ((bottomsideY - topsideY) * boardRatioHeight)

print("x,y: \t" + str((x, y)))
</code>```

This calculates 1 x,y coordinate. To calculate X, it calcaluates x at the left side of the board(leftsideX), the right side of the board(rightsideX), and multiplies the 2 based on the ratio(boardRatioWidth) of how far the coordinate is. The same is being done for Y but the other way around.

Body:
I am trying to extract a rectangle that is on a boardgame(called sub in the attached illustration) from a picture (called main in the attached illustration). I know the position of the rectange relative to the board, and I know the position of the board relative to the picture. My goal is to extract the rectangle from the picture with getPerspectiveTransform.

In the following image the rectangle has been replace by a single coordinate of one of the corners to make the illustration simpler.

For the coordinate on the picture i expect a coordinate of something in the range of (290,190).

I tried using getPerspectiveTransform twice: once to get the board(sub) and then extract the rectangle from the resulting board(sub) image. But that leads to quality loss and is a hit on performance.

I also tried multiplying 2 matrixes with each other with the goal of getting the coordinates for the inner rectangle, but that didn't work. This calculation does not work in a 2d space. My knowledge of matrixes is almost none. My attempt:

main_width = 4000
mainheight = 2250

subwidth = 800
subheight = 533
# [top-left, top-right, bottom-right, bottom-left]
main  = np.float32([[386/main_width, 90/mainheight],[3441/main_width, 72/mainheight],[301/main_width, 2174/mainheight],[3540/main_width, 2163/mainheight]])
sub  = np.float32([[132/subwidth,56/subheight],[145/subwidth,79/subheight],[137/subwidth,83/subheight],[126/subwidth,59/subheight]])

innerRectangle = cv2.multiply(main,sub)
print(innerRectangle)

How do I extract the coordinates of the inner rectangle?

Body:
Well, I couldn't get it to work with the libraries, so I tried programming it myself. I came up with the following:

import numpy as np

main_width = 4000
mainheight = 2250

subwidth = 990
subheight = 660

#                   0            1               2               3
#                   [top-left,   top-right,      bottom-right,   bottom-left]
main = np.float32([ [386, 90],   [3437, 72],     [3538, 2165],   [300, 2175]])
sub = np.float32([  [166, 68],   [180, 98],      [169, 103],     [156, 73]])

subTopLeftX = sub[0][0]
boardRatioWidth = subTopLeftX/subwidth#132/800
print("boardRatioWidth: \t" + str(boardRatioWidth))#.165

subTopLeftY = sub[0][1]
boardRatioHeight = subTopLeftY/subheight#58/533
print("boardRatioHeight: \t" + str(boardRatioHeight))#0.108

#              386 +          ((291-386) * 0.108)
leftsideX = main[0][0] + ((main[3][0] - main[0][0]) * boardRatioHeight)
#3444 + ((3555-3444) * 0.108)
rightsideX = main[1][0] + ((main[2][0] - main[1][0]) * (boardRatioHeight))

x = leftsideX + ((rightsideX - leftsideX) * boardRatioWidth)

#88 + ((70 - 88 ) * .165)
topsideY = main[0][1] + ((main[1][1] - main[0][1]) * boardRatioWidth)
print("topsideY: \t" + str(topsideY))
bottomsideY = main[3][1] + ((main[2][1] - main[3][1]) * (boardRatioWidth))
print("bottomsideY: \t" + str(bottomsideY))

#87 + ((2172 - 87) * .108)
y = topsideY + ((bottomsideY - topsideY) * boardRatioHeight)

print("x,y: \t" + str((x, y)))

This calculates 1 x,y coordinate. To calculate X, it calcaluates x at the left side of the board(leftsideX), the right side of the board(rightsideX), and multiplies the 2 based on the ratio(boardRatioWidth) of how far the coordinate is. The same is being done for Y but the other way around.


问:
I am not able to add custom CSS to the scroll bar that i have created in a Card component in MUI react
```<code>import React from "react";
import Card from "@mui/material/Card";
import CardActions from "@mui/material/CardActions";
import CardContent from "@mui/material/CardContent";
import CardMedia from "@mui/material/CardMedia";
import Button from "@mui/material/Button";
import Typography from "@mui/material/Typography";
import Grid from "@mui/material/Grid";
import ShareIcon from "@mui/icons-material/Share";
import LocalLibraryIcon from "@mui/icons-material/LocalLibrary";
import { makeStyles } from '@mui/styles';

const useStyles = makeStyles({
  scrollBar: {
    "::-webkit-scrollbar": {
      width: "3px",
    },

    "::-webkit-scrollbar-track": {
      boxShadow: "inset 0 0 5px rgb(255, 251, 251)",
      borderRadius: "10px",
    },

    "::-webkit-scrollbar-thumb": {
      background: "#077DFA",
      borderRadius: "10px",
    },

    "::-webkit-scrollbar-thumb:hover": {
      background: "rgb(255, 251, 251)",
    }
  }
});

export default function MediaCard(props) {
  const classes = useStyles()

  return (

        <Grid item md={4} >

          <Card className={classes.scrollBar} sx={{ maxWidth: 345 , maxHeight : 345, overflowY: "scroll"}}>
            <CardMedia
              component="img"
              height="190"
              image={props.img}
              alt={props.alt}

            />

            <CardContent>
              <Typography gutterBottom variant="h5" component="div">
                {props.headline}
              </Typography>
              <Typography variant="body2" color="text.secondary">
                {props.content}
              </Typography>
            </CardContent>
            <CardActions>
              <Button
                size="small"
                href=""
                variant="contained"
                endIcon={<ShareIcon />}
              >
                {" "}
                Share
              </Button>
              <Button
                sx={{ marginLeft: ".5rem" }}
                target="_blank"
                size="small"
                variant="contained"
                href={props.learnMore}
                endIcon={<LocalLibraryIcon />}
              >
                Learn More
              </Button>
            </CardActions>
          </Card>
        </Grid>
  );
}
</code>```

When I create a custom styles for the scroll bar by importing makeStyles function and store that under the useStyles hook and when I fire that hook and store it under classes, and finally use that classes inside class name of Card component, I see scrollbar styles unchanged. What could be the cause of this problem?

答:
You are just missing the ampersand (&) before the colon inside the scrollBar css. Try again:

```<code>import React from "react";
import Card from "@mui/material/Card";
import CardActions from "@mui/material/CardActions";
import CardContent from "@mui/material/CardContent";
import CardMedia from "@mui/material/CardMedia";
import Button from "@mui/material/Button";
import Typography from "@mui/material/Typography";
import Grid from "@mui/material/Grid";
import ShareIcon from "@mui/icons-material/Share";
import LocalLibraryIcon from "@mui/icons-material/LocalLibrary";
import { makeStyles } from '@mui/styles';

const useStyles = makeStyles({
  scrollBar: {
    "&::-webkit-scrollbar": {
      width: "3px",
    },

    "&::-webkit-scrollbar-track": {
      boxShadow: "inset 0 0 5px rgb(255, 251, 251)",
      borderRadius: "10px",
    },

    "&::-webkit-scrollbar-thumb": {
      background: "#077DFA",
      borderRadius: "10px",
    },

    "&::-webkit-scrollbar-thumb:hover": {
      background: "rgb(255, 251, 251)",
    }
  }
});

export default function MediaCard(props) {
  const classes = useStyles()

  return (

        <Grid item md={4} >

          <Card className={classes.scrollBar} sx={{ maxWidth: 345 , maxHeight : 345, overflowY: "scroll"}}>
            <CardMedia
              component="img"
              height="190"
              image={props.img}
              alt={props.alt}

            />

            <CardContent>
              <Typography gutterBottom variant="h5" component="div">
                {props.headline}
              </Typography>
              <Typography variant="body2" color="text.secondary">
                {props.content}
              </Typography>
            </CardContent>
            <CardActions>
              <Button
                size="small"
                href=""
                variant="contained"
                endIcon={<ShareIcon />}
              >
                {" "}
                Share
              </Button>
              <Button
                sx={{ marginLeft: ".5rem" }}
                target="_blank"
                size="small"
                variant="contained"
                href={props.learnMore}
                endIcon={<LocalLibraryIcon />}
              >
                Learn More
              </Button>
            </CardActions>
          </Card>
        </Grid>
  );
}
</code>```

Body:
import React from "react";
import Card from "@mui/material/Card";
import CardActions from "@mui/material/CardActions";
import CardContent from "@mui/material/CardContent";
import CardMedia from "@mui/material/CardMedia";
import Button from "@mui/material/Button";
import Typography from "@mui/material/Typography";
import Grid from "@mui/material/Grid";
import ShareIcon from "@mui/icons-material/Share";
import LocalLibraryIcon from "@mui/icons-material/LocalLibrary";
import { makeStyles } from '@mui/styles';

const useStyles = makeStyles({
  scrollBar: {
    "::-webkit-scrollbar": {
      width: "3px",
    },

    "::-webkit-scrollbar-track": {
      boxShadow: "inset 0 0 5px rgb(255, 251, 251)",
      borderRadius: "10px",
    },

    "::-webkit-scrollbar-thumb": {
      background: "#077DFA",
      borderRadius: "10px",
    },

    "::-webkit-scrollbar-thumb:hover": {
      background: "rgb(255, 251, 251)",
    }
  }
});

export default function MediaCard(props) {
  const classes = useStyles()

  return (

        <Grid item md={4} >

          <Card className={classes.scrollBar} sx={{ maxWidth: 345 , maxHeight : 345, overflowY: "scroll"}}>
            <CardMedia
              component="img"
              height="190"
              image={props.img}
              alt={props.alt}

            />

            <CardContent>
              <Typography gutterBottom variant="h5" component="div">
                {props.headline}
              </Typography>
              <Typography variant="body2" color="text.secondary">
                {props.content}
              </Typography>
            </CardContent>
            <CardActions>
              <Button
                size="small"
                href=""
                variant="contained"
                endIcon={<ShareIcon />}
              >
                {" "}
                Share
              </Button>
              <Button
                sx={{ marginLeft: ".5rem" }}
                target="_blank"
                size="small"
                variant="contained"
                href={props.learnMore}
                endIcon={<LocalLibraryIcon />}
              >
                Learn More
              </Button>
            </CardActions>
          </Card>
        </Grid>
  );
}

When I create a custom styles for the scroll bar by importing makeStyles function and store that under the useStyles hook and when I fire that hook and store it under classes, and finally use that classes inside class name of Card component, I see scrollbar styles unchanged. What could be the cause of this problem?

Body:
You are just missing the ampersand (&) before the colon inside the scrollBar css. Try again:

import React from "react";
import Card from "@mui/material/Card";
import CardActions from "@mui/material/CardActions";
import CardContent from "@mui/material/CardContent";
import CardMedia from "@mui/material/CardMedia";
import Button from "@mui/material/Button";
import Typography from "@mui/material/Typography";
import Grid from "@mui/material/Grid";
import ShareIcon from "@mui/icons-material/Share";
import LocalLibraryIcon from "@mui/icons-material/LocalLibrary";
import { makeStyles } from '@mui/styles';

const useStyles = makeStyles({
  scrollBar: {
    "&::-webkit-scrollbar": {
      width: "3px",
    },

    "&::-webkit-scrollbar-track": {
      boxShadow: "inset 0 0 5px rgb(255, 251, 251)",
      borderRadius: "10px",
    },

    "&::-webkit-scrollbar-thumb": {
      background: "#077DFA",
      borderRadius: "10px",
    },

    "&::-webkit-scrollbar-thumb:hover": {
      background: "rgb(255, 251, 251)",
    }
  }
});

export default function MediaCard(props) {
  const classes = useStyles()

  return (

        <Grid item md={4} >

          <Card className={classes.scrollBar} sx={{ maxWidth: 345 , maxHeight : 345, overflowY: "scroll"}}>
            <CardMedia
              component="img"
              height="190"
              image={props.img}
              alt={props.alt}

            />

            <CardContent>
              <Typography gutterBottom variant="h5" component="div">
                {props.headline}
              </Typography>
              <Typography variant="body2" color="text.secondary">
                {props.content}
              </Typography>
            </CardContent>
            <CardActions>
              <Button
                size="small"
                href=""
                variant="contained"
                endIcon={<ShareIcon />}
              >
                {" "}
                Share
              </Button>
              <Button
                sx={{ marginLeft: ".5rem" }}
                target="_blank"
                size="small"
                variant="contained"
                href={props.learnMore}
                endIcon={<LocalLibraryIcon />}
              >
                Learn More
              </Button>
            </CardActions>
          </Card>
        </Grid>
  );
}


问:
Angular, Init form inputs are invalid but value is valid
I made an angular form with two inputs number and one select.
I fill these inputs with a model values, but the two numbers inputs is invalid and i need to click inside it to change it to valid.

I use inputs like this :

```<code><input type="text"
  name="price"
  id="price"
  [(ngModel)]="chair.price"
  formControlName="price"
  class="form-control form-control-lg form-control-solid"
  [ngClass]="{
      'is-invalid': editPriceForm.controls['price'].invalid,
      'is-valid':editPriceForm.controls['price'].valid
   }"
/>
</code>```

So in the initial render form, i get the good value in the inputs but the class of the input is 'is-invalid', and i don't know why. I try to trigget a markAllAsTouched but nothing change.

When i click inside the input, and click out, the class change to become valid.

Do you know if something is possible to tell to the form to be rechecked after filling data ?

答:
This happens because the code is always executing, without checking if the user made any changes for it to check. What you should do is the following:

```<code>    <input type="text"
      name="price"
      id="price"
      [(ngModel)]="chair.price"
      formControlName="price"
      class="form-control form-control-lg form-control-solid"
      [ngClass]="{
                  'is-invalid': editPriceForm.controls['price'].invalid &&
                                editPriceForm.controls['price'].touched
                  }"
    />
</code>```

With what I added that was editPriceForm.controls['price'].touched the code is only executed if the user clicked on the input

Body:
I made an angular form with two inputs number and one select.
I fill these inputs with a model values, but the two numbers inputs is invalid and i need to click inside it to change it to valid.

I use inputs like this :

<input type="text"
  name="price"
  id="price"
  [(ngModel)]="chair.price"
  formControlName="price"
  class="form-control form-control-lg form-control-solid"
  [ngClass]="{
      'is-invalid': editPriceForm.controls['price'].invalid,
      'is-valid':editPriceForm.controls['price'].valid
   }"
/>

So in the initial render form, i get the good value in the inputs but the class of the input is 'is-invalid', and i don't know why. I try to trigget a markAllAsTouched but nothing change.

When i click inside the input, and click out, the class change to become valid.

Do you know if something is possible to tell to the form to be rechecked after filling data ?

Body:
This happens because the code is always executing, without checking if the user made any changes for it to check. What you should do is the following:

    <input type="text"
      name="price"
      id="price"
      [(ngModel)]="chair.price"
      formControlName="price"
      class="form-control form-control-lg form-control-solid"
      [ngClass]="{
                  'is-invalid': editPriceForm.controls['price'].invalid &&
                                editPriceForm.controls['price'].touched
                  }"
    />

With what I added that was editPriceForm.controls['price'].touched the code is only executed if the user clicked on the input


问:
Keeping elements in their relative position to the background when resizing window?
I'd like the logo to "follow the movement" of the centered background (a picture) when resizing the window. Is it possible ? I've tried a lot of things, but couldn't get it.

Background

div.container{
     width:1164px;
    height: 776px;
    margin:0px;
    border:none;
    line-height:150%;

background-image: url('background');
    background-repeat: no-repeat;
    background-attachment:fixed;
    background-position:left:45px;top:20px;

    }

Logo

答:
If you are trying to center the content only horizontally you can try
div.container{margin:0 auto}
and put the background image on the body like this
body {background-image: url('background'); background-position: 50% 0px;}</p>

ContentLicense: CC BY-SA 3.0


问:
Class AMSupportURLConnectionDelegate is implemented in both
I'm trying to build a flutter app on M1 mac and getting the following error.

```<code>$ flutter build ios --release
Building XXX for device (ios-release)...
Automatically signing iOS for device deployment using specified development team in Xcode project: XXX
Running pod install...                                             13.2s
Running Xcode build...
Xcode build done.                                            6.7s
Failed to build iOS app
Error output from Xcode build:
↳
    objc[65074]: Class AMSupportURLConnectionDelegate is implemented in both ?? (0x1f66de518) and ?? (0x1160d82b8). One
    of the two will be used. Which one is undefined.
    objc[65074]: Class AMSupportURLSession is implemented in both ?? (0x1f66de568) and ?? (0x1160d8308). One of the two
    will be used. Which one is undefined.
    ** BUILD FAILED **

Xcode's output:
↳
    note: Using new build system
    note: Building targets in parallel
    note: Planning build
    note: Constructing build description
    error: The linked framework 'Pods_Runner.framework' is missing one or more architectures required by this target:
    armv7. (in target 'Runner' from project 'Runner')

Encountered error while building for device.
</code>```

Here is my flutter doctor -v

```<code>flutter doctor -v
[✓] Flutter (Channel stable, 1.22.4, on macOS 11.0 20A2411 darwin-arm, locale en-AU)
    • Flutter version 1.22.4 at /Users/mlee/development/flutter
    • Framework revision 1aafb3a8b9 (3 weeks ago), 2020-11-13 09:59:28 -0800
    • Engine revision 2c956a31c0
    • Dart version 2.10.4

[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.2)
    • Android SDK at /Users/mlee/Library/Android/sdk
    • Platform android-30, build-tools 30.0.2
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 12.2)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 12.2, Build version 12B45b
    • CocoaPods version 1.10.0

[!] Android Studio (version 4.1)
    • Android Studio at /Applications/Android Studio.app/Contents
    ✗ Flutter plugin not installed; this adds Flutter specific functionality.
    ✗ Dart plugin not installed; this adds Dart specific functionality.
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)

[✓] VS Code (version 1.51.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.16.0

[✓] Connected device (2 available)

! Doctor found issues in 1 category.
</code>```

答:
For me the issue was that when I was doing the setup steps for Firebase Crashlytics, I didn't remove the < > characters, just replaced googleAppId with my app ID.

```<code>$PODS_ROOT/FirebaseCrashlytics/upload-symbols --build-phase --validate -ai <googleAppId>
$PODS_ROOT/FirebaseCrashlytics/upload-symbols --build-phase -ai <googleAppId>
</code>```

You might have an other issue, so go to xcode and run from there, you'll see a more detailed error message.

Body:
I'm trying to build a flutter app on M1 mac and getting the following error.

$ flutter build ios --release
Building XXX for device (ios-release)...
Automatically signing iOS for device deployment using specified development team in Xcode project: XXX
Running pod install...                                             13.2s
Running Xcode build...
Xcode build done.                                            6.7s
Failed to build iOS app
Error output from Xcode build:
↳
    objc[65074]: Class AMSupportURLConnectionDelegate is implemented in both ?? (0x1f66de518) and ?? (0x1160d82b8). One
    of the two will be used. Which one is undefined.
    objc[65074]: Class AMSupportURLSession is implemented in both ?? (0x1f66de568) and ?? (0x1160d8308). One of the two
    will be used. Which one is undefined.
    ** BUILD FAILED **

Xcode's output:
↳
    note: Using new build system
    note: Building targets in parallel
    note: Planning build
    note: Constructing build description
    error: The linked framework 'Pods_Runner.framework' is missing one or more architectures required by this target:
    armv7. (in target 'Runner' from project 'Runner')

Encountered error while building for device.

Here is my flutter doctor -v

flutter doctor -v
[✓] Flutter (Channel stable, 1.22.4, on macOS 11.0 20A2411 darwin-arm, locale en-AU)
    • Flutter version 1.22.4 at /Users/mlee/development/flutter
    • Framework revision 1aafb3a8b9 (3 weeks ago), 2020-11-13 09:59:28 -0800
    • Engine revision 2c956a31c0
    • Dart version 2.10.4

[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.2)
    • Android SDK at /Users/mlee/Library/Android/sdk
    • Platform android-30, build-tools 30.0.2
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 12.2)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 12.2, Build version 12B45b
    • CocoaPods version 1.10.0

[!] Android Studio (version 4.1)
    • Android Studio at /Applications/Android Studio.app/Contents
    ✗ Flutter plugin not installed; this adds Flutter specific functionality.
    ✗ Dart plugin not installed; this adds Dart specific functionality.
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6915495)

[✓] VS Code (version 1.51.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.16.0

[✓] Connected device (2 available)

! Doctor found issues in 1 category.

Body:
For me the issue was that when I was doing the setup steps for Firebase Crashlytics, I didn't remove the < > characters, just replaced googleAppId with my app ID.

$PODS_ROOT/FirebaseCrashlytics/upload-symbols --build-phase --validate -ai <googleAppId>
$PODS_ROOT/FirebaseCrashlytics/upload-symbols --build-phase -ai <googleAppId>

You might have an other issue, so go to xcode and run from there, you'll see a more detailed error message.