问:
Extracting strings from unserialized object (PHP)
I've unserialized an object in PHP which gives the below output. I'd like to extract the 2 URLs (or how ever many there will be) from the [file_url] index and store them into the database (by doing a foreach and then INSERT INTO via SQL?). Could anyone tell me the best way to achieve this? I've never worked with serializing/unserializing objects before.

```<code>Array
(
    [file] => Array
        (
            [success] => 1
            [file_url] => Array
                (
                    [0] => https://example.com/wp-content/uploads/2022/02/test1.png
                    [1] => https://example.com/wp-content/uploads/2022/02/test2.jpg
                )

            [file_path] => Array
                (
                    [0] => /var/www/html/wp-content/uploads/2022/02/test1.png
                    [1] => /var/www/html/wp-content/uploads/2022/02/test2.jpg
                )

        )

)
</code>```

答:
You can simply use indexes. something like

$value = $arr['file'][x][y]

This is a multidimentional array. Its a 3 dimentional array to be exact.

Examples:

```<code>$value = $arr['file']['success']
$value = $arr['file']['file_path'][0]
</code>```

You could also do

$value = $arr['file'][0]

Example of other dimentional arrays

```<code>$cars = array (
  array("Volvo",22,18),
  array("BMW",15,13),
);
</code>```

With SQL?

Sure, use PDO and bindParam for that crisp security

```<code>$query = $con->prepare("UPDATE nearly_inactive SET :email = :emailaddr WHERE EmailSent = :id");
$query->bindParam(':email', $email, PDO::PARAM_STR);
$query->bindParam(':emailaddr', $emailaddr, PDO::PARAM_STR);
$query->bindParam(':id', $id, PDO::PARAM_STR);
$update->execute();
</code>```

Body:
I've unserialized an object in PHP which gives the below output. I'd like to extract the 2 URLs (or how ever many there will be) from the [file_url] index and store them into the database (by doing a foreach and then INSERT INTO via SQL?). Could anyone tell me the best way to achieve this? I've never worked with serializing/unserializing objects before.

Array
(
    [file] => Array
        (
            [success] => 1
            [file_url] => Array
                (
                    [0] => https://example.com/wp-content/uploads/2022/02/test1.png
                    [1] => https://example.com/wp-content/uploads/2022/02/test2.jpg
                )

            [file_path] => Array
                (
                    [0] => /var/www/html/wp-content/uploads/2022/02/test1.png
                    [1] => /var/www/html/wp-content/uploads/2022/02/test2.jpg
                )

        )

)

Body:
You can simply use indexes. something like

$value = $arr['file'][x][y]

This is a multidimentional array. Its a 3 dimentional array to be exact.

Examples:

$value = $arr['file']['success']
$value = $arr['file']['file_path'][0]

You could also do

$value = $arr['file'][0]

Example of other dimentional arrays

$cars = array (
  array("Volvo",22,18),
  array("BMW",15,13),
);

With SQL?

Sure, use PDO and bindParam for that crisp security

$query = $con->prepare("UPDATE nearly_inactive SET :email = :emailaddr WHERE EmailSent = :id");
$query->bindParam(':email', $email, PDO::PARAM_STR);
$query->bindParam(':emailaddr', $emailaddr, PDO::PARAM_STR);
$query->bindParam(':id', $id, PDO::PARAM_STR);
$update->execute();


来源: stackexchange

问:
Average of rows in SQL
here my table
Table

I want to find the average of MTK+IPA+PJOK
table 2

with this code

```<code>SELECT induk, nama, kelas,
       SUM(if (kdmapel=“111”,ratarata,0)) as MTK,
       SUM(if (kdmapel=“112”,ratarata,0)) as IPA,
       SUM(if (kdmapel=“115”,ratarata,0)) as PJOK,
       ((MTK+IPA+PJOK)/3) as NAR
from nilai
WHERE kelas=1 and semester=“ganjil”
group by induk
</code>```

but it doesn't work, the error said

#1054 - Unknown column 'MTK' in 'field list'

答:
Looks like you are referencing the alias name and it doesn’t know what that is.

Either write it as a CTE and then add the alias columns together or first store the results in a temp table and then add them.

Something like this

```<code>;With myCte as
(

SELECT induk,
       nama,
       kelas,
       SUM(if (kdmapel='111',ratarata,0)) as MTK,
       SUM(if (kdmapel='112',ratarata,0)) as IPA,
       SUM(if (kdmapel='115',ratarata,0)) as PJOK
      from nilai WHERE kelas=1 and semester='ganjil'
      group by induk

)
Select *,
 ((MTK+IPA+PJOK)/3) as NAR
  From myCte
</code>```

ContentLicense: CC BY-SA 4.0

Title: Average of rows in SQL

Body:
here my table
Table

I want to find the average of MTK+IPA+PJOK
table 2

with this code

SELECT induk, nama, kelas,
       SUM(if (kdmapel=“111”,ratarata,0)) as MTK,
       SUM(if (kdmapel=“112”,ratarata,0)) as IPA,
       SUM(if (kdmapel=“115”,ratarata,0)) as PJOK,
       ((MTK+IPA+PJOK)/3) as NAR
from nilai
WHERE kelas=1 and semester=“ganjil”
group by induk

but it doesn't work, the error said

#1054 - Unknown column 'MTK' in 'field list'

Body:
Looks like you are referencing the alias name and it doesn’t know what that is.

Either write it as a CTE and then add the alias columns together or first store the results in a temp table and then add them.

Something like this

;With myCte as
(

SELECT induk,
       nama,
       kelas,
       SUM(if (kdmapel='111',ratarata,0)) as MTK,
       SUM(if (kdmapel='112',ratarata,0)) as IPA,
       SUM(if (kdmapel='115',ratarata,0)) as PJOK
      from nilai WHERE kelas=1 and semester='ganjil'
      group by induk

)
Select *,
 ((MTK+IPA+PJOK)/3) as NAR
  From myCte


问:
How to get value from the second table if it's null in the first one
I have a little issue with a SQL query. So. I have three tables: Artists, Albums and Songs. Songs belong to some Album OR some Artist (only one from these two). Albums belong to only Artists. And I want to receive all recordings of songs that are in albums and that are without them with the name of the artist in each. How to do that?

Code that doesn't work:

```<code>select song_name, genre, lyrics,
concat(first_name, ' ', last_name) as full_name, album_name
from songs
left join artists on songs.artist_id = songs.artist_id
left join albums on artists.artist_id = albums.artist_id
</code>```

Result of this code

Instead of this, I want to see the name of each artist whether he has an album or not.

答:
Have you tried to use COALESCE?

COALESCE (argument_1, argument_2, …);
```

If one argument is null, the next one will be shown. Use as fist argument record of table one and as second table two.

Body:
I have a little issue with a SQL query. So. I have three tables: Artists, Albums and Songs. Songs belong to some Album OR some Artist (only one from these two). Albums belong to only Artists. And I want to receive all recordings of songs that are in albums and that are without them with the name of the artist in each. How to do that?

Code that doesn't work:

select song_name, genre, lyrics,
concat(first_name, ' ', last_name) as full_name, album_name
from songs
left join artists on songs.artist_id = songs.artist_id
left join albums on artists.artist_id = albums.artist_id

Result of this code

Instead of this, I want to see the name of each artist whether he has an album or not.

Body:
Have you tried to use COALESCE?

COALESCE (argument_1, argument_2, …);

If one argument is null, the next one will be shown. Use as fist argument record of table one and as second table two.


问:
Unable to add boolean value to contextProperties map of JAXBDataBinding in cxf beans xml
I am trying to set com.sun.xml.bind.treatEverythingNillable property to true as mentioned in document. But is throwing error.

How can I set the com.sun.xml.bind.treatEverythingNillable to Boolean TRUE Object?

https://cxf.apache.org/docs/jaxb.html

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws"
        xmlns:cxf="http://cxf.apache.org/core" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd http://www.springframework.org/schema/util
           http://www.springframework.org/schema/util/spring-util.xsd">
        <!-- <import resource="classpath:META-INF/cxf/cxf.xml" />
        <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
        <import resource="classpath:META-INF/cxf/cxf-servlet.xml" /> -->
        <jaxws:endpoint
                xmlns:tns="http://xmlns.chetan.com/oxp/service/v2"
                id="StudentService"
                implementor="com.chetan.webservices.cxf.StudentService"
                wsdlLocation="WEB-INF/wsdl/StudentService.wsdl"
                endpointName="tns:StudentService"
                serviceName="tns:StudentService"
                address="/v2/StudentService">
            <jaxws:dataBinding>
              <bean class="org.apache.cxf.jaxb.JAXBDataBinding">
                <property name="contextProperties">
                  <map>
                    <entry>
                      <key><value>com.sun.xml.bind.treatEverythingNillable</value></key>
                      <value>true</value>
                    </entry>
                  </map>
                </property>
              </bean>
            </jaxws:dataBinding>
        </jaxws:endpoint>
        <bean id="DocumentBuilderFactory" class="com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl">
        </bean>
        <bean id="cxf" class="org.apache.cxf.bus.spring.SpringBus"/>
        <cxf:bus>
            <cxf:properties>
               <entry key="org.apache.cxf.stax.maxChildElements" value="250000"/>
               <entry key="org.apache.cxf.stax.maxElementDepth" value="500"/>
               <!--<entry key="org.apache.cxf.stax.maxAttributeCount" value="500/>-->
               <!-- <entry key="org.apache.cxf.stax.maxAttributeSize" value="65536"/>-->
               <entry key="org.apache.cxf.stax.maxTextLength" value="1073741824"/>
            </cxf:properties>
        </cxf:bus>
</beans>
</code>```

Error

```<code>Caused by: javax.xml.bind.JAXBException: true is not a valid value for property "com.sun.xml.bind.treatEverythingNillable"
    at com.sun.xml.bind.v2.ContextFactory.getPropertyValue(ContextFactory.java:177)
    at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:99)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:247)
    at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:234)
    at javax.xml.bind.ContextFinder.find(ContextFinder.java:441)
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:641)
    at org.apache.cxf.common.jaxb.JAXBContextCache$2.run(JAXBContextCache.java:345)
    at org.apache.cxf.common.jaxb.JAXBContextCache$2.run(JAXBContextCache.java:343)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.apache.cxf.common.jaxb.JAXBContextCache.createContext(JAXBContextCache.java:343)
    at org.apache.cxf.common.jaxb.JAXBContextCache.getCachedContextAndSchemas(JAXBContextCache.java:245)
    at org.apache.cxf.jaxb.JAXBDataBinding.createJAXBContextAndSchemas(JAXBDataBinding.java:496)
    at org.apache.cxf.jaxb.JAXBDataBinding.initialize(JAXBDataBinding.java:355)
    ... 44 more
</code>```

