问:
show 2 digits max after floating point ... only if it is a float number with more than 2 float digits
in my app i do some math and the result can be float or int

i want to show the final result with two digit after the decimal point max ... if result is a float number

there are two options  to do this

```<code>number_format($final ,2);
</code>```

and

```<code>sprintf ("%.2f", $final );
</code>```

but problem is ... if my final result is a int like 25 i end up with

```<code>25.00
</code>```

or if final result is some thing like 12.3 it gives me

```<code>12.30
</code>```

and i dont want that

is there any way to format a number to show 2 digits after float point ONLY IF it's a float number with more than 2 digits after decimal point  ? or should i do some checking before formatting my number  ?

答:
Try below function to maintain a constant 2 digits after decimal point

in case you want to change the number of digits change AFTER_DESIMAL_DIGITS value

```<code>function decimal_digit_maintainer($value){
    define("AFTER_DESIMAL_DIGITS ",2);
    $value_array = explode('.',$value);
    if(isset($value_array[1])){
        $value_array[1] =  str_pad($value_array[1],AFTER_DESIMAL_DIGITS,'0',STR_PAD_RIGHT);
    }
    return implode('.',$value_array);
}
</code>```

Body:
in my app i do some math and the result can be float or int

i want to show the final result with two digit after the decimal point max ... if result is a float number

there are two options  to do this

number_format($final ,2);

and

sprintf ("%.2f", $final );

but problem is ... if my final result is a int like 25 i end up with

25.00

or if final result is some thing like 12.3 it gives me

12.30

and i dont want that

is there any way to format a number to show 2 digits after float point ONLY IF it's a float number with more than 2 digits after decimal point  ? or should i do some checking before formatting my number  ?

Body:
Try below function to maintain a constant 2 digits after decimal point

in case you want to change the number of digits change AFTER_DESIMAL_DIGITS value

function decimal_digit_maintainer($value){
    define("AFTER_DESIMAL_DIGITS ",2);
    $value_array = explode('.',$value);
    if(isset($value_array[1])){
        $value_array[1] =  str_pad($value_array[1],AFTER_DESIMAL_DIGITS,'0',STR_PAD_RIGHT);
    }
    return implode('.',$value_array);
}


来源: stackexchange

问:
Display a warning message with a specific CSS format
I saw the dialog as the picture below,

That is an warning message for erroneous MAC address format after the input text submitted. I would like to verify the input immediately not after it is submitted. Where can I find this css style?

答:
Try this:

body {
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", sans-serif;
    font-size: 112.5%;
    margin-left: auto;
    margin-right: auto;
    max-width: 40em;
    width: 88%;
}

/**
 * Form Styles
 */
label {
    display: block;
    font-weight: bold;
    margin-bottom: 0.5em;
}

.label-normal {
    font-weight: normal;
}

.pattern {
    color: #808080;
    font-size: 0.8em;
    font-weight: normal;
}

.supports-color .color,
.supports-date .date,
.supports-time .time,
.supports-month .mont {
    display: none;
}

input,
select {
    display: inline-block;
    font-size: 1em;
    margin-bottom: 1em;
    padding: 0.25em 0.5em;
    width: 100%;
}

[type="checkbox"],
[type="radio"] {
    margin-bottom: 0.5em;
    width: auto;
}

.button {
    background-color: #0088cc;
    border: 1px solid #0088cc;
    border-radius: 1px;
    color: #ffffff;
    display: inline-block;
    font-size: 0.9375em;
    font-weight: normal;
    line-height: 1.2;
    margin-right: 0.3125em;
    margin-bottom: 0.3125em;
    padding: 0.5em 0.6875em;
    width: auto;
}

.button:active,
.button:focus,
.button:hover {
    background-color: #005580;
    border-color: #005580;
    color: #ffffff;
    text-decoration: none;
}

