问:
RegEx for capturing part of a string
I am trying to grab top level Markdown headings (i.e., headings beginning with a single hash -- # Introduction) in an .md doc with Python's re library and cannot for the life of me figure this out.

Here is the code I'm trying to execute:

```<code>import re

pattern = r"(# .+?\\n)"

text = r"# Title\n## Chapter\n### sub-chapter#### What a lovely day.\n"

header = re.search(pattern, text)
print(header.string)
</code>```

The result from the print(header.string) is:

# Title\n## Chapter\n### sub-chapter#### What a lovely day.\n whereas I only want # Title\n

This example on regex101 says it should work, but I can't figure out why it isn't. https://regex101.com/r/u4ZIE0/9

答:
You get that result because you use header.string which is calling .string on a Match object which will give you back the string passed to match() or search().

The string already has newlines in it:

```<code>text = r"# Title\n## Chapter\n### sub-chapter#### What a lovely day.\n"
</code>```

So if you use your pattern (note that it will also match the newline), you could update your code to:

```<code>import re

pattern = r"(# .+?\\n)"
text = r"# Title\n## Chapter\n### sub-chapter#### What a lovely day.\n"
header = re.search(pattern, text)
print(header.group())
</code>```

Python demo

Note that re.search looks for the first location where the regex produces a match.

Another option to match your value could be matching from the start of the string a # followed by a space and then any character except a newline until the end of the string:

```<code>^# .*$
</code>```

For example:

```<code>import re

pattern = r"^# .*$"
text = "# Title\n## Chapter\n### sub-chapter#### What a lovely day.\n"
header = re.search(pattern, text, re.M)
print(header.group())
</code>```

Python demo

If there can not be any more # following after, you might also use a negated character class to match not a # or a newline:

```<code>^# [^#\n\r]+$
</code>```

Title: RegEx for capturing part of a string

Body:
I am trying to grab top level Markdown headings (i.e., headings beginning with a single hash -- # Introduction) in an .md doc with Python's re library and cannot for the life of me figure this out.

Here is the code I'm trying to execute:

import re

pattern = r"(# .+?\\n)"

text = r"# Title\n## Chapter\n### sub-chapter#### What a lovely day.\n"

header = re.search(pattern, text)
print(header.string)

The result from the print(header.string) is:

# Title\n## Chapter\n### sub-chapter#### What a lovely day.\n whereas I only want # Title\n

This example on regex101 says it should work, but I can't figure out why it isn't. https://regex101.com/r/u4ZIE0/9

Body:
You get that result because you use header.string which is calling .string on a Match object which will give you back the string passed to match() or search().

The string already has newlines in it:

text = r"# Title\n## Chapter\n### sub-chapter#### What a lovely day.\n"

So if you use your pattern (note that it will also match the newline), you could update your code to:

import re

pattern = r"(# .+?\\n)"
text = r"# Title\n## Chapter\n### sub-chapter#### What a lovely day.\n"
header = re.search(pattern, text)
print(header.group())

Python demo

Note that re.search looks for the first location where the regex produces a match.

Another option to match your value could be matching from the start of the string a # followed by a space and then any character except a newline until the end of the string:

^# .*$

For example:

import re

pattern = r"^# .*$"
text = "# Title\n## Chapter\n### sub-chapter#### What a lovely day.\n"
header = re.search(pattern, text, re.M)
print(header.group())

Python demo

If there can not be any more # following after, you might also use a negated character class to match not a # or a newline:

^# [^#\n\r]+$


来源: stackexchange

问:
Multiconfiguration / matrix build pipeline in Jenkins
What is modern best practice for multi-configuration builds (with Jenkins)?

I want to support multiple branches and multiple configurations.

For example for each version V1, V2 of the software I want builds targeting
platforms P1 and P2.

We have managed to set up multi-branch declarative pipelines. Each build has its own docker so its easy to support multiple platforms.

```<code>pipeline {
    agent none
    stages {
        stage('Build, test and deploy for P1) {
            agent {
                dockerfile {
                   filename 'src/main/docker/Jenkins-P1.Dockerfile'
                }
            }
            steps {
               sh buildit...
            }
        }
        stage('Build, test and deploy for P2) {
            agent {
                dockerfile {
                   filename 'src/main/docker/Jenkins-P2.Dockerfile'
                }
            }
            steps {
               sh buildit...
            }
        }
    }
}
</code>```

This gives one job covering multiple platforms but there is no separate red/blue status for each platform.
There is good argument that this does not matter as you should not release unless the build works for all platforms.

However, I would like a separate status indicator for each configuration. This suggests I should use a multi-configuration build which triggers a parameterised build for each configuration as below (and the linked question):

```<code>pipeline {
    parameters {
      choice(name: 'Platform',choices: ['P1', 'P2'], description: 'Target OS platform', )
    }
    agent {
       filename someMagicToGetDockerfilePathFromPlatform()
    }
    stages {
        stage('Build, test and deploy for P1) {
            steps {
               sh buildit...
            }
        }
    }
}
</code>```

There are several problems with this:

A declarative pipeline has more constraints over how it is scripted

Multi-configuration builds cannot trigger declarative pipelines (even with the parameterized triggers plugin I get "project is not buildable").

This also begs the question what use are parameters in declarative pipelines?

Is there a strategy that gives the best of both worlds i.e:

pipeline as code

separate status indicators

limited repetition?

答:
I think the cleanest approach is to have this all in a pipeline similar to the first one you presented, the only modification I would see here is making those parallel, so you would actually try and build/test for both platforms.

To reuse the previous stage's workspace you could do: reuseNode true

Something similar to this flow, that would have parallel build for platforms

```<code>pipeline {
    agent 'docker'
    stages {
      stage('Common pre') { ... }
      stage('Build all platforms') {
      parallel {
        stage('Build, test and deploy for P1') {
            agent {
                dockerfile {
                   filename 'src/main/docker/Jenkins-P1.Dockerfile'
                   reuseNode true
                }
            }
            steps {
               sh buildit...
            }
        }
        stage('Build, test and deploy for P2') {
            agent {
                dockerfile {
                   filename 'src/main/docker/Jenkins-P2.Dockerfile'
                   reuseNode true
                }
            }
            steps {
               sh buildit...
            }
        }
      }
      }
      stage('Common post parallel') { ... }
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
What is modern best practice for multi-configuration builds (with Jenkins)?

I want to support multiple branches and multiple configurations.

For example for each version V1, V2 of the software I want builds targeting
platforms P1 and P2.

We have managed to set up multi-branch declarative pipelines. Each build has its own docker so its easy to support multiple platforms.

pipeline {
    agent none
    stages {
        stage('Build, test and deploy for P1) {
            agent {
                dockerfile {
                   filename 'src/main/docker/Jenkins-P1.Dockerfile'
                }
            }
            steps {
               sh buildit...
            }
        }
        stage('Build, test and deploy for P2) {
            agent {
                dockerfile {
                   filename 'src/main/docker/Jenkins-P2.Dockerfile'
                }
            }
            steps {
               sh buildit...
            }
        }
    }
}

This gives one job covering multiple platforms but there is no separate red/blue status for each platform.
There is good argument that this does not matter as you should not release unless the build works for all platforms.

However, I would like a separate status indicator for each configuration. This suggests I should use a multi-configuration build which triggers a parameterised build for each configuration as below (and the linked question):

pipeline {
    parameters {
      choice(name: 'Platform',choices: ['P1', 'P2'], description: 'Target OS platform', )
    }
    agent {
       filename someMagicToGetDockerfilePathFromPlatform()
    }
    stages {
        stage('Build, test and deploy for P1) {
            steps {
               sh buildit...
            }
        }
    }
}

There are several problems with this:

A declarative pipeline has more constraints over how it is scripted

Multi-configuration builds cannot trigger declarative pipelines (even with the parameterized triggers plugin I get "project is not buildable").

This also begs the question what use are parameters in declarative pipelines?

Is there a strategy that gives the best of both worlds i.e:

pipeline as code

separate status indicators

limited repetition?

Body:
I think the cleanest approach is to have this all in a pipeline similar to the first one you presented, the only modification I would see here is making those parallel, so you would actually try and build/test for both platforms.

To reuse the previous stage's workspace you could do: reuseNode true

Something similar to this flow, that would have parallel build for platforms

pipeline {
    agent 'docker'
    stages {
      stage('Common pre') { ... }
      stage('Build all platforms') {
      parallel {
        stage('Build, test and deploy for P1') {
            agent {
                dockerfile {
                   filename 'src/main/docker/Jenkins-P1.Dockerfile'
                   reuseNode true
                }
            }
            steps {
               sh buildit...
            }
        }
        stage('Build, test and deploy for P2') {
            agent {
                dockerfile {
                   filename 'src/main/docker/Jenkins-P2.Dockerfile'
                   reuseNode true
                }
            }
            steps {
               sh buildit...
            }
        }
      }
      }
      stage('Common post parallel') { ... }
    }
}


问:
apply() function not working on individual rows
I have written a function to extract data from a large matrix ("c.mat") for each row in a data.frame ("df.1"). The data.frame has an indexing row in it ("df.1$hour") which corresponds to the relevant column in the matrix. There is an equal number of rows between the matrix and the data.frame so the function goes:

```<code>assignUV.FUN <- function(df, mat){
  num=df$hour
  value = mat[as.numeric(rownames(df)),num]
  return(value)
}
</code>```

Quite simple. However when using apply to run this for each row:

```<code>df.1 <- data.frame(hour= round(runif(10,1,100)), x = seq(1,10, length=10))
c.mat <- matrix(runif(1000,1,5), nrow=10)

try <- apply(df.1, 1, assignUV.FUN, mat = c.mat, df=df.1)
</code>```

I get the error:

```<code>Error in FUN(newX[, i], ...) : unused argument (newX[, i])
</code>```

I'm sure there is a conflict here whereby I am calling the data.frame twice, once from inside the assignUV.FUN function and once with apply but I can;t figure out why this won't work.

Any thoughts? It works fine if I just run on a single row:

```<code>assignUV.FUN(df = df.1[1,], mat=c.mat)
</code>```

答:
If I have understood you correctly, you want to subset c.mat for every row in df.1 based on value in hour column. I don't think apply is the best choice here since you want to subset it by both row and column index. apply passes the value of the row and not it's index which you need for subsetting.  One option from the apply family is to use mapply

```<code>mapply(function(x, y) c.mat[x, y], seq_len(nrow(df.1)), df.1$hour)
#[1] 2.472 3.980 3.654 4.868 4.204 3.320 4.191 3.296 1.016 4.353
</code>```

Or a vectorised approach would be

```<code>c.mat[cbind(1:nrow(df.1), df.1$hour)]
#[1] 2.472 3.980 3.654 4.868 4.204 3.320 4.191 3.296 1.016 4.353
</code>```

To get into details of why it works when you apply for one row individually and not when you use apply notice when you subset one row it is still a one row dataframe with header.

```<code>df.1[1, ]
#  hour x
#1   31 1

class(df.1[1, ])
#[1] "data.frame"
</code>```

So when you do df$hour in the assignUV.FUN function you will get a value

```<code>df.1[1, ]$hour
#[1] 31
</code>```

However, that is not the case with apply

```<code>apply(df.1[1, ], 1, class)
#        1
#"numeric"
</code>```

and if you try to extract the value

```<code>apply(df.1[1, ], 1, function(x) x$hour)
</code>```

Error in x$hour : $ operator is invalid for atomic vectors

You can solve the above issue by using position instead of name by doing

```<code>apply(df.1[1, ], 1, function(x) x[1])
#31
</code>```

but this gives you column to subset from c.mat and not the row.

data

```<code>set.seed(100)
df.1 <- data.frame(hour= round(runif(10,1,100)), x = seq(1,10, length=10))
c.mat <- matrix(runif(1000,1,5), nrow=10)
</code>```

Body:
I have written a function to extract data from a large matrix ("c.mat") for each row in a data.frame ("df.1"). The data.frame has an indexing row in it ("df.1$hour") which corresponds to the relevant column in the matrix. There is an equal number of rows between the matrix and the data.frame so the function goes:

assignUV.FUN <- function(df, mat){
  num=df$hour
  value = mat[as.numeric(rownames(df)),num]
  return(value)
}

Quite simple. However when using apply to run this for each row:

df.1 <- data.frame(hour= round(runif(10,1,100)), x = seq(1,10, length=10))
c.mat <- matrix(runif(1000,1,5), nrow=10)

try <- apply(df.1, 1, assignUV.FUN, mat = c.mat, df=df.1)

I get the error:

Error in FUN(newX[, i], ...) : unused argument (newX[, i])

I'm sure there is a conflict here whereby I am calling the data.frame twice, once from inside the assignUV.FUN function and once with apply but I can;t figure out why this won't work.

Any thoughts? It works fine if I just run on a single row:

assignUV.FUN(df = df.1[1,], mat=c.mat)

Body:
If I have understood you correctly, you want to subset c.mat for every row in df.1 based on value in hour column. I don't think apply is the best choice here since you want to subset it by both row and column index. apply passes the value of the row and not it's index which you need for subsetting.  One option from the apply family is to use mapply

mapply(function(x, y) c.mat[x, y], seq_len(nrow(df.1)), df.1$hour)
#[1] 2.472 3.980 3.654 4.868 4.204 3.320 4.191 3.296 1.016 4.353

Or a vectorised approach would be

c.mat[cbind(1:nrow(df.1), df.1$hour)]
#[1] 2.472 3.980 3.654 4.868 4.204 3.320 4.191 3.296 1.016 4.353

To get into details of why it works when you apply for one row individually and not when you use apply notice when you subset one row it is still a one row dataframe with header.

df.1[1, ]
#  hour x
#1   31 1

class(df.1[1, ])
#[1] "data.frame"

So when you do df$hour in the assignUV.FUN function you will get a value

df.1[1, ]$hour
#[1] 31

However, that is not the case with apply

apply(df.1[1, ], 1, class)
#        1
#"numeric"

and if you try to extract the value

apply(df.1[1, ], 1, function(x) x$hour)

Error in x$hour : $ operator is invalid for atomic vectors

You can solve the above issue by using position instead of name by doing

apply(df.1[1, ], 1, function(x) x[1])
#31

but this gives you column to subset from c.mat and not the row.

data

set.seed(100)
df.1 <- data.frame(hour= round(runif(10,1,100)), x = seq(1,10, length=10))
c.mat <- matrix(runif(1000,1,5), nrow=10)


问:
Cannot delete Firebase user
When trying to delete a firebase user an error is thrown and it is unsuccessful.

I have tried Changing permissions, and making multiple user accounts.

```<code>  static Future deleteCurrectUser() async {
    FirebaseUser user = await FirebaseAuth.instance.currentUser();
    if (user == null) {
        throw('No user');
    }else{

    user.delete().then((result) {
        print('User deleted');
        return true;
        }).catchError((e) {
        Sentry.report(e);
        return false;
        }).timeout(databaseTimeoutDuration,
            onTimeout: () => throw (TimeoutException(
                'Timedout trying to delete current user',
                databaseTimeoutDuration)));
    }
</code>```

}

The error thrown is :

I/flutter (22331): PlatformException(USER_REQUIRED, Please authenticate with Firebase first, null)

答:
Probably because user token is expired. For some firebase operations like delete or updateProfile is needed reauth the user before. Below a single snipet to user reauth.

```<code>static Future<FirebaseUser> reauthCurrentUser() async {
    FirebaseUser fbUser = await FirebaseAuth.instance.currentUser();
    // this object holds user email and password needed to make reauth.
    UserRepository repository = UserRepository.instance;
    AuthCredential credential;

    // assumuming that user auth using email & password
    credential = EmailAuthProvider.getCredential(
        email: repository.userLogin,
        password: repository.userPassword);

    fbUser = await fbUser.reauthenticateWithCredential( credential )
        .catchError((error){ print("FirebaseAuthHelper::reauthCurrentUser $error"); });
    // force reloading...
    await fbUser.reload();
    return fbUser;
  }
</code>```

Title: Cannot delete Firebase user

Body:
When trying to delete a firebase user an error is thrown and it is unsuccessful.

I have tried Changing permissions, and making multiple user accounts.

  static Future deleteCurrectUser() async {
    FirebaseUser user = await FirebaseAuth.instance.currentUser();
    if (user == null) {
        throw('No user');
    }else{

    user.delete().then((result) {
        print('User deleted');
        return true;
        }).catchError((e) {
        Sentry.report(e);
        return false;
        }).timeout(databaseTimeoutDuration,
            onTimeout: () => throw (TimeoutException(
                'Timedout trying to delete current user',
                databaseTimeoutDuration)));
    }

}

The error thrown is :

I/flutter (22331): PlatformException(USER_REQUIRED, Please authenticate with Firebase first, null)

Body:
Probably because user token is expired. For some firebase operations like delete or updateProfile is needed reauth the user before. Below a single snipet to user reauth.

static Future<FirebaseUser> reauthCurrentUser() async {
    FirebaseUser fbUser = await FirebaseAuth.instance.currentUser();
    // this object holds user email and password needed to make reauth.
    UserRepository repository = UserRepository.instance;
    AuthCredential credential;

    // assumuming that user auth using email & password
    credential = EmailAuthProvider.getCredential(
        email: repository.userLogin,
        password: repository.userPassword);

    fbUser = await fbUser.reauthenticateWithCredential( credential )
        .catchError((error){ print("FirebaseAuthHelper::reauthCurrentUser $error"); });
    // force reloading...
    await fbUser.reload();
    return fbUser;
  }


问:
How to align DIV boxes next to each other in a container?
I would like to align my div boxes for a client's website all perfectly next to each other and without some being bigger than others. Here is the page relating to the code: https://www.imaniskinclinic.com/treatments

The boxes are not inline and some are obviously bigger than others. I added a div box container which I thought would hold the boxes more nicely but it doesn't seem to have worked.

Can anyone give me some assistance and guidance on what I must do?

Here is the code: CSS then HTML

.box {
  background-color: white; /* for visualization purposes */
  display: inline-block;
  max-width: 100%;

}

div.gallery {
    margin: 5px;
    border: 1px solid #ccc;
    width: 200px;
 height: 200px;
 background: #f8abbe;
}

div.gallery:hover {
    border: 1px solid #ffffff;
}

div.gallery img {
    width: 100%;
    height: auto;
}

div.desc {
    padding: 10px;
    text-align: center;
 font-family : verdana, arial, helvetica, helve, sans-serif;
 color: #ffffff;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>
<div class="box">
  <div class="gallery">

    <img src="images/acne.jpg" alt="Acne" width="300" height="200">

  <div class="desc">Acne Treatments</div>
</div>

<div class="gallery">

    <img src="images/hairremoval.jpg" alt="Hair Removal" width="300" height="200">

  <div class="desc">Laser Hair Removal</div>
</div>

<div class="gallery">

    <img src="images/electrolysis.jpg" alt="Electrolysis" width="300" height="200">

  <div class="desc">Electrolysis</div>
</div>

<div class="gallery">

    <img src="images/threadveins.jpg" alt="Thread Veins" width="300" height="200">

  <div class="desc">Thread Veins</div>
</div>

<div class="gallery">

    <img src="images/microderm.jpg" alt="Microdermabrasion" width="300" height="200">

  <div class="desc">Microdermabrasion</div>
</div>

<div class="gallery">

    <img src="images/rosacea.jpg" alt="Rosacea" width="300" height="200">

  <div class="desc">Rosacea</div>
</div>

<div class="gallery">

    <img src="images/pigmentation.jpg" alt="Pigmentation" width="300" height="200">

  <div class="desc">Pigmentation</div>
</div>

<div class="gallery">

    <img src="images/skinpeels.jpg" alt="Skin Peels" width="300" height="200">

  <div class="desc">Skin Peels</div>
</div>

<div class="gallery">

    <img src="images/botox.jpg" alt="Botox/Lipfillers" width="300" height="200">

  <div class="desc">Botox & Lipfillers</div>
</div>

<div class="gallery">

    <img src="images/microblading.png" alt="Semi Perm" width="300" height="200">

  <div class="desc">Eyebrow Microblading & Semi-Permanent Make-up</div>
</div>

<div class="gallery">

    <img src="images/mc.jpg" alt="Massage and Cupping" width="300" height="200">

  <div class="desc">Massage & Cupping</div>
</div>

</div></code>```

答:
Just added display: inline-block;
If you play a little bit with sizes of divs it will look better

.box {
  background-color: white; /* for visualization purposes */
  display: inline-block;
  max-width: 100%;

}

div.gallery {
    margin: 5px;
    border: 1px solid #ccc;
    width: 200px;
 height: 200px;
 background: #f8abbe;
  display: inline-block;
}

div.gallery:hover {
    border: 1px solid #ffffff;
}

div.gallery img {
    width: 100%;
    height: auto;
}

div.desc {
    padding: 10px;
    text-align: center;
 font-family : verdana, arial, helvetica, helve, sans-serif;
 color: #ffffff;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>
<div class="box">
  <div class="gallery">

    <img src="images/acne.jpg" alt="Acne" width="300" height="200">

  <div class="desc">Acne Treatments</div>
</div>

<div class="gallery">

    <img src="images/hairremoval.jpg" alt="Hair Removal" width="300" height="200">

  <div class="desc">Laser Hair Removal</div>
</div>

<div class="gallery">

    <img src="images/electrolysis.jpg" alt="Electrolysis" width="300" height="200">

  <div class="desc">Electrolysis</div>
</div>

<div class="gallery">

    <img src="images/threadveins.jpg" alt="Thread Veins" width="300" height="200">

  <div class="desc">Thread Veins</div>
</div>

<div class="gallery">

    <img src="images/microderm.jpg" alt="Microdermabrasion" width="300" height="200">

  <div class="desc">Microdermabrasion</div>
</div>

<div class="gallery">

    <img src="images/rosacea.jpg" alt="Rosacea" width="300" height="200">

  <div class="desc">Rosacea</div>
</div>

<div class="gallery">

    <img src="images/pigmentation.jpg" alt="Pigmentation" width="300" height="200">

  <div class="desc">Pigmentation</div>
</div>

<div class="gallery">

    <img src="images/skinpeels.jpg" alt="Skin Peels" width="300" height="200">

  <div class="desc">Skin Peels</div>
</div>

<div class="gallery">

    <img src="images/botox.jpg" alt="Botox/Lipfillers" width="300" height="200">

  <div class="desc">Botox & Lipfillers</div>
</div>

<div class="gallery">

    <img src="images/microblading.png" alt="Semi Perm" width="300" height="200">

  <div class="desc">Eyebrow Microblading & Semi-Permanent Make-up</div>
</div>

<div class="gallery">

    <img src="images/mc.jpg" alt="Massage and Cupping" width="300" height="200">

  <div class="desc">Massage & Cupping</div>
</div>

</div></code>```

Body:
I would like to align my div boxes for a client's website all perfectly next to each other and without some being bigger than others. Here is the page relating to the code: https://www.imaniskinclinic.com/treatments

The boxes are not inline and some are obviously bigger than others. I added a div box container which I thought would hold the boxes more nicely but it doesn't seem to have worked.

Can anyone give me some assistance and guidance on what I must do?

Here is the code: CSS then HTML

.box {
  background-color: white; /* for visualization purposes */
  display: inline-block;
  max-width: 100%;

}

div.gallery {
    margin: 5px;
    border: 1px solid #ccc;
    width: 200px;
 height: 200px;
 background: #f8abbe;
}

div.gallery:hover {
    border: 1px solid #ffffff;
}

div.gallery img {
    width: 100%;
    height: auto;
}

div.desc {
    padding: 10px;
    text-align: center;
 font-family : verdana, arial, helvetica, helve, sans-serif;
 color: #ffffff;
}

Acne Treatments

Laser Hair Removal

Electrolysis

Thread Veins

Microdermabrasion

Rosacea

Pigmentation

Skin Peels

Botox & Lipfillers

Eyebrow Microblading & Semi-Permanent Make-up

Massage & Cupping

Body:
Just added display: inline-block;
If you play a little bit with sizes of divs it will look better

.box {
  background-color: white; /* for visualization purposes */
  display: inline-block;
  max-width: 100%;

}

div.gallery {
    margin: 5px;
    border: 1px solid #ccc;
    width: 200px;
 height: 200px;
 background: #f8abbe;
  display: inline-block;
}

div.gallery:hover {
    border: 1px solid #ffffff;
}

div.gallery img {
    width: 100%;
    height: auto;
}

div.desc {
    padding: 10px;
    text-align: center;
 font-family : verdana, arial, helvetica, helve, sans-serif;
 color: #ffffff;
}

<div class="box">
  <div class="gallery">
  <a href="aesthetics/acne.htm" >
    <img src="images/acne.jpg" alt="Acne" width="300" height="200">
  </a>
  <div class="desc">Acne Treatments</div>
</div>

<div class="gallery">
  <a href="aesthetics/hair%20removal.htm">
    <img src="images/hairremoval.jpg" alt="Hair Removal" width="300" height="200">
  </a>
  <div class="desc">Laser Hair Removal</div>
</div>

<div class="gallery">
  <a href="aesthetics/electrolysis.htm">
    <img src="images/electrolysis.jpg" alt="Electrolysis" width="300" height="200">
  </a>
  <div class="desc">Electrolysis</div>
</div>

<div class="gallery">
  <a href="aesthetics/thread%20veins.htm">
    <img src="images/threadveins.jpg" alt="Thread Veins" width="300" height="200">
  </a>
  <div class="desc">Thread Veins</div>
</div>

<div class="gallery">
  <a href="aesthetics/microderm.htm" >
    <img src="images/microderm.jpg" alt="Microdermabrasion" width="300" height="200">
  </a>
  <div class="desc">Microdermabrasion</div>
</div>

<div class="gallery">
  <a href="aesthetics/rosacea.htm" >
    <img src="images/rosacea.jpg" alt="Rosacea" width="300" height="200">
  </a>
  <div class="desc">Rosacea</div>
</div>

<div class="gallery">
  <a href="aesthetics/pigmentation.htm" >
    <img src="images/pigmentation.jpg" alt="Pigmentation" width="300" height="200">
  </a>
  <div class="desc">Pigmentation</div>
</div>

<div class="gallery">
  <a href="aesthetics/skin%20peels.htm" >
    <img src="images/skinpeels.jpg" alt="Skin Peels" width="300" height="200">
  </a>
  <div class="desc">Skin Peels</div>
</div>

<div class="gallery">
  <a href="aesthetics/botox_lipfillers.htm" >
    <img src="images/botox.jpg" alt="Botox/Lipfillers" width="300" height="200">
  </a>
  <div class="desc">Botox & Lipfillers</div>
</div>

<div class="gallery">
  <a href="aesthetics/semiperm.htm" >
    <img src="images/microblading.png" alt="Semi Perm" width="300" height="200">
  </a>
  <div class="desc">Eyebrow Microblading & Semi-Permanent Make-up</div>
</div>

<div class="gallery">
  <a href="aesthetics/mc.html" >
    <img src="images/mc.jpg" alt="Massage and Cupping" width="300" height="200">
  </a>
  <div class="desc">Massage & Cupping</div>
</div>

</div>


问:
Android InputType.TYPE_NUMBER_VARIATION_PASSWORD to visible number password (Only Numbers)
I Implemented an Edittext that accepts numberPassword and also allows a user to show password & hide password. It works but there is one Issue i cannot solve.

I used InputType.TYPE_CLASS_NUMBER and InputType.TYPE_NUMBER_VARIATION_PASSWORD to hide the password which works, I used InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD to make it visible.

But then the InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD also allows user to enter both Characters & numbers but I do NOT want that. I want users to be able to enter numbers ONLY.

Please how can I achieve this?

this is my code below:

```<code>private fun setShowHiddenField(field: TextInputEditText, checked: Boolean){
        if(checked){
            field.inputType = InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
        } else {
            field.inputType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_VARIATION_PASSWORD
        }
        field.setSelection(field.getText().toString().length)
    }
</code>```

Edit

For anyone asking why I didn't do it in XML? Even if you do it in xml, using InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD would still bring up a keyboard allowing both Texts & Numbers.

I have my code for Edittext below:

```<code><android.support.design.widget.TextInputEditText
                android:id="@+id/cardNumberEditText"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="numberPassword"
                android:maxLines="1"
                android:digits="1234567890"
                tools:ignore="LabelFor,NegativeMargin"/>
</code>```

Think of this like a Edittext accepting a PIN CODE that you also want to give users the option to view the PIN & hide it.

I am using a Checkbox to allow user choose to hide or show. So i cannot use password options like passwordToggleContentDescription or passwordToggleEnabled or passwordToggleTint

答:
I have found a way to solve my problem, not a direct solution but it works.

You might technically see the keyboard change quickly from letters to numbers when using an Emulator, but this works pretty fine on Device as you can hardly notice the quick change except you pay so much attention.

```<code>private fun setShowHiddenField(field: TextInputEditText, checked: Boolean){
        if(checked){
            field.inputType = InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD

            // set keyboard back to allowing only digits & specify them
            field.keyListener = DigitsKeyListener.getInstance("0123456789")

        } else {
            field.inputType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_VARIATION_PASSWORD
        }
        field.setSelection(field.getText().toString().length)
    }
</code>```

Body:
I Implemented an Edittext that accepts numberPassword and also allows a user to show password & hide password. It works but there is one Issue i cannot solve.

I used InputType.TYPE_CLASS_NUMBER and InputType.TYPE_NUMBER_VARIATION_PASSWORD to hide the password which works, I used InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD to make it visible.

But then the InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD also allows user to enter both Characters & numbers but I do NOT want that. I want users to be able to enter numbers ONLY.

Please how can I achieve this?

this is my code below:

private fun setShowHiddenField(field: TextInputEditText, checked: Boolean){
        if(checked){
            field.inputType = InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
        } else {
            field.inputType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_VARIATION_PASSWORD
        }
        field.setSelection(field.getText().toString().length)
    }

Edit

For anyone asking why I didn't do it in XML? Even if you do it in xml, using InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD would still bring up a keyboard allowing both Texts & Numbers.

I have my code for Edittext below:

<android.support.design.widget.TextInputEditText
                android:id="@+id/cardNumberEditText"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="numberPassword"
                android:maxLines="1"
                android:digits="1234567890"
                tools:ignore="LabelFor,NegativeMargin"/>

Think of this like a Edittext accepting a PIN CODE that you also want to give users the option to view the PIN & hide it.

I am using a Checkbox to allow user choose to hide or show. So i cannot use password options like passwordToggleContentDescription or passwordToggleEnabled or passwordToggleTint

Body:
I have found a way to solve my problem, not a direct solution but it works.

You might technically see the keyboard change quickly from letters to numbers when using an Emulator, but this works pretty fine on Device as you can hardly notice the quick change except you pay so much attention.

private fun setShowHiddenField(field: TextInputEditText, checked: Boolean){
        if(checked){
            field.inputType = InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD

            // set keyboard back to allowing only digits & specify them
            field.keyListener = DigitsKeyListener.getInstance("0123456789")

        } else {
            field.inputType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_VARIATION_PASSWORD
        }
        field.setSelection(field.getText().toString().length)
    }


问:
How are these extra error log files created?
One of our clients has been having a lot of network problems lately.
When I went to retrieve the errors text file on their server computer I discovered about a dozen files, one was the correctly named file

"errors.txt"

but the others had names like

"errors (computernameA v1).txt"

"errors (computernameA v2).txt"

"errors (computernameB v1).txt"
 etc etc.

Our software is definitely not creating files with these names
although it is creating their content.

The network being down will obviously throw errors in very many places in the client application. Part of the handling of all errors is to log them to the server computer.
The routine that does this first tries to find the error file and if it can't do so it tries to create it. Some of these other error files contain a lot of errors suggesting
that a local 'shadow' of the error.txt being used for successive errors while the network was down over a not insignicant time period? then once the network is back up again this is being put onto the server and renamed so as not to clash with existing file names

can someone please explain what's happening here and what software is doing it?

edit

In response to a request for the relevant code

```<code>170   On Error Resume Next
      Dim fs
180    Set fs = CreateObject("Scripting.FileSystemObject")
       Dim Item1 As String
       Dim Item2 As String
190    Item1 = strErrorFolder
200    If fs.FolderExists(strErrorFolder) <> True Then
210           MkDir Item1
220    End If

230    Item1 = strErrorFolder & "\Errors.txt"
240    If fs.FileExists(Item1) <> True Then
250    Item2 = App.Path & "Blank.txt"
260           FileCopy Item2, Item1
270           Item2 = ""
280           SetAttr Item1, vbNormal
290           Open Item1 For Output As #1
300           Write #1, "ErrorDateTime", "ErrorUser", "DatabaseAddress", "ProgramVersion", "Module", "SubRoutine", "LineNumber", "ErrorCode", "ErrorDescription"
310           Close #1
320    End If

330    Open Item1 For Append As #1
340           Write #1, ErrorDateTime, ErrorUser, Left(PANDATABASE, 1), ProgramVersion, Module, SubRoutine, LineNumber, ErrorCode, ErrorDescription
350           Close #1

360   On Error GoTo 0

End Sub 'errorhandled not
</code>```

答:
Run FileMon on the machine an then cause the error condition. Check the FileMon log to see what created the files.

As divo pointed out, you may need to use ProcMon instead.

OwnerDisplayName: kjack

ContentLicense: CC BY-SA 2.5

Body:
One of our clients has been having a lot of network problems lately.
When I went to retrieve the errors text file on their server computer I discovered about a dozen files, one was the correctly named file

"errors.txt"

but the others had names like

"errors (computernameA v1).txt"

"errors (computernameA v2).txt"

"errors (computernameB v1).txt"
 etc etc.

Our software is definitely not creating files with these names
although it is creating their content.

The network being down will obviously throw errors in very many places in the client application. Part of the handling of all errors is to log them to the server computer.
The routine that does this first tries to find the error file and if it can't do so it tries to create it. Some of these other error files contain a lot of errors suggesting
that a local 'shadow' of the error.txt being used for successive errors while the network was down over a not insignicant time period? then once the network is back up again this is being put onto the server and renamed so as not to clash with existing file names

can someone please explain what's happening here and what software is doing it?

edit

In response to a request for the relevant code

170   On Error Resume Next
      Dim fs
180    Set fs = CreateObject("Scripting.FileSystemObject")
       Dim Item1 As String
       Dim Item2 As String
190    Item1 = strErrorFolder
200    If fs.FolderExists(strErrorFolder) <> True Then
210           MkDir Item1
220    End If

230    Item1 = strErrorFolder & "\Errors.txt"
240    If fs.FileExists(Item1) <> True Then
250    Item2 = App.Path & "Blank.txt"
260           FileCopy Item2, Item1
270           Item2 = ""
280           SetAttr Item1, vbNormal
290           Open Item1 For Output As #1
300           Write #1, "ErrorDateTime", "ErrorUser", "DatabaseAddress", "ProgramVersion", "Module", "SubRoutine", "LineNumber", "ErrorCode", "ErrorDescription"
310           Close #1
320    End If

330    Open Item1 For Append As #1
340           Write #1, ErrorDateTime, ErrorUser, Left(PANDATABASE, 1), ProgramVersion, Module, SubRoutine, LineNumber, ErrorCode, ErrorDescription
350           Close #1

360   On Error GoTo 0

End Sub 'errorhandled not

LastEditorDisplayName: kjack

OwnerDisplayName: EBGreen

LastEditorDisplayName: EBGreen


问:
Edit several hundred Protocol Buffer serialized messages read from database
For an operation on my application, I need to read from database & then edit several hundred Protocol Buffer serialized messages. In each PB message, there are actually 4 int fields and one boolean field, and in the new message only the the boolean field is required to be changed.

I am in doubt what would be the best way to accomplish this, and thus seeking your help & expert opinion.

I guess building the entire messages once again by creating builder objects would be rather too much expensive..

答: I suggest you benchmark and see how long it takes.  You might be able to do this in under a 1 ms, meaning any IO you perform is likely to be more expensive than how you process the data.</p>

ContentLicense: CC BY-SA 3.0


问:
How to import Base64 PublicKey via WebCrypto "importKey" in ReactJS script?
I'm trying to import a Base64 PublicKey using the Web Crypto API function importKey. The purpose is to create a simple modal for parsing a PublicKey and enabling the encryption of a password.

I've tried to import the PublicKey as a Uint8Array using the "raw" method for the importKey function - see below script:

```<code>import buffer from 'buffer'

let kpub = "U6uvqoxXGj17tFS5C05tSWohDQl2u1ugiHyNKXB9WF0UiYaxa5FxiLX/LxGeDUPMyLmWBGBUjpTzh1owF9RWug=="
let buff = new Buffer(kpub, 'base64');

window.crypto.subtle.importKey(
  "raw",
  buff,
  {
      name: "ECDH",
      namedCurve: "P-256",
  },
  false,
  []
)
.then(function(publicKey){
  console.log(publicKey);
})
.catch(function(err){
  console.error(err);
});

</code>```

I expected this to produce the imported version of the input, kpub. However, the output is not shown in the console - and when the error handling is enabled, I get a DOMException instead.

Any idea what part I'm doing wrong?

As an alternative, it might be easier to convert the publicKey into the JWK format. As an example, I've confirmed that the below JWK works as intended in the importKey function. However, if I'm to use this I struggle with how to convert my input kpub to the x and y coordinates:

```<code>const jwkKey = {
  "kty":"EC",
  "crv":"P-256",
  "x":"f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU",
  "y":"x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0",
  "kid":"Id that can be uniquely Identified"
}
</code>```

Any help is greatly appreciated.

答:
With some help from Dmitry Chestnykh, I got it working by prepending a single byte, 0x04:</p>

```<code>const device_kpub_base64 = "U6uvqoxXGj17tFS5C05tSWohDQl2u1ugiHyNKXB9WF0UiYaxa5FxiLX/LxGeDUPMyLmWBGBUjpTzh1owF9RWug=="
const prepend_byte = new Buffer([4])
let device_kpub_buffer = new Buffer(device_kpub_base64, 'base64');
device_kpub_buffer = Buffer.concat([prepend_byte, device_kpub_buffer])

// Import the device public key into the web crypto API
window.crypto.subtle.importKey(
  "raw",
  device_kpub_buffer,
  {
      name: "ECDH",
      namedCurve: "P-256",
  },
  true,
  []
)
.then(function(devicePublicKey){
  console.log(devicePublicKey);
})
.catch(function(err){
  console.error(err);
});
</code>```

Body:
I'm trying to import a Base64 PublicKey using the Web Crypto API function importKey. The purpose is to create a simple modal for parsing a PublicKey and enabling the encryption of a password.

I've tried to import the PublicKey as a Uint8Array using the "raw" method for the importKey function - see below script:

import buffer from 'buffer'

let kpub = "U6uvqoxXGj17tFS5C05tSWohDQl2u1ugiHyNKXB9WF0UiYaxa5FxiLX/LxGeDUPMyLmWBGBUjpTzh1owF9RWug=="
let buff = new Buffer(kpub, 'base64');

window.crypto.subtle.importKey(
  "raw",
  buff,
  {
      name: "ECDH",
      namedCurve: "P-256",
  },
  false,
  []
)
.then(function(publicKey){
  console.log(publicKey);
})
.catch(function(err){
  console.error(err);
});

I expected this to produce the imported version of the input, kpub. However, the output is not shown in the console - and when the error handling is enabled, I get a DOMException instead.

Any idea what part I'm doing wrong?

As an alternative, it might be easier to convert the publicKey into the JWK format. As an example, I've confirmed that the below JWK works as intended in the importKey function. However, if I'm to use this I struggle with how to convert my input kpub to the x and y coordinates:

const jwkKey = {
  "kty":"EC",
  "crv":"P-256",
  "x":"f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU",
  "y":"x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0",
  "kid":"Id that can be uniquely Identified"
}

Any help is greatly appreciated.

Body:
With some help from Dmitry Chestnykh, I got it working by prepending a single byte, 0x04:

const device_kpub_base64 = "U6uvqoxXGj17tFS5C05tSWohDQl2u1ugiHyNKXB9WF0UiYaxa5FxiLX/LxGeDUPMyLmWBGBUjpTzh1owF9RWug=="
const prepend_byte = new Buffer([4])
let device_kpub_buffer = new Buffer(device_kpub_base64, 'base64');
device_kpub_buffer = Buffer.concat([prepend_byte, device_kpub_buffer])

// Import the device public key into the web crypto API
window.crypto.subtle.importKey(
  "raw",
  device_kpub_buffer,
  {
      name: "ECDH",
      namedCurve: "P-256",
  },
  true,
  []
)
.then(function(devicePublicKey){
  console.log(devicePublicKey);
})
.catch(function(err){
  console.error(err);
});


问:
If column A's value is within the range of Column B and C then copy
in this project i have to check column's A value between Column B and Column C. If  columnA's values>= Columns B value or Columns A value<= Columns C value then i need to copy column d and e values and need to put into sheet1 column G and H. Column A is in sheet1 and Column B, C, D and E in sheet2.

I am sorry with my wordings i know its difficult to understand. If someone can help me with this i would be forever grateful. Thank you

```<code>             A       B    c   D     E
             1       1    9   Dog   Naruto
             11      10   19  Cat   one piece
             21      20   30  Duck  lo

          i want the outcome like this
           A    G       H
           1    Dog     Naruto
           11   cat     One piece
           21    duck     lo
</code>```

答:
See below code (not tested).</p>

```<code>Sub ColumnCheck()

Dim i As Long
Dim lRow As Long
Dim colA As Double, colB As Double, colC As Double

'assuming both sheets have the same amount of data rows
lRow = Sheets("Sheet1").Range("A" & Sheets("Sheet1").Rows.Count).End(xlUp).Row

'now loop
For i = 2 To lRow
    colA = Sheets("Sheet1").Range("A" & i).Value
    colB = Sheets("Sheet2").Range("B" & i).Value
    colC = Sheets("Sheet2").Range("C" & i).Value

    If colA >= colB Or colA <= colC Then
        'if true - set values
        Sheets("Sheet1").Range("G" & i).Value = Sheets("Sheet2").Range("D" & i).Value
        Sheets("Sheet1").Range("H" & i).Value = Sheets("Sheet2").Range("E" & i).Value
    End If
Next i

End Sub
</code>```

Body:
in this project i have to check column's A value between Column B and Column C. If  columnA's values>= Columns B value or Columns A value<= Columns C value then i need to copy column d and e values and need to put into sheet1 column G and H. Column A is in sheet1 and Column B, C, D and E in sheet2.

I am sorry with my wordings i know its difficult to understand. If someone can help me with this i would be forever grateful. Thank you

             A       B    c   D     E
             1       1    9   Dog   Naruto
             11      10   19  Cat   one piece
             21      20   30  Duck  lo

          i want the outcome like this
           A    G       H
           1    Dog     Naruto
           11   cat     One piece
           21    duck     lo

Body:
See below code (not tested).

Sub ColumnCheck()

Dim i As Long
Dim lRow As Long
Dim colA As Double, colB As Double, colC As Double

'assuming both sheets have the same amount of data rows
lRow = Sheets("Sheet1").Range("A" & Sheets("Sheet1").Rows.Count).End(xlUp).Row

'now loop
For i = 2 To lRow
    colA = Sheets("Sheet1").Range("A" & i).Value
    colB = Sheets("Sheet2").Range("B" & i).Value
    colC = Sheets("Sheet2").Range("C" & i).Value

    If colA >= colB Or colA <= colC Then
        'if true - set values
        Sheets("Sheet1").Range("G" & i).Value = Sheets("Sheet2").Range("D" & i).Value
        Sheets("Sheet1").Range("H" & i).Value = Sheets("Sheet2").Range("E" & i).Value
    End If
Next i

End Sub


问:
using phpexcel in codeigniter
i am using the phpexcel library to export my report to excel file.
but i want to have my own excel file and use it with phpexcel.
here is the code i used:

```<code>public function event_reportexcel($id)
{
    $this->load->library('excel');
    $this->excel->setActiveSheetIndex(0);
    $this->excel->getActiveSheet()->setTitle('test worksheet');
    $this->excel->getActiveSheet()->setCellValue('A1', 'This is just some text value');
    $this->excel->getActiveSheet()->getStyle('A1')->getFont()->setSize(20);
    $this->excel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
    $this->excel->getActiveSheet()->mergeCells('A1:D1');
    $this->excel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

    $filename='just_some_random_name.xls'; //save our workbook as this file name
    header('Content-Type: application/vnd.ms-excel'); //mime type
    header('Content-Disposition: attachment;filename="'.$filename.'"'); //tell browser what's the file name
    header('Cache-Control: max-age=0'); //no cache

    $objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');
    //force user to download the Excel file without writing it to server's HD
    $objWriter->save('php://output');
}
</code>```

it will put my data in a new excel file, but i need this function to use a excel file as template.

答:
THis will help u

public function export()
{
    $this->load->model('authors_model');
    $this->load->library('excel');

    $object = new PHPExcel();

    $object->setActiveSheetIndex(0);

    $table_columns = ['ID', 'first_name', 'last_name', 'Email', 'BirthDate', 'Added'];

    $column = 1;

    foreach ($table_columns as $dd)
    {
        $object
            ->getActiveSheet()
            ->setCellValueByColumnAndRow($column,1, $dd);

        $column++;
    }

    $employee_data = $this->authors_model->get_all_data();

    $row_no = 2 ;
    foreach ($employee_data as  $value)
    {
        $object->getActiveSheet()->setCellValueByColumnAndRow(0 ,$row_no,$value->id );
        $object->getActiveSheet()->setCellValueByColumnAndRow(1 ,$row_no,$value->first_name );
        $object->getActiveSheet()->setCellValueByColumnAndRow(2 ,$row_no,$value->last_name );
        $object->getActiveSheet()->setCellValueByColumnAndRow(3 ,$row_no,$value->email );
        $object->getActiveSheet()->setCellValueByColumnAndRow(4 ,$row_no,$value->birthdate );
        $object->getActiveSheet()->setCellValueByColumnAndRow(5 ,$row_no,$value->added );

        $row_no++;
    }

    ob_end_clean();

    header('Content-Type: application/vnd.ms-excel'); //mime type
    header("Content-Disposition: attachment; filename=\"filename.xls\"");
    header("Cache-Control: max-age=0");

    $objWriter = PHPExcel_IOFactory::createWriter($object, 'Excel5');
    $objWriter->save('php://output');
}
```

Title: using phpexcel in codeigniter

Body:
i am using the phpexcel library to export my report to excel file.
but i want to have my own excel file and use it with phpexcel.
here is the code i used:

public function event_reportexcel($id)
{
    $this->load->library('excel');
    $this->excel->setActiveSheetIndex(0);
    $this->excel->getActiveSheet()->setTitle('test worksheet');
    $this->excel->getActiveSheet()->setCellValue('A1', 'This is just some text value');
    $this->excel->getActiveSheet()->getStyle('A1')->getFont()->setSize(20);
    $this->excel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
    $this->excel->getActiveSheet()->mergeCells('A1:D1');
    $this->excel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

    $filename='just_some_random_name.xls'; //save our workbook as this file name
    header('Content-Type: application/vnd.ms-excel'); //mime type
    header('Content-Disposition: attachment;filename="'.$filename.'"'); //tell browser what's the file name
    header('Cache-Control: max-age=0'); //no cache

    $objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');
    //force user to download the Excel file without writing it to server's HD
    $objWriter->save('php://output');
}

it will put my data in a new excel file, but i need this function to use a excel file as template.


问:
How to change color of tableview background
I am trying to figure how to change the color of the background of a plain uitableview after the using has scrolled past the top or bottom of the table. Not sure what its called but if you look at the mail app, if you scroll down, whilst already at the top of the table, the background is a dark gray color with a slight gradient. Anyone know how i go about implementing this?</p>

答:
```<code>tableView.backgroundColor = [UIColor redColor];
</code>```

will provide a red color background for your table view

Other options include

```<code>tableView.backgroundColor = [UIColor colorWithPatternImage:anImage];
tableView.backgroundColor = [UIColor colorWithRed: green: blue: alpha: ];
tableView.backgroundColor = [UIColor colorWithHue: saturation: brightness: alpha: ];
tableView.backgroundColor = [UIColor colorWithCGColor:cgColor];
</code>```

Body:
tableView.backgroundColor = [UIColor redColor];

will provide a red color background for your table view

Other options include

tableView.backgroundColor = [UIColor colorWithPatternImage:anImage];
tableView.backgroundColor = [UIColor colorWithRed: green: blue: alpha: ];
tableView.backgroundColor = [UIColor colorWithHue: saturation: brightness: alpha: ];
tableView.backgroundColor = [UIColor colorWithCGColor:cgColor];


问:
SQL concatenate strings in single value
I have two tables, users_tbl and images tbl.

Every user can have more than one image.

I'm trying to select all the users and concatenate the user image in a single row

Example :

Users tbl

```<code>user_id    user_name
--------------------
 1          david
 2          tarik
</code>```

images tbl

```<code>image_id   user_id   image_url
-------------------------------
1            1      "image 12312 url"
2            1      "image 123 url"
3            1      "image 313 url"
4            1      "image 212 url"
5            2      "my image url"
5            2      "my image url2"
</code>```

I need a select statement that returns the following result:

```<code>user_id   image_url
----------------------------------------------------------------------
    1     "image 12312 url ,image 123 url,image 313 url,image 212 url"
    2     "my image url , my image url2"
</code>```

答:
In SQL Server 2012, you would use for xml path:

```<code>select u.*,
       stuff( (select ', ' + i.image_url
               from images i
               where i.user_id = u.user_id
               for xml path ('')
              ), 1, 2, ''
            ) as image_urls
from users u;
</code>```

EDIT:

If you want the comma at the end, leave out the stuff() and use:

```<code>select u.*,
       (select i.image_url + ', '
        from images i
        where i.user_id = u.user_id
        for xml path ('')
       ) as image_urls
from users u;
</code>```

Title: SQL concatenate strings in single value

Body:
I have two tables, users_tbl and images tbl.

Every user can have more than one image.

I'm trying to select all the users and concatenate the user image in a single row

Example :

Users tbl

user_id    user_name
--------------------
 1          david
 2          tarik

images tbl

image_id   user_id   image_url
-------------------------------
1            1      "image 12312 url"
2            1      "image 123 url"
3            1      "image 313 url"
4            1      "image 212 url"
5            2      "my image url"
5            2      "my image url2"

I need a select statement that returns the following result:

user_id   image_url
----------------------------------------------------------------------
    1     "image 12312 url ,image 123 url,image 313 url,image 212 url"
    2     "my image url , my image url2"

Body:
In SQL Server 2012, you would use for xml path:

select u.*,
       stuff( (select ', ' + i.image_url
               from images i
               where i.user_id = u.user_id
               for xml path ('')
              ), 1, 2, ''
            ) as image_urls
from users u;

EDIT:

If you want the comma at the end, leave out the stuff() and use:

select u.*,
       (select i.image_url + ', '
        from images i
        where i.user_id = u.user_id
        for xml path ('')
       ) as image_urls
from users u;


问:
How to append a list into a list
I want to append something that will output like list1. a list inside a list, how do i do that?
I don't care how u put abc into a list, but I want to know how to put that list into list1, so that list1 can be a list inside a list.
I want the output to be like this</p>

```<code>x = a,b,c
list1 = []
list1 = [[a,b,c],[a,b,c]]
</code>```

答:
The function "append" is used to add an object to the end of a list. Since a list is an object, if you append another list onto a list, the first list will be a single object at the end of the list.

```<code>my_list = ['a', 'b', 'c']
another_list = [1, 2, 3]
my_list.append(another_list)
print(my_list)
= "['a', 'b', 'c', [1, 2, 3]]"
</code>```

You get the same result using the syntax:

```<code>my_list = ['a', 'b', 'c']
new_list = [my_list, my_list, my_list]
print(new_list)
= "[['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]"
</code>```

The function "extend" iterates over its argument adding each element to the list and extending the list. The length of the list increases by number of elements added.

```<code>my_list = ['a', 'b', 'c']
another_list = [1, 2, 3]
my_list.extend(another_list)
print(my_list)
= "['a', 'b', 'c', 1, 2, 3]
</code>```

You can get the same result as extend using a simple sum between lists:

```<code>my_list = ['a', 'b', 'c']
another_list = [1, 2, 3]
print(my_list + another_list)
= "['a', 'b', 'c', 1, 2, 3]
</code>```

Title: How to append a list into a list

Body:
I want to append something that will output like list1. a list inside a list, how do i do that?
I don't care how u put abc into a list, but I want to know how to put that list into list1, so that list1 can be a list inside a list.
I want the output to be like this

x = a,b,c
list1 = []
list1 = [[a,b,c],[a,b,c]]

Body:
The function "append" is used to add an object to the end of a list. Since a list is an object, if you append another list onto a list, the first list will be a single object at the end of the list.

my_list = ['a', 'b', 'c']
another_list = [1, 2, 3]
my_list.append(another_list)
print(my_list)
= "['a', 'b', 'c', [1, 2, 3]]"

You get the same result using the syntax:

my_list = ['a', 'b', 'c']
new_list = [my_list, my_list, my_list]
print(new_list)
= "[['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]"

The function "extend" iterates over its argument adding each element to the list and extending the list. The length of the list increases by number of elements added.

my_list = ['a', 'b', 'c']
another_list = [1, 2, 3]
my_list.extend(another_list)
print(my_list)
= "['a', 'b', 'c', 1, 2, 3]

You can get the same result as extend using a simple sum between lists:

my_list = ['a', 'b', 'c']
another_list = [1, 2, 3]
print(my_list + another_list)
= "['a', 'b', 'c', 1, 2, 3]


问:
Php problem, trying to change multiple numbers in a file. Str_replace replaces everything till max
I'm trying to make script that increases all grades in textfile by +1. Like 0 -> 1, 1 -> 2 etc. Grade 5 should not be increased at all, as it's best from 0-5.

Problem is that my script gives following output:
New grades:

```<code>5
5
5
5
5
5
</code>```

When it should give:
New grades:

```<code>1
5
2
4
3
5
</code>```

It seems that str_replace() searches for 0, turns it to 1, then finds that 1 again and replaces it with 2.... and in the end all of grades are 5. Is there way to do this only once for each grade? I tried preg_replace(), but it gives error:

PHP Warning:  preg_replace(): Delimiter must not be alphanumeric or backslash

Here's my script:

```<code><?php
$file = 'grades.txt';
$file_contents = file_get_contents($file);

$fh = fopen($file, "w");
$file_contents = str_replace(['0','1','2','3','4'],['1','2','3','4','5'],$file_contents);

fwrite($fh, $file_contents);
fclose($fh);

echo "New grades:\n";
echo $file_contents;
?>
</code>```

答:
Replace it the other way around - from highest to lowest (instead of lowest to highest). This way you will replace 4 by 5, then there are no 4s - next, you replace 3 by 4, and so on - thus there are no overlaps.

$file_contents = "1 2 3 4 5 4 5 2 1";
$result = str_replace(range(4, 0), range(5, 1), $file_contents);
echo $result;
```

Live demo at https://3v4l.org/hBB3R

Body:
I'm trying to make script that increases all grades in textfile by +1. Like 0 -> 1, 1 -> 2 etc. Grade 5 should not be increased at all, as it's best from 0-5.

Problem is that my script gives following output:
New grades:

5
5
5
5
5
5

When it should give:
New grades:

1
5
2
4
3
5

It seems that str_replace() searches for 0, turns it to 1, then finds that 1 again and replaces it with 2.... and in the end all of grades are 5. Is there way to do this only once for each grade? I tried preg_replace(), but it gives error:

PHP Warning:  preg_replace(): Delimiter must not be alphanumeric or backslash

Here's my script:

<?php
$file = 'grades.txt';
$file_contents = file_get_contents($file);

$fh = fopen($file, "w");
$file_contents = str_replace(['0','1','2','3','4'],['1','2','3','4','5'],$file_contents);

fwrite($fh, $file_contents);
fclose($fh);

echo "New grades:\n";
echo $file_contents;
?>

Body:
Replace it the other way around - from highest to lowest (instead of lowest to highest). This way you will replace 4 by 5, then there are no 4s - next, you replace 3 by 4, and so on - thus there are no overlaps.

$file_contents = "1 2 3 4 5 4 5 2 1";
$result = str_replace(range(4, 0), range(5, 1), $file_contents);
echo $result;

Live demo at https://3v4l.org/hBB3R


问:
How to access ElasticSearch domain endpoint URL in AWS?
I have created elasticsearch domain in AWS and integrated with cloudwatch logs which eventually sends logs to elasticsearch cluster with help of lambda function. It has got successfully created and it gives me one endpoint URL, something like this `https://search-elkprod-c63hwtlyqgdogkw55w6osdfzwu.eu-west-1.es.amazonaws.com'.

When i click this link i get this message :

```<code>{
  "name" : "S7hluCW",
  "cluster_name" : "567294256180:elkprod",
  "cluster_uuid" : "4UdCvJT9R4-H05MSXqg9tQ",
  "version" : {
    "number" : "6.5.4",
    "build_flavor" : "oss",
    "build_type" : "zip",
    "build_hash" : "d2ef93d",
    "build_date" : "2019-04-08T13:15:27.206923Z",
    "build_snapshot" : false,
    "lucene_version" : "7.5.0",
    "minimum_wire_compatibility_version" : "5.6.0",
    "minimum_index_compatibility_version" : "5.0.0"
  },
  "tagline" : "You Know, for Search"
}
</code>```

Now my questions are:

How to access this cluster? I want to check whether my logs are going to the
cluster or not.

If this is a cluster, where are the instances that would have been launched with this cluster?

Please help me on this. Please let me know if you need any more clarification.

答:
To answer the second part of your question, "If this is a cluster, where are the instances that would have been launched with this cluster?":

This instances are created and managed by AWS so you dont have direct access to them (you cant SSH to them or anything). The only way for you to interact with them is through endpoint and services that can use that endpoint (kibana, curl, cerebro...)

Body:
I have created elasticsearch domain in AWS and integrated with cloudwatch logs which eventually sends logs to elasticsearch cluster with help of lambda function. It has got successfully created and it gives me one endpoint URL, something like this `https://search-elkprod-c63hwtlyqgdogkw55w6osdfzwu.eu-west-1.es.amazonaws.com'.

When i click this link i get this message :

{
  "name" : "S7hluCW",
  "cluster_name" : "567294256180:elkprod",
  "cluster_uuid" : "4UdCvJT9R4-H05MSXqg9tQ",
  "version" : {
    "number" : "6.5.4",
    "build_flavor" : "oss",
    "build_type" : "zip",
    "build_hash" : "d2ef93d",
    "build_date" : "2019-04-08T13:15:27.206923Z",
    "build_snapshot" : false,
    "lucene_version" : "7.5.0",
    "minimum_wire_compatibility_version" : "5.6.0",
    "minimum_index_compatibility_version" : "5.0.0"
  },
  "tagline" : "You Know, for Search"
}

Now my questions are:

How to access this cluster? I want to check whether my logs are going to the
cluster or not.

If this is a cluster, where are the instances that would have been launched with this cluster?

Please help me on this. Please let me know if you need any more clarification.


问:
Copy last row on change - simultaneous entries
I have a google script that copies the last row on that spreadsheet to another spreadsheet sheet every time an entry is made. This entry is not linked to a Google form at all - so it is not bound to an onFormSubmit trigger - this submission is made from a JotForm form and inserted into the spreadsheet automatically. What I would like to know if my code will always work even if say two users make their submissions at the same time.

The code works fine - there seems to be no problem with that. I use the On change trigger. But I'd like to make sure it would always work. Many thanks for your help in advance.

```<code>function copyLastRow() {
  var target = SpreadsheetApp.openById('xxxxx').getSheetByName('Records');
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
 var lastrow = sheet.getLastRow();
 var sourceData = sheet.getRange(lastrow, 1, 1, 10).getValues();
 target.appendRow(sourceData[0]);
}
</code>```

答:
This is kind of the template I imagine you could use in completing this objective.</p>

```<code>function updateSpreadsheet() {

  //Open Form Responses Spreadsheet and get the Sheet you are reading data from
  // You will need to update ID and SheetName parameters for your own sheets.
  var formResponses = SpreadsheetApp.openById(ID).getSheetByName(SheetName);

  //Open destinationSheet that you are writing to and get the sheet that you are writing to
  // You will need to update ID and SheetName parameters for your own sheets.
  var destinationSheet = SpreadsheetApp.openById(ID).getSheetByName(SheetName);

  //Getting last rows from formResponse and destinationSheet
  //It is not totally necessary to create everything as a variable, but I wanted to make it explicit what I am doing here
  var formResponsesLastRow = formResponses.getLastRow();
  var destinationSheetLastRow = destinationSheet.getLastRow();

  //We are going to calculate the difference between the formResponse and destinationSheet
  //This lets us know how many more rows have been added since we last updated destinationSheet
  var numberNewRows = formResponsesLastRow - destinationSheetLastRow;

  //Now get the new data to Write
  var dataToWrite = formResponses.getRange((formResponsesLastRow - numberNewRows) + 1 , 1, numberNewRows, 3).getValues();

  //Write to destinationSheet
  destinationSheet.getRange(destinationSheetLastRow + 1, 1, numberNewRows, 3).setValues(dataToWrite);

}
</code>```

Body:
I have a google script that copies the last row on that spreadsheet to another spreadsheet sheet every time an entry is made. This entry is not linked to a Google form at all - so it is not bound to an onFormSubmit trigger - this submission is made from a JotForm form and inserted into the spreadsheet automatically. What I would like to know if my code will always work even if say two users make their submissions at the same time.

The code works fine - there seems to be no problem with that. I use the On change trigger. But I'd like to make sure it would always work. Many thanks for your help in advance.

function copyLastRow() {
  var target = SpreadsheetApp.openById('xxxxx').getSheetByName('Records');
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
 var lastrow = sheet.getLastRow();
 var sourceData = sheet.getRange(lastrow, 1, 1, 10).getValues();
 target.appendRow(sourceData[0]);
}

Body:
This is kind of the template I imagine you could use in completing this objective.

function updateSpreadsheet() {

  //Open Form Responses Spreadsheet and get the Sheet you are reading data from
  // You will need to update ID and SheetName parameters for your own sheets.
  var formResponses = SpreadsheetApp.openById(ID).getSheetByName(SheetName);

  //Open destinationSheet that you are writing to and get the sheet that you are writing to
  // You will need to update ID and SheetName parameters for your own sheets.
  var destinationSheet = SpreadsheetApp.openById(ID).getSheetByName(SheetName);

  //Getting last rows from formResponse and destinationSheet
  //It is not totally necessary to create everything as a variable, but I wanted to make it explicit what I am doing here
  var formResponsesLastRow = formResponses.getLastRow();
  var destinationSheetLastRow = destinationSheet.getLastRow();

  //We are going to calculate the difference between the formResponse and destinationSheet
  //This lets us know how many more rows have been added since we last updated destinationSheet
  var numberNewRows = formResponsesLastRow - destinationSheetLastRow;

  //Now get the new data to Write
  var dataToWrite = formResponses.getRange((formResponsesLastRow - numberNewRows) + 1 , 1, numberNewRows, 3).getValues();

  //Write to destinationSheet
  destinationSheet.getRange(destinationSheetLastRow + 1, 1, numberNewRows, 3).setValues(dataToWrite);

}


问:
return array of controls as aggregation in sap ui5
I have a use case where I want to add two sap.m.Input controls in the FormElement. But I have certain conditions on which these two Input controls can be changed. As I have seen in many examples, .bindAggregation method returns only one control. Can I make it return array of controls?

```<code>var oInput1 = new sap.m.Input();
var oInput2 = new sap.m.Input();
var oInput3 = new sap.m.Input();

var oFormElement = new sap.ui.layout.form.FormElement();
oFormElement.bindAggregation("fields", "properties", function(sId, oContext){
    var value = oContext.getProperty("value");
    if (value > 5) {
        return [oInput1, oInput3];
    } else {
        return [oInput1, oInput2];
    }
});
</code>```

I have written this sample but it show nothing. How to return array of controls in .bindAggregation. I was trying to use HBox in the fields, but it has a risk of causing the layout issues. Can anyone help?

Thanks in advance.

答:
You can't return multiple elements in your factory function. The factory function will be called for each context and must return exactly one element.

If you can't modify your service to return one context for each input, you might consider constructing your form in JavaScript instead of using data binding. This means to

request the properties from your service

loop through each property and add input(s) to the form element using the FormElement.addField method.

Body:
I have a use case where I want to add two sap.m.Input controls in the FormElement. But I have certain conditions on which these two Input controls can be changed. As I have seen in many examples, .bindAggregation method returns only one control. Can I make it return array of controls?

var oInput1 = new sap.m.Input();
var oInput2 = new sap.m.Input();
var oInput3 = new sap.m.Input();

var oFormElement = new sap.ui.layout.form.FormElement();
oFormElement.bindAggregation("fields", "properties", function(sId, oContext){
    var value = oContext.getProperty("value");
    if (value > 5) {
        return [oInput1, oInput3];
    } else {
        return [oInput1, oInput2];
    }
});

I have written this sample but it show nothing. How to return array of controls in .bindAggregation. I was trying to use HBox in the fields, but it has a risk of causing the layout issues. Can anyone help?

Thanks in advance.


问:
WIndows Git-bash run docker.sock

Problem

OS: Windows 10
I cannot run code bellow in git bash.

Tried using it with winpty but does not help. If I run it from cmd, it has no issues, but that is not a solution because I have a lot of commands in .sh format, so I need bash functionality. I googled the problem, but solutions are only to run from cmd.

Code below is one line

```<code>docker run  -v /var/run/docker.sock:/var/run/docker.sock -d --
publish=127.0.0.1:8000:80 --network net_basic gliderlabs/logspout
</code>```

Results

I expect something similar to that:

docker run  -v /var/run/docker.sock:/var/run/docker.sock -d --publish=127.0.0.1:8000:80 --network net_basic gliderlabs/logspout

249a69afcdb3d80e4783c439083ec1ffd30946ccec77f2b64f66a0b41afe29e7

I get that:

docker run  -v /var/run/docker.sock:/var/run/docker.sock -d --publish=127.0.0.1:8000:80 --network net_basic gliderlabs/logspout

C:/Program Files/Docker/Docker/Resources/bin/docker.exe: Error response from daemon: Mount denied:
The source path "C:/Program Files/Git/var/run/docker.sock;C"
doesn't exist and is not known to Docker.
See 'C:/Program Files/Docker/Docker/Resources/bin/docker.exe run --help'.

答:
This smells to me like you didn't share your drive in Docker settings.
Right click on Docker icon in system tray and select Settings.
After that go to "Shared Drives" and select a drive you want to share with Docker daemon and click "Apply".

Docker for Windows is buggy sometimes and if that doesn't work from first, just restart Docker and it should work.

Title: WIndows Git-bash run docker.sock

Body:
Problem

OS: Windows 10
I cannot run code bellow in git bash.

Tried using it with winpty but does not help. If I run it from cmd, it has no issues, but that is not a solution because I have a lot of commands in .sh format, so I need bash functionality. I googled the problem, but solutions are only to run from cmd.

Code below is one line

docker run  -v /var/run/docker.sock:/var/run/docker.sock -d --
publish=127.0.0.1:8000:80 --network net_basic gliderlabs/logspout

Results

I expect something similar to that:

docker run  -v /var/run/docker.sock:/var/run/docker.sock -d --publish=127.0.0.1:8000:80 --network net_basic gliderlabs/logspout

249a69afcdb3d80e4783c439083ec1ffd30946ccec77f2b64f66a0b41afe29e7

I get that:

docker run  -v /var/run/docker.sock:/var/run/docker.sock -d --publish=127.0.0.1:8000:80 --network net_basic gliderlabs/logspout

C:/Program Files/Docker/Docker/Resources/bin/docker.exe: Error response from daemon: Mount denied:
The source path "C:/Program Files/Git/var/run/docker.sock;C"
doesn't exist and is not known to Docker.
See 'C:/Program Files/Docker/Docker/Resources/bin/docker.exe run --help'.


问:
Java, Simplified check if int array contains int
Basically my mate has been saying that I could make my code shorter by using a different way of checking if an int array contains an int, although he won't tell me what it is :P.

Current:

```<code>public boolean contains(final int[] array, final int key) {
    for (final int i : array) {
        if (i == key) {
            return true;
        }
    }
    return false;
}
</code>```

Have also tried this, although it always returns false for some reason.

```<code>public boolean contains(final int[] array, final int key) {
    return Arrays.asList(array).contains(key);
}
</code>```

Could anyone help me out?

Thank you.

答:
You can convert your primitive int array into an arraylist of Integers using below Java 8 code,

```<code>List<Integer> arrayElementsList = Arrays.stream(yourArray).boxed().collect(Collectors.toList());
</code>```

And then use contains() method to check if the list contains a particular element,

```<code>boolean containsElement = arrayElementsList.contains(key);
</code>```

Body:
Basically my mate has been saying that I could make my code shorter by using a different way of checking if an int array contains an int, although he won't tell me what it is :P.

Current:

public boolean contains(final int[] array, final int key) {
    for (final int i : array) {
        if (i == key) {
            return true;
        }
    }
    return false;
}

Have also tried this, although it always returns false for some reason.

public boolean contains(final int[] array, final int key) {
    return Arrays.asList(array).contains(key);
}

Could anyone help me out?

Thank you.

Body:
You can convert your primitive int array into an arraylist of Integers using below Java 8 code,

List<Integer> arrayElementsList = Arrays.stream(yourArray).boxed().collect(Collectors.toList());

And then use contains() method to check if the list contains a particular element,

boolean containsElement = arrayElementsList.contains(key);


问:
How do I access the Notification (foundation class) and not my (custom class named Notification)?
Problem is, I want to create an extension on my Extension file something like below.

```<code>extension Notification.Name {
    static let value = Notification.Name(rawValue: "value")
}
</code>```

But unfortunately, it is reading my custom class named Notification, and I just want to access directly to the foundation this time... so I can go to .Name

Is there some way like mentions as in android like @DoNotReadCustomClass just besides the method? haha or something like that?

@onlyGoForFundationClass?
@exeptionForThisTimeOnCustomClass or something like that?

thanks.

答:
You can prefix it with the name of the module that declares the class. In this case it would be:</p>

```<code>extension Foundation.Notification.Name {
    static let value = Foundation.Notification.Name(rawValue: "value")
}
</code>```

Body:
Problem is, I want to create an extension on my Extension file something like below.

extension Notification.Name {
    static let value = Notification.Name(rawValue: "value")
}

But unfortunately, it is reading my custom class named Notification, and I just want to access directly to the foundation this time... so I can go to .Name

Is there some way like mentions as in android like @DoNotReadCustomClass just besides the method? haha or something like that?

@onlyGoForFundationClass?
@exeptionForThisTimeOnCustomClass or something like that?

thanks.

Body:
You can prefix it with the name of the module that declares the class. In this case it would be:

extension Foundation.Notification.Name {
    static let value = Foundation.Notification.Name(rawValue: "value")
}


问:
Why does Java allow only a single method X when implementing 2 interfaces that both declare X but which differ in their throws clauses?
This is closely related to, but is not the same question as: Java - Method name collision in interface implementation

When there are two Java interfaces that share a method with almost the same signature like so:

```<code>import java.io.IOException;

interface ISomething1 {
    void doSomething();
}

interface ISomething2 {
    void doSomething() throws IOException;
}

class Impl implements ISomething1, ISomething2 {
  public void doSomething() {
    throw new IOException(); // this does not compile since ISomething1.doSomething does not declare a throws clause
  }

  public static void main(String args[]) throws IOException {
    Impl i = new Impl();
    i.doSomething();
  }
}
</code>```

Why is it that Java enforces that only a single method implement both these interface methods even though technically they differ in signature?

Note also that in the example above, the implementation of Impl.doSomething needs to NOT throw an IOException as otherwise the compiler complains that ISomething1.doSomething must also declare that it throws IOException effectively making the throws clause in ISomething2.doSomething useless.

Am I missing something obvious here? Thanks in advance for responses.

答: The method signature does not consist of the Exception thrown or the return value type. Therefore, to the compiler, both interfaces are declaring the same method.</p>

Body:
This is closely related to, but is not the same question as: Java - Method name collision in interface implementation

When there are two Java interfaces that share a method with almost the same signature like so:

import java.io.IOException;

interface ISomething1 {
    void doSomething();
}

interface ISomething2 {
    void doSomething() throws IOException;
}

class Impl implements ISomething1, ISomething2 {
  public void doSomething() {
    throw new IOException(); // this does not compile since ISomething1.doSomething does not declare a throws clause
  }

  public static void main(String args[]) throws IOException {
    Impl i = new Impl();
    i.doSomething();
  }
}

Why is it that Java enforces that only a single method implement both these interface methods even though technically they differ in signature?

Note also that in the example above, the implementation of Impl.doSomething needs to NOT throw an IOException as otherwise the compiler complains that ISomething1.doSomething must also declare that it throws IOException effectively making the throws clause in ISomething2.doSomething useless.

Am I missing something obvious here? Thanks in advance for responses.


问:
Is sql with more where condition faster than those with less in mysql?
I hava big table need to be queried by a datetime column every 5 minutes.

My solution is like this:

```<code>select * from tbl_name where datetime_col < '2019-05-26 20:49:00' and tag_col = 0;
</code>```

,and do something with the result set,and if the "something" succeeds,then update the row and set the tag_col to 1.

One of my colleague has a solution like this:

```<code>select * from tbl_name where datetime_col < '2019-05-26 20:49:00' and datetime_col >= '2019-05-26 20:44:00' and tag_col = 0;
</code>```

,and do something with the result set,and if the "something" fails,update the row and add 5 minutes to the datetime_col(so that it will be selected next time),and if the "something" succeeds,also update the row and set the tag_col to 1.

My question is whose sql is faster (or they are equally fast) when there is index on the datetime_col?
Thanks.

答:
If you execute this query:

```<code>select *
from tbl_name
where datetime_col < '2019-05-26 20:49:00'
</code>```

You are presumably going to be returns lots and lots of data, because -- by your description -- you have a "big table".  You then have to forage through this to get the results you want.

If you execute:

```<code>select *
from tbl_name
where datetime_col < '2019-05-26 20:49:00'
order by datetime_col desc;
</code>```

Then I think MySQL will use the index and be able to return the rows that you want. However, you are still returning lots and lots of rows. You should test if the performance is okay.

Your colleague's query is:

```<code>select *
from tbl_name
where datetime_col < '2019-05-26 20:49:00' and
      datetime_col >= '2019-05-26 20:44:00';'
</code>```

This returns only the rows you want -- presumably a much smaller set.  It should use the index to find those rows.

I would expect that your colleague is correct.  Even if the rows don't exist and you have to issue another query, that is probably faster than returning almost the entire table.

Body:
I hava big table need to be queried by a datetime column every 5 minutes.

My solution is like this:

select * from tbl_name where datetime_col < '2019-05-26 20:49:00' and tag_col = 0;

,and do something with the result set,and if the "something" succeeds,then update the row and set the tag_col to 1.

One of my colleague has a solution like this:

select * from tbl_name where datetime_col < '2019-05-26 20:49:00' and datetime_col >= '2019-05-26 20:44:00' and tag_col = 0;

,and do something with the result set,and if the "something" fails,update the row and add 5 minutes to the datetime_col(so that it will be selected next time),and if the "something" succeeds,also update the row and set the tag_col to 1.

My question is whose sql is faster (or they are equally fast) when there is index on the datetime_col?
Thanks.

Body:
If you execute this query:

select *
from tbl_name
where datetime_col < '2019-05-26 20:49:00'

You are presumably going to be returns lots and lots of data, because -- by your description -- you have a "big table".  You then have to forage through this to get the results you want.

If you execute:

select *
from tbl_name
where datetime_col < '2019-05-26 20:49:00'
order by datetime_col desc;

Then I think MySQL will use the index and be able to return the rows that you want. However, you are still returning lots and lots of rows. You should test if the performance is okay.

Your colleague's query is:

select *
from tbl_name
where datetime_col < '2019-05-26 20:49:00' and
      datetime_col >= '2019-05-26 20:44:00';'

This returns only the rows you want -- presumably a much smaller set.  It should use the index to find those rows.

I would expect that your colleague is correct.  Even if the rows don't exist and you have to issue another query, that is probably faster than returning almost the entire table.


问:
file_get_contents with spaces in URL
I have an issue where even if I replace the spaces to %20 and get this content the ultimate url the browser gets turns the "%20" into "%2520"

Here's my code, any suggestions to get this to work? it seems easy but I'm stuck :/

```<code><?php
//$_GET['song'] will contain a song name with spaces
$song = str_replace(array("%20", "&", "?" , "/"), array(" ", "", "", ""), $_GET['song']);

// I use this to check how the GET 'song' looks after the str_replace
$list = "http://www.lyrdb.com/lookup.php?q=" . $song . "&for=fullt";
echo "list url is " . $list . "<hr>";

$content = file_get_contents("http://www.lyrdb.com/lookup.php?q=" . str_replace(" ", "%20", $song) . "&for=fullt");

echo $content;
?>
</code>```

if you go to http://webservices.lyrdb.com/lookup.php?q=red%20hot%20chili%20peppers&for=fullt The result should output a list of lyric codes.

When i go to my website /?song=red hot chili peppers  , it too converts spaces to %20 's but if it seems the browser converts the %'s to %25.

Can someone help me out?

答:
```<code>$data = json_encode($_POST);

$url = "http://www.index.com?data=";

echo file_get_contents($url . urlencode($data));
</code>```

Title: file_get_contents with spaces in URL

Body:
I have an issue where even if I replace the spaces to %20 and get this content the ultimate url the browser gets turns the "%20" into "%2520"

Here's my code, any suggestions to get this to work? it seems easy but I'm stuck :/

<?php
//$_GET['song'] will contain a song name with spaces
$song = str_replace(array("%20", "&", "?" , "/"), array(" ", "", "", ""), $_GET['song']);

// I use this to check how the GET 'song' looks after the str_replace
$list = "http://www.lyrdb.com/lookup.php?q=" . $song . "&for=fullt";
echo "list url is " . $list . "
";

$content = file_get_contents("http://www.lyrdb.com/lookup.php?q=" . str_replace(" ", "%20", $song) . "&for=fullt");

echo $content;
?>

if you go to http://webservices.lyrdb.com/lookup.php?q=red%20hot%20chili%20peppers&for=fullt The result should output a list of lyric codes.

When i go to my website /?song=red hot chili peppers  , it too converts spaces to %20 's but if it seems the browser converts the %'s to %25.

Can someone help me out?


问:
Node.js: how to consume SOAP XML web service
I wonder what is the best way to consume SOAP XML web service with node.js

Thanks!

答:
For those who are new to SOAP and want a quick explanation and guide, I strongly recommend this awesome article.

You can also use node-soap package, with this simple tutorial.


问:
Nuxtjs, how to add data attribute to body tag
I need to add some data attributes for body tag. How can i do that?

```

答:
You can achieve that by putting your attributes in the head object of your component declaration :

```<code><script>
export default {
  head: {
     bodyAttrs: {
       'data-spy': 'scroll',
       'data-target': '.navbar-nav',
       'data-offset': '110'
     }
  }
  // ...
}
</script>
</code>```

Body:
You can achieve that by putting your attributes in the head object of your component declaration :

<script>
export default {
  head: {
     bodyAttrs: {
       'data-spy': 'scroll',
       'data-target': '.navbar-nav',
       'data-offset': '110'
     }
  }
  // ...
}
</script>


问:
How forget what it learned OR How to start two different neural network?
I Use library brain.js.
https://github.com/BrainJS/brain.js
I dont understand.

For example I start neural network use "data 1" and get "answer 1".
How to do forget this data and start teaching use new "data 2" for new "answer 2"?
The first, what i think, it is restart program, but how use javascript code.
Or me need ask question in github?

答:
Use:

```<code>var net1 = new brain.NeuralNetwork();
var res1 = net1.train(arr1);

var net2 = new brain.NeuralNetwork();
var res2 = net2.train(arr2);
</code>```

may be

Body:
Use:

var net1 = new brain.NeuralNetwork();
var res1 = net1.train(arr1);

var net2 = new brain.NeuralNetwork();
var res2 = net2.train(arr2);

may be


问:
What's the limit to the number of requests sent to stackAPI per second?
What's the limit to the number of requests sent to stack overflow API per second?

I set waiting time of 10 seconds, but it didn't help.

答: The Throttles page details some of the rate limits, namely - no more than 30 requests per second, and a daily limit of 10,000 requests.</p>


问:
How to place login form to the right side of the page using angulat6 material
I am doing project in angular6 material. I have designed login page using angular6 material, but I am not able to place that login form to the right of the page.

I have tried using margin-top, margin-bottom, margin-left and right but non of them working.

Any help please..

Here is my code
app.component.html

        <mat-card class="example-card">

              <mat-grid-list cols="1" rowHeight=5:1>
                  <mat-grid-tile>
                    <mat-card class="login">Login</mat-card>
                  </mat-grid-tile>
                  <mat-grid-tile>
                      <mat-form-field>
                          <input matInput placeholder="name">
                          <mat-icon>account_circle</mat-icon>

                        </mat-form-field>
                      </mat-grid-tile>

                      <mat-grid-tile>
                          <mat-form-field>
                              <input matInput placeholder="password">
                          <mat-icon>visibility</mat-icon>

                            </mat-form-field>
                          </mat-grid-tile>
                          <mat-grid-tile>
                              <button mat-raised-button color="accent">Submit</button>
                          </mat-grid-tile>

                </mat-grid-list>
        </mat-card>

    ```
</div>
</div>
</p>

<p>app.component.css</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>html, body {
        height: 100%;
        background-image: url("/assets/pencil4.jpg");
        background-position: center;
        background-size: cover;
        /* background-attachment: fixed; */

      }
       */

    mat-card{
        display: flex;
        height:41% ;
        background-color: gray;
      }

     .login{
        width:90%;
        height:30% ;
        background-color: #FFDE03;
        font-weight: 800;
        border-radius: 5px;
    }

     mat-form-field{
        width:90%;
    }

    mat-grid-tile{
        width:400px;
    }

    .example-card {
        max-width: 300px;
      } </code>```

If magin-top:800px,

If I use padding-top:300px;

答:
Add CSS to example-card.
use margin-left and margin-top for align to right place.

 .example-card {
        max-width: 300px;
        margin-left: 800px;
        margin-top:100px;
      } ```

if margin-top not works. try padding-top

see my example

https://stackblitz.com/edit/angular-qfadvh

Body:
I am doing project in angular6 material. I have designed login page using angular6 material, but I am not able to place that login form to the right of the page.

I have tried using margin-top, margin-bottom, margin-left and right but non of them working.

Any help please..

Here is my code
app.component.html

        <mat-card class="example-card">

              <mat-grid-list cols="1" rowHeight=5:1>
                  <mat-grid-tile>
                    <mat-card class="login">Login</mat-card>
                  </mat-grid-tile>
                  <mat-grid-tile>
                      <mat-form-field>
                          <input matInput placeholder="name">
                          <mat-icon>account_circle</mat-icon>

                        </mat-form-field>
                      </mat-grid-tile>

                      <mat-grid-tile>
                          <mat-form-field>
                              <input matInput placeholder="password">
                          <mat-icon>visibility</mat-icon>

                            </mat-form-field>
                          </mat-grid-tile>
                          <mat-grid-tile>
                              <button mat-raised-button color="accent">Submit</button>
                          </mat-grid-tile>

                </mat-grid-list>
        </mat-card>

app.component.css

html, body {
        height: 100%;
        background-image: url("/assets/pencil4.jpg");
        background-position: center;
        background-size: cover;
        /* background-attachment: fixed; */

      }
       */

    mat-card{
        display: flex;
        height:41% ;
        background-color: gray;
      }

     .login{
        width:90%;
        height:30% ;
        background-color: #FFDE03;
        font-weight: 800;
        border-radius: 5px;
    }

     mat-form-field{
        width:90%;
    }

    mat-grid-tile{
        width:400px;
    }

    .example-card {
        max-width: 300px;
      }

If magin-top:800px,

If I use padding-top:300px;

Body:
Add CSS to example-card.
use margin-left and margin-top for align to right place.

 .example-card {
        max-width: 300px;
        margin-left: 800px;
        margin-top:100px;
      }

if margin-top not works. try padding-top

see my example

https://stackblitz.com/edit/angular-qfadvh


问:
POP3 GetMessages with UIDS
I use MailKit version 1.18.1.1 and I would like to switch to the latest version but I can't because GetMessages no longer accepts a list of UIDS but wants a list of int32. Why? Is there no possibility to use the old version of GetMessages again? My mail client uses to compare the list of UIDS in the database with the one read on the POP server to define which UIDS to download. Thank you for any replies and suggestions</p>

答:
I dropped the APIs that accepted UIDs because it required MailKit to keep its own copy of a UID-to-index mapping which not only meant more memory usage but it was also more complicated to keep in sync with the server.

What you need to do now is to call client.GetMessageUids() to get your own list of UIDs and then figure out which indexes you want based on that UID list.

```<code>var uids = client.GetMessageUids ();
var indexes = new List<int> ();

for (int i = 0; i < uids.Length, i++) {
    if (!HaveSeen (uids[i]))
        indexes.Add (i);
}

// now you have a list of indexes that you want
</code>```

Title: POP3 GetMessages with UIDS

Body:
I dropped the APIs that accepted UIDs because it required MailKit to keep its own copy of a UID-to-index mapping which not only meant more memory usage but it was also more complicated to keep in sync with the server.

What you need to do now is to call client.GetMessageUids() to get your own list of UIDs and then figure out which indexes you want based on that UID list.

var uids = client.GetMessageUids ();
var indexes = new List<int> ();

for (int i = 0; i < uids.Length, i++) {
    if (!HaveSeen (uids[i]))
        indexes.Add (i);
}

// now you have a list of indexes that you want