Windows 10 + JDK8 + Tomcat 8.75 + JAXB 3.3.10

答:
Copy / pasting the answer from the ticket (https://issues.apache.org/jira/browse/CXF-8656). The problem is that you initialize this property with string value "true", not boolean value true as property expects:

```<code><key><value>com.sun.xml.bind.treatEverythingNillable</value></key>
<value>true</value>
</code>```

Please use:

```<code> <key><value>com.sun.xml.bind.treatEverythingNillable</value></key>
 <value type="java.lang.Boolean">true</value>
</code>```

Body:
I am trying to set com.sun.xml.bind.treatEverythingNillable property to true as mentioned in document. But is throwing error.

How can I set the com.sun.xml.bind.treatEverythingNillable to Boolean TRUE Object?

https://cxf.apache.org/docs/jaxb.html

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws"
        xmlns:cxf="http://cxf.apache.org/core" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd http://www.springframework.org/schema/util
           http://www.springframework.org/schema/util/spring-util.xsd">

        <jaxws:endpoint
                xmlns:tns="http://xmlns.chetan.com/oxp/service/v2"
                id="StudentService"
                implementor="com.chetan.webservices.cxf.StudentService"
                wsdlLocation="WEB-INF/wsdl/StudentService.wsdl"
                endpointName="tns:StudentService"
                serviceName="tns:StudentService"
                address="/v2/StudentService">
            <jaxws:dataBinding>
              <bean class="org.apache.cxf.jaxb.JAXBDataBinding">
                <property name="contextProperties">
                  <map>
                    <entry>
                      <key><value>com.sun.xml.bind.treatEverythingNillable</value></key>
                      <value>true</value>
                    </entry>
                  </map>
                </property>
              </bean>
            </jaxws:dataBinding>
        </jaxws:endpoint>
        <bean id="DocumentBuilderFactory" class="com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl">
        </bean>
        <bean id="cxf" class="org.apache.cxf.bus.spring.SpringBus"/>
        <cxf:bus>
            <cxf:properties>
               <entry key="org.apache.cxf.stax.maxChildElements" value="250000"/>
               <entry key="org.apache.cxf.stax.maxElementDepth" value="500"/>

               <entry key="org.apache.cxf.stax.maxTextLength" value="1073741824"/>
            </cxf:properties>
        </cxf:bus>
</beans>

Error

Caused by: javax.xml.bind.JAXBException: true is not a valid value for property "com.sun.xml.bind.treatEverythingNillable"
    at com.sun.xml.bind.v2.ContextFactory.getPropertyValue(ContextFactory.java:177)
    at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:99)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:247)
    at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:234)
    at javax.xml.bind.ContextFinder.find(ContextFinder.java:441)
    at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:641)
    at org.apache.cxf.common.jaxb.JAXBContextCache$2.run(JAXBContextCache.java:345)
    at org.apache.cxf.common.jaxb.JAXBContextCache$2.run(JAXBContextCache.java:343)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.apache.cxf.common.jaxb.JAXBContextCache.createContext(JAXBContextCache.java:343)
    at org.apache.cxf.common.jaxb.JAXBContextCache.getCachedContextAndSchemas(JAXBContextCache.java:245)
    at org.apache.cxf.jaxb.JAXBDataBinding.createJAXBContextAndSchemas(JAXBDataBinding.java:496)
    at org.apache.cxf.jaxb.JAXBDataBinding.initialize(JAXBDataBinding.java:355)
    ... 44 more

Windows 10 + JDK8 + Tomcat 8.75 + JAXB 3.3.10