.button:active {
    box-shadow: inset 0 0.15625em 0.25em rgba(0, 0, 0, 0.15), 0 1px 0.15625em rgba(0, 0, 0, 0.05);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
    <div>
        <label for="text">Text Input</label>
        <input type="text" id="text" required>
    </div>

    <div>
        <label for="minmaxlength">Text with Min and Max Length</label>
        <input type="text" id="minmaxlength" minlength="3" maxlength="12">
    </div>

    <div>
        <label for="password">Password (must contain at least 1 uppercase character, 1 lowercase character, and 1 number)</label>
        <input type="password" id="password" pattern="^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).*$" required>
    </div>

    <div>
        <label for="passwordwithtitle">Password with Title Attribute</label>
        <input type="password" id="passwordwithtitle" pattern="^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).*$" title="Please include at least 1 uppercase character, 1 lowercase character, and 1 number." required>
    </div>

    <div>
        <label for="passwordcombined">Password with Pattern and Min Length</label>
        <input type="password" id="passwordcombined" minlength="8" pattern="^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).*$" title="Please include at least 1 uppercase character, 1 lowercase character, and 1 number." required>
    </div>

    <input type="submit" class="button" value="Submit">
</form></code>```

ContentLicense: CC BY-SA 4.0

Body:
Try this:

body {
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", sans-serif;
    font-size: 112.5%;
    margin-left: auto;
    margin-right: auto;
    max-width: 40em;
    width: 88%;
}

/**
 * Form Styles
 */
label {
    display: block;
    font-weight: bold;
    margin-bottom: 0.5em;
}

.label-normal {
    font-weight: normal;
}

.pattern {
    color: #808080;
    font-size: 0.8em;
    font-weight: normal;
}

.supports-color .color,
.supports-date .date,
.supports-time .time,
.supports-month .mont {
    display: none;
}

input,
select {
    display: inline-block;
    font-size: 1em;
    margin-bottom: 1em;
    padding: 0.25em 0.5em;
    width: 100%;
}

[type="checkbox"],
[type="radio"] {
    margin-bottom: 0.5em;
    width: auto;
}

.button {
    background-color: #0088cc;
    border: 1px solid #0088cc;
    border-radius: 1px;
    color: #ffffff;
    display: inline-block;
    font-size: 0.9375em;
    font-weight: normal;
    line-height: 1.2;
    margin-right: 0.3125em;
    margin-bottom: 0.3125em;
    padding: 0.5em 0.6875em;
    width: auto;
}

.button:active,
.button:focus,
.button:hover {
    background-color: #005580;
    border-color: #005580;
    color: #ffffff;
    text-decoration: none;
}

.button:active {
    box-shadow: inset 0 0.15625em 0.25em rgba(0, 0, 0, 0.15), 0 1px 0.15625em rgba(0, 0, 0, 0.05);
}

<form>
    <div>
        <label for="text">Text Input</label>
        <input type="text" id="text" required>
    </div>

    <div>
        <label for="minmaxlength">Text with Min and Max Length</label>
        <input type="text" id="minmaxlength" minlength="3" maxlength="12">
    </div>

    <div>
        <label for="password">Password (must contain at least 1 uppercase character, 1 lowercase character, and 1 number)</label>
        <input type="password" id="password" pattern="^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).*$" required>
    </div>

    <div>
        <label for="passwordwithtitle">Password with Title Attribute</label>
        <input type="password" id="passwordwithtitle" pattern="^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).*$" title="Please include at least 1 uppercase character, 1 lowercase character, and 1 number." required>
    </div>

    <div>
        <label for="passwordcombined">Password with Pattern and Min Length</label>
        <input type="password" id="passwordcombined" minlength="8" pattern="^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).*$" title="Please include at least 1 uppercase character, 1 lowercase character, and 1 number." required>
    </div>

    <input type="submit" class="button" value="Submit">
</form>


问:
hamburger menu covers logo
My hamburger menu blocks part of the logo on smaller screen sizes, and I'm not sure how to fix it so that the logo appears in front of the menu before the menu is clicked. This is what I mean.

I tried setting the background of the label .menu to transparent but the logo appears after the menu is clicked. I'm talking about this.

Any help would be appreciated.

Also, I know my code's messy. I'll fix it later, so don't judge the messy code, please.

.logo {
  position: fixed;
  width: 100%;
  top: -15px;
  height: auto;
  left: 50%;
  transform: translate(-50%);
}

.midnight-logo {
  width: 40%;
  margin: 0 auto;
  display: block;
}

label .hamburger {
  position: fixed;
  display: inline-block;
  top: 30px;
  left: 30px;
  width: 30px;
  height: 2px;
  display: block;
  transform-origin: center;
  -webkit-transition: .5s ease-in-out;
  transition: .5s ease-in-out;
  background: #C8C8C8;
}

label .hamburger:after,
label .hamburger:before {
  transition: .5s ease-in-out;
  content: "";
  position: absolute;
  display: block;
  width: 100%;
  height: 100%;
  background: #C8C8C8;
}

label .hamburger:before {
  top: -10px;
}

label .hamburger:after {
  bottom: -10px;
}

label input {
  display: none;
}

label input:checked+.menu {
  box-shadow: 0 0 0 100vw #000, 0 0 0 100vh #000;
  border-radius: 0;
}

label input:checked+.menu .hamburger {
  transform: rotate(45deg);
}

label input:checked+.menu .hamburger:after {
  transform: rotate(90deg);
  bottom: 0;
}

label input:checked+.menu .hamburger:before {
  transform: rotate(90deg);
  top: 0;
}

label input:checked+.menu+ul {
  display: block;
}

label .menu {
  position: fixed;
  top: -100px;
  z-index: 1;
  width: 100px;
  height: 155px;
  border-radius: 50% 50% 50% 50%;
  transition: .5s ease-in-out;
  box-shadow: 0 0 0 0 #000, 0 0 0 0 #000;
  cursor: pointer;
  background: #000;
}

label ul {
  z-index: 200;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: none;
  transition: .25s 0s ease-in-out;
  list-style-type: none;
  font-size: 40px;
  font-family: 'Tangerine', cursive;
}

label a {
  margin-bottom: 1em;
  display: block;
  text-decoration: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img class="logo" src="https://i.ibb.co/xsQHR3Y/midnight-logo.png">

<label>

                <input type="checkbox">

                <span class="menu">

                <span class="hamburger"> </span> </span>

                    <ul>

                        <li>  Home  </li>

                        <li>  About  </li>

                        <li>  Contact  </li>

                    </ul>

            </label></code>```

答:
Try adding these edits to the .logo class in CSS:

z-index: 3;
 pointer-events: none;

This will make the logo start out above the menu. The pointer-events styling lets the menu stay clickable even though it's under the logo. However, it will stay on top after the menu is clicked.

If you don't want it to stay on top, add some Javascript onclick event to the menu. So that the logo reverts to a lower z-index when the menu is clicked. Something like .

Then put some Javascript between  tags. I used the code below in the snippet. Hope this helps!

function logoBack() {
var logo = document.getElementsByClassName('logo')[0];
logo.style.zIndex = "0";
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.logo {
  position: fixed;
  width: 100%;
  top: -15px;
  height: auto;
  left: 50%;
  transform: translate(-50%);
  z-index: 3;
  pointer-events: none;
}

.midnight-logo {
  width: 40%;
  margin: 0 auto;
  display: block;
}

label .hamburger {
  position: fixed;
  display: inline-block;
  top: 30px;
  left: 30px;
  width: 30px;
  height: 2px;
  display: block;
  transform-origin: center;
  -webkit-transition: .5s ease-in-out;
  transition: .5s ease-in-out;
  background: #C8C8C8;
}

label .hamburger:after,
label .hamburger:before {
  transition: .5s ease-in-out;
  content: "";
  position: absolute;
  display: block;
  width: 100%;
  height: 100%;
  background: #C8C8C8;
}

label .hamburger:before {
  top: -10px;
}

label .hamburger:after {
  bottom: -10px;
}

label input {
  display: none;
}

label input:checked+.menu {
  box-shadow: 0 0 0 100vw #000, 0 0 0 100vh #000;
  border-radius: 0;
}

label input:checked+.menu .hamburger {
  transform: rotate(45deg);
}

label input:checked+.menu .hamburger:after {
  transform: rotate(90deg);
  bottom: 0;
}

label input:checked+.menu .hamburger:before {
  transform: rotate(90deg);
  top: 0;
}

label input:checked+.menu+ul {
  display: block;
}

label .menu {
  position: fixed;
  top: -100px;
  z-index: 1;
  width: 100px;
  height: 155px;
  border-radius: 50% 50% 50% 50%;
  transition: .5s ease-in-out;
  box-shadow: 0 0 0 0 #000, 0 0 0 0 #000;
  cursor: pointer;
  background: #000;

}

label ul {
  z-index: 200;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: none;
  transition: .25s 0s ease-in-out;
  list-style-type: none;
  font-size: 40px;
  font-family: 'Tangerine', cursive;
}

label a {
  margin-bottom: 1em;
  display: block;
  text-decoration: none;
}</code>```

<DOCTYPE! HTML>

                <input type="checkbox">

  Home

  About

  Contact

            ```

Title: hamburger menu covers logo

Body:
My hamburger menu blocks part of the logo on smaller screen sizes, and I'm not sure how to fix it so that the logo appears in front of the menu before the menu is clicked. This is what I mean.

I tried setting the background of the label .menu to transparent but the logo appears after the menu is clicked. I'm talking about this.

Any help would be appreciated.

Also, I know my code's messy. I'll fix it later, so don't judge the messy code, please.

.logo {
  position: fixed;
  width: 100%;
  top: -15px;
  height: auto;
  left: 50%;
  transform: translate(-50%);
}

.midnight-logo {
  width: 40%;
  margin: 0 auto;
  display: block;
}

label .hamburger {
  position: fixed;
  display: inline-block;
  top: 30px;
  left: 30px;
  width: 30px;
  height: 2px;
  display: block;
  transform-origin: center;
  -webkit-transition: .5s ease-in-out;
  transition: .5s ease-in-out;
  background: #C8C8C8;
}

label .hamburger:after,
label .hamburger:before {
  transition: .5s ease-in-out;
  content: "";
  position: absolute;
  display: block;
  width: 100%;
  height: 100%;
  background: #C8C8C8;
}

label .hamburger:before {
  top: -10px;
}

label .hamburger:after {
  bottom: -10px;
}

label input {
  display: none;
}

label input:checked+.menu {
  box-shadow: 0 0 0 100vw #000, 0 0 0 100vh #000;
  border-radius: 0;
}

label input:checked+.menu .hamburger {
  transform: rotate(45deg);
}

label input:checked+.menu .hamburger:after {
  transform: rotate(90deg);
  bottom: 0;
}

label input:checked+.menu .hamburger:before {
  transform: rotate(90deg);
  top: 0;
}

label input:checked+.menu+ul {
  display: block;
}

label .menu {
  position: fixed;
  top: -100px;
  z-index: 1;
  width: 100px;
  height: 155px;
  border-radius: 50% 50% 50% 50%;
  transition: .5s ease-in-out;
  box-shadow: 0 0 0 0 #000, 0 0 0 0 #000;
  cursor: pointer;
  background: #000;
}

label ul {
  z-index: 200;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: none;
  transition: .25s 0s ease-in-out;
  list-style-type: none;
  font-size: 40px;
  font-family: 'Tangerine', cursive;
}

label a {
  margin-bottom: 1em;
  display: block;
  text-decoration: none;
}

                <input type="checkbox">

  Home

  About

  Contact

Body:
Try adding these edits to the .logo class in CSS:

z-index: 3;
 pointer-events: none;

This will make the logo start out above the menu. The pointer-events styling lets the menu stay clickable even though it's under the logo. However, it will stay on top after the menu is clicked.

If you don't want it to stay on top, add some Javascript onclick event to the menu. So that the logo reverts to a lower z-index when the menu is clicked. Something like <span class="menu" onclick="logoBack()">.

Then put some Javascript between <script></script> tags. I used the code below in the snippet. Hope this helps!

function logoBack() {
var logo = document.getElementsByClassName('logo')[0];
logo.style.zIndex = "0";
};

.logo {
  position: fixed;
  width: 100%;
  top: -15px;
  height: auto;
  left: 50%;
  transform: translate(-50%);
  z-index: 3;
  pointer-events: none;
}

.midnight-logo {
  width: 40%;
  margin: 0 auto;
  display: block;
}

label .hamburger {
  position: fixed;
  display: inline-block;
  top: 30px;
  left: 30px;
  width: 30px;
  height: 2px;
  display: block;
  transform-origin: center;
  -webkit-transition: .5s ease-in-out;
  transition: .5s ease-in-out;
  background: #C8C8C8;
}

label .hamburger:after,
label .hamburger:before {
  transition: .5s ease-in-out;
  content: "";
  position: absolute;
  display: block;
  width: 100%;
  height: 100%;
  background: #C8C8C8;
}

label .hamburger:before {
  top: -10px;
}

label .hamburger:after {
  bottom: -10px;
}

label input {
  display: none;
}

label input:checked+.menu {
  box-shadow: 0 0 0 100vw #000, 0 0 0 100vh #000;
  border-radius: 0;
}

label input:checked+.menu .hamburger {
  transform: rotate(45deg);
}

label input:checked+.menu .hamburger:after {
  transform: rotate(90deg);
  bottom: 0;
}

label input:checked+.menu .hamburger:before {
  transform: rotate(90deg);
  top: 0;
}

label input:checked+.menu+ul {
  display: block;
}

label .menu {
  position: fixed;
  top: -100px;
  z-index: 1;
  width: 100px;
  height: 155px;
  border-radius: 50% 50% 50% 50%;
  transition: .5s ease-in-out;
  box-shadow: 0 0 0 0 #000, 0 0 0 0 #000;
  cursor: pointer;
  background: #000;

}

label ul {
  z-index: 200;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: none;
  transition: .25s 0s ease-in-out;
  list-style-type: none;
  font-size: 40px;
  font-family: 'Tangerine', cursive;
}

label a {
  margin-bottom: 1em;
  display: block;
  text-decoration: none;
}

<DOCTYPE! HTML>
<head>
</head>

<body>
<img class="logo" src="https://i.ibb.co/xsQHR3Y/midnight-logo.png">

<label>
                <input type="checkbox">

                <span class="menu" onclick="logoBack()">

                <span class="hamburger"> </span> </span>

                    <ul>

                        <li> <a href="home.html"> Home </a> </li>

                        <li> <a href="about.html"> About </a> </li>

                        <li> <a href="contact.html"> Contact </a> </li>

                    </ul>

            </label>

            </body>

            </html>


问:
Spring boot Mongo DB .yml configuration
When I use MySQL and hibernate for spring boot, I use below configuration in  .yml file

```<code>spring:
  datasource:
    url: jdbc:mysql://localhost/userName?zeroDateTimeBehavior=convertToNull
    username: userName
    password: password
    driverClassName: com.mysql.jdbc.Driver

  jpa:
    show-sql: false
    hibernate:
      dialect: org.hibernate.dialect.MySQLDialect
      format_sql: false
      ddl-auto: update
</code>```

If it is mongoDB instead of MySQL and hibernate how does it change?

答:
The mongodb properties are all prefixed with spring.data.mongodb. For user property you would use

```<code>spring:
  data:
      mongodb:
        user: test
        password: passwordvalue
        uri: mongodb://host:27017/db
</code>```

The list of available mongodb properties are here:

```<code>https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html
</code>```

You can find them at source for how they are loaded on github:

https://github.com/spring-projects/spring-boot/blob/v2.1.5.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/MongoProperties.java

Title: Spring boot Mongo DB .yml configuration

Body:
When I use MySQL and hibernate for spring boot, I use below configuration in  .yml file

spring:
  datasource:
    url: jdbc:mysql://localhost/userName?zeroDateTimeBehavior=convertToNull
    username: userName
    password: password
    driverClassName: com.mysql.jdbc.Driver

  jpa:
    show-sql: false
    hibernate:
      dialect: org.hibernate.dialect.MySQLDialect
      format_sql: false
      ddl-auto: update

If it is mongoDB instead of MySQL and hibernate how does it change?

Body:
The mongodb properties are all prefixed with spring.data.mongodb. For user property you would use

spring:
  data:
      mongodb:
        user: test
        password: passwordvalue
        uri: mongodb://host:27017/db

The list of available mongodb properties are here:

https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html

You can find them at source for how they are loaded on github:

https://github.com/spring-projects/spring-boot/blob/v2.1.5.RELEASE/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mongo/MongoProperties.java


问:
Finding the first duplicate of an array
I've decided to learn python and I use CodeFight to train. The first Interview Practice exercice is about finding the first duplicate of an array and returning it or retruning -1 if there isn't any. This is the code I wrote:

```<code>def firstDuplicate(a):
b=[]
print(len(a))
for i in range(len(a)):
    if a[i] in b:
        return(a[i])
    elif a[i] not in b and i == (len(a)-1):
        return(-1)
    else:
        b.append(a[i])
</code>```

I pass all the tests except the last 3. I says that my program takes longer than 4000ms to execute. I guess the array is very long and the duplicate is at the end. How can I reduce this execution time ? Thanks in advance.

答:
```<code>from collections import Counter
list1 = [1,2,2,3,4,4]
dict1 = Counter(list1)
duplist = [key for (key,value) in dict1.items()if value >1]
for item in list1:
    if item in duplist:
        print ('first dup',item )
        break
</code>```

ContentLicense: CC BY-SA 3.0

Title: Finding the first duplicate of an array

Body:
I've decided to learn python and I use CodeFight to train. The first Interview Practice exercice is about finding the first duplicate of an array and returning it or retruning -1 if there isn't any. This is the code I wrote:

def firstDuplicate(a):
b=[]
print(len(a))
for i in range(len(a)):
    if a[i] in b:
        return(a[i])
    elif a[i] not in b and i == (len(a)-1):
        return(-1)
    else:
        b.append(a[i])

I pass all the tests except the last 3. I says that my program takes longer than 4000ms to execute. I guess the array is very long and the duplicate is at the end. How can I reduce this execution time ? Thanks in advance.


问:
Set index to group of repetitive row values in a csv file using Python
I am new to python. I want to set index to specific set of row elements which are repetitive for each group.
My dataframe:

```<code>data_dict ={'0_deg': [2, 11, 21, -17, 5, 40, 22, 7, 20, -6, -6, -6, 24, 21, 20, 61, 21, 5, 2, 17],
 '10_deg': [12, -21, 11, 1, 4, -2, 33, 53, 18, 10, -3, -1, 23, 18, 23, 8, 11, -25, 21, -14],
 '20_deg': [23, -10, 3, 20, -41, 13, 10, 5, -9, 7, -4, -21, 14, -26, -31, 9, 1, -15, 3, -6],
 '30_deg': [12, 9, -5, 4, 9, -46, 1, -8, -27, 3, -9, -14, 15, -6, 14, 7, -11, 5, 19, -4]}
</code>```

```<code>data_dict = pd.read_csv('Dataset.csv')
data_dict = data_dict.set_index('Indexes')

#row idx of a group in this list
idx =[4,10,37,109,133]
</code>```

Here a list is created as idx and index values are written maunally.

But for a bigger matrix of 1000+ indexes(random values) per group, this would be a very difficult task.

What I want is that when I read a CSV file, the 1st value in the row should be selected and until the same value occurs in the same index, it should be considered as 1 group, and the indexes for 1st group must get stored in idx

Eg: In my small version of dataset, from 1st column Indexes, the 1st values i.e. 4,10,37,109,133 are my indexxes for 1st group. These values repeat in same sequence for next groups.
Only they shoud not be entered manually in code. A group should be considered unitl next 4 occurs. So index values 4 to 133 must be considered as 1 group under idx. This is because I need idx for further part of the code.

My actual dataset has 1000+ index values per group. So idx must automatically take all values of a group.

```<code># getting some dimensions and sorting the data
row_idx_length = len(idx)
group_length = len(data_dict['0_deg'])
number_of_groups = len(data_dict.keys())
idx = idx*number_of_groups
data_arr = np.zeros((group_length,number_of_groups),dtype=np.int32)
</code>```

答:
I believe you need numpy.tile with integer division for number of repeating:

```<code>df.index = np.tile(idx, len(df.index) // len(idx))
</code>```

But if get error (N and M are some integer numbers):

ValueError: Length mismatch: Expected axis has N elements, new values have M elements

It means in last group missing some elements, so add next group by 1 and filter by length of index of DataFrame:

```<code>#added 150 to idx list
idx =[4,10,37,109,133,150]
df.index = np.tile(idx, len(df.index) // len(idx) + 1)[:len(df.index)]
print (df)
     0_deg  10_deg  20_deg  30_deg
4        2      12      23      12
10      11     -21     -10       9
37      21      11       3      -5
109    -17       1      20       4
133      5       4     -41       9
150     40      -2      13     -46
4       22      33      10       1
10       7      53       5      -8
37      20      18      -9     -27
109     -6      10       7       3
133     -6      -3      -4      -9
150     -6      -1     -21     -14
4       24      23      14      15
10      21      18     -26      -6
37      20      23     -31      14
109     61       8       9       7
133     21      11       1     -11
150      5     -25     -15       5
4        2      21       3      19
10      17     -14      -6      -4
</code>```

Body:
I am new to python. I want to set index to specific set of row elements which are repetitive for each group.
My dataframe:

data_dict ={'0_deg': [2, 11, 21, -17, 5, 40, 22, 7, 20, -6, -6, -6, 24, 21, 20, 61, 21, 5, 2, 17],
 '10_deg': [12, -21, 11, 1, 4, -2, 33, 53, 18, 10, -3, -1, 23, 18, 23, 8, 11, -25, 21, -14],
 '20_deg': [23, -10, 3, 20, -41, 13, 10, 5, -9, 7, -4, -21, 14, -26, -31, 9, 1, -15, 3, -6],
 '30_deg': [12, 9, -5, 4, 9, -46, 1, -8, -27, 3, -9, -14, 15, -6, 14, 7, -11, 5, 19, -4]}

data_dict = pd.read_csv('Dataset.csv')
data_dict = data_dict.set_index('Indexes')

#row idx of a group in this list
idx =[4,10,37,109,133]

Here a list is created as idx and index values are written maunally.

But for a bigger matrix of 1000+ indexes(random values) per group, this would be a very difficult task.

What I want is that when I read a CSV file, the 1st value in the row should be selected and until the same value occurs in the same index, it should be considered as 1 group, and the indexes for 1st group must get stored in idx

Eg: In my small version of dataset, from 1st column Indexes, the 1st values i.e. 4,10,37,109,133 are my indexxes for 1st group. These values repeat in same sequence for next groups.
Only they shoud not be entered manually in code. A group should be considered unitl next 4 occurs. So index values 4 to 133 must be considered as 1 group under idx. This is because I need idx for further part of the code.

My actual dataset has 1000+ index values per group. So idx must automatically take all values of a group.

# getting some dimensions and sorting the data
row_idx_length = len(idx)
group_length = len(data_dict['0_deg'])
number_of_groups = len(data_dict.keys())
idx = idx*number_of_groups
data_arr = np.zeros((group_length,number_of_groups),dtype=np.int32)

Body:
I believe you need numpy.tile with integer division for number of repeating:

df.index = np.tile(idx, len(df.index) // len(idx))

But if get error (N and M are some integer numbers):

ValueError: Length mismatch: Expected axis has N elements, new values have M elements

It means in last group missing some elements, so add next group by 1 and filter by length of index of DataFrame:

#added 150 to idx list
idx =[4,10,37,109,133,150]
df.index = np.tile(idx, len(df.index) // len(idx) + 1)[:len(df.index)]
print (df)
     0_deg  10_deg  20_deg  30_deg
4        2      12      23      12
10      11     -21     -10       9
37      21      11       3      -5
109    -17       1      20       4
133      5       4     -41       9
150     40      -2      13     -46
4       22      33      10       1
10       7      53       5      -8
37      20      18      -9     -27
109     -6      10       7       3
133     -6      -3      -4      -9
150     -6      -1     -21     -14
4       24      23      14      15
10      21      18     -26      -6
37      20      23     -31      14
109     61       8       9       7
133     21      11       1     -11
150      5     -25     -15       5
4        2      21       3      19
10      17     -14      -6      -4


问:
How to implement an efficient image compressing?
I would like to compress images before uploaded and hosted on storage reference. Is there any way to achieve this efficiently ?

Even if quality will not be the best, the point is to reduce the size .

```<code>private void StoringImageToFirebaseStorage()
    {

        String uri = PostsImagesRefrence.child("Post Images").child(ImageUri.getLastPathSegment() + postRandomName + ".jpg").toString();

        StorageReference filePath = PostsImagesRefrence.child("Post Images").child(ImageUri.getLastPathSegment() + postRandomName + ".jpg");

        filePath.putFile(ImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task){
                if (task.isSuccessful()){
                    downloadUrl = task.getResult().getDownloadUrl().toString();
                    SavingInformationToDatabase();
                }
                else
                {.....}
    }

private void OpenGallery() {
                Intent galleryIntent = new Intent();
                galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
                galleryIntent.setType("image/*");
                startActivityForResult(galleryIntent, Gallery_Pick);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode==Gallery_Pick && resultCode==RESULT_OK && data!=null{
            ImageUri = data.getData();
            PostImage.setImageURI(ImageUri);
            PostImage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v){
                    OpenGallery();
                {...}
    }
</code>```

答:
Hello you can use this simple light weight library to compress your images in any size you want and it will also help you to upload those images directly in bytes to firebase.

Image Compressor

```<code>  new ImageCompressor(imageFile.getAbsolutePath(), imageFilePath, new ImageCompressListener() {
                            @Override
                            public void onImageCompressed(byte[] outputImageBaos, File imageFile) {
                                if (outputImageBaos != null) {
                                    final StorageReference mediaFileRef = mStoreRef.child("images/" + imageFilePath);
                                    currenTask = mediaFileRef.putBytes(outputImageBaos);

                                    currenTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
                                        @Override
                                        public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
                                            if (!task.isSuccessful()) {
                                                throw task.getException();
                                            }

                                            // Continue with the task to get the download URL
                                            return mediaFileRef.getDownloadUrl();
                                        }
                                    }).addOnCompleteListener(new OnCompleteListener<Uri>() {
                                        @Override
                                        public void onComplete(@NonNull Task<Uri> task) {
                                            if (task.isSuccessful()) {
                                                String downloadUri = task.getResult().toString();

                                            }
                                        }
                                    });
                                    currenTask.addOnFailureListener(new OnFailureListener() {
                                        @Override
                                        public void onFailure(@NonNull Exception e) {
                                            sendProgressBroadcast(AppConstants.UPLOAD_FAILED, -1);
                                        }
                                    }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                                        @Override
                                        public void onProgress(com.google.firebase.storage.UploadTask.TaskSnapshot taskSnapshot) {
                                            int progress = (int) ((100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount());
                                            sendProgressBroadcast(AppConstants.UPLOAD_PROGRESS, progress);
                                        }
                                    });
                                }
                            }
                        });
</code>```

Body:
I would like to compress images before uploaded and hosted on storage reference. Is there any way to achieve this efficiently ?

Even if quality will not be the best, the point is to reduce the size .

private void StoringImageToFirebaseStorage()
    {

        String uri = PostsImagesRefrence.child("Post Images").child(ImageUri.getLastPathSegment() + postRandomName + ".jpg").toString();

        StorageReference filePath = PostsImagesRefrence.child("Post Images").child(ImageUri.getLastPathSegment() + postRandomName + ".jpg");

        filePath.putFile(ImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task){
                if (task.isSuccessful()){
                    downloadUrl = task.getResult().getDownloadUrl().toString();
                    SavingInformationToDatabase();
                }
                else
                {.....}
    }

private void OpenGallery() {
                Intent galleryIntent = new Intent();
                galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
                galleryIntent.setType("image/*");
                startActivityForResult(galleryIntent, Gallery_Pick);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode==Gallery_Pick && resultCode==RESULT_OK && data!=null{
            ImageUri = data.getData();
            PostImage.setImageURI(ImageUri);
            PostImage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v){
                    OpenGallery();
                {...}
    }

Body:
Hello you can use this simple light weight library to compress your images in any size you want and it will also help you to upload those images directly in bytes to firebase.

Image Compressor

  new ImageCompressor(imageFile.getAbsolutePath(), imageFilePath, new ImageCompressListener() {
                            @Override
                            public void onImageCompressed(byte[] outputImageBaos, File imageFile) {
                                if (outputImageBaos != null) {
                                    final StorageReference mediaFileRef = mStoreRef.child("images/" + imageFilePath);
                                    currenTask = mediaFileRef.putBytes(outputImageBaos);

                                    currenTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
                                        @Override
                                        public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
                                            if (!task.isSuccessful()) {
                                                throw task.getException();
                                            }

                                            // Continue with the task to get the download URL
                                            return mediaFileRef.getDownloadUrl();
                                        }
                                    }).addOnCompleteListener(new OnCompleteListener<Uri>() {
                                        @Override
                                        public void onComplete(@NonNull Task<Uri> task) {
                                            if (task.isSuccessful()) {
                                                String downloadUri = task.getResult().toString();

                                            }
                                        }
                                    });
                                    currenTask.addOnFailureListener(new OnFailureListener() {
                                        @Override
                                        public void onFailure(@NonNull Exception e) {
                                            sendProgressBroadcast(AppConstants.UPLOAD_FAILED, -1);
                                        }
                                    }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                                        @Override
                                        public void onProgress(com.google.firebase.storage.UploadTask.TaskSnapshot taskSnapshot) {
                                            int progress = (int) ((100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount());
                                            sendProgressBroadcast(AppConstants.UPLOAD_PROGRESS, progress);
                                        }
                                    });
                                }
                            }
                        });


问:
What's the difference between hacks and messy/bad code
When is code a hack?

People seem to define a hack as ugly coding to solve a problem but how is that different from writing messy code.

Also is the only difference between a problem coded badly and a problem hacked the mindset of the programmer?

When I say hack I mean in the programming/development sense not the illegal sense.

答:
A hack implies that the programmer is using a system in a way it was not designed for. For a hack to take place, the system must have a clear way it was designed. This design is then violated by the hack.

Ugly coding usually implies there is no clear design to hack. A hack is no longer a hack if it is just as ugly as the surrounding code.

Normally hacks are quick and dirty solutions which the programmer intents to rectify some day. Ugly programming has a way of never getting fixed.


问:
Efficient way to order a dictionary by value and stringify it
I have a dictionary with string keys and int values

```<code>for word in coocc[query]:
    resp[word]=coocc[query][word]
</code>```

{"share": 1, "pizza": 3, "eating": 1,...}

I need to sort by value and return a json string.

The following works:

```<code>sortedList=sorted(resp.items(), key=operator.itemgetter(1), reverse=True)
sortedDict=collections.OrderedDict(sortedList)
return json.dumps(sortedDict)
</code>```

'{"cheese": 4, "pizza": 3, "table": 3,..}

but it doesn't seems very efficient to me

答:
```<code>json.dumps(sorted(yourdict.items(), key=operator.itemgetter(1),reverse=True))
</code>```

you can find more details
Here

Body:
I have a dictionary with string keys and int values

for word in coocc[query]:
    resp[word]=coocc[query][word]

{"share": 1, "pizza": 3, "eating": 1,...}

I need to sort by value and return a json string.

The following works:

sortedList=sorted(resp.items(), key=operator.itemgetter(1), reverse=True)
sortedDict=collections.OrderedDict(sortedList)
return json.dumps(sortedDict)

'{"cheese": 4, "pizza": 3, "table": 3,..}

but it doesn't seems very efficient to me

Body:
json.dumps(sorted(yourdict.items(), key=operator.itemgetter(1),reverse=True))

you can find more details
Here


问:
How do I verify text on one page then validate it is that same text on another page using Selenium C#?
For Example: Log into a webpage that has text (unknown to user), then verify it has the same text on another page.</p>

答:
You could go for something like:

Locate HTML Body object for the first page using XPath like:

```<code>driver.FindElement(By.XPath("//body"))
</code>```

Get innerText property value of the HTML body

Split it into separate strings using line separator character

Perform steps 1 - 3 for the second page

Iterate the strings extracted from the first page and look for matches in the strings from the second page

Do what you need with the results

Example code:

```<code>driver.Url = "https://stackoverflow.com";

string firstPageText = driver.FindElement(By.XPath("//body")).GetAttribute("innerText");
HashSet<string> firstPageLines = new HashSet<string>(firstPageText.Split('\n'));

driver.Url = "https://stackoverflow.com/questions/56366177/how-do-i-verify-text-on-one-page-then-validate-it-is-that-same-text-on-another-p";

string secondPageText = driver.FindElement(By.XPath("//body")).GetAttribute("innerText");
HashSet<string> secondPageLines = new HashSet<string>(secondPageText.Split('\n'));

foreach (string line in firstPageLines) {
    if (secondPageLines.Contains(line)) {
        Console.WriteLine("This line is present in both pages: " + line);
    }
}
</code>```

Example output:

Body:
You could go for something like:

Locate HTML Body object for the first page using XPath like:

driver.FindElement(By.XPath("//body"))

Get innerText property value of the HTML body

Split it into separate strings using line separator character

Perform steps 1 - 3 for the second page

Iterate the strings extracted from the first page and look for matches in the strings from the second page

Do what you need with the results

Example code:

driver.Url = "https://stackoverflow.com";

string firstPageText = driver.FindElement(By.XPath("//body")).GetAttribute("innerText");
HashSet<string> firstPageLines = new HashSet<string>(firstPageText.Split('\n'));

driver.Url = "https://stackoverflow.com/questions/56366177/how-do-i-verify-text-on-one-page-then-validate-it-is-that-same-text-on-another-p";

string secondPageText = driver.FindElement(By.XPath("//body")).GetAttribute("innerText");
HashSet<string> secondPageLines = new HashSet<string>(secondPageText.Split('\n'));

foreach (string line in firstPageLines) {
    if (secondPageLines.Contains(line)) {
        Console.WriteLine("This line is present in both pages: " + line);
    }
}

Example output:


问:
SQL Server "Maximum Server Memory" - seems to have no effect on Virtual Size
On 32 bit windows xp, sql server express, I set SQL Server "Maximum Server Memory" to 200 MB, but as soon as I start it, in Sysinternals Process Explorer I still see Virtual Size consumed of 1.5 GB.

Now I know this is no big deal if the Virtual Size is small, but when other applications max out the physical memory (Internet Explorer cough), I then get windows "virtual memory too small" errors, so then I think it does become a problem.

Any ideas?

答: Behavior by design, per http://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=377495.  The memory is reserved, but not committed.</p>

OwnerDisplayName: tbone

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: JohnW


问:
Stacked bootstrap progress bars using Angular?
Bootstrap 4 and earlier versions allow stacking multiple bars in a progress bar, as illustrated at https://v4-alpha.getbootstrap.com/components/progress/ with code:

```<code><div class="progress">
  <div class="progress-bar" role="progressbar" style="width: 15%" aria-valuenow="15" aria-valuemin="0" aria-valuemax="100"></div>
  <div class="progress-bar bg-success" role="progressbar" style="width: 30%" aria-valuenow="30" aria-valuemin="0" aria-valuemax="100"></div>
  <div class="progress-bar bg-info" role="progressbar" style="width: 20%" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100"></div>
</div>
</code>```

However, ng-bootstrap seems to allow only one bar for NgbProgressbar as illustrated at https://ng-bootstrap.github.io/#/components/progressbar with code:

```<code><p><ngb-progressbar type="success" [value]="25"></ngb-progressbar></p>
</code>```

I see some code at https://embed.plnkr.co/rx4RJUFjHqGYMA3jRxDL/ for stacked progress bars using Bootstrap 3 and a beta version of Angular 2, but it uses deprecated calls such as to CORE_DIRECTIVES and when I tried to run the code without that and in an Angular 4  / Bootstrap 4 environment the output was quite mangled.

Anyone know of a good way to get stacked progress bars in Angular 4 with Bootstrap 4?

答:
In case you need (pure angular progress-bar using flex-layout- style as you need)</p>

```<code>    <div fxLayout="row" class="custom-progressbar">
                                      <div fxFlex="15" class="stat-bar bar-fail" matTooltipPosition="above" matTooltip="fail"></div>
                                      <div fxFlex="30" class="stat-bar bar-pass" matTooltipPosition="above" matTooltip="pass"></div>
                                      <div fxFlex="20" class="stat-bar bar-inprogress" matTooltipPosition="above" matTooltip="inprogress"></div>
                                      <div fxFlex="30" class="stat-bar bar-expire" matTooltipPosition="above" matTooltip="expire"></div>
                                      <div fxFlex="5" class="stat-bar bar-expiring" matTooltipPosition="above" matTooltip="expiring"></div>
 </div>

//CSS
    .bar-fail {
    background: mat-color($mat-red, 500);
  }

  .bar-pass {
    background: mat-color($mat-green, 500);
  }

  .bar-inprogress {
    background: mat-color($mat-blue, 500);
  }

  .bar-expire {
    background: mat-color($mat-amber, 500);
  }

  .bar-expiring {
    background: mat-color($mat-orange, 500);
  }
.custom-progressbar {
  width: 206px;
  height: 14px;
  margin-left: 16px;
  background: mat-color($mat-grey, A100);
  border-radius: 15px;
  overflow: hidden;
  border: 1px solid mat-color($mat-lgrey, 500);
  align-items: center;}
</code>```

Body:
Bootstrap 4 and earlier versions allow stacking multiple bars in a progress bar, as illustrated at https://v4-alpha.getbootstrap.com/components/progress/ with code:

However, ng-bootstrap seems to allow only one bar for NgbProgressbar as illustrated at https://ng-bootstrap.github.io/#/components/progressbar with code:

<ngb-progressbar type="success" [value]="25"></ngb-progressbar>

I see some code at https://embed.plnkr.co/rx4RJUFjHqGYMA3jRxDL/ for stacked progress bars using Bootstrap 3 and a beta version of Angular 2, but it uses deprecated calls such as to CORE_DIRECTIVES and when I tried to run the code without that and in an Angular 4  / Bootstrap 4 environment the output was quite mangled.

Anyone know of a good way to get stacked progress bars in Angular 4 with Bootstrap 4?

Body:
In case you need (pure angular progress-bar using flex-layout- style as you need)

    <div fxLayout="row" class="custom-progressbar">
                                      <div fxFlex="15" class="stat-bar bar-fail" matTooltipPosition="above" matTooltip="fail"></div>
                                      <div fxFlex="30" class="stat-bar bar-pass" matTooltipPosition="above" matTooltip="pass"></div>
                                      <div fxFlex="20" class="stat-bar bar-inprogress" matTooltipPosition="above" matTooltip="inprogress"></div>
                                      <div fxFlex="30" class="stat-bar bar-expire" matTooltipPosition="above" matTooltip="expire"></div>
                                      <div fxFlex="5" class="stat-bar bar-expiring" matTooltipPosition="above" matTooltip="expiring"></div>
 </div>

//CSS
    .bar-fail {
    background: mat-color($mat-red, 500);
  }

  .bar-pass {
    background: mat-color($mat-green, 500);
  }

  .bar-inprogress {
    background: mat-color($mat-blue, 500);
  }

  .bar-expire {
    background: mat-color($mat-amber, 500);
  }

  .bar-expiring {
    background: mat-color($mat-orange, 500);
  }
.custom-progressbar {
  width: 206px;
  height: 14px;
  margin-left: 16px;
  background: mat-color($mat-grey, A100);
  border-radius: 15px;
  overflow: hidden;
  border: 1px solid mat-color($mat-lgrey, 500);
  align-items: center;}


问:
URL Rewrites are not generated after product import
I am trying to import products into my store however the rewrites are not generated in the database at all so the long default url remains. Anyone faced this issue and solved it before without using an external module?
The URL key is correctly set at the product page.

incorrect url

答:
You can use faonni module indexer which will create URL rewrite for your products category and cms pages.

After installing the extension you can run indexer commands as follows.

```<code>php bin/magento indexer:reindex category_url_rewrite
php bin/magento indexer:reindex product_url_rewrite
php bin/magento indexer:reindex cms_page_url_rewrite
</code>```

Body:
You can use faonni module indexer which will create URL rewrite for your products category and cms pages.

After installing the extension you can run indexer commands as follows.

php bin/magento indexer:reindex category_url_rewrite
php bin/magento indexer:reindex product_url_rewrite
php bin/magento indexer:reindex cms_page_url_rewrite


问:
How to add return value from function into dataframe Column?
I want to add multiple return values from function into one column, for example, here I am splitting the combined hours and minutes and adding into different variables "hour" and "minute" each. Now I want to add these values in one data frame column. </p>

```<code>def issuetimesplit(x):
    hour = str(x)[:-2]
    minutes = str(x)[-2:]
    time = print(f"{hour} : {minutes}")
    return time

for i,v in timeData.items():
    issuetimesplit(v)
</code>```

答:
Let me sum the comments up.

You can't use print to define a string variable.

In the function, your new string can be returned immediately. It means time variable is not needed. However, it is not a mistake to define it.

You can use apply() function, that could be a solution for your problem.

The code is following.

```<code># import pandas
import pandas as pd

# define function
def make_new_time_feature(row):
    hour = row['old_time_feature'][:-2]
    minutes = row['old_time_feature'][-2:]
    return f'{hour} : {minutes}'

# call apply
your_df['new_time_feature'] = your_df.apply(lambda row: make_new_time_feature(row), axis=1)
</code>```

Body:
I want to add multiple return values from function into one column, for example, here I am splitting the combined hours and minutes and adding into different variables "hour" and "minute" each. Now I want to add these values in one data frame column.

def issuetimesplit(x):
    hour = str(x)[:-2]
    minutes = str(x)[-2:]
    time = print(f"{hour} : {minutes}")
    return time

for i,v in timeData.items():
    issuetimesplit(v)

Body:
Let me sum the comments up.

You can't use print to define a string variable.

In the function, your new string can be returned immediately. It means time variable is not needed. However, it is not a mistake to define it.

You can use apply() function, that could be a solution for your problem.

The code is following.

# import pandas
import pandas as pd

# define function
def make_new_time_feature(row):
    hour = row['old_time_feature'][:-2]
    minutes = row['old_time_feature'][-2:]
    return f'{hour} : {minutes}'

# call apply
your_df['new_time_feature'] = your_df.apply(lambda row: make_new_time_feature(row), axis=1)


问:
Append the next line to previous line
I have file of 5GB in this format:

```<code>dn: cn
changetype: add
objectclass: ine
hghsfgdsdsdsd
mail: surcom
surname: satya2
givenname: surya2
cn: surya2
</code>```

```<code>dn: cn
changetype: add
objectclass: inetOrgPerson
surname: sa
sddsds
givenname: s
cn: sur
</code>```

as you can see the Object class and surname are getting to the next line.
I want then in same line.
And below code achieves it, but it throws memory error for large files,
can you change this code so that it works efficiently for large files.

```<code>import re

pattern = re.compile(r"(\w+):(.*)")

with open("uservolvo2.ldif", "r") as f:
    new_lines = []

    for line in f:

        if line.endswith('\n'):
            line = line[:-1]

        if line == "":
            new_lines.append(line)
            continue

        l = pattern.search(line)

        if l:
            new_lines.append(line)
        else:
            new_lines[-1] += line

with open("user_modified.ldif", "a") as f:
    f.write("\n".join(new_lines))
    f.write("\n\n")
</code>```

答:
I suppose the most efficient way is to create another empty text file (modified.txt), iter through the original text file and append processed line to the new file.

```<code>with open('file.txt', 'r') as file, open('modified.txt', 'a') as modified:
    line = file.readline()
    while line:
        line = file.readline()
        #do procssing
        modified.write(line)
</code>```

Title: Append the next line to previous line

Body:
I have file of 5GB in this format:

dn: cn
changetype: add
objectclass: ine
hghsfgdsdsdsd
mail: surcom
surname: satya2
givenname: surya2
cn: surya2

dn: cn
changetype: add
objectclass: inetOrgPerson
surname: sa
sddsds
givenname: s
cn: sur

as you can see the Object class and surname are getting to the next line.
I want then in same line.
And below code achieves it, but it throws memory error for large files,
can you change this code so that it works efficiently for large files.

import re

pattern = re.compile(r"(\w+):(.*)")

with open("uservolvo2.ldif", "r") as f:
    new_lines = []

    for line in f:

        if line.endswith('\n'):
            line = line[:-1]

        if line == "":
            new_lines.append(line)
            continue

        l = pattern.search(line)

        if l:
            new_lines.append(line)
        else:
            new_lines[-1] += line

with open("user_modified.ldif", "a") as f:
    f.write("\n".join(new_lines))
    f.write("\n\n")

Body:
I suppose the most efficient way is to create another empty text file (modified.txt), iter through the original text file and append processed line to the new file.

with open('file.txt', 'r') as file, open('modified.txt', 'a') as modified:
    line = file.readline()
    while line:
        line = file.readline()
        #do procssing
        modified.write(line)


问:
With same nodejs version and yarn.lock, install frozen-lockfile works on Ubuntu but fail on Mac
This is my understanding of how yarn nodejs package management works

yarn.lock declares the exact version of packages installed on your project. This list of package is independent of OS.

Criteria affect what specific will be added into the yarn.lock file include:

current node version

package.json file

-> Current OS doesn't affect what package is put inside yarn.lock when you run yarn install

What I did:

run yarn install on Ubuntu 14.04 -> generates yarn.lock

copy this yarn.lock onto a Mac machine

USE THE SAME nodejs version as the one on Ubuntu 14.04, run yarn install --frozen-lockfile

And the the installation fails. But when I use a different version of nodejs on Mac, running yarn install --frozen-lockfile works.

So does this mean with:

Same yarn.lock file

Same nodejs

one CAN'T GUARANTEED the installation would work across all OS?

答:
yarn.lock it won't work 100% on other platforms until unless all dependencies support cross platforms

Just checked my yarn.lock they add some dependencies based on an operating system in my case it was is-windows module added

Check all your packages are supported for cross platforms because sometimes many packages are platform specific, You can check all dependencies on packages.json of that package

OR

Do not push yarn.lock if you use the application on different operating systems.


问:
What the difference between "arrays of parameterized type( List<String>[] )" and "array of type variable( T[] )"?
Update: Although I have got the answer, it seems my description of the question is not very clear. So I changed a lot to make others understand my question.

My understanding of the reason why arrays of a parameterized type not allowed:

Integer[] b = {1,2,3};
Object[] a = b;
String[] c = {"123"};
a[0] = c; // Exception in thread "main" java.lang.ArrayStoreException
Integer i = b[0];
```
```// Not really allowed.
List<String>[] lsa = new List<String>[10];
Object o = lsa;
Object[] oa = (Object[]) o;
List<Integer> li = new ArrayList<Integer>();
li.add(new Integer(3));
// Unsound, but passes run time store check
oa[1] = li;

// Run-time error: ClassCastException.
String s = lsa[1].get(0);
```
<p>These two pieces of code has the same structure.</p>
<p>In piece 1, <code>Object[] a = b</code> makes both <code>a</code> and <code>b</code> point to the same variable <code>b</code>. So <code>a[0] = c</code> is actually changing <code>b</code>. This kind of operation won't cause any warning while compiling but will throw an ArrayStoreException.</p>
<p>In piece 2,<code>Object o = lsa; Object[] oa = (Object[]) o;</code> makes both <code>oa</code> and <code>lsa</code> point to the same variable <code>lsa</code>, and <code>oa[1] = li;</code>
is actually changing <code>lsa</code>.</p>
<p>So I think it's this reason why not allow using arrays of parameterized type.</p>
<p>If my understanding is right, the case like <code>T[] myArray</code> should also be rejected. Because the code below also has the same structure.</p>
```import java.util.*;

public class Test {
    public static <T> void test(T[] t) {
        Object[] a = t;
        String[] c = {"123"};
        a[0] = c;
        T i = t[0];
    }

    public static void main(String[] args) {
        Integer[] t = {1,2,3};
        test(t);
    }
}
```
<p>But in the Java tutorial,</p>
```<T> T[] makeArray(T t) {
    return new T[100]; // Error.
}
```
<p>The reason it gives is</p>
<blockquote>
<p>Since type variables don't exist at run time, there is no way to determine what the actual array type would be.</p>
</blockquote>
<p>Not the reason I expect.</p>
<p>It also says</p>
<blockquote>
<p>The way to work around these kinds of limitations is to use class literals as run-time type tokens</p>
</blockquote>
<p>So I found an example at Generics gotchas. The code at "The road not taken" section:</p>
```public class ArrayList<V> implements List<V> {
  private V[] backingArray;
  private Class<V> elementType;

  public ArrayList(Class<V> elementType) {
    this.elementType = elementType;
    backingArray = (V[]) Array.newInstance(elementType, DEFAULT_LENGTH);
  }
}
```

It seems using class literals already solve the problem of using array of type variable( T[] ). But the problem of the structure I mentioned at the beginning is still exist. Recall I think the structure of the three pieces of code all lead to no compiling warning but runtime error.

So, what's wrong with my understanding?

Thank you so much for your time :)

答:
For you first question

why arrays of parameterized type not allowed?

I find  the answer

Can I create an array whose component type is a concrete parameterized type?

No, because it is not type-safe.

Then, I'm trying to explain  why the  example code throw exception?

java compile not found the problem during compile time,  each type cast look like legal. (ArrayStoreException is RuntimeException)

when you put a String element in Integer Array, the exception happen.
you can use javac and javap to look into the bytecode.
T[] t's type is Object[],so variable a (reference type) will refer to  a Integer[] Object. the exception happened when you put a String element into a  Integer Array

I think the problem is not relate to java generic, so i change the example as follow to reproduce the exception.

```<code>public class Test {

    public static void main(String[] args) {
        Integer[] t = {1,2,3};
        Object[] a = t;
        a[2] = "aaa";
    }
}
</code>```

Body:
Update: Although I have got the answer, it seems my description of the question is not very clear. So I changed a lot to make others understand my question.

My understanding of the reason why arrays of a parameterized type not allowed:

Integer[] b = {1,2,3};
Object[] a = b;
String[] c = {"123"};
a[0] = c; // Exception in thread "main" java.lang.ArrayStoreException
Integer i = b[0];

// Not really allowed.
List<String>[] lsa = new List<String>[10];
Object o = lsa;
Object[] oa = (Object[]) o;
List<Integer> li = new ArrayList<Integer>();
li.add(new Integer(3));
// Unsound, but passes run time store check
oa[1] = li;

// Run-time error: ClassCastException.
String s = lsa[1].get(0);

These two pieces of code has the same structure.

In piece 1, Object[] a = b makes both a and b point to the same variable b. So a[0] = c is actually changing b. This kind of operation won't cause any warning while compiling but will throw an ArrayStoreException.

In piece 2,Object o = lsa; Object[] oa = (Object[]) o; makes both oa and lsa point to the same variable lsa, and oa[1] = li;
is actually changing lsa.

So I think it's this reason why not allow using arrays of parameterized type.

If my understanding is right, the case like T[] myArray should also be rejected. Because the code below also has the same structure.

import java.util.*;

public class Test {
    public static <T> void test(T[] t) {
        Object[] a = t;
        String[] c = {"123"};
        a[0] = c;
        T i = t[0];
    }

    public static void main(String[] args) {
        Integer[] t = {1,2,3};
        test(t);
    }
}

But in the Java tutorial,

<T> T[] makeArray(T t) {
    return new T[100]; // Error.
}

The reason it gives is

Since type variables don't exist at run time, there is no way to determine what the actual array type would be.

Not the reason I expect.

It also says

The way to work around these kinds of limitations is to use class literals as run-time type tokens

So I found an example at Generics gotchas. The code at "The road not taken" section:

public class ArrayList<V> implements List<V> {
  private V[] backingArray;
  private Class<V> elementType;

  public ArrayList(Class<V> elementType) {
    this.elementType = elementType;
    backingArray = (V[]) Array.newInstance(elementType, DEFAULT_LENGTH);
  }
}

It seems using class literals already solve the problem of using array of type variable( T[] ). But the problem of the structure I mentioned at the beginning is still exist. Recall I think the structure of the three pieces of code all lead to no compiling warning but runtime error.

So, what's wrong with my understanding?

Thank you so much for your time :)

Body:
For you first question

why arrays of parameterized type not allowed?

I find  the answer

Can I create an array whose component type is a concrete parameterized type?

No, because it is not type-safe.

Then, I'm trying to explain  why the  example code throw exception?

java compile not found the problem during compile time,  each type cast look like legal. (ArrayStoreException is RuntimeException)

when you put a String element in Integer Array, the exception happen.
you can use javac and javap to look into the bytecode.
T[] t's type is Object[],so variable a (reference type) will refer to  a Integer[] Object. the exception happened when you put a String element into a  Integer Array

I think the problem is not relate to java generic, so i change the example as follow to reproduce the exception.

public class Test {

    public static void main(String[] args) {
        Integer[] t = {1,2,3};
        Object[] a = t;
        a[2] = "aaa";
    }
}


问:
How do I create a subnav in a vertical navbar
I am trying to create a sub nav in my vertical bar. Here is a short explanation:

I have tried to use the syntax for my about to be used for the courses but the link won't activate.

My Bootstrap:

```<code>    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel = "stylesheet" href = "Stylesheet.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
    <script src = "script.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
    <link rel='stylesheet' href='https://use.fontawesome.com/releases/v5.7.0/css/all.css' integrity='sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ' crossorigin='anonymous'>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</code>```

My CSS Code:

```<code>   .side-menu-wrapper {
       background: rgba(0,114,187,0.7);
       padding: 40px 0 0 40px;
       position: fixed;
       top: 0;
       right: 0;
       height: 100%;
       z-index: 2;
       transition: 0.5s;
       width: 250px;
       font: 20px "Courier New", Courier, monospace;
       box-sizing: border-box;
    }

    .side-menu-wrapper > ul{
        list-style:none;
        padding:0;
        margin:0;
        overflow-y: auto;
        height:95%;
      }

   .side-menu-wrapper > ul > li > a {
       display: block;
       padding: 6px 4px 6px 4px;
       color: white;
       transition: 0.3s;
       text-decoration: none;
    }

    .side-menu-wrapper > a.menu-close {
       padding: 8px 0 4px 23px;
       color: white;
       display: block;
       margin: -30px 0 -10px -20px;
       font-size: 35px;
       text-decoration: none;
     }

    .menu-overlay {
        height: 100%;
        width: 0;
        position: fixed;
        z-index: 1;
        top: 0;
        left: 0;
        background-color: rgba(0,0,0,.7);
        overflow-y: auto;
        overflow-x: hidden;
        text-align: center;
        opacity: 0;
        transition: opacity 1s;
     }

    .active-item{
        list-style:none;
     }

     .item{
         list-style:none;
         color:white;
      }

     input{
         width: 130px;
     }
</code>```

My HTML code:

```<code>         <div class="menu-overlay "></div>
            <div id="main-menu" class="side-menu-wrapper">
               <a href="#" class="menu-close">×</a>
                  <ul>
                     <li>
                        <form class="example" action="action_page.php">
                        <input type="text" placeholder="Search.."
                         name="search">
                           <button type="submit">
                              <i class="fa fa-search"></i>
                          </button>
                         </form>
                     </li>
                     <li>
                        <a href="#" target="_blank" rel="nofollow">
                           Home
                        </a>
                     </li>
                     <li>
                <a href="#sub-menu" class="active" data-
                 toggle="collapse" data-parent="#main-menu">
                    About
                    <span class="ml-2" style="font-size: 12px;">
                        ▼
                    </span>
                </a>
                <div class="collapse" id="sub-menu">
                  <ul>
                    <li class = "item" href="#" target="_blank"
                    rel="nofollow">
                      <a >Introduction</a>
                    </li>
                    <li class = "item" href="#" target="_blank"
                    rel="nofollow">
                      <a >Mission</a>
                    </li>
                    <li class = "item" href="#" target="_blank"
                     rel="nofollow">
                       <a >Vision</a>
                    </li>
                  </ul>
                </div>
              </li>
              <li>
                <a href="#sub-menu1" class="active" data-
                toggle="collapse" data-parent="#main-menu">
                    Courses
                    <span class="ml-2" style="font-size: 12px;">
                        ▼
                    </span>
                 </a>
                <div class="collapse" id="sub-menu1">
                    <ul>
                        <li href="#sub-menu1.1" class="active-item"
                         data-toggle="collapse" data-parent="#main-
                          menu">
                            <a>
                              Diploma in Information Technology
                            </a>
                            <ul class="collapse" id="sub-menu1.1">
                                <li class = "item" href="#"
                                target="_blank" rel="nofollow">
                                  <a>
                                    Prof.Diploma in IT Support(Hardware)
                                  </a>
                                </li>
                                <li class = "item" href="#"
                                target="_blank" rel="nofollow">
                                    <a>Prof.Diploma in Software
                                       Engineering (Programming)
                                     </a>
                                </li>
                                <li class = "item" href="#"
                                 target="_blank" rel="nofollow">
                                    <a>
                                      Diploma in Videogame Programming
                                    </a>
                                </li>
                                <li class = "item" href="#"
                                target="_blank" rel="nofollow">
                                    <a>
                                      View All
                                    </a>
                                </li>
                            </ul>
                        </li>
                    </ul>
                </div>
              </li>
              <li>
                <a href="#" target="_blank" rel="nofollow">Flickr</a>
              </li>
            </ul>
          </div>
</code>```

So as you can see I am trying to create a sub nav for my courses link but I have no idea. Please check my HTML code to make sure I am all good.

答:
Use data-target to target the div you want to collapse instead of data-parent, I've renamed sub-menu1 to sub-menu2 so one can clearly differentiate them.

For more informations on how the collapse component works, please click here.

Working snippet below :

 .side-menu-wrapper {
       background: rgba(0,114,187,0.7);
       padding: 40px 0 0 40px;
       position: fixed;
       top: 0;
       right: 0;
       height: 100%;
       z-index: 2;
       transition: 0.5s;
       width: 250px;
       font: 20px "Courier New", Courier, monospace;
       box-sizing: border-box;
    }

    .side-menu-wrapper > ul{
        list-style:none;
        padding:0;
        margin:0;
        overflow-y: auto;
        height:95%;
      }

   .side-menu-wrapper > ul > li > a {
       display: block;
       padding: 6px 4px 6px 4px;
       color: white;
       transition: 0.3s;
       text-decoration: none;
    }

    .side-menu-wrapper > a.menu-close {
       padding: 8px 0 4px 23px;
       color: white;
       display: block;
       margin: -30px 0 -10px -20px;
       font-size: 35px;
       text-decoration: none;
     }

    .menu-overlay {
        height: 100%;
        width: 0;
        position: fixed;
        z-index: 1;
        top: 0;
        left: 0;
        background-color: rgba(0,0,0,.7);
        overflow-y: auto;
        overflow-x: hidden;
        text-align: center;
        opacity: 0;
        transition: opacity 1s;
     }

    .active-item{
        list-style:none;
     }

     .item{
         list-style:none;
         color:white;
      }

     input{
         width: 130px;
     }```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel = "stylesheet" href = "Stylesheet.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
    <script src = "script.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
    <link rel='stylesheet' href='https://use.fontawesome.com/releases/v5.7.0/css/all.css' integrity='sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ' crossorigin='anonymous'>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

  <div class="side-menu-wrapper">
  ×
    <ul>
    <li>
      <form class="example" action="action_page.php">
        <input type="text" placeholder="Search.."
               name="search">
        <button type="submit">
          <i class="fa fa-search"></i>
        </button>
      </form>
      </li>
      <li>
        Home
      </li>
      <li>
        About <span class="ml-2" style="font-size: 12px;">▼</span>
        <div class="collapse" id="sub-menu">
          <ul>
            <li class = "item" href="#" target="_blank" rel="nofollow">
              Introduction
            </li>
            <li class = "item" href="#" target="_blank" rel="nofollow">
              Mission
            </li>
            <li class = "item" href="#" target="_blank" rel="nofollow">
              Vision
            </li>
          </ul>
        </div>
      </li>
   <li>
        Courses <span class="ml-2" style="font-size: 12px;">▼</span>
        <div class="collapse" id="sub-menu2">
          <ul>
            <li class = "item" href="#" target="_blank" rel="nofollow">
              Diploma in Information Technology
            </li>
            <li class = "item" href="#" target="_blank" rel="nofollow">
              Prof.Diploma in IT Support(Hardware)
            </li>
            <li class = "item" href="#" target="_blank" rel="nofollow">
              Prof.Diploma in Software
                                       Engineering (Programming)
            </li>
      <li class = "item" href="#" target="_blank" rel="nofollow">
              Diploma in Videogame Programming
            </li>
      <li class = "item" href="#" target="_blank" rel="nofollow">
              View All
            </li>
          </ul>
        </div>
      </li>
      <li>
        Flickr
      </li>
    </ul>
  </div></code>```

EDIT : after discussion with OP, here is another example with a sub-menu within a sub-menu (took the Mission link in About sub-menu as an example) :

 .side-menu-wrapper {
       background: rgba(0,114,187,0.7);
       padding: 40px 0 0 40px;
       position: fixed;
       top: 0;
       right: 0;
       height: 100%;
       z-index: 2;
       transition: 0.5s;
       width: 250px;
       font: 20px "Courier New", Courier, monospace;
       box-sizing: border-box;
    }

    .side-menu-wrapper > ul{
        list-style:none;
        padding:0;
        margin:0;
        overflow-y: auto;
        height:95%;
      }

   .side-menu-wrapper > ul > li > a {
       display: block;
       padding: 6px 4px 6px 4px;
       color: white;
       transition: 0.3s;
       text-decoration: none;
    }

    .side-menu-wrapper > a.menu-close {
       padding: 8px 0 4px 23px;
       color: white;
       display: block;
       margin: -30px 0 -10px -20px;
       font-size: 35px;
       text-decoration: none;
     }

    .menu-overlay {
        height: 100%;
        width: 0;
        position: fixed;
        z-index: 1;
        top: 0;
        left: 0;
        background-color: rgba(0,0,0,.7);
        overflow-y: auto;
        overflow-x: hidden;
        text-align: center;
        opacity: 0;
        transition: opacity 1s;
     }

    .active-item{
        list-style:none;
     }

     .item{
         list-style:none;
         color:white;
      }

     input{
         width: 130px;
     }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel = "stylesheet" href = "Stylesheet.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
    <script src = "script.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
    <link rel='stylesheet' href='https://use.fontawesome.com/releases/v5.7.0/css/all.css' integrity='sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ' crossorigin='anonymous'>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

  <div class="side-menu-wrapper">
  ×
    <ul>
    <li>
      <form class="example" action="action_page.php">
        <input type="text" placeholder="Search.."
               name="search">
        <button type="submit">
          <i class="fa fa-search"></i>
        </button>
      </form>
      </li>
      <li>
        Home
      </li>
      <li>
        About <span class="ml-2" style="font-size: 12px;">▼</span>
        <div class="collapse" id="sub-menu">
          <ul>
            <li class = "item" href="#" target="_blank" rel="nofollow">
              Introduction
            </li>
            <li class = "item" href="#" target="_blank" rel="nofollow">
              Mission <span class="ml-2" style="font-size: 12px;">▼</span>
       <div class="collapse" id="sub-sub-menu">
          <ul>
            <li class = "item" href="#" target="_blank" rel="nofollow">
              First mission
            </li>
            <li class = "item" href="#" target="_blank" rel="nofollow">
              Second mission
            </li>
            <li class = "item" href="#" target="_blank" rel="nofollow">
              Third mission
            </li>
          </ul>
        </div>
            </li>
            <li class = "item" href="#" target="_blank" rel="nofollow">
              Vision
            </li>
          </ul>
        </div>
      </li>
   <li>
        Courses <span class="ml-2" style="font-size: 12px;">▼</span>
        <div class="collapse" id="sub-menu2">
          <ul>
            <li class = "item" href="#" target="_blank" rel="nofollow">
              Diploma in Information Technology
            </li>
            <li class = "item" href="#" target="_blank" rel="nofollow">
              Prof.Diploma in IT Support(Hardware)
            </li>
            <li class = "item" href="#" target="_blank" rel="nofollow">
              Prof.Diploma in Software
                                       Engineering (Programming)
            </li>
      <li class = "item" href="#" target="_blank" rel="nofollow">
              Diploma in Videogame Programming
            </li>
      <li class = "item" href="#" target="_blank" rel="nofollow">
              View All
            </li>
          </ul>
        </div>
      </li>
      <li>
        Flickr
      </li>
    </ul>
  </div></code>```

Body:
I am trying to create a sub nav in my vertical bar. Here is a short explanation:

I have tried to use the syntax for my about to be used for the courses but the link won't activate.

My Bootstrap:

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel = "stylesheet" href = "Stylesheet.css">

    <link rel='stylesheet' href='https://use.fontawesome.com/releases/v5.7.0/css/all.css' integrity='sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ' crossorigin='anonymous'>

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

My CSS Code:

   .side-menu-wrapper {
       background: rgba(0,114,187,0.7);
       padding: 40px 0 0 40px;
       position: fixed;
       top: 0;
       right: 0;
       height: 100%;
       z-index: 2;
       transition: 0.5s;
       width: 250px;
       font: 20px "Courier New", Courier, monospace;
       box-sizing: border-box;
    }

    .side-menu-wrapper > ul{
        list-style:none;
        padding:0;
        margin:0;
        overflow-y: auto;
        height:95%;
      }

   .side-menu-wrapper > ul > li > a {
       display: block;
       padding: 6px 4px 6px 4px;
       color: white;
       transition: 0.3s;
       text-decoration: none;
    }

    .side-menu-wrapper > a.menu-close {
       padding: 8px 0 4px 23px;
       color: white;
       display: block;
       margin: -30px 0 -10px -20px;
       font-size: 35px;
       text-decoration: none;
     }

    .menu-overlay {
        height: 100%;
        width: 0;
        position: fixed;
        z-index: 1;
        top: 0;
        left: 0;
        background-color: rgba(0,0,0,.7);
        overflow-y: auto;
        overflow-x: hidden;
        text-align: center;
        opacity: 0;
        transition: opacity 1s;
     }

    .active-item{
        list-style:none;
     }

     .item{
         list-style:none;
         color:white;
      }

     input{
         width: 130px;
     }

My HTML code:

               ×

                        <form class="example" action="action_page.php">
                        <input type="text" placeholder="Search.."
                         name="search">
                           <button type="submit">

                          </button>
                         </form>

                           Home

                    About

                        ▼

                      Introduction

                      Mission

                       Vision

                    Courses

                        ▼

                              Diploma in Information Technology

                                    Prof.Diploma in IT Support(Hardware)

                                    Prof.Diploma in Software
                                       Engineering (Programming)

                                      Diploma in Videogame Programming

                                      View All

                Flickr

So as you can see I am trying to create a sub nav for my courses link but I have no idea. Please check my HTML code to make sure I am all good.

Body:
Use data-target to target the div you want to collapse instead of data-parent, I've renamed sub-menu1 to sub-menu2 so one can clearly differentiate them.

For more informations on how the collapse component works, please click here.

Working snippet below :

 .side-menu-wrapper {
       background: rgba(0,114,187,0.7);
       padding: 40px 0 0 40px;
       position: fixed;
       top: 0;
       right: 0;
       height: 100%;
       z-index: 2;
       transition: 0.5s;
       width: 250px;
       font: 20px "Courier New", Courier, monospace;
       box-sizing: border-box;
    }

    .side-menu-wrapper > ul{
        list-style:none;
        padding:0;
        margin:0;
        overflow-y: auto;
        height:95%;
      }

   .side-menu-wrapper > ul > li > a {
       display: block;
       padding: 6px 4px 6px 4px;
       color: white;
       transition: 0.3s;
       text-decoration: none;
    }

    .side-menu-wrapper > a.menu-close {
       padding: 8px 0 4px 23px;
       color: white;
       display: block;
       margin: -30px 0 -10px -20px;
       font-size: 35px;
       text-decoration: none;
     }

    .menu-overlay {
        height: 100%;
        width: 0;
        position: fixed;
        z-index: 1;
        top: 0;
        left: 0;
        background-color: rgba(0,0,0,.7);
        overflow-y: auto;
        overflow-x: hidden;
        text-align: center;
        opacity: 0;
        transition: opacity 1s;
     }

    .active-item{
        list-style:none;
     }

     .item{
         list-style:none;
         color:white;
      }

     input{
         width: 130px;
     }

 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel = "stylesheet" href = "Stylesheet.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
    <script src = "script.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
    <link rel='stylesheet' href='https://use.fontawesome.com/releases/v5.7.0/css/all.css' integrity='sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ' crossorigin='anonymous'>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

  <div class="side-menu-wrapper">
  <a href="#" class="menu-close">×</a>
    <ul>
    <li>
      <form class="example" action="action_page.php">
        <input type="text" placeholder="Search.."
               name="search">
        <button type="submit">
          <i class="fa fa-search"></i>
        </button>
      </form>
      </li>
      <li>
        <a href="#" target="_blank" rel="nofollow">Home</a>
      </li>
      <li>
        <a href="#sub-menu" class="active" data-toggle="collapse" data-target="#sub-menu">About <span class="ml-2" style="font-size: 12px;">&#x25BC;</span></a>
        <div class="collapse" id="sub-menu">
          <ul>
            <li class = "item" href="#" target="_blank" rel="nofollow">
              <a >Introduction</a>
            </li>
            <li class = "item" href="#" target="_blank" rel="nofollow">
              <a >Mission</a>
            </li>
            <li class = "item" href="#" target="_blank" rel="nofollow">
              <a >Vision</a>
            </li>
          </ul>
        </div>
      </li>
   <li>
        <a href="#sub-menu2" class="active" data-toggle="collapse" data-target="#sub-menu2">Courses <span class="ml-2" style="font-size: 12px;">&#x25BC;</span></a>
        <div class="collapse" id="sub-menu2">
          <ul>
            <li class = "item" href="#" target="_blank" rel="nofollow">
              <a >Diploma in Information Technology</a>
            </li>
            <li class = "item" href="#" target="_blank" rel="nofollow">
              <a >Prof.Diploma in IT Support(Hardware)</a>
            </li>
            <li class = "item" href="#" target="_blank" rel="nofollow">
              <a >Prof.Diploma in Software
                                       Engineering (Programming)</a>
            </li>
      <li class = "item" href="#" target="_blank" rel="nofollow">
              <a >Diploma in Videogame Programming</a>
            </li>
      <li class = "item" href="#" target="_blank" rel="nofollow">
              <a >View All</a>
            </li>
          </ul>
        </div>
      </li>
      <li>
        <a href="#" target="_blank" rel="nofollow">Flickr</a>
      </li>
    </ul>
  </div>

EDIT : after discussion with OP, here is another example with a sub-menu within a sub-menu (took the Mission link in About sub-menu as an example) :

 .side-menu-wrapper {
       background: rgba(0,114,187,0.7);
       padding: 40px 0 0 40px;
       position: fixed;
       top: 0;
       right: 0;
       height: 100%;
       z-index: 2;
       transition: 0.5s;
       width: 250px;
       font: 20px "Courier New", Courier, monospace;
       box-sizing: border-box;
    }

    .side-menu-wrapper > ul{
        list-style:none;
        padding:0;
        margin:0;
        overflow-y: auto;
        height:95%;
      }

   .side-menu-wrapper > ul > li > a {
       display: block;
       padding: 6px 4px 6px 4px;
       color: white;
       transition: 0.3s;
       text-decoration: none;
    }

    .side-menu-wrapper > a.menu-close {
       padding: 8px 0 4px 23px;
       color: white;
       display: block;
       margin: -30px 0 -10px -20px;
       font-size: 35px;
       text-decoration: none;
     }

    .menu-overlay {
        height: 100%;
        width: 0;
        position: fixed;
        z-index: 1;
        top: 0;
        left: 0;
        background-color: rgba(0,0,0,.7);
        overflow-y: auto;
        overflow-x: hidden;
        text-align: center;
        opacity: 0;
        transition: opacity 1s;
     }

    .active-item{
        list-style:none;
     }

     .item{
         list-style:none;
         color:white;
      }

     input{
         width: 130px;
     }

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel = "stylesheet" href = "Stylesheet.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
    <script src = "script.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
    <link rel='stylesheet' href='https://use.fontawesome.com/releases/v5.7.0/css/all.css' integrity='sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ' crossorigin='anonymous'>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

  <div class="side-menu-wrapper">
  <a href="#" class="menu-close">×</a>
    <ul>
    <li>
      <form class="example" action="action_page.php">
        <input type="text" placeholder="Search.."
               name="search">
        <button type="submit">
          <i class="fa fa-search"></i>
        </button>
      </form>
      </li>
      <li>
        <a href="#" target="_blank" rel="nofollow">Home</a>
      </li>
      <li>
        <a href="#sub-menu" class="active" data-toggle="collapse" data-target="#sub-menu">About <span class="ml-2" style="font-size: 12px;">&#x25BC;</span></a>
        <div class="collapse" id="sub-menu">
          <ul>
            <li class = "item" href="#" target="_blank" rel="nofollow">
              <a >Introduction</a>
            </li>
            <li class = "item" href="#" target="_blank" rel="nofollow">
              <a href="#sub-sub-menu" class="active text-decoration-none text-white" data-toggle="collapse" data-target="#sub-sub-menu">Mission <span class="ml-2" style="font-size: 12px;">&#x25BC;</span></a>
       <div class="collapse" id="sub-sub-menu">
          <ul>
            <li class = "item" href="#" target="_blank" rel="nofollow">
              <a >First mission</a>
            </li>
            <li class = "item" href="#" target="_blank" rel="nofollow">
              <a >Second mission</a>
            </li>
            <li class = "item" href="#" target="_blank" rel="nofollow">
              <a >Third mission</a>
            </li>
          </ul>
        </div>
            </li>
            <li class = "item" href="#" target="_blank" rel="nofollow">
              <a >Vision</a>
            </li>
          </ul>
        </div>
      </li>
   <li>
        <a href="#sub-menu2" class="active" data-toggle="collapse" data-target="#sub-menu2">Courses <span class="ml-2" style="font-size: 12px;">&#x25BC;</span></a>
        <div class="collapse" id="sub-menu2">
          <ul>
            <li class = "item" href="#" target="_blank" rel="nofollow">
              <a >Diploma in Information Technology</a>
            </li>
            <li class = "item" href="#" target="_blank" rel="nofollow">
              <a >Prof.Diploma in IT Support(Hardware)</a>
            </li>
            <li class = "item" href="#" target="_blank" rel="nofollow">
              <a >Prof.Diploma in Software
                                       Engineering (Programming)</a>
            </li>
      <li class = "item" href="#" target="_blank" rel="nofollow">
              <a >Diploma in Videogame Programming</a>
            </li>
      <li class = "item" href="#" target="_blank" rel="nofollow">
              <a >View All</a>
            </li>
          </ul>
        </div>
      </li>
      <li>
        <a href="#" target="_blank" rel="nofollow">Flickr</a>
      </li>
    </ul>
  </div>


问:
Using sapply inside sapply
I need to execute sapply inside another sapply.

This is the working code I have.

```<code>animal <- c("Dog", "Cat", "Bird", "Fish", "Monkey", "Lion", "Dolphin", "Panda")
a <- as.data.frame(sapply(1:7, function(y) rbinom(30, 1, sample(seq(.4, .9, by=.1), 1, prob = NULL))))
colnames(a) <- (animal)
</code>```

I would like to build this data frame 10 time without doing this.

```<code>animal <- c("Dog", "Cat", "Bird", "Fish", "Monkey", "Lion", "Dolphin", "Panda")

a <- as.data.frame(sapply(1:7, function(y) rbinom(30, 1, sample(seq(.4, .9, by=.1), 1, prob = NULL))))
colnames(a) <- (animal)

b <- as.data.frame(sapply(1:7, function(y) rbinom(30, 1, sample(seq(.4, .9, by=.1), 1, prob = NULL))))
colnames(b) <- (animal)

...

j <- as.data.frame(sapply(1:7, function(y) rbinom(30, 1, sample(seq(.4, .9, by=.1), 1, prob = NULL))))
colnames(j) <- (animal)
</code>```

I have tried this without success

```<code>sapply(letters[1:10], function(z) as.data.frame(sapply(1:7, function(y) rbinom(300, 1, sample(seq(.4, .9, by=.1), 1, prob = NULL)))), colnames(letters[1:10]) <- (animal))
</code>```

Thanks

答:
If you need to do this with two apply type functions, you can do something like this:

Also you have Eight animals in animal and only making 7 columns. So I have shortened animal.

Using lapply on the outer loop will always return a list, which makes it a bit neater than sapply from what I understand you are trying to do.

```<code>animal <- c("Dog", "Cat", "Bird", "Fish", "Monkey", "Lion", "Dolphin")

lapply(1:10, function(x){
  a <- as.data.frame(
    sapply(1:7, function(y) rbinom(30, 1, sample(seq(.4, .9, by=.1), 1, prob = NULL)))
  )
  names(a) <- (animal)
  a
})
</code>```

Title: Using sapply inside sapply

Body:
I need to execute sapply inside another sapply.

This is the working code I have.

animal <- c("Dog", "Cat", "Bird", "Fish", "Monkey", "Lion", "Dolphin", "Panda")
a <- as.data.frame(sapply(1:7, function(y) rbinom(30, 1, sample(seq(.4, .9, by=.1), 1, prob = NULL))))
colnames(a) <- (animal)

I would like to build this data frame 10 time without doing this.

animal <- c("Dog", "Cat", "Bird", "Fish", "Monkey", "Lion", "Dolphin", "Panda")

a <- as.data.frame(sapply(1:7, function(y) rbinom(30, 1, sample(seq(.4, .9, by=.1), 1, prob = NULL))))
colnames(a) <- (animal)

b <- as.data.frame(sapply(1:7, function(y) rbinom(30, 1, sample(seq(.4, .9, by=.1), 1, prob = NULL))))
colnames(b) <- (animal)

...

j <- as.data.frame(sapply(1:7, function(y) rbinom(30, 1, sample(seq(.4, .9, by=.1), 1, prob = NULL))))
colnames(j) <- (animal)

I have tried this without success

sapply(letters[1:10], function(z) as.data.frame(sapply(1:7, function(y) rbinom(300, 1, sample(seq(.4, .9, by=.1), 1, prob = NULL)))), colnames(letters[1:10]) <- (animal))

Thanks

Body:
If you need to do this with two apply type functions, you can do something like this:

Also you have Eight animals in animal and only making 7 columns. So I have shortened animal.

Using lapply on the outer loop will always return a list, which makes it a bit neater than sapply from what I understand you are trying to do.

animal <- c("Dog", "Cat", "Bird", "Fish", "Monkey", "Lion", "Dolphin")

lapply(1:10, function(x){
  a <- as.data.frame(
    sapply(1:7, function(y) rbinom(30, 1, sample(seq(.4, .9, by=.1), 1, prob = NULL)))
  )
  names(a) <- (animal)
  a
})


问:
How to have a User Account for different entities in Spring JPA?
I'm making a system (using Spring + JPA with MySQL) that shows the best applicants for a certain job offer. The company and the applicants have their respective user account, and with that, they can fill in their personal/company information and their job profile/job offer conditions. With that, the system should match the job conditions (like 3+ years of experience in C) with the applicant's job profile.

My problem is that the User Account is created first, and should be independent, but these two different entities (Applicant and Company), with different attributes, are using it. So if I do something like create an applicant and company in the User Account, one of them will be always null.

How can I solve this? I guess the problem would be something like: how to implement a user account that can hold data from different entities that have different attributes (therefore, can't be grouped)? (In fact, I need one more entity, but I tried to simplify it to illustrate the problem more clearly).

答:
I found what I needed here: https://thoughts-on-java.org/complete-guide-inheritance-strategies-jpa-hibernate/

The problem was the mapping, not the class design per se. I could create interfaces and abstract classes to solve it in the Java world, but in the SQL world that's not possible, so the mapping is the key. In this case, I was looking for the Joined table mapping, but I realized I needed it just to not have null fields in my UserAccount, because I don't need a polymorphic query (e.g. give me the names of every 'user type' (Person, Company)), and it would be too costly performance wise to implement it that way, so I'll trade off space for performance, and I'll just reference all three user types in the User Account, leaving two of those three fields null forever.

PS: Single table mapping won't help because I do need to use not null conditions.