Body:
Copy / pasting the answer from the ticket (https://issues.apache.org/jira/browse/CXF-8656). The problem is that you initialize this property with string value "true", not boolean value true as property expects:

<key><value>com.sun.xml.bind.treatEverythingNillable</value></key>
<value>true</value>

Please use:

 <key><value>com.sun.xml.bind.treatEverythingNillable</value></key>
 <value type="java.lang.Boolean">true</value>


答:
SELECT
    song_name,
    genre,
    lyrics,
    CONCAT(first_name, ' ', last_name) as full_name,
    album_name
FROM songs
LEFT JOIN albums
       ON songs.album_id = album.id
LEFT JOIN artists
       ON songs.artist_id = artists.id OR albums.artist_id = artist.id
```

I'm pretty sure this'll do it!

Title: How to get value from the second table if it's null in the first one

Body:
SELECT
    song_name,
    genre,
    lyrics,
    CONCAT(first_name, ' ', last_name) as full_name,
    album_name
FROM songs
LEFT JOIN albums
       ON songs.album_id = album.id
LEFT JOIN artists
       ON songs.artist_id = artists.id OR albums.artist_id = artist.id

I'm pretty sure this'll do it!


问:
Hide css grid item without display none
I have a css grid. Items are animated in using transform scaleY. I also have a search field which hides items on demand. The problem is when I hide an item (remove shown class) grid is not re-adjusted because it seems like item although it has height 0 / scaleY 0, it still behaves as part of the grid. I have made a demo to illustrate (one item is hidden for display purpose). Can this be achieved without using display none when I hide the items in grid?

var items = document.querySelectorAll('.item:not(.hidden)')

for (var i = 0, len = items.length; i < len; i++) {
  items[i].classList.add('shown')
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.wrap {
  display: grid;
  grid-gap: 1rem;
  justify-items: center;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
}

.item {
  padding: 50px;
  background-color: #ccc;
  overflow: hidden;
  box-sizing: border-box;
  transform: scaleY(0);
  transform-style: flat;
  height: 0;
}

.shown {
  transform: scaleY(1);
  opacity: 1;
  height: auto;
}</code>```

1

2

3

4

5

6

7

```

答:
If you don't want to use display:none you can remove the item.  Why can't you use display:none as that would make it easier to display it later?

var items = document.querySelectorAll('.item:not(.hidden)')

document.querySelectorAll('.hidden')[0].remove()

for (var i = 0, len = items.length; i < len; i++) {
  items[i].classList.add('shown')
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.wrap {
  display: grid;
  grid-gap: 1rem;
  justify-items: center;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
}

.item {
  padding: 50px;
  background-color: #ccc;
  overflow: hidden;
  box-sizing: border-box;
  transform: scaleY(0);
  transform-style: flat;
  height: 0;
}

.shown {
  transform: scaleY(1);
  opacity: 1;
  height: auto;
}</code>```

1

2

3

4

5

6

7

```

Title: Hide css grid item without display none

Body:
I have a css grid. Items are animated in using transform scaleY. I also have a search field which hides items on demand. The problem is when I hide an item (remove shown class) grid is not re-adjusted because it seems like item although it has height 0 / scaleY 0, it still behaves as part of the grid. I have made a demo to illustrate (one item is hidden for display purpose). Can this be achieved without using display none when I hide the items in grid?

var items = document.querySelectorAll('.item:not(.hidden)')

for (var i = 0, len = items.length; i < len; i++) {
  items[i].classList.add('shown')
}

.wrap {
  display: grid;
  grid-gap: 1rem;
  justify-items: center;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
}

.item {
  padding: 50px;
  background-color: #ccc;
  overflow: hidden;
  box-sizing: border-box;
  transform: scaleY(0);
  transform-style: flat;
  height: 0;
}

.shown {
  transform: scaleY(1);
  opacity: 1;
  height: auto;
}

1

2

3

4

5

6

7

Body:
If you don't want to use display:none you can remove the item.  Why can't you use display:none as that would make it easier to display it later?

var items = document.querySelectorAll('.item:not(.hidden)')

document.querySelectorAll('.hidden')[0].remove()

for (var i = 0, len = items.length; i < len; i++) {
  items[i].classList.add('shown')
}

.wrap {
  display: grid;
  grid-gap: 1rem;
  justify-items: center;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
}

.item {
  padding: 50px;
  background-color: #ccc;
  overflow: hidden;
  box-sizing: border-box;
  transform: scaleY(0);
  transform-style: flat;
  height: 0;
}

.shown {
  transform: scaleY(1);
  opacity: 1;
  height: auto;
}

<div class="wrap">
  <div class="item">1</div>
  <div class="item hidden">2</div>
  <div class="item">3</div>
  <div class="item">4</div>
  <div class="item">5</div>
  <div class="item">6</div>
  <div class="item">7</div>

</div>


问:
Why when I use onClick with radio button make them have to click twice to make radio button to be selected?
now, I using radio button to render 2 components differently I use onClick with radio button to [isRepeat,setisRepeat] setState value

```<code>  <input
     required
     id="singleClass"
     name="classType"
     type="radio"
     className="inputContainer"
     value={1}
     OnClick={() => setisRepeat("oneTime")}
     ></input>

     <label>ครั้งเดียว</label>
   <input
     required
     id="repeatClass"
     name="classType"
     type="radio"
     className="inputContainer"
     value={2}
     onClick={() => setisRepeat("repeat")}
     ></input>
</code>```

and render component like this

```<code>    {isRepeat === "oneTime" && (
        <>...</>
    )}
    {isRepeat === "repeat" && (
        <div>...</div>
    )}
</code>```

but when I using onClick() with radio button, It's make user to click "twice" to make radio button checked

(actually, setState work fine when click radio button but radio button didn't be checked. It should be checked and setState at the same time to make user not confuse)

ps. I already using document.getElementByName('classType').value === 1 or 2   to render different items, but didn't work

答:
You should use onChange with input as:

```<code>onChange={() => setisRepeat("oneTime")}
</code>```

instead of onClick

Demo

```<code>export default function App() {
  const [isRepeat, setisRepeat] = useState(""); // You can also give the initial value

  return (
    <div>
      <input
        required
        id="singleClass"
        name="classType"
        type="radio"
        className="inputContainer"
        value={1}
        onChange={() => setisRepeat("oneTime")}
      ></input>

      <label>ครั้งเดียว</label>
      <input
        required
        id="repeatClass"
        name="classType"
        type="radio"
        className="inputContainer"
        value={2}
        onChange={() => setisRepeat("repeat")}
      ></input>

      <br />

      {isRepeat === "oneTime" && <> One Time </>}
      {isRepeat === "repeat" && <div> Repeat </div>}
    </div>
  );
}
</code>```

Body:
now, I using radio button to render 2 components differently I use onClick with radio button to [isRepeat,setisRepeat] setState value

  <input
     required
     id="singleClass"
     name="classType"
     type="radio"
     className="inputContainer"
     value={1}
     OnClick={() => setisRepeat("oneTime")}
     ></input>

     ครั้งเดียว
   <input
     required
     id="repeatClass"
     name="classType"
     type="radio"
     className="inputContainer"
     value={2}
     onClick={() => setisRepeat("repeat")}
     ></input>

and render component like this

    {isRepeat === "oneTime" && (
        <>...</>
    )}
    {isRepeat === "repeat" && (

...

    )}

but when I using onClick() with radio button, It's make user to click "twice" to make radio button checked

(actually, setState work fine when click radio button but radio button didn't be checked. It should be checked and setState at the same time to make user not confuse)

ps. I already using document.getElementByName('classType').value === 1 or 2   to render different items, but didn't work

Body:
You should use onChange with input as:

onChange={() => setisRepeat("oneTime")}

instead of onClick

Demo

export default function App() {
  const [isRepeat, setisRepeat] = useState(""); // You can also give the initial value

  return (
    <div>
      <input
        required
        id="singleClass"
        name="classType"
        type="radio"
        className="inputContainer"
        value={1}
        onChange={() => setisRepeat("oneTime")}
      ></input>

      <label>ครั้งเดียว</label>
      <input
        required
        id="repeatClass"
        name="classType"
        type="radio"
        className="inputContainer"
        value={2}
        onChange={() => setisRepeat("repeat")}
      ></input>

      <br />

      {isRepeat === "oneTime" && <> One Time </>}
      {isRepeat === "repeat" && <div> Repeat </div>}
    </div>
  );
}


问:
Cannot group data by a column in R
I want to get a count of how many times each Player's name appears in my data frame ph1. My code is showing how many times each name is in the dataset, but I cannot group it by nso I can see how many times each Player's name is in the dataset.

I would prefer a dplyr solution but am open to others.

For example:

```<code>n Number_Players
1  21
2  2
</code>```

Code

```<code>ph1 %>%
     filter(!is.na(Player)) %>%
     group_by(Player) %>%
     mutate(n= n()) %>%
     relocate(n, .after=Player)
</code>```

Sample of how my output is appearing

```<code>Player              n   Year    PA  AB
Peavy, Jake         1   2008    58  49
Gallardo, Yovani    1   2014    59  53
Stratton, Chris     1   2018    50  43
Cashner, Andrew     1   2015    61  60
Anderson, Chase     1   2016    52  45
Burnes, Corbin      1   2021    59  52
Wolf, Randy         1   2009    80  67
Davies, Zach        2   2016    61  53
Senzatela, Antonio  1   2021    51  39
Syndergaard, Noah   2   2015    50  43
</code>```

Sample data

```<code>structure(list(Player = c("Peavy, Jake", "Gallardo, Yovani",
"Stratton, Chris", "Cashner, Andrew", "Anderson, Chase", "Burnes, Corbin",
"Wolf, Randy", "Davies, Zach", "Senzatela, Antonio", "Syndergaard, Noah",
"Syndergaard, Noah", "Davies, Zach", "Sánchez, Aníbal", "Hudson, Dakota",
"Leake, Mike", "De La Rosa, Jorge", "Cueto, Johnny", "González, Gio",
"Peralta, Wily", "Vólquez, Edinson", "Ryu, Hyun Jin", "Dempster, Ryan",
"Holland, Derek", "Wheeler, Zack", "Sabathia, CC"), Year = c(2008,
2014, 2018, 2015, 2016, 2021, 2009, 2016, 2021, 2015, 2016, 2019,
2019, 2019, 2016, 2015, 2008, 2015, 2014, 2014, 2014, 2009, 2018,
2014, 2008), PA = c(58, 59, 50, 61, 52, 59, 80, 61, 51, 50, 67,
54, 56, 59, 55, 50, 56, 56, 68, 64, 56, 75, 56, 62, 50), AB = c(49,
53, 43, 60, 45, 52, 67, 53, 39, 43, 58, 51, 52, 51, 49, 48, 45,
43, 57, 53, 47, 64, 53, 50, 48)), row.names = c(NA, -25L), class = c("tbl_df",
"tbl", "data.frame"))
</code>```

I checked the existing stackoverflow solutions, but did not see one that matches my need. If one exists, I would appreciate it if you could provide its link.

答:
We may use count to return the frequency count and then do a grouping on the count to do the count or n() again

```<code>library(dplyr)
ph1 %>%
 filter(!is.na(Player)) %>%
 count(Player) %>%
 group_by(n) %>%
 summarise(Number_Players = n())
</code>```

-output

```<code># A tibble: 2 × 2
      n Number_Players
  <int>          <int>
1     1             21
2     2              2
</code>```

or in base R, we can use table twice

```<code>stack(table(table(ph1$Player)))[2:1]
</code>```

Title: Cannot group data by a column in R

Body:
I want to get a count of how many times each Player's name appears in my data frame ph1. My code is showing how many times each name is in the dataset, but I cannot group it by nso I can see how many times each Player's name is in the dataset.

I would prefer a dplyr solution but am open to others.

For example:

n Number_Players
1  21
2  2

Code

ph1 %>%
     filter(!is.na(Player)) %>%
     group_by(Player) %>%
     mutate(n= n()) %>%
     relocate(n, .after=Player)

Sample of how my output is appearing

Player              n   Year    PA  AB
Peavy, Jake         1   2008    58  49
Gallardo, Yovani    1   2014    59  53
Stratton, Chris     1   2018    50  43
Cashner, Andrew     1   2015    61  60
Anderson, Chase     1   2016    52  45
Burnes, Corbin      1   2021    59  52
Wolf, Randy         1   2009    80  67
Davies, Zach        2   2016    61  53
Senzatela, Antonio  1   2021    51  39
Syndergaard, Noah   2   2015    50  43

Sample data

structure(list(Player = c("Peavy, Jake", "Gallardo, Yovani",
"Stratton, Chris", "Cashner, Andrew", "Anderson, Chase", "Burnes, Corbin",
"Wolf, Randy", "Davies, Zach", "Senzatela, Antonio", "Syndergaard, Noah",
"Syndergaard, Noah", "Davies, Zach", "Sánchez, Aníbal", "Hudson, Dakota",
"Leake, Mike", "De La Rosa, Jorge", "Cueto, Johnny", "González, Gio",
"Peralta, Wily", "Vólquez, Edinson", "Ryu, Hyun Jin", "Dempster, Ryan",
"Holland, Derek", "Wheeler, Zack", "Sabathia, CC"), Year = c(2008,
2014, 2018, 2015, 2016, 2021, 2009, 2016, 2021, 2015, 2016, 2019,
2019, 2019, 2016, 2015, 2008, 2015, 2014, 2014, 2014, 2009, 2018,
2014, 2008), PA = c(58, 59, 50, 61, 52, 59, 80, 61, 51, 50, 67,
54, 56, 59, 55, 50, 56, 56, 68, 64, 56, 75, 56, 62, 50), AB = c(49,
53, 43, 60, 45, 52, 67, 53, 39, 43, 58, 51, 52, 51, 49, 48, 45,
43, 57, 53, 47, 64, 53, 50, 48)), row.names = c(NA, -25L), class = c("tbl_df",
"tbl", "data.frame"))

I checked the existing stackoverflow solutions, but did not see one that matches my need. If one exists, I would appreciate it if you could provide its link.

Body:
We may use count to return the frequency count and then do a grouping on the count to do the count or n() again

library(dplyr)
ph1 %>%
 filter(!is.na(Player)) %>%
 count(Player) %>%
 group_by(n) %>%
 summarise(Number_Players = n())

-output

# A tibble: 2 × 2
      n Number_Players
  <int>          <int>
1     1             21
2     2              2

or in base R, we can use table twice

stack(table(table(ph1$Player)))[2:1]


问:
Passing Variable from JS to VB.net
I have a variable that gets a value in a js function. I need to get its value as a double into a vb.net variable.

I have tried putting the variable into a label then  grabbing it from the label in vb.net  as shown in the code below:

Js part.

```<code>document.getElementById("Label1").innerText = nwLat;
</code>```

then in the vb part

```<code>   Dim nwLat As Double
    nwLat = Label1.Text
    MsgBox(nwLat)
</code>```

it does not work for me any ideas? the error that comes up is
 Input string was not in a correct format.

Cheers!

答:
You need to use the ClientID or the UniqueID:</p>

```<code>document.getElementById("<%=Label1.UniqueID%>").innerText = "Hi";
</code>```

ContentLicense: CC BY-SA 3.0

Title: Passing Variable from JS to VB.net

Body:
I have a variable that gets a value in a js function. I need to get its value as a double into a vb.net variable.

I have tried putting the variable into a label then  grabbing it from the label in vb.net  as shown in the code below:

Js part.

document.getElementById("Label1").innerText = nwLat;

then in the vb part

   Dim nwLat As Double
    nwLat = Label1.Text
    MsgBox(nwLat)

it does not work for me any ideas? the error that comes up is
 Input string was not in a correct format.

Cheers!

Body:
You need to use the ClientID or the UniqueID:

document.getElementById("<%=Label1.UniqueID%>").innerText = "Hi";


问:
How to pass event's argument to a ReactiveCommand?
I have a custom control, which raises an event with an argument. I can bind a command to the event, but within the command handler argument is always null.

Here is the command binding:

```<code>this.BindCommand(ViewModel,
    vm => vm.MyCommand,
    v => v.InstanceOfCustomControl,
    toEvent: nameof(MyCustomControl.CustomEvent))
.DisposeWith(d);
</code>```

Here is the command definition and implementation:

```<code>MyCommand = ReactiveCommand
    .CreateFromTask<CustomEventArgs, Unit>(MyCommandImpl);

public ReactiveCommand<CustomEventArgs, Unit> MyCommand{ get; set; }
private Task<Unit> MyCommandImpl(CustomEventArgs args)
{
    if (args is null) throw new Exception("WTF?");
}
</code>```

I know for 100% that when event leaves custom control, it's argument is not null (=contains a value). But it arrives to the reactive command as null. What am I doing wrong?

答:
I feel better of the hack way introduced in the doc.

MyControl.Events().ValueChanged
    .Select(arg => arg.NewValue)
    .InvokeCommand(this, x => x.ViewModel!.WindowWidthChanged)
    .DisposeWith(d);
```

But I still wonder what's the usage of BindCommand "withParameter".

Body:
I have a custom control, which raises an event with an argument. I can bind a command to the event, but within the command handler argument is always null.

Here is the command binding:

this.BindCommand(ViewModel,
    vm => vm.MyCommand,
    v => v.InstanceOfCustomControl,
    toEvent: nameof(MyCustomControl.CustomEvent))
.DisposeWith(d);

Here is the command definition and implementation:

MyCommand = ReactiveCommand
    .CreateFromTask<CustomEventArgs, Unit>(MyCommandImpl);

public ReactiveCommand<CustomEventArgs, Unit> MyCommand{ get; set; }
private Task<Unit> MyCommandImpl(CustomEventArgs args)
{
    if (args is null) throw new Exception("WTF?");
}

I know for 100% that when event leaves custom control, it's argument is not null (=contains a value). But it arrives to the reactive command as null. What am I doing wrong?

Body:
I feel better of the hack way introduced in the doc.

MyControl.Events().ValueChanged
    .Select(arg => arg.NewValue)
    .InvokeCommand(this, x => x.ViewModel!.WindowWidthChanged)
    .DisposeWith(d);

But I still wonder what's the usage of BindCommand "withParameter".


问:
Remove curly braces and equal sign from data retrieved from firebase
So, I am using android studio to make an app that displays data stored in firebase real-time database. The app is simple, it displays the name and phone number from firebase to the app.

The app works fine and even displays the data but the only thing is it displays the data/values with curly braces and an equal sign (like a JSON format) is there anyway I can make it display just the desired values and not the extra signs and punctuation

Code:

```<code>ArrayList<String> list =new ArrayList<>();
ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.list_view, list);
listView.setAdapter(adapter);

DatabaseReference ref= FirebaseDatabase.getInstance().getReference().child("Car Wash");

ref.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        list.clear();
        for(DataSnapshot snapshot: dataSnapshot.getChildren()){
            list.add(snapshot.getValue().toString());
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {

    }
});
</code>```

答:
What you're seeing is the toString() output of the value a Firebase DataSnapshot that represents an object with multiple values.

You'll want to get the individual values from that snapshot, and display their values with something like this:

```<code>String name = snapshot.child("Name").getValue(String.class);
String phoneNr = snapshot.child("Phone Number").getValue(String.class);
list.add(name+" ("+phoneNr+")");
</code>```

Body:
So, I am using android studio to make an app that displays data stored in firebase real-time database. The app is simple, it displays the name and phone number from firebase to the app.

The app works fine and even displays the data but the only thing is it displays the data/values with curly braces and an equal sign (like a JSON format) is there anyway I can make it display just the desired values and not the extra signs and punctuation

Code:

ArrayList<String> list =new ArrayList<>();
ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.list_view, list);
listView.setAdapter(adapter);

DatabaseReference ref= FirebaseDatabase.getInstance().getReference().child("Car Wash");

ref.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        list.clear();
        for(DataSnapshot snapshot: dataSnapshot.getChildren()){
            list.add(snapshot.getValue().toString());
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {

    }
});

Body:
What you're seeing is the toString() output of the value a Firebase DataSnapshot that represents an object with multiple values.

You'll want to get the individual values from that snapshot, and display their values with something like this:

String name = snapshot.child("Name").getValue(String.class);
String phoneNr = snapshot.child("Phone Number").getValue(String.class);
list.add(name+" ("+phoneNr+")");


问:
Blazor WASM Load Data before Render Page
I would like to load some Data before I Render my Blazor Application because in depndency to the loaded data I would like to render my app (layout, navbar ...)

Now I want to use the OnInitialised method instead of OnInitialisedAsync and with no async and await keywords.

But now I had a problem to convert the data which I get back from my API.

```<code>protected override void OnInitialized()
    {
        try
        {   Console.WriteLine("Test1Mainasync");
            LoadCategories();
        }
        catch (Exception e)
        {

            jsRuntime.ToastrError(e.Message);
        }
    }

    private void LoadCategories()
    {

        IEnumerable<CategorieDTO> CategoriesInit1  = new List<CategorieDTO>();
        CategoriesInit1  =  categorieService.GetAllCategories();

        SD.Categories = CategoriesInit1.ToList();
        //foreach(var categorie in CategoriesInit){
        //    SD.Categories.Append(categorie);
        //}

        Console.WriteLine("Test1Main");

    }
</code>```

Has someone an idea why this converting issues happen?

答:
Your call to API endpoint return an awaitable task but not the IEnumerable, So you can not assign awaitable task to IEnumerable so this piece of code wont work

```<code>private void LoadCategories()
    {
        IEnumerable<CategorieDTO> CategoriesInit1  = new List<CategorieDTO>();
        CategoriesInit1  =  categorieService.GetAllCategories();
}
</code>```

You should have your LoadCategories function like this

```<code>private async Task LoadCategories()
{
    IEnumerable<CategorieDTO> CategoriesInit1  = new List<CategorieDTO>();
    CategoriesInit1  = await categorieService.GetAllCategories();
}
</code>```

API calls should be awaitable, else it will stuck your UI

You can use this solution as well

```<code>private void LoadCategories()
    {
       var t = Task.Run(() => categorieService.GetAllCategories()()).GetAwaiter();
        t.OnCompleted(() =>
        {
            CategoriesInit1 = t.GetResult();

            //  you may need to call statehaschanged as well
            StateHasChanged();
        });
}
</code>```

Body:
I would like to load some Data before I Render my Blazor Application because in depndency to the loaded data I would like to render my app (layout, navbar ...)

Now I want to use the OnInitialised method instead of OnInitialisedAsync and with no async and await keywords.

But now I had a problem to convert the data which I get back from my API.

protected override void OnInitialized()
    {
        try
        {   Console.WriteLine("Test1Mainasync");
            LoadCategories();
        }
        catch (Exception e)
        {

            jsRuntime.ToastrError(e.Message);
        }
    }

    private void LoadCategories()
    {

        IEnumerable<CategorieDTO> CategoriesInit1  = new List<CategorieDTO>();
        CategoriesInit1  =  categorieService.GetAllCategories();

        SD.Categories = CategoriesInit1.ToList();
        //foreach(var categorie in CategoriesInit){
        //    SD.Categories.Append(categorie);
        //}

        Console.WriteLine("Test1Main");

    }

Has someone an idea why this converting issues happen?

Body:
Your call to API endpoint return an awaitable task but not the IEnumerable, So you can not assign awaitable task to IEnumerable so this piece of code wont work

private void LoadCategories()
    {
        IEnumerable<CategorieDTO> CategoriesInit1  = new List<CategorieDTO>();
        CategoriesInit1  =  categorieService.GetAllCategories();
}

You should have your LoadCategories function like this

private async Task LoadCategories()
{
    IEnumerable<CategorieDTO> CategoriesInit1  = new List<CategorieDTO>();
    CategoriesInit1  = await categorieService.GetAllCategories();
}

API calls should be awaitable, else it will stuck your UI

You can use this solution as well

private void LoadCategories()
    {
       var t = Task.Run(() => categorieService.GetAllCategories()()).GetAwaiter();
        t.OnCompleted(() =>
        {
            CategoriesInit1 = t.GetResult();

            //  you may need to call statehaschanged as well
            StateHasChanged();
        });
}


问:
Is there a way to understand what is causing a crash involving `_NSTouchBarFinderObservation`?
My Crashlytics is showing multiple users experiencing the following crash (see below).
The only way I have been able to recreate this (which I doubt the users are doing) is to bring up the Xcode Touch Bar simulator and switch between generations whilst the app is running:

The following devices and OSes have reported the crash:

macOS 12.2.0 MacBookPro16,1

macOS 12.2.0 MacBookPro15,4

macOS 12.1.0 MacBookPro15,4

macOS 12.0.0 MacBookPro15,4

My app is:

on macOS only

written in SwiftUI containing an NSViewController and NSTextView

never touching/observing/making reference to the touch bar.

Would anyone know the reason for this crash?

```<code>Cannot remove an observer <_NSTouchBarFinderObservation 0x6000026f6260> for the key path "nextResponder" from <GUL_SwiftUI.AppDelegate-0624A6E4-3CE4-4739-BDD0-0721CE556CBA 0x600000290360> because it is not registered as an observer.
2022-02-13 14:28:47.289790+0400 Lyrcs[63176:1681748] [General] (
    0   CoreFoundation                      0x00000001c1dd41cc __exceptionPreprocess + 240
    1   libobjc.A.dylib                     0x00000001c1b257b8 objc_exception_throw + 60
    2   Foundation                          0x00000001c2c1b96c -[NSObject(NSKeyValueObserverRegistration) _removeObserver:forProperty:] + 668
    3   Foundation                          0x00000001c2c1b67c -[NSObject(NSKeyValueObserverRegistration) removeObserver:forKeyPath:] + 144
    4   Foundation                          0x00000001c2c1b304 -[NSObject(NSKeyValueObserverRegistration) removeObserver:forKeyPath:context:] + 204
    5   AppKit                              0x00000001c4f29df8 -[_NSTouchBarFinderObservation invalidate] + 316
    6   AppKit                              0x00000001c4f2a2ec -[NSTouchBarFinder invalidate] + 268
    7   AppKit                              0x00000001c48ae584 -[NSApplicationFunctionRowController _teardown] + 104
    8   AppKit                              0x00000001c48ae31c -[NSApplicationFunctionRowController _sync] + 484
    9   Foundation                          0x00000001c2bfa13c NSKeyValueNotifyObserver + 292
    10  Foundation                          0x00000001c2cc655c NSKeyValueDidChange + 356
    11  Foundation                          0x00000001c2d79770 NSKeyValueDidChangeWithPerThreadPendingNotifications + 160
    12  AppKit                              0x00000001c5173f80 __33+[NSFunctionRowDevice initialize]_block_invoke.1 + 492
    13  AppKit                              0x00000001c5174324 ___NSMainRunLoopPerformBlockInModes_block_invoke + 44
    14  CoreFoundation                      0x00000001c1d54708 __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 28
    15  CoreFoundation                      0x00000001c1d5457c __CFRunLoopDoBlocks + 412
    16  CoreFoundation                      0x00000001c1d531f4 __CFRunLoopRun + 800
    17  CoreFoundation                      0x00000001c1d52734 CFRunLoopRunSpecific + 600
    18  HIToolbox                           0x00000001ca8e4f68 RunCurrentEventLoopInMode + 292
    19  HIToolbox                           0x00000001ca8e4cdc ReceiveNextEventCommon + 552
    20  HIToolbox                           0x00000001ca8e4a9c _BlockUntilNextEventMatchingListInModeWithFilter + 72
    21  AppKit                              0x00000001c48a8ce0 _DPSNextEvent + 844
    22  AppKit                              0x00000001c48a7584 -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 1332
    23  AppKit                              0x00000001c48995a4 -[NSApplication run] + 596
    24  AppKit                              0x00000001c486ac78 NSApplicationMain + 1064
    25  SwiftUI                             0x00000001e6779c9c $s7SwiftUI6runAppys5NeverOSo21NSApplicationDelegate_So11NSResponderCXcFTf4e_nAA07TestingdG0C_Tg5 + 148
    26  SwiftUI                             0x00000001e72a3a54 $s7SwiftUI6runAppys5NeverOxAA0D0RzlF + 260
    27  SwiftUI                             0x00000001e6d3366c $s7SwiftUI3AppPAAE4mainyyFZ + 128
</code>```

答:
Turns out the culprit was Firebase Analytics.
The solution to prevent this crash was to add the FirebaseAppDelegateProxyEnabled to the info plist and give it a Boolean value of NO. Seems like SwiftUI, macOS and Firebase Analytics don't play nicely together.

Body:
My Crashlytics is showing multiple users experiencing the following crash (see below).
The only way I have been able to recreate this (which I doubt the users are doing) is to bring up the Xcode Touch Bar simulator and switch between generations whilst the app is running:

The following devices and OSes have reported the crash:

macOS 12.2.0 MacBookPro16,1

macOS 12.2.0 MacBookPro15,4

macOS 12.1.0 MacBookPro15,4

macOS 12.0.0 MacBookPro15,4

My app is:

on macOS only

written in SwiftUI containing an NSViewController and NSTextView

never touching/observing/making reference to the touch bar.

Would anyone know the reason for this crash?

Cannot remove an observer <_NSTouchBarFinderObservation 0x6000026f6260> for the key path "nextResponder" from <GUL_SwiftUI.AppDelegate-0624A6E4-3CE4-4739-BDD0-0721CE556CBA 0x600000290360> because it is not registered as an observer.
2022-02-13 14:28:47.289790+0400 Lyrcs[63176:1681748] [General] (
    0   CoreFoundation                      0x00000001c1dd41cc __exceptionPreprocess + 240
    1   libobjc.A.dylib                     0x00000001c1b257b8 objc_exception_throw + 60
    2   Foundation                          0x00000001c2c1b96c -[NSObject(NSKeyValueObserverRegistration) _removeObserver:forProperty:] + 668
    3   Foundation                          0x00000001c2c1b67c -[NSObject(NSKeyValueObserverRegistration) removeObserver:forKeyPath:] + 144
    4   Foundation                          0x00000001c2c1b304 -[NSObject(NSKeyValueObserverRegistration) removeObserver:forKeyPath:context:] + 204
    5   AppKit                              0x00000001c4f29df8 -[_NSTouchBarFinderObservation invalidate] + 316
    6   AppKit                              0x00000001c4f2a2ec -[NSTouchBarFinder invalidate] + 268
    7   AppKit                              0x00000001c48ae584 -[NSApplicationFunctionRowController _teardown] + 104
    8   AppKit                              0x00000001c48ae31c -[NSApplicationFunctionRowController _sync] + 484
    9   Foundation                          0x00000001c2bfa13c NSKeyValueNotifyObserver + 292
    10  Foundation                          0x00000001c2cc655c NSKeyValueDidChange + 356
    11  Foundation                          0x00000001c2d79770 NSKeyValueDidChangeWithPerThreadPendingNotifications + 160
    12  AppKit                              0x00000001c5173f80 __33+[NSFunctionRowDevice initialize]_block_invoke.1 + 492
    13  AppKit                              0x00000001c5174324 ___NSMainRunLoopPerformBlockInModes_block_invoke + 44
    14  CoreFoundation                      0x00000001c1d54708 __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 28
    15  CoreFoundation                      0x00000001c1d5457c __CFRunLoopDoBlocks + 412
    16  CoreFoundation                      0x00000001c1d531f4 __CFRunLoopRun + 800
    17  CoreFoundation                      0x00000001c1d52734 CFRunLoopRunSpecific + 600
    18  HIToolbox                           0x00000001ca8e4f68 RunCurrentEventLoopInMode + 292
    19  HIToolbox                           0x00000001ca8e4cdc ReceiveNextEventCommon + 552
    20  HIToolbox                           0x00000001ca8e4a9c _BlockUntilNextEventMatchingListInModeWithFilter + 72
    21  AppKit                              0x00000001c48a8ce0 _DPSNextEvent + 844
    22  AppKit                              0x00000001c48a7584 -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 1332
    23  AppKit                              0x00000001c48995a4 -[NSApplication run] + 596
    24  AppKit                              0x00000001c486ac78 NSApplicationMain + 1064
    25  SwiftUI                             0x00000001e6779c9c $s7SwiftUI6runAppys5NeverOSo21NSApplicationDelegate_So11NSResponderCXcFTf4e_nAA07TestingdG0C_Tg5 + 148
    26  SwiftUI                             0x00000001e72a3a54 $s7SwiftUI6runAppys5NeverOxAA0D0RzlF + 260
    27  SwiftUI                             0x00000001e6d3366c $s7SwiftUI3AppPAAE4mainyyFZ + 128


问:
Python convert child dicts with same key name to csv (DictWriter)
I have a list of json file like below:

```<code>[
{"A":{"value":1}, "B":{"value":2}},
{"A":{"value":9}, "B":{"value":3}}
]
</code>```

Which I want to turn to csv like so:

```<code>A.value,B.value
1,2
9,3
</code>```

The issue is that I have nested keys which have the same name : value but should be in a separate column. I could not find an elegant solution to this anywhere yet. I would like to be able to do something like:

```<code>data = json.load(open(file, 'r'))
with open("output.csv", "w") as f:

        columns = ["A.value","B.value"]
        cw = csv.DictWriter(f, columns)
        cw.writeheader()
        cw.writerows(data)
</code>```

Which I know would work if I did not have any nested keys. I found other questions similar to this but I don't think this applies to my situation.

As an extra challenge:

I'd rather keep a generic approach. Later I might have a list of jsons like:

```<code>  [
    {"A":{"value":1}, "B":{"value":2}, "key":90},
    {"A":{"value":9}, "B":{"value":3}, "key":91}
    ]
</code>```

Meaning not all keys I want to add to csv will have a nested value key!

**output ^ **

```<code> A.value,B.value,key
    1,2,90
    9,3,91
</code>```

答:
This should do the job:

```<code>cw.writerows([{f'{key}.value':val['value'] for key, val in row.items()} for row in data])
</code>```

or as regular loop:

```<code>for row in data:
    cw.writerow({f'{key}.value':val['value'] for key, val in row.items()})
</code>```

EDIT

```<code>import csv

data = [
    {"A":{"value":1}, "B":{"value":2}, "key":90},
    {"A":{"value":9}, "B":{"value":3}, "key":91}
    ]

def parse(row):
    for key, value in row.items():
        try:
            yield f'{key}.value', value['value']
        except TypeError:
            yield key, value

with open("output.csv", "w") as f:
    columns =  ['A.value', 'B.value', 'key']
    cw = csv.DictWriter(f, columns)
    cw.writeheader()
    cw.writerows(dict(parse(row)) for row in data)
</code>```

The only thing I don't like is the hardcoded headers

Body:
I have a list of json file like below:

[
{"A":{"value":1}, "B":{"value":2}},
{"A":{"value":9}, "B":{"value":3}}
]

Which I want to turn to csv like so:

A.value,B.value
1,2
9,3

The issue is that I have nested keys which have the same name : value but should be in a separate column. I could not find an elegant solution to this anywhere yet. I would like to be able to do something like:

data = json.load(open(file, 'r'))
with open("output.csv", "w") as f:

        columns = ["A.value","B.value"]
        cw = csv.DictWriter(f, columns)
        cw.writeheader()
        cw.writerows(data)

Which I know would work if I did not have any nested keys. I found other questions similar to this but I don't think this applies to my situation.

As an extra challenge:

I'd rather keep a generic approach. Later I might have a list of jsons like:

  [
    {"A":{"value":1}, "B":{"value":2}, "key":90},
    {"A":{"value":9}, "B":{"value":3}, "key":91}
    ]

Meaning not all keys I want to add to csv will have a nested value key!

**output ^ **

 A.value,B.value,key
    1,2,90
    9,3,91

Body:
This should do the job:

cw.writerows([{f'{key}.value':val['value'] for key, val in row.items()} for row in data])

or as regular loop:

for row in data:
    cw.writerow({f'{key}.value':val['value'] for key, val in row.items()})

EDIT

import csv

data = [
    {"A":{"value":1}, "B":{"value":2}, "key":90},
    {"A":{"value":9}, "B":{"value":3}, "key":91}
    ]

def parse(row):
    for key, value in row.items():
        try:
            yield f'{key}.value', value['value']
        except TypeError:
            yield key, value

with open("output.csv", "w") as f:
    columns =  ['A.value', 'B.value', 'key']
    cw = csv.DictWriter(f, columns)
    cw.writeheader()
    cw.writerows(dict(parse(row)) for row in data)

The only thing I don't like is the hardcoded headers


问:
Reflection with Powershell
I have a set of .NET Assemblies (all under the same directory) and some of those contain classes which implement an abstract class. I would like a Powershell script to find all the classes which implement my abstract class, and execute a method on each of them.

Does anybody have an idea on how to do this?

Thanks!

答:
The same way as you do it with c# but with PowerShell syntax.

Take a look at Assembly.GetTypes and Type.IsSubclassOf.

ContentLicense: CC BY-SA 2.5

Title: Reflection with Powershell

OwnerDisplayName: Shay Erlichmen


问:
running hadoop on Google app engine?
Is it possible to run map reduce jobs on Google app engine?

Any reference or tutorial would help

Thanks

答:
Sort of.

You can't use the actual MapReduce framework - the architecture is too incompatible with AppEngine.

However, there is an equivalent system built specficially for GAE - appengine-mapreduce. That site is a bit confusing, as the first version of the code only supported mappers, without the subsequent reduce step - recently they released a version with full mapreduce support, but some of the documentation still referes to the earlier mapper-only one.

The best introduction is the GoogleIO talk from Mike Aizatskyi.

Title: running hadoop on Google app engine?


问:
Scala: List[Future] to Future[List] disregarding failed futures
I'm looking for a way to convert an arbitrary length list of Futures to a Future of List. I'm using Playframework, so ultimately, what I really want is a Future[Result], but to make things simpler, let's just say Future[List[Int]] The normal way to do this would be to use Future.sequence(...) but there's a twist... The list I'm given usually has around 10-20 futures in it, and it's not uncommon for one of those futures to fail (they are making external web service requests).

Instead of having to retry all of them in the event that one of them fails, I'd like to be able to get at the ones that succeeded and return those.

For example, doing the following doesn't work:

```<code>import scala.concurrent._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.Success
import scala.util.Failure

val listOfFutures = Future.successful(1) :: Future.failed(new Exception("Failure")) ::
                    Future.successful(3) :: Nil

val futureOfList = Future.sequence(listOfFutures)

futureOfList onComplete {
  case Success(x) => println("Success!!! " + x)
  case Failure(ex) => println("Failed !!! " + ex)
}

scala> Failed !!! java.lang.Exception: Failure
</code>```

Instead of getting the only the exception, I'd like to be able to pull the 1 and 3 out of there. I tried using Future.fold, but that apparently just calls Future.sequence behind the scenes.

答:
If you need to keep failed futures for some reason, e.g., logging or conditional processing, this works with Scala 2.12+. You can find working code here.</p>
```<code>val f1 = Future(1)
val f2 = Future(2)
val ff = Future.failed(new Exception())

val futures: Seq[Future[Either[Throwable, Int]]] =
  Seq(f1, f2, ff).map(_.transform(f => Success(f.toEither)))

val sum = Future
  .sequence(futures)
  .map { eithers =>
    val (failures, successes) = eithers.partitionMap(identity)

    val fsum = failures.map(_ => 100).sum
    val ssum = successes.sum

    fsum + ssum
  }

assert(Await.result(sum, 1.second) == 103)
</code>```

Body:
I'm looking for a way to convert an arbitrary length list of Futures to a Future of List. I'm using Playframework, so ultimately, what I really want is a Future[Result], but to make things simpler, let's just say Future[List[Int]] The normal way to do this would be to use Future.sequence(...) but there's a twist... The list I'm given usually has around 10-20 futures in it, and it's not uncommon for one of those futures to fail (they are making external web service requests).

Instead of having to retry all of them in the event that one of them fails, I'd like to be able to get at the ones that succeeded and return those.

For example, doing the following doesn't work:

import scala.concurrent._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.Success
import scala.util.Failure

val listOfFutures = Future.successful(1) :: Future.failed(new Exception("Failure")) ::
                    Future.successful(3) :: Nil

val futureOfList = Future.sequence(listOfFutures)

futureOfList onComplete {
  case Success(x) => println("Success!!! " + x)
  case Failure(ex) => println("Failed !!! " + ex)
}

scala> Failed !!! java.lang.Exception: Failure

Instead of getting the only the exception, I'd like to be able to pull the 1 and 3 out of there. I tried using Future.fold, but that apparently just calls Future.sequence behind the scenes.

Body:
If you need to keep failed futures for some reason, e.g., logging or conditional processing, this works with Scala 2.12+. You can find working code here.

val f1 = Future(1)
val f2 = Future(2)
val ff = Future.failed(new Exception())

val futures: Seq[Future[Either[Throwable, Int]]] =
  Seq(f1, f2, ff).map(_.transform(f => Success(f.toEither)))

val sum = Future
  .sequence(futures)
  .map { eithers =>
    val (failures, successes) = eithers.partitionMap(identity)

    val fsum = failures.map(_ => 100).sum
    val ssum = successes.sum

    fsum + ssum
  }

assert(Await.result(sum, 1.second) == 103)


问:
Get child element from element through an event with Vue
Goal

What I'm trying to achieve is that whenever the user clicks on the .menu-item element, the dropdown element .menu-item-dropdown will get a class that will show the element.

Problem

Currently, when I click on the .menu-item class element, the returned value from the console.log in showMobileNavDropdown() returns null. When clicking, the event.target element is .menu-item-main and not .menu-item. This happens only when I click on the text of the li. Otherwise this works as intended.

What would be the best way to include the li text so that I can still grab the .menu-item-dropdown class?

Vue

```<code><template>
    <div>
        <nav class="nav">
            <div class="nav-left">
                <img class="logo" src="/images/logo.svg" alt="" />
            </div>
            <div class="nav-center">
                <ul class="menu-items">
                    <li
                        class="menu-item"
                        @click="showMobileNavDropdown($event)"
                    >
                        <!-- Main Title On Nav -->
                        <a class="menu-item-main" href="#">Company</a>

                        <!-- Dropdown -->
                        <div class="menu-item-dropdown">
                            <ul>
                                <li class="">
                                    <a href="">About</a>
                                </li>
                                <li class="">
                                    <a href="">Contact</a>
                                </li>
                            </ul>
                        </div>
                    </li>
                </ul>
            </div>

            <div class="nav-right">
                <a href="" class="btn">Contact us</a>
            </div>

            <div class="hamburger" @click="openMobileNav">
                <span class="ham-line"></span>
                <span class="ham-line ham-line-2"></span>
            </div>
        </nav>

        <div class="mobile-nav"></div>
    </div>
</template>

<script>
export default {
    methods: {
        openMobileNav() {
            var mobileNav = document.querySelector(".mobile-nav");
            mobileNav.classList.toggle("showMobileNav");
        },

        // This function
        showMobileNavDropdown(event) {
            console.log(event); // This element returns 'menu-item-main' and not 'menu-item'
            console.log(event.target.querySelector(".menu-item-dropdown"));
        },
    },
};
</script>

</code>```

答:
The solution was to either grab the element, and if that returned null, grab the sibling. This way, it's always possible to select the .menu-item-dropdown element. When clicking on the element, it can either be a child or sibling.

Part of Solution

var element =
        event.target.querySelector(".menu-item-dropdown") ||
        event.target.nextElementSibling;

element.classList.toggle("hide_drop");
```

Body:
Goal

What I'm trying to achieve is that whenever the user clicks on the .menu-item element, the dropdown element .menu-item-dropdown will get a class that will show the element.

Problem

Currently, when I click on the .menu-item class element, the returned value from the console.log in showMobileNavDropdown() returns null. When clicking, the event.target element is .menu-item-main and not .menu-item. This happens only when I click on the text of the li. Otherwise this works as intended.

What would be the best way to include the li text so that I can still grab the .menu-item-dropdown class?

Vue

<template>

                        Company

                                    About

                                    Contact

                Contact us

</template>


问:
Django model data not appearing
My model data for my website wont appear on new page when using slug and I am unsure as to why this is happening as I managed to get it to work with the previous page of the website but when I try to call it on my html page nothing will load now and I use the slug in the view to access the page.

Models.py

```<code>class Parasite(models.Model):
    name = models.CharField(max_length=128, unique=True)
    slug = models.SlugField(max_length=100, unique=True)
    description = models.TextField(max_length=100000)
    image = models.ImageField(upload_to='parasite_images', default='default/default.jpg', blank=True)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super(Parasite, self).save(*args, **kwargs)

    def __str__(self):
        return self.name
</code>```

views.py

```<code>def view_parasite(request,parasite_name_slug):
    context_dict = {}
    try:
        parasite = Parasite.objects.get(slug=parasite_name_slug)
        context_dict['parasites'] = parasite
    except Parasite.DoesNotExist:
       context_dict['parasites'] = None
    return render(request, 'parasites_app/viewpara.html', context = context_dict)
</code>```

viewpara.html

```<code>{% extends 'parasites_app/base.html' %}
{% load static %}
{% block content_block %}

{% for p in parasite %}
    <h3>{{p.name}}</h3>

{% endfor %}

{% endblock %}
</code>```

urls.py

```<code> urlpatterns = [

             path('login/', views.user_login, name='login'),
                path('logout/', views.user_logout, name='logout'),
                path('admin/', admin.site.urls),
                path('', views.public, name='public'),
                path('public/', views.public, name='public'),
                path('private/', views.logged_in_content, name='private'),
                path('public/<slug:parasite_name_slug>/',views.view_parasite, name='view_parasite'),
                path('<slug:post_name_slug>/', views.show_post, name='show_post'),

        ]

        urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
        urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
</code>```

答:
First mistake - you are getting one Parasite object (cause you use method get) and you call it with plural name 'parasites':

```<code>parasite = Parasite.objects.get(slug=parasite_name_slug)
context_dict['parasites'] = parasite
</code>```

Second mistake - when you want to show it in template, you call for single parasite, but you decided to name the key parasites.

```<code>{% for p in parasite %}
</code>```

Third mistake - don't use for loop for one object, just call it.

Answer:

views.py

```<code>parasite = Parasite.objects.get(slug=parasite_name_slug)
context_dict['parasite'] = parasite
</code>```

viewpara.html

```<code>{% block content_block %}

    {{ parasite.name }}

{% endblock %}
</code>```

Title: Django model data not appearing

Body:
My model data for my website wont appear on new page when using slug and I am unsure as to why this is happening as I managed to get it to work with the previous page of the website but when I try to call it on my html page nothing will load now and I use the slug in the view to access the page.

Models.py

class Parasite(models.Model):
    name = models.CharField(max_length=128, unique=True)
    slug = models.SlugField(max_length=100, unique=True)
    description = models.TextField(max_length=100000)
    image = models.ImageField(upload_to='parasite_images', default='default/default.jpg', blank=True)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super(Parasite, self).save(*args, **kwargs)

    def __str__(self):
        return self.name

views.py

def view_parasite(request,parasite_name_slug):
    context_dict = {}
    try:
        parasite = Parasite.objects.get(slug=parasite_name_slug)
        context_dict['parasites'] = parasite
    except Parasite.DoesNotExist:
       context_dict['parasites'] = None
    return render(request, 'parasites_app/viewpara.html', context = context_dict)

viewpara.html

{% extends 'parasites_app/base.html' %}
{% load static %}
{% block content_block %}

{% for p in parasite %}

{{p.name}}

{% endfor %}

{% endblock %}

urls.py

 urlpatterns = [

             path('login/', views.user_login, name='login'),
                path('logout/', views.user_logout, name='logout'),
                path('admin/', admin.site.urls),
                path('', views.public, name='public'),
                path('public/', views.public, name='public'),
                path('private/', views.logged_in_content, name='private'),
                path('public/<slug:parasite_name_slug>/',views.view_parasite, name='view_parasite'),
                path('<slug:post_name_slug>/', views.show_post, name='show_post'),

        ]

        urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
        urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

Body:
First mistake - you are getting one Parasite object (cause you use method get) and you call it with plural name 'parasites':

parasite = Parasite.objects.get(slug=parasite_name_slug)
context_dict['parasites'] = parasite

Second mistake - when you want to show it in template, you call for single parasite, but you decided to name the key parasites.

{% for p in parasite %}

Third mistake - don't use for loop for one object, just call it.

Answer:

views.py

parasite = Parasite.objects.get(slug=parasite_name_slug)
context_dict['parasite'] = parasite

viewpara.html

{% block content_block %}

    {{ parasite.name }}

{% endblock %}


问:
How to handle imbalanced data in general
I have been working on the case study where data is highly imbalanced. we have been taught we can handle the imbalanced data by either under sampling the majority class or over sampling the minority class.
I wanted to ask if there is any other way/method that can be used to handle imbalanced data?

this question is more on conceptual side than programming.

for example,
I was thinking if we could put some weight on minority class (conceptually) to make the model emphasize on identifying pattern in minority class.
I don't know how that can be done but this concept theoretically should work.

feel free to put crazy ideas too.

答:
Your weights idea is not far off. This can be done. In fact, most sklearn Models give you the option to specify class weights. This however is often not enough for very extreme cases (e.g. 95%/5% split or more extreme).

There are specific oversampling techniques such as SMOTE (and related techniques) which go a step further than classic oversampling and generate synthetic samples based on a K Nearest Neighbors Algorithm.

If the classes are extremely imbalanced a "classic" classification approach may not be enough and you might have to look into anomaly detection algorithms.


问:
How to add automatically expanding horizontal space in libreoffice (similar to say flex justify-content space-around)
I'm trying to achieve this effect:

```<code>|First phrase...............................................Second phrase|
</code>```

Where the | markers above denote the page margins, and ....... represents a 'horizontal space' (which may or may not use space as the character, a 'dot' as above, or any other character), which effectively expands to take as much space as possible between the two pieces of text.

This is pretty common, e.g., when designing a table of contents manually*, or when trying to achieve the kind of "chapter X...........page Y" effect in headers.

I know there's a specific and easy way to introduce this kind of 'expanding horizontal space', because I've done it in the past. But I just can't find it anymore. I just vaguely remember that the relevant menu allowed you to specify what character you wanted to use in this 'expanding space'. Also, it may or may not have involved the use of tabs.

Any ideas?

* Yes I know about the "Table of Contents" menu option, no I'm not trying to design a table of contents, it was just an example :)

答:
I remembered.

Create a tab stop on the horizontal ruler above the page, right click to convert from a 'left' stop to a 'right' stop, and drag that stop all the way to the right margin.

Then, next time you press 'tab', the tab will automatically push any content to the right of your cursor, all the way to the right margin.

If you optionally also specify a fill character in the 'Tabs' tab of the 'Paragraph' formatting menu, the tab space will be filled with that character.

Body:
I'm trying to achieve this effect:

|First phrase...............................................Second phrase|

Where the | markers above denote the page margins, and ....... represents a 'horizontal space' (which may or may not use space as the character, a 'dot' as above, or any other character), which effectively expands to take as much space as possible between the two pieces of text.

This is pretty common, e.g., when designing a table of contents manually*, or when trying to achieve the kind of "chapter X...........page Y" effect in headers.

I know there's a specific and easy way to introduce this kind of 'expanding horizontal space', because I've done it in the past. But I just can't find it anymore. I just vaguely remember that the relevant menu allowed you to specify what character you wanted to use in this 'expanding space'. Also, it may or may not have involved the use of tabs.

Any ideas?

* Yes I know about the "Table of Contents" menu option, no I'm not trying to design a table of contents, it was just an example :)


问:
Angular 6 HostBinding with multiple values?
I have successfully used @HostBinding in my Angular 6 app to apply properties to the host component, as in applying a class when a variable is true:

@HostBinding('class.compact-ui') isCompact;

Now, however, I need to assign one of 4 possible classes based on the model of a select menu. For example, user can red, blue, or green.

I suppose I can use multiple host bindings for when any of the colors are true:

@HostBinding('class.green-ui') uiColor === 'green';

But that seems wrong. What's the proper way to do this?

答:
Note: This is for the latest versions of angular and may not work on older versions (as per the question title).

An object can also be returned which will add all the true values to the element and remove all the false values from the element.

  /** The size of the button. */
  @Input() size: ButtonSize = 'md';

  /** The classes to attach to the element. */
  @HostBinding('class')
  get elementClasses() {
    return {
      'primary-button': true,
      [`primary-button--${this.size}`]: true,
      'primary-button--color': false
    }
  }
```


答:
In the first input you have a typo. You have OnClick but you want onClick

It works for me with one click like this
(I removed a few props to make it shorter)

```<code>import React from 'react';
import { useState } from 'react';

const Demo = () => {
  const [isRepeat, setIsRepeat] = useState('');
  return (
    <>
      <input type="radio" value={1} onClick={() => setIsRepeat('oneTime')}></input>

      <label>ครั้งเดียว</label>
      <input type="radio" value={2} onClick={() => setIsRepeat('repeat')}></input>

      {isRepeat === 'oneTime' && <span>One Time</span>}
      {isRepeat === 'repeat' && <span>repeat</span>}
    </>
  );
};
export default Demo;

</code>```

Title: Why when I use onClick with radio button make them have to click twice to make radio button to be selected?

Body:
now, I using radio button to render 2 components differently I use onClick with radio button to [isRepeat,setisRepeat] setState value

  <input
     required
     id="singleClass"
     name="classType"
     type="radio"
     className="inputContainer"
     value={1}
     OnClick={() => setisRepeat("oneTime")}
     ></input>

     ครั้งเดียว
   <input
     required
     id="repeatClass"
     name="classType"
     type="radio"
     className="inputContainer"
     value={2}
     onClick={() => setisRepeat("repeat")}
     ></input>

and render component like this

    {isRepeat === "oneTime" && (
        <>...</>
    )}
    {isRepeat === "repeat" && (

...

    )}

but when I using onClick() with radio button, It's make user to click "twice" to make radio button checked

(actually, setState work fine when click radio button but radio button didn't be checked. It should be checked and setState at the same time to make user not confuse)

ps. I already using document.getElementByName('classType').value === 1 or 2   to render different items, but didn't work

Body:
In the first input you have a typo. You have OnClick but you want onClick

It works for me with one click like this
(I removed a few props to make it shorter)

import React from 'react';
import { useState } from 'react';

const Demo = () => {
  const [isRepeat, setIsRepeat] = useState('');
  return (
    <>
      <input type="radio" value={1} onClick={() => setIsRepeat('oneTime')}></input>

      <label>ครั้งเดียว</label>
      <input type="radio" value={2} onClick={() => setIsRepeat('repeat')}></input>

      {isRepeat === 'oneTime' && <span>One Time</span>}
      {isRepeat === 'repeat' && <span>repeat</span>}
    </>
  );
};
export default Demo;


问:
Adding number to beginning of integer
I know that this may be a dumb question, but I am still learning C so I don't know all the nuances.

Basically the gist of my question is that say I have the separate integers 1, 3 and 2. I want to add 2 to 1 that makes it 21. I know I could do 2*10, then add 1. Then add 3 to the beginning making it 321. Basically I need to add one number to the beginning of another number multiple times. Sadly, I cannot use the pow function for this.

Let me know if you need me to explain it anymore.

答:
Well, you can try out this program.

```<code>#include <stdio.h>
#include <string.h>

int power(int base, int exp) {
    int res = 1;
    while (exp > 0) {
        res *= base;
        exp--;
    }

    return res;
}

int main() {
    int someNumber = 7, length, numToAdd = 3;
    char string[10];
    sprintf(string, "%d", someNumber);
    length = strlen(string);
    someNumber = numToAdd * power(10, length) + someNumber;
    printf("%d\n", someNumber);
}
</code>```

I hope the code is self explanatory.

Title: Adding number to beginning of integer

Body:
Well, you can try out this program.

#include <stdio.h>
#include <string.h>

int power(int base, int exp) {
    int res = 1;
    while (exp > 0) {
        res *= base;
        exp--;
    }

    return res;
}

int main() {
    int someNumber = 7, length, numToAdd = 3;
    char string[10];
    sprintf(string, "%d", someNumber);
    length = strlen(string);
    someNumber = numToAdd * power(10, length) + someNumber;
    printf("%d\n", someNumber);
}

I hope the code is self explanatory.


问:
Bootstrap carousel & Google Font Issues
I know this has been asked many times, but I still cannot seem to fix my code. As you can see, I am copied the code directly from bootstrap, and I was able to get my buttons to appear, but they are not activating. Also, google fonts was directly imported, but it too is not changing my fonts as it should. It is remaining as default.

#title {
  background-color: #FF4C68;
  color: WHITE;
}
.container-fluid{
  padding: 3% 15%;
}
/* H1 FONT FAMILY NOT WORKING */
h1 {
  font-family: "Montserrat-Black";
  font-size: 3.5rem;
  line-height: 1.5;
}
h2 {
  font-family: "Montserrat-Bold";
  font-size: 3rem;
  line-height: 1.5;
}
h3{
  font-family: "Montserrat-Bold";
  font-size: 1.5rem;
}
p{
  color: #8F8F8F;
}
body {
  font-family: "Montserrat";
}
/* NAVIGATION BAR */

.navbar {
  padding-bottom: 4.5rem;
}

.navbar-brand {
  font-family: 'Ubuntu';
  font-size: 2.5rem;
  font-weight: bold;
  color: yellow;
}

.nav-item {
  padding: 0 18px;
}

.nav-link {
  font-size: 1.2rem;
  font-family: "Montserrat-Light";
}

/* DOWNLOAD BUTTONS */
.download-button {
  margin: 5% 3% 5%;
}

/* TITLE IMAGE */
.title-image {
  width: 60%;
  transform: rotate(45deg);
}

/* FEATURES SECTION */
#features {
  padding: 7% 15%;
  text-align: center;
  padding: 5%;
}
/* CHANGE PADDING ABOVE IF FIRST BODY ISNT LOOKING RIGHT */

.icon{
  color: #ef8172;
  margin-bottom: 1rem;
}
.icon:hover{
  color: #ff4c68;
}

/* TESTIMONIAL SECTION */
#testimonials {
  text-align: center;
  background-color: #ef8172;
  color: #fff;
}
.testimonial-img{
  width: 10%;
  border-radius: 100%;
  margin: 20px;
}
#press {
  background-color: #ef8172;
  text-align: center;
  padding-bottom: 3%;
}
.press-logo {
  width: 15%;
  margin: 20px 20px 50px;
}
.carousel-item {
  padding: 7% 15%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>TinDog</title>

  <!-- BOOTSTRAP SCRIPTS -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

  <!-- Google Fonts -->
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@100;400;900&family=Ubuntu&display=swap" rel="stylesheet">

  <!-- CSS STYLESHEETS -->
  <link href="https://fonts.googleapis.com/css2?family=Montserrat&family=Ubuntu&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="css/styles.css">

  <!-- C:\Users\dparr\Downloads\TinDog-Start-master\TinDog-Start-master\css\styles.css -->

  <!-- FONT AWESOME -->
  <script src="https://kit.fontawesome.com/849c3de797.js" crossorigin="anonymous"></script>

</head>

<body>

  <section id="title">
    <div class="container-fluid">

      <!-- Nav Bar -->
      <nav class="navbar navbar-expand-lg navbar-dark">
        Tindog
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
          <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarSupportedContent">
          <ul class="navbar-nav ml-auto">
            <li class="nav-item">
              Contact
            </li>
            <li class="nav-item">
              Pricing
            </li>
            <li class="nav-item">
              Download
            </li>
          </ul>
        </div>

      </nav>

      <!-- Title -->

      <div class="row">
        <div class="col-lg-6">
          <h1>Meet new and interesting dogs nearby.</h1>
          <button type="button" class="btn btn-primary btn-lg download-button"><i class="fa-brands fa-apple"></i> Download</button>
          <button type="button" class="btn btn-outline-light btn-lg download-button"><i class="fa-brands fa-google-play"></i> Download</button>
        </div>

        <div class="col-lg-6">
          <img class="title-image" src="images/iphone6.png" alt="iphone-mockup">
        </div>
      </div>
  </section>

  <!-- Features -->

  <section id="features">

    <div class="row">
      <div class="feature-box col-lg-4">
        <i class="icon fa-solid fa-circle-check fa-4x"></i>
        <h3>Easy to use.</h3>
        <p>So easy to use, even your dog could do it.</p>
      </div>

      <div class="feature-box col-lg-4">
        <i class="icon fa-solid fa-bullseye fa-4x"></i>
        <h3>Elite Clientele</h3>
        <p>We have all the dogs, the greatest dogs.</p>
      </div>

      <div class="feature-box col-lg-4">
        <i class="icon fa-solid fa-heart fa-4x"></i>
        <h3>Guaranteed to work.</h3>
        <p>Find the love of your dog's life or your money back.</p>
      </div>
    </div>

  </section>

  <!-- Testimonials -->

  <section id="testimonials">

    <div id="#testimonial-carousel" class="carousel slide" data-bs-ride="false" data-pause="hover">
      <div class="carousel-inner">
        <div class="carousel-item active">
          <h2>I no longer have to sniff other dogs for love. I've found the hottest Corgi on TinDog. Woof.</h2>
          <img class="testimonial-img" src="images/dog-img.jpg" alt="dog-profile">
          <em>Pebbles, New York</em>
        </div>
        <div class="carousel-item">
          <h2 class="testimonial-text">My dog used to be so lonely, but with TinDog's help, they've found the love of their life. I think.</h2>
          <img class="testimonial-image" src="images/lady-img.jpg" alt="lady-profile">
          <em>Beverly, Illinois</em>
        </div>
      </div>
      <button class="carousel-control-prev" type="button" data-bs-target="#testimonial-carousel" data-bs-slide="prev">
        <span class="carousel-control-prev-icon" aria-hidden="true"></span>
        <span class="visually-hidden">Previous</span>
      </button>
      <button class="carousel-control-next" type="button" data-bs-target="#testimonial-carousel" data-bs-slide="next">
        <span class="carousel-control-next-icon" aria-hidden="true"></span>
        <span class="visually-hidden">Next</span>
      </button>
    </div>

  </section>

  <!-- Press -->

  <section id="press">
    <img class="press-logo" src="images/techcrunch.png" alt="tc-logo">
    <img class="press-logo" src="images/tnw.png" alt="tnw-logo">
    <img class="press-logo" src="images/bizinsider.png" alt="biz-insider-logo">
    <img class="press-logo" src="images/mashable.png" alt="mashable-logo">

  </section>

  <!-- Pricing -->

  <section id="pricing">

    <h2>A Plan for Every Dog's Needs</h2>
    <p>Simple and affordable price plans for your and your dog.</p>

    <h3>Chihuahua</h3>
    <h2>Free</h2>
    <p>5 Matches Per Day</p>
    <p>10 Messages Per Day</p>
    <p>Unlimited App Usage</p>
    <button type="button">Sign Up</button>

    <h3>Labrador</h3>
    <h2>$49 / mo</h2>
    <p>Unlimited Matches</p>
    <p>Unlimited Messages</p>
    <p>Unlimited App Usage</p>
    <button type="button">Sign Up</button>

    <h3>Mastiff</h3>
    <h2>$99 / mo</h2>
    <p>Pirority Listing</p>
    <p>Unlimited Matches</p>
    <p>Unlimited Messages</p>
    <p>Unlimited App Usage</p>
    <button type="button">Sign Up</button>

  </section>

  <!-- Call to Action -->

  <section id="cta">

    <h3>Find the True Love of Your Dog's Life Today.</h3>
    <button type="button">Download</button>
    <button type="button">Download</button>

  </section>

  <!-- Footer -->

  <footer id="footer">

    <p>© Copyright TinDog</p>

  </footer>

</body>

</html></code>```

答:
1. What exactly is wrong with the buttons? Carousel

Read how to connect the 5 Budstrap correctly

The scripts should be plugged at the very bottom, before

```<code><script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
</code>```

2. Connecting fonts

html:

```<code><link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap" rel="stylesheet">
</code>```

css:

```<code>font-family: 'Montserrat', sans-serif;
font-weight: 900;
</code>```

Title: Bootstrap carousel & Google Font Issues

Body:
I know this has been asked many times, but I still cannot seem to fix my code. As you can see, I am copied the code directly from bootstrap, and I was able to get my buttons to appear, but they are not activating. Also, google fonts was directly imported, but it too is not changing my fonts as it should. It is remaining as default.

#title {
  background-color: #FF4C68;
  color: WHITE;
}
.container-fluid{
  padding: 3% 15%;
}
/* H1 FONT FAMILY NOT WORKING */
h1 {
  font-family: "Montserrat-Black";
  font-size: 3.5rem;
  line-height: 1.5;
}
h2 {
  font-family: "Montserrat-Bold";
  font-size: 3rem;
  line-height: 1.5;
}
h3{
  font-family: "Montserrat-Bold";
  font-size: 1.5rem;
}
p{
  color: #8F8F8F;
}
body {
  font-family: "Montserrat";
}
/* NAVIGATION BAR */

.navbar {
  padding-bottom: 4.5rem;
}

.navbar-brand {
  font-family: 'Ubuntu';
  font-size: 2.5rem;
  font-weight: bold;
  color: yellow;
}

.nav-item {
  padding: 0 18px;
}

.nav-link {
  font-size: 1.2rem;
  font-family: "Montserrat-Light";
}

/* DOWNLOAD BUTTONS */
.download-button {
  margin: 5% 3% 5%;
}

/* TITLE IMAGE */
.title-image {
  width: 60%;
  transform: rotate(45deg);
}

/* FEATURES SECTION */
#features {
  padding: 7% 15%;
  text-align: center;
  padding: 5%;
}
/* CHANGE PADDING ABOVE IF FIRST BODY ISNT LOOKING RIGHT */

.icon{
  color: #ef8172;
  margin-bottom: 1rem;
}
.icon:hover{
  color: #ff4c68;
}

/* TESTIMONIAL SECTION */
#testimonials {
  text-align: center;
  background-color: #ef8172;
  color: #fff;
}
.testimonial-img{
  width: 10%;
  border-radius: 100%;
  margin: 20px;
}
#press {
  background-color: #ef8172;
  text-align: center;
  padding-bottom: 3%;
}
.press-logo {
  width: 15%;
  margin: 20px 20px 50px;
}
.carousel-item {
  padding: 7% 15%;
}

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>TinDog</title>

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@100;400;900&family=Ubuntu&display=swap" rel="stylesheet">

  <link href="https://fonts.googleapis.com/css2?family=Montserrat&family=Ubuntu&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="css/styles.css">

        Tindog
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

        </button>

              Contact

              Pricing

              Download

Meet new and interesting dogs nearby.

          <button type="button" class="btn btn-primary btn-lg download-button"> Download</button>
          <button type="button" class="btn btn-outline-light btn-lg download-button"> Download</button>

Easy to use.

So easy to use, even your dog could do it.

Elite Clientele

We have all the dogs, the greatest dogs.

Guaranteed to work.

Find the love of your dog's life or your money back.

I no longer have to sniff other dogs for love. I've found the hottest Corgi on TinDog. Woof.

          Pebbles, New York

My dog used to be so lonely, but with TinDog's help, they've found the love of their life. I think.

          Beverly, Illinois

      <button class="carousel-control-prev" type="button" data-bs-target="#testimonial-carousel" data-bs-slide="prev">

        Previous
      </button>
      <button class="carousel-control-next" type="button" data-bs-target="#testimonial-carousel" data-bs-slide="next">

        Next
      </button>

A Plan for Every Dog's Needs

Simple and affordable price plans for your and your dog.

Chihuahua

Free

5 Matches Per Day

10 Messages Per Day

Unlimited App Usage

    <button type="button">Sign Up</button>

Labrador

$49 / mo

Unlimited Matches

Unlimited Messages

Unlimited App Usage

    <button type="button">Sign Up</button>

Mastiff

$99 / mo

Pirority Listing

Unlimited Matches

Unlimited Messages

Unlimited App Usage

    <button type="button">Sign Up</button>

Find the True Love of Your Dog's Life Today.

    <button type="button">Download</button>
    <button type="button">Download</button>

© Copyright TinDog

Body:
1. What exactly is wrong with the buttons? Carousel

Read how to connect the 5 Budstrap correctly

The scripts should be plugged at the very bottom, before </body>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

2. Connecting fonts

html:

<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap" rel="stylesheet">

css:

font-family: 'Montserrat', sans-serif;
font-weight: 